diff --git a/assets/AIChatPage-DH58XfsA.js b/assets/AIChatPage-CEm6qhAI.js similarity index 95% rename from assets/AIChatPage-DH58XfsA.js rename to assets/AIChatPage-CEm6qhAI.js index 4ccec58b938b2feaefc7f5816cedaa5d8030e062..f361c8e570aa153d957778f55eff2f47693fd482 100644 --- a/assets/AIChatPage-DH58XfsA.js +++ b/assets/AIChatPage-CEm6qhAI.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{aG as B,u as z,_ as F,h as C,m as I,O as H}from"./index-BvEKrMkD.js";import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as O}from"./button-Bfg1pO9T.js";import{I as A}from"./input-B3TmduBc.js";import W from"./ChatMarkdown-Chh6462P.js";import{P as G}from"./plus-IoQaIojF.js";import{S as Y}from"./search-CHZcTJmD.js";import{T as Q}from"./trash-2-B056YIHV.js";import{C as q}from"./chevron-left-DFU37_wB.js";import{S as K}from"./send-BivcIdIA.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";function U(a){return a?a instanceof Date?a.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):typeof a=="object"&&"toDate"in a?a.toDate().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):String(a):""}const ue=()=>{const{sessions:a,activeSessionId:o,isLoading:l,loadingSessionId:L,setActiveSessionId:n,createNewSession:c,sendMessage:T,deleteSession:_,getActiveSession:M,sessionsLoaded:g}=B(),{userProfile:m}=z(),[x,P]=r.useState(""),[i,y]=r.useState(""),[j,w]=r.useState(!1),h=r.useRef(null),u=r.useRef(!0),p=r.useRef(!1),d=M(),f=d?.messages||[],D=f.some(t=>t.sender==="ai"&&t.id.startsWith("stream-")),v=l&&o===L&&!D,N=(t="auto")=>{const s=h.current;s&&s.scrollTo({top:s.scrollHeight,behavior:t})},E=()=>{const t=h.current;return t?t.scrollHeight-t.scrollTop-t.clientHeight<=120:!0},R=()=>{u.current=E()};r.useEffect(()=>{F(async()=>{const{warmupBackend:t}=await import("./index-BvEKrMkD.js").then(s=>s.b8);return{warmupBackend:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({warmupBackend:t})=>{t()}).catch(t=>{console.warn("AI chat warmup skipped:",t)})},[]),r.useEffect(()=>{if(g&&a.length===0){const t={id:"welcome-"+Date.now(),sender:"ai",text:"Hi! I'm your AI math tutor. What would you like to learn about today?",timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},s=c(t);n(s)}},[g]),r.useEffect(()=>{if(!u.current)return;const t=window.requestAnimationFrame(()=>N("auto"));return()=>window.cancelAnimationFrame(t)},[f,v]),r.useEffect(()=>{u.current=!0,N("auto")},[o]);const k=async()=>{if(!(!i.trim()||l||j||p.current)){p.current=!0,w(!0);try{let t=o;t||(t=c(),n(t));const s=i.trim();y(""),await T(t,s)}finally{p.current=!1,w(!1)}}},S=()=>{const t={id:"welcome-"+Date.now(),sender:"ai",text:"Hi! I'm your AI math tutor. What would you like to learn about today?",timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},s=c(t);n(s)},$=(t,s)=>{s.stopPropagation(),_(t)},b=a.filter(t=>t.title.toLowerCase().includes(x.toLowerCase())||t.preview.toLowerCase().includes(x.toLowerCase()));return e.jsxs("div",{className:"h-full min-h-0 overflow-hidden flex md:gap-4 px-0 md:px-4 sm:px-6 xl:px-10 py-0 md:py-6",children:[e.jsxs("div",{className:`${o?"hidden md:flex":"flex"} w-full md:w-80 min-h-0 flex-col bg-[#f7f9fc] rounded-none md:rounded-3xl border-0 md:border border-[#dde3eb] overflow-hidden`,children:[e.jsxs("div",{className:"p-4 border-b border-[#dde3eb] flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 md:w-12 md:h-12 bg-gradient-to-r from-sky-600 to-sky-500 rounded-xl md:rounded-2xl flex items-center justify-center shrink-0",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-8 h-8 md:w-10 md:h-10 object-contain drop-shadow-md"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm md:text-base font-bold font-display text-[#0a1628]",children:"L.O.L.I."}),e.jsx("p",{className:"text-[10px] text-[#5a6578]",children:"Your AI Math Tutor"})]})]}),e.jsxs("button",{onClick:S,className:"bg-gradient-to-r from-sky-600 to-sky-500 hover:from-sky-700 hover:to-sky-600 text-white px-3 py-2 rounded-xl text-xs font-bold transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-1.5 shrink-0",children:[e.jsx(G,{size:14}),"New Chat"]})]}),e.jsxs("div",{className:"relative mt-3",children:[e.jsx(Y,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500",size:14}),e.jsx(A,{type:"text",placeholder:"Search conversations...",value:x,onChange:t=>P(t.target.value),className:"w-full pl-9 pr-3 py-2 text-xs rounded-xl border-[#dde3eb] focus:border-sky-600 focus:ring-2 focus:ring-sky-100"})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between mb-2 px-2",children:e.jsxs("span",{className:"text-xs font-bold text-[#5a6578]",children:[b.length," Conversations"]})}),e.jsx(C,{children:b.map(t=>e.jsxs(I.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},onClick:()=>n(t.id),className:`group p-3 rounded-2xl cursor-pointer transition-all duration-200 border relative ${o===t.id?"bg-sky-50 border-sky-200 shadow-sm":"bg-[#edf1f7] border-transparent hover:bg-[#dde3eb] hover:border-[#dde3eb]"}`,children:[e.jsxs("div",{className:"flex items-start justify-between mb-1",children:[e.jsx("h3",{className:`text-xs font-bold mb-0.5 pr-6 line-clamp-1 ${o===t.id?"text-sky-700":"text-[#0a1628]"}`,children:t.title}),e.jsx("button",{onClick:s=>$(t.id,s),className:"absolute top-2 right-2 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-red-100 text-slate-500 hover:text-red-600 transition-all",children:e.jsx(Q,{size:12})})]}),e.jsx("p",{className:"text-[10px] text-[#5a6578] mb-2 line-clamp-2",children:t.preview}),e.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[e.jsx("span",{className:"text-slate-500",children:t.date}),e.jsxs("span",{className:`px-2 py-0.5 rounded-full ${o===t.id?"bg-sky-100 text-sky-600":"bg-[#dde3eb] text-[#5a6578]"}`,children:[t.messageCount," msgs"]})]})]},t.id))}),b.length===0&&e.jsxs("div",{className:"text-center py-8",children:[e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-16 h-16 object-contain mx-auto mb-2 opacity-60 drop-shadow-sm grayscale contrast-50"}),e.jsx("p",{className:"text-sm text-slate-500",children:"No conversations found"}),e.jsx("p",{className:"text-xs text-slate-500/60 mt-1",children:"Start a new chat!"})]})]})]}),e.jsx("div",{className:`${o?"flex":"hidden md:flex"} flex-1 min-h-0 flex-col bg-[#f7f9fc] rounded-none md:rounded-3xl border-0 md:border border-[#dde3eb] overflow-hidden`,children:o?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-3 md:p-4 border-b border-[#dde3eb] flex items-center justify-between flex-shrink-0 bg-white md:bg-transparent shadow-sm md:shadow-none z-10 relative",children:[e.jsxs("div",{className:"flex items-center gap-2 md:gap-3",children:[e.jsx("button",{onClick:()=>n(null),className:"md:hidden p-1.5 -ml-1 text-slate-500 hover:text-slate-800 rounded-lg hover:bg-slate-100",children:e.jsx(q,{size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-bold font-display text-[#0a1628] text-sm md:text-base",children:d?.title}),e.jsx("p",{className:"text-[10px] md:text-xs text-[#5a6578]",children:d?.date})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:d?.topics.map((t,s)=>e.jsx("span",{className:"px-3 py-1 bg-sky-50 text-sky-600 text-xs font-bold rounded-lg",children:t},s))})]}),e.jsxs("div",{ref:h,onScroll:R,className:"flex-1 overflow-y-auto overscroll-contain p-4 md:p-6 space-y-4 bg-[#edf1f7] min-h-0",children:[e.jsx(C,{children:f.map(t=>e.jsxs(I.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`flex items-end gap-2 ${t.sender==="user"?"justify-end":"justify-start"}`,children:[t.sender!=="user"&&e.jsx("div",{className:"w-7 h-7 rounded-full bg-gradient-to-r from-sky-600 to-sky-500 flex items-center justify-center flex-shrink-0 mb-1",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI",className:"w-5 h-5 object-contain"})}),e.jsxs("div",{className:`max-w-[70%] rounded-2xl px-5 py-3 ${t.sender==="user"?"bg-gradient-to-r from-sky-600 to-sky-500 text-white":"bg-white text-[#0a1628] shadow-md border border-[#dde3eb]"}`,children:[t.sender==="user"?e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:t.text}):e.jsx(W,{children:t.text}),e.jsx("p",{className:`text-[10px] mt-1.5 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:U(t.timestamp)})]}),t.sender==="user"&&e.jsx(H,{src:m?.photo,name:m?.name,gender:m?.gender,className:"w-7 h-7 flex-shrink-0 mb-1",fallbackClassName:"text-[10px]"})]},t.id))}),v&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white text-[#0a1628] shadow-md border border-[#dde3eb] rounded-2xl px-5 py-3 max-w-[70%]",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:150ms]"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:300ms]"})]})})})]}),e.jsx("div",{className:"p-3 md:p-4 border-t border-[#dde3eb] bg-white flex-shrink-0",children:e.jsxs("div",{className:"flex gap-2 md:gap-3",children:[e.jsx(A,{type:"text",value:i,onChange:t=>y(t.target.value),onKeyPress:t=>t.key==="Enter"&&k(),placeholder:"Ask me anything about math...",className:"flex-1 px-5 py-3 rounded-xl border-[#dde3eb] focus:border-sky-600 focus:ring-2 focus:ring-sky-100 text-sm"}),e.jsx(O,{onClick:k,disabled:!i.trim()||l||j,className:"px-6 bg-gradient-to-r from-sky-600 to-sky-500 hover:from-sky-700 hover:to-sky-600 text-white rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg",children:e.jsx(K,{size:18})})]})})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-8 text-center",children:[e.jsx("div",{className:"w-24 h-24 bg-gradient-to-r from-sky-100 to-cyan-100 rounded-3xl flex items-center justify-center mb-6",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-20 h-20 object-contain drop-shadow-lg"})}),e.jsx("h2",{className:"text-2xl font-bold font-display text-[#0a1628] mb-1",children:"Welcome to L.O.L.I."}),e.jsx("p",{className:"text-sky-600 text-sm font-bold tracking-wide uppercase mb-4",children:"Logical Operations & Learning Intelligence"}),e.jsx("p",{className:"text-[#5a6578] mb-6 max-w-md",children:"Your personal AI math tutor is here to help! Start a new conversation or select one from the sidebar."}),e.jsx("button",{onClick:S,className:"px-6 py-3 bg-gradient-to-r from-sky-600 to-sky-500 hover:from-sky-700 hover:to-sky-600 text-white rounded-xl font-bold shadow-lg hover:shadow-xl transition-all",children:"Start Your First Chat"}),e.jsx("div",{className:"mt-8 grid grid-cols-3 gap-4 max-w-2xl",children:["Algebra","Geometry","Calculus"].map(t=>e.jsxs("div",{className:"p-4 bg-[#edf1f7] rounded-xl border border-[#dde3eb]",children:[e.jsx("p",{className:"text-sm font-bold text-[#0a1628]",children:t}),e.jsxs("p",{className:"text-xs text-[#5a6578] mt-1",children:["Get help with ",t.toLowerCase()]})]},t))})]})})]})};export{ue as default}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{aG as B,u as z,_ as F,h as C,m as I,O as H}from"./index-BdLfAeGL.js";import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as O}from"./button-BbJLXpfi.js";import{I as A}from"./input-CHfZS1wQ.js";import W from"./ChatMarkdown-SgVutDBu.js";import{P as G}from"./plus-Z9YkmuN1.js";import{S as Y}from"./search-gQ2OCqgd.js";import{T as Q}from"./trash-2-f-pq6QuO.js";import{C as q}from"./chevron-left-CNwzgiLt.js";import{S as K}from"./send-CxDLfaHq.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";function U(a){return a?a instanceof Date?a.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):typeof a=="object"&&"toDate"in a?a.toDate().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):String(a):""}const ue=()=>{const{sessions:a,activeSessionId:o,isLoading:l,loadingSessionId:L,setActiveSessionId:n,createNewSession:c,sendMessage:T,deleteSession:_,getActiveSession:M,sessionsLoaded:g}=B(),{userProfile:m}=z(),[x,P]=r.useState(""),[i,y]=r.useState(""),[j,w]=r.useState(!1),h=r.useRef(null),u=r.useRef(!0),p=r.useRef(!1),d=M(),f=d?.messages||[],D=f.some(t=>t.sender==="ai"&&t.id.startsWith("stream-")),v=l&&o===L&&!D,N=(t="auto")=>{const s=h.current;s&&s.scrollTo({top:s.scrollHeight,behavior:t})},E=()=>{const t=h.current;return t?t.scrollHeight-t.scrollTop-t.clientHeight<=120:!0},R=()=>{u.current=E()};r.useEffect(()=>{F(async()=>{const{warmupBackend:t}=await import("./index-BdLfAeGL.js").then(s=>s.b8);return{warmupBackend:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({warmupBackend:t})=>{t()}).catch(t=>{console.warn("AI chat warmup skipped:",t)})},[]),r.useEffect(()=>{if(g&&a.length===0){const t={id:"welcome-"+Date.now(),sender:"ai",text:"Hi! I'm your AI math tutor. What would you like to learn about today?",timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},s=c(t);n(s)}},[g]),r.useEffect(()=>{if(!u.current)return;const t=window.requestAnimationFrame(()=>N("auto"));return()=>window.cancelAnimationFrame(t)},[f,v]),r.useEffect(()=>{u.current=!0,N("auto")},[o]);const k=async()=>{if(!(!i.trim()||l||j||p.current)){p.current=!0,w(!0);try{let t=o;t||(t=c(),n(t));const s=i.trim();y(""),await T(t,s)}finally{p.current=!1,w(!1)}}},S=()=>{const t={id:"welcome-"+Date.now(),sender:"ai",text:"Hi! I'm your AI math tutor. What would you like to learn about today?",timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},s=c(t);n(s)},$=(t,s)=>{s.stopPropagation(),_(t)},b=a.filter(t=>t.title.toLowerCase().includes(x.toLowerCase())||t.preview.toLowerCase().includes(x.toLowerCase()));return e.jsxs("div",{className:"h-full min-h-0 overflow-hidden flex md:gap-4 px-0 md:px-4 sm:px-6 xl:px-10 py-0 md:py-6",children:[e.jsxs("div",{className:`${o?"hidden md:flex":"flex"} w-full md:w-80 min-h-0 flex-col bg-[#f7f9fc] rounded-none md:rounded-3xl border-0 md:border border-[#dde3eb] overflow-hidden`,children:[e.jsxs("div",{className:"p-4 border-b border-[#dde3eb] flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 md:w-12 md:h-12 bg-gradient-to-r from-sky-600 to-sky-500 rounded-xl md:rounded-2xl flex items-center justify-center shrink-0",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-8 h-8 md:w-10 md:h-10 object-contain drop-shadow-md"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm md:text-base font-bold font-display text-[#0a1628]",children:"L.O.L.I."}),e.jsx("p",{className:"text-[10px] text-[#5a6578]",children:"Your AI Math Tutor"})]})]}),e.jsxs("button",{onClick:S,className:"bg-gradient-to-r from-sky-600 to-sky-500 hover:from-sky-700 hover:to-sky-600 text-white px-3 py-2 rounded-xl text-xs font-bold transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-1.5 shrink-0",children:[e.jsx(G,{size:14}),"New Chat"]})]}),e.jsxs("div",{className:"relative mt-3",children:[e.jsx(Y,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500",size:14}),e.jsx(A,{type:"text",placeholder:"Search conversations...",value:x,onChange:t=>P(t.target.value),className:"w-full pl-9 pr-3 py-2 text-xs rounded-xl border-[#dde3eb] focus:border-sky-600 focus:ring-2 focus:ring-sky-100"})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between mb-2 px-2",children:e.jsxs("span",{className:"text-xs font-bold text-[#5a6578]",children:[b.length," Conversations"]})}),e.jsx(C,{children:b.map(t=>e.jsxs(I.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},onClick:()=>n(t.id),className:`group p-3 rounded-2xl cursor-pointer transition-all duration-200 border relative ${o===t.id?"bg-sky-50 border-sky-200 shadow-sm":"bg-[#edf1f7] border-transparent hover:bg-[#dde3eb] hover:border-[#dde3eb]"}`,children:[e.jsxs("div",{className:"flex items-start justify-between mb-1",children:[e.jsx("h3",{className:`text-xs font-bold mb-0.5 pr-6 line-clamp-1 ${o===t.id?"text-sky-700":"text-[#0a1628]"}`,children:t.title}),e.jsx("button",{onClick:s=>$(t.id,s),className:"absolute top-2 right-2 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-red-100 text-slate-500 hover:text-red-600 transition-all",children:e.jsx(Q,{size:12})})]}),e.jsx("p",{className:"text-[10px] text-[#5a6578] mb-2 line-clamp-2",children:t.preview}),e.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[e.jsx("span",{className:"text-slate-500",children:t.date}),e.jsxs("span",{className:`px-2 py-0.5 rounded-full ${o===t.id?"bg-sky-100 text-sky-600":"bg-[#dde3eb] text-[#5a6578]"}`,children:[t.messageCount," msgs"]})]})]},t.id))}),b.length===0&&e.jsxs("div",{className:"text-center py-8",children:[e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-16 h-16 object-contain mx-auto mb-2 opacity-60 drop-shadow-sm grayscale contrast-50"}),e.jsx("p",{className:"text-sm text-slate-500",children:"No conversations found"}),e.jsx("p",{className:"text-xs text-slate-500/60 mt-1",children:"Start a new chat!"})]})]})]}),e.jsx("div",{className:`${o?"flex":"hidden md:flex"} flex-1 min-h-0 flex-col bg-[#f7f9fc] rounded-none md:rounded-3xl border-0 md:border border-[#dde3eb] overflow-hidden`,children:o?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-3 md:p-4 border-b border-[#dde3eb] flex items-center justify-between flex-shrink-0 bg-white md:bg-transparent shadow-sm md:shadow-none z-10 relative",children:[e.jsxs("div",{className:"flex items-center gap-2 md:gap-3",children:[e.jsx("button",{onClick:()=>n(null),className:"md:hidden p-1.5 -ml-1 text-slate-500 hover:text-slate-800 rounded-lg hover:bg-slate-100",children:e.jsx(q,{size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-bold font-display text-[#0a1628] text-sm md:text-base",children:d?.title}),e.jsx("p",{className:"text-[10px] md:text-xs text-[#5a6578]",children:d?.date})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:d?.topics.map((t,s)=>e.jsx("span",{className:"px-3 py-1 bg-sky-50 text-sky-600 text-xs font-bold rounded-lg",children:t},s))})]}),e.jsxs("div",{ref:h,onScroll:R,className:"flex-1 overflow-y-auto overscroll-contain p-4 md:p-6 space-y-4 bg-[#edf1f7] min-h-0",children:[e.jsx(C,{children:f.map(t=>e.jsxs(I.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`flex items-end gap-2 ${t.sender==="user"?"justify-end":"justify-start"}`,children:[t.sender!=="user"&&e.jsx("div",{className:"w-7 h-7 rounded-full bg-gradient-to-r from-sky-600 to-sky-500 flex items-center justify-center flex-shrink-0 mb-1",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI",className:"w-5 h-5 object-contain"})}),e.jsxs("div",{className:`max-w-[70%] rounded-2xl px-5 py-3 ${t.sender==="user"?"bg-gradient-to-r from-sky-600 to-sky-500 text-white":"bg-white text-[#0a1628] shadow-md border border-[#dde3eb]"}`,children:[t.sender==="user"?e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:t.text}):e.jsx(W,{children:t.text}),e.jsx("p",{className:`text-[10px] mt-1.5 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:U(t.timestamp)})]}),t.sender==="user"&&e.jsx(H,{src:m?.photo,name:m?.name,gender:m?.gender,className:"w-7 h-7 flex-shrink-0 mb-1",fallbackClassName:"text-[10px]"})]},t.id))}),v&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white text-[#0a1628] shadow-md border border-[#dde3eb] rounded-2xl px-5 py-3 max-w-[70%]",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:150ms]"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:300ms]"})]})})})]}),e.jsx("div",{className:"p-3 md:p-4 border-t border-[#dde3eb] bg-white flex-shrink-0",children:e.jsxs("div",{className:"flex gap-2 md:gap-3",children:[e.jsx(A,{type:"text",value:i,onChange:t=>y(t.target.value),onKeyPress:t=>t.key==="Enter"&&k(),placeholder:"Ask me anything about math...",className:"flex-1 px-5 py-3 rounded-xl border-[#dde3eb] focus:border-sky-600 focus:ring-2 focus:ring-sky-100 text-sm"}),e.jsx(O,{onClick:k,disabled:!i.trim()||l||j,className:"px-6 bg-gradient-to-r from-sky-600 to-sky-500 hover:from-sky-700 hover:to-sky-600 text-white rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg",children:e.jsx(K,{size:18})})]})})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-8 text-center",children:[e.jsx("div",{className:"w-24 h-24 bg-gradient-to-r from-sky-100 to-cyan-100 rounded-3xl flex items-center justify-center mb-6",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-20 h-20 object-contain drop-shadow-lg"})}),e.jsx("h2",{className:"text-2xl font-bold font-display text-[#0a1628] mb-1",children:"Welcome to L.O.L.I."}),e.jsx("p",{className:"text-sky-600 text-sm font-bold tracking-wide uppercase mb-4",children:"Logical Operations & Learning Intelligence"}),e.jsx("p",{className:"text-[#5a6578] mb-6 max-w-md",children:"Your personal AI math tutor is here to help! Start a new conversation or select one from the sidebar."}),e.jsx("button",{onClick:S,className:"px-6 py-3 bg-gradient-to-r from-sky-600 to-sky-500 hover:from-sky-700 hover:to-sky-600 text-white rounded-xl font-bold shadow-lg hover:shadow-xl transition-all",children:"Start Your First Chat"}),e.jsx("div",{className:"mt-8 grid grid-cols-3 gap-4 max-w-2xl",children:["Algebra","Geometry","Calculus"].map(t=>e.jsxs("div",{className:"p-4 bg-[#edf1f7] rounded-xl border border-[#dde3eb]",children:[e.jsx("p",{className:"text-sm font-bold text-[#0a1628]",children:t}),e.jsxs("p",{className:"text-xs text-[#5a6578] mt-1",children:["Get help with ",t.toLowerCase()]})]},t))})]})})]})};export{ue as default}; diff --git a/assets/AdminDashboard-By-BB3KI.js b/assets/AdminDashboard-CMvLZSCj.js similarity index 98% rename from assets/AdminDashboard-By-BB3KI.js rename to assets/AdminDashboard-CMvLZSCj.js index cc2a90e3e9e1744377ae3fe987b52c5599463677..bcf9cc532b9f6e7497fef7c9211e4531c4ef52db 100644 --- a/assets/AdminDashboard-By-BB3KI.js +++ b/assets/AdminDashboard-CMvLZSCj.js @@ -1,4 +1,4 @@ -import{j as e,r,d as Ss}from"./vendor-react-B4AQeu28.js";import{C as it,S as nt,a as qs}from"./Sidebar-CR8IPH6O.js";import ct from"./ConfirmModal-DE1CbRDa.js";import{e as we,o as Te,g as M,n as Se,j as S,h as _t,m as re,q as V,R as Me,k as Ot,v as Cs,Q as Bt,S as Gt,p as ot,u as cs,L as dt,V as As,y as xt,w as De,U as Pe,G as is,i as qt,W as Hs,X as Ws,Y as Vs,r as Ht,A as Qs,Z as Fe,$ as Wt,B as Vt,T as mt,b as He,H as Qt,a0 as Xt,a1 as Kt,E as Yt,M as Zt,O as Jt}from"./index-BvEKrMkD.js";import{B as E}from"./button-Bfg1pO9T.js";import{S as J,a as ee,b as Ue,c as se,d as C}from"./select-CU8TeDXy.js";import{I as xe}from"./input-B3TmduBc.js";import{S as rs}from"./subjects-ChEJ6J55.js";import{getDocs as F,query as ve,collection as L,orderBy as We,deleteDoc as ea,doc as Es,limit as ns,where as Ve,addDoc as sa,serverTimestamp as ta,updateDoc as ws}from"./vendor-firebase-firestore-CNv3xXal.js";import{U as es}from"./upload-COEzjD21.js";import{D as fe}from"./LogoutActionButton-Cu6gWsBL.js";import{F as Ce,A as _e,N as aa}from"./NotificationDropdown-txVZGqve.js";import{T as je}from"./trash-2-B056YIHV.js";import{S as Xs}from"./sparkles-av0wSNZT.js";import{S as Ks,D as ht,a as pt,b as ut,c as gt,e as la}from"./dialog-F21mi9j3.js";import{D as Ps}from"./download-BYKPAk50.js";import{S as zs}from"./shield-check-X3NwQ434.js";import{S as bt}from"./search-CHZcTJmD.js";import{C as Rs}from"./clock-0vnF72R6.js";import{E as ft,a as ra}from"./eye-DbYh0OO3.js";import{C as jt}from"./chevron-left-DFU37_wB.js";import{C as vt}from"./chevron-right-CbKJd0ln.js";import{C as Re}from"./circle-alert-fPu7cawt.js";import{I as wt}from"./info-CMvRmbQw.js";import{C as ia,a as na}from"./vendor-radix-C5nwdvGr.js";import{C as ca}from"./check-BmWAQELM.js";import{M as oa}from"./mail-DahQBvd1.js";import{P as Ys}from"./plus-IoQaIojF.js";import{S as Nt}from"./save-DAHVTL2X.js";import{C as da}from"./chart-column-DKW3TTRX.js";import{u as xa}from"./useQuery-a95tRwQa.js";import{X as Ms}from"./x-BYtx1i07.js";import{D as ma}from"./dollar-sign-DWer_VPF.js";import{S as ha}from"./switch-kakgyvwt.js";import{u as pa,t as ua,a as ga}from"./useSubjectAvailability-C0TzAHAR.js";import{C as ba}from"./chevron-up-CDr90bpM.js";import{C as fa}from"./circle-help-DeWZHKak.js";import{B as ja}from"./bell-C57aSZcx.js";import{R as Zs,B as va,C as wa,X as Na,Y as ya,T as ka,a as Js,P as Sa,d as Ca,b as et}from"./vendor-charts-CAmziV1y.js";import{C as Ns}from"./circle-check-E415RSic.js";import"./tooltip-DDXcKYaB.js";import"./shirt-DFiZ2C4J.js";import"./log-out-BDL1J1Fs.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";import"./formatDistanceToNow-5Jvf3U0l.js";/** +import{j as e,r,d as Ss}from"./vendor-react-B4AQeu28.js";import{C as it,S as nt,a as qs}from"./Sidebar-BohFsvbI.js";import ct from"./ConfirmModal-DPzAgSP6.js";import{e as we,o as Te,g as M,n as Se,j as S,h as _t,m as re,q as V,R as Me,k as Ot,v as Cs,Q as Bt,S as Gt,p as ot,u as cs,L as dt,V as As,y as xt,w as De,U as Pe,G as is,i as qt,W as Hs,X as Ws,Y as Vs,r as Ht,A as Qs,Z as Fe,$ as Wt,B as Vt,T as mt,b as He,H as Qt,a0 as Xt,a1 as Kt,E as Yt,M as Zt,O as Jt}from"./index-BdLfAeGL.js";import{B as E}from"./button-BbJLXpfi.js";import{S as J,a as ee,b as Ue,c as se,d as C}from"./select-C3tB_0M-.js";import{I as xe}from"./input-CHfZS1wQ.js";import{S as rs}from"./subjects-Dw9HR29l.js";import{getDocs as F,query as ve,collection as L,orderBy as We,deleteDoc as ea,doc as Es,limit as ns,where as Ve,addDoc as sa,serverTimestamp as ta,updateDoc as ws}from"./vendor-firebase-firestore-CNv3xXal.js";import{U as es}from"./upload-CbDKucU9.js";import{D as fe}from"./LogoutActionButton-Baak8j6y.js";import{F as Ce,A as _e,N as aa}from"./NotificationDropdown-DW0msTLi.js";import{T as je}from"./trash-2-f-pq6QuO.js";import{S as Xs}from"./sparkles-DnAkO9TX.js";import{S as Ks,D as ht,a as pt,b as ut,c as gt,e as la}from"./dialog-BW6ddbOv.js";import{D as Ps}from"./download-CPe9YOUv.js";import{S as zs}from"./shield-check-DqqR-L0T.js";import{S as bt}from"./search-gQ2OCqgd.js";import{C as Rs}from"./clock-CpBwkoND.js";import{E as ft,a as ra}from"./eye-8D1uq8DN.js";import{C as jt}from"./chevron-left-CNwzgiLt.js";import{C as vt}from"./chevron-right-BRRve0zL.js";import{C as Re}from"./circle-alert-ByVTnT3r.js";import{I as wt}from"./info-D1mJ7S8g.js";import{C as ia,a as na}from"./vendor-radix-C5nwdvGr.js";import{C as ca}from"./check-DbVe23hB.js";import{M as oa}from"./mail-9RdsJqkx.js";import{P as Ys}from"./plus-Z9YkmuN1.js";import{S as Nt}from"./save-CUEUjfb0.js";import{C as da}from"./chart-column-Dl7iJ2BC.js";import{u as xa}from"./useQuery-fA8_Syr9.js";import{X as Ms}from"./x-BLhsirCD.js";import{D as ma}from"./dollar-sign-BFLnKeOT.js";import{S as ha}from"./switch-BZ2ceCBk.js";import{u as pa,t as ua,a as ga}from"./useSubjectAvailability-BUrciGBC.js";import{C as ba}from"./chevron-up-uSn_SWll.js";import{C as fa}from"./circle-help-CZDuv1Gp.js";import{B as ja}from"./bell-C5_RRTsA.js";import{R as Zs,B as va,C as wa,X as Na,Y as ya,T as ka,a as Js,P as Sa,d as Ca,b as et}from"./vendor-charts-CAmziV1y.js";import{C as Ns}from"./circle-check-CuVe-qlS.js";import"./tooltip-Blvwukwg.js";import"./shirt-iZ6vtR5i.js";import"./log-out-CccGdaTy.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";import"./formatDistanceToNow-DQ9IJwBi.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/AssessmentPage-DWkUbkQS.js b/assets/AssessmentPage-CNGTAZUT.js similarity index 95% rename from assets/AssessmentPage-DWkUbkQS.js rename to assets/AssessmentPage-CNGTAZUT.js index c68b0b5169c4a080b0089dcde0b6193dc500647f..fc04847100cbb086f5ed013f09cee374ad5913a2 100644 --- a/assets/AssessmentPage-DWkUbkQS.js +++ b/assets/AssessmentPage-CNGTAZUT.js @@ -1,7 +1,7 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-BVFD1ZML.js","assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{e as V,_ as M,m as i,Z,h as G,T as H,F as W,r as X}from"./index-BvEKrMkD.js";import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as K}from"./button-Bfg1pO9T.js";import{s as ee}from"./diagnosticService-BvH8S98K.js";import{M as te}from"./maximize-2-BUGGXJYn.js";import{X as se}from"./x-BYtx1i07.js";import{C as ne}from"./clock-0vnF72R6.js";import{C as re}from"./circle-check-big-mtMsU82c.js";import{C as ae}from"./chevron-right-CbKJd0ln.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-h2NDr2Mk.js","assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{e as V,_ as M,m as i,Z,h as G,T as H,F as W,r as X}from"./index-BdLfAeGL.js";import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as K}from"./button-BbJLXpfi.js";import{s as ee}from"./diagnosticService-DmVYM_3F.js";import{M as te}from"./maximize-2-C5LwFHUQ.js";import{X as se}from"./x-BLhsirCD.js";import{C as ne}from"./clock-CpBwkoND.js";import{C as re}from"./circle-check-big-B54zXy3k.js";import{C as ae}from"./chevron-right-BRRve0zL.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const ie=[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]],le=V("minimize-2",ie),Se=({testId:T,questions:f,userName:$,onComplete:B,onCancel:L})=>{const[h,_]=r.useState("testing"),[a,S]=r.useState(0),[o,b]=r.useState(null),[u,E]=r.useState(()=>{try{const t=sessionStorage.getItem("mathpulse_diagnostic_responses");return t?JSON.parse(t):[]}catch{return[]}}),[g,k]=r.useState([]),[x,z]=r.useState(0),[C,D]=r.useState(null),[A,w]=r.useState(!1),c=r.useRef(null),F=r.useRef(Date.now()),p=r.useRef(!1),d=f.length,l=f[a],P=Math.round((a+(o?1:0))/d*100),v=t=>t==="easy"?60:t==="hard"?120:90,[q]=r.useState(Array.from({length:10},(t,s)=>({id:s,size:Math.random()*80+30,x:Math.random()*100,y:Math.random()*100,duration:Math.random()*20+15,delay:Math.random()*-20,color:["bg-purple-500/10","bg-blue-500/10","bg-cyan-500/10","bg-emerald-500/10"][Math.floor(Math.random()*4)]})));r.useEffect(()=>{const t=v(l?.difficulty||"medium");return F.current=Date.now(),p.current=!1,z(t),c.current&&clearInterval(c.current),c.current=setInterval(()=>{const s=Math.floor((Date.now()-F.current)/1e3),n=Math.max(0,t-s);z(n),n<=0&&!p.current&&(p.current=!0,clearInterval(c.current))},250),()=>{c.current&&clearInterval(c.current)}},[a]),r.useEffect(()=>{if(x===0&&p.current&&h==="testing"){const t=v(l?.difficulty||"medium"),s=[...u,{question_id:l.question_id,student_answer:o||"",time_spent_seconds:t}],n=[...g,!1];k(n),E(s),b(null),am+1):I(s)}},[x]);const O=r.useCallback(()=>{const t=document.getElementById("assessment-container");t&&(document.fullscreenElement?document.exitFullscreen&&document.exitFullscreen().then(()=>{w(!1)}).catch(s=>{console.error("Exit fullscreen error:",s)}):t.requestFullscreen().then(()=>{w(!0)}).catch(s=>{console.error("Fullscreen error:",s)}))},[]);r.useEffect(()=>{const t=()=>{w(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",t),()=>document.removeEventListener("fullscreenchange",t)},[]);const Q=t=>{b(t)},U=()=>{if(!o)return;c.current&&clearInterval(c.current);const t=v(l?.difficulty||"medium")-x,s=[...g,!0],n=[...u,{question_id:l.question_id,student_answer:o,time_spent_seconds:t}];k(s),E(n),b(null),am+1):I(n)},I=async t=>{_("submitting"),D(null);try{sessionStorage.setItem("mathpulse_diagnostic_responses",JSON.stringify(t))}catch{}try{const s=await ee(T,t);sessionStorage.removeItem("mathpulse_diagnostic"),sessionStorage.removeItem("mathpulse_diagnostic_responses"),_("results");try{const{emitPipelineEvent:n,getStudentContext:m}=await M(async()=>{const{emitPipelineEvent:j,getStudentContext:N}=await import("./pipelineService-BVFD1ZML.js");return{emitPipelineEvent:j,getStudentContext:N}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),{auth:R}=await M(async()=>{const{auth:j}=await import("./index-BvEKrMkD.js").then(N=>N.b7);return{auth:j}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])),y=m();y&&R.currentUser&&n({student_id:R.currentUser.uid,event_type:"diagnostic",event_data:{overall_score:s.overall_score_percent,mastery_summary:s.mastery_summary},occurred_at:new Date().toISOString(),class_id:y.classId,teacher_id:y.teacherId})}catch{}setTimeout(()=>{B({overallRisk:s.overall_risk,overallScorePercent:s.overall_score_percent,intervention:s.recommended_intervention,xpEarned:s.xp_earned,badgeUnlocked:s.badge_unlocked})},3e3)}catch(s){const n=s instanceof Error?s.message:"Submission failed. Your answers are saved locally.";D(n)}},Y=t=>{const s=Math.floor(t/60),n=t%60;return`${s}:${n.toString().padStart(2,"0")}`},J=["A","B","C","D"];return e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-md flex items-center justify-center p-4 sm:p-6 overflow-hidden",children:e.jsxs("div",{id:"assessment-container",className:"bg-white/95 backdrop-blur-xl border border-white/20 rounded-3xl shadow-[0_0_50px_rgba(0,0,0,0.3)] w-full max-w-4xl h-[95vh] sm:h-[90vh] md:h-[85vh] flex flex-col relative z-10 overflow-hidden transition-all duration-300",children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none z-0 overflow-hidden",children:q.map(t=>e.jsx(i.div,{className:`absolute rounded-full blur-3xl ${t.color.replace("/10","/30")}`,style:{width:t.size*1.5,height:t.size*1.5,left:`${t.x}%`,top:`${t.y}%`},animate:{x:[0,Math.random()*100-50,0],y:[0,Math.random()*100-50,0],scale:[1,1.3,1]},transition:{duration:t.duration,repeat:1/0,ease:"linear",delay:t.delay}},t.id))}),e.jsxs(i.div,{className:"shrink-0 text-white border-b border-white/10 shadow-md relative z-10",style:{backgroundColor:"#9956DE"},children:[e.jsxs("div",{className:"flex items-center justify-between p-4 sm:p-5 md:p-6",children:[e.jsxs("div",{className:"flex-1 min-w-0 mr-2",children:[e.jsx("h2",{className:"text-lg sm:text-xl md:text-2xl font-bold truncate",children:"Diagnostic Assessment"}),e.jsxs("p",{className:"text-white/80 text-xs sm:text-sm font-medium truncate",children:[l.domain," • ",l.difficulty]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:O,className:"w-9 h-9 sm:w-10 sm:h-10 bg-white/20 hover:bg-white/30 rounded-xl flex items-center justify-center transition-colors",title:A?"Exit Fullscreen":"Enter Fullscreen",children:A?e.jsx(le,{size:18}):e.jsx(te,{size:18})}),e.jsx("button",{onClick:L,className:"w-9 h-9 sm:w-10 sm:h-10 bg-white/20 hover:bg-white/30 rounded-xl flex items-center justify-center transition-colors",children:e.jsx(se,{size:20})})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 sm:px-5 md:px-6 pb-3 sm:pb-4 md:pb-5",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"bg-white/20 px-3 py-1 rounded-full flex items-center gap-1",children:[e.jsx(Z,{size:16}),e.jsxs("span",{className:"font-bold text-sm",children:[u.length," / ",d]})]})}),e.jsxs("div",{className:`flex items-center gap-1 px-3 py-1 rounded-full ${x<=10?"bg-red-500/80 animate-pulse":"bg-white/20"}`,children:[e.jsx(ne,{size:16}),e.jsx("span",{className:"font-bold text-sm",children:Y(x)})]})]}),e.jsxs("div",{className:"px-4 sm:px-5 md:px-6 pb-3 sm:pb-4 md:pb-5",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Question ",a+1," of ",d]}),e.jsxs("span",{className:"text-sm font-bold",children:[P,"%"]})]}),e.jsx("div",{className:"flex items-center gap-1",children:f.map((t,s)=>{let n="bg-white/30";return s{const s=l.options[t];if(!s)return null;const n=o===t;let m="bg-[#edf1f7] hover:bg-[#dde3eb] border-[#dde3eb]";return n&&(m="bg-purple-50 border-[#9956DE]"),e.jsx(i.button,{whileHover:{scale:1.01},whileTap:{scale:.99},onClick:()=>Q(t),className:`w-full text-left p-2.5 sm:p-3 md:p-4 rounded-xl border-2 transition-all ${m} cursor-pointer shadow-sm hover:shadow-md flex items-center min-h-[3rem] sm:min-h-[4rem] md:min-h-[5rem]`,children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 w-full min-w-0",children:[e.jsx("div",{className:`w-8 h-8 sm:w-10 sm:h-10 rounded-xl shrink-0 flex items-center justify-center font-bold text-sm sm:text-base ${n?"bg-[#9956DE] text-white shadow-inner":"bg-white text-[#0a1628] shadow-sm"}`,children:t}),e.jsx("span",{className:"font-semibold text-[#0a1628] text-xs sm:text-sm md:text-base break-words",children:s}),n&&e.jsx(re,{size:18,className:"ml-auto text-[#9956DE] flex-shrink-0"})]})},t)})})]},a)})}),e.jsx("div",{className:"p-4 sm:p-5 md:p-6 bg-[#edf1f7] border-t border-[#dde3eb]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm text-[#5a6578]",children:o?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(H,{size:16}),"Ready for the next one!"]}):e.jsx("span",{children:x<=10?`Auto-skipping in ${x}s...`:"Select an answer to continue"})}),e.jsxs(K,{onClick:U,disabled:!o,className:`font-bold px-6 py-2.5 sm:py-3 rounded-xl flex items-center gap-2 transition-all shadow-md hover:shadow-lg text-sm ${o?"bg-[#9956DE] hover:bg-[#8850CE] text-white shadow-[#9956DE]/20":"bg-[#dde3eb] text-slate-500 cursor-not-allowed"}`,children:[a=d*.7?"bg-gradient-to-br from-[#75D06A] to-[#6ED1CF]":"bg-gradient-to-br from-[#FFB356] to-[#FF8B8B]"}`,children:u.length>=d*.7?e.jsx(W,{size:48,className:"text-white"}):e.jsx(X,{size:48,className:"text-white"})}),e.jsx("h2",{className:"text-3xl font-bold font-display text-[#0a1628] mb-2",children:"Assessment Complete!"}),e.jsxs("p",{className:"text-[#5a6578] mb-6",children:["Great job, ",$,"! Your personalized learning path is ready."]}),e.jsxs("div",{className:"bg-gradient-to-br from-[#1FA7E1]/10 to-[#6ED1CF]/10 rounded-2xl p-5 mb-5",children:[e.jsxs("div",{className:"text-sm text-[#5a6578] mb-2",children:["You answered ",u.length," questions"]}),e.jsx("div",{className:"text-xs text-[#5a6578]",children:"Results will be available shortly..."})]}),e.jsx("p",{className:"text-xs text-slate-400 mb-4",children:"Redirecting to dashboard..."})]})})]})})};export{Se as default}; + */const ie=[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]],le=V("minimize-2",ie),Se=({testId:T,questions:f,userName:$,onComplete:B,onCancel:L})=>{const[h,_]=r.useState("testing"),[a,S]=r.useState(0),[o,b]=r.useState(null),[u,E]=r.useState(()=>{try{const t=sessionStorage.getItem("mathpulse_diagnostic_responses");return t?JSON.parse(t):[]}catch{return[]}}),[g,k]=r.useState([]),[x,z]=r.useState(0),[C,D]=r.useState(null),[A,w]=r.useState(!1),c=r.useRef(null),F=r.useRef(Date.now()),p=r.useRef(!1),d=f.length,l=f[a],P=Math.round((a+(o?1:0))/d*100),v=t=>t==="easy"?60:t==="hard"?120:90,[q]=r.useState(Array.from({length:10},(t,s)=>({id:s,size:Math.random()*80+30,x:Math.random()*100,y:Math.random()*100,duration:Math.random()*20+15,delay:Math.random()*-20,color:["bg-purple-500/10","bg-blue-500/10","bg-cyan-500/10","bg-emerald-500/10"][Math.floor(Math.random()*4)]})));r.useEffect(()=>{const t=v(l?.difficulty||"medium");return F.current=Date.now(),p.current=!1,z(t),c.current&&clearInterval(c.current),c.current=setInterval(()=>{const s=Math.floor((Date.now()-F.current)/1e3),n=Math.max(0,t-s);z(n),n<=0&&!p.current&&(p.current=!0,clearInterval(c.current))},250),()=>{c.current&&clearInterval(c.current)}},[a]),r.useEffect(()=>{if(x===0&&p.current&&h==="testing"){const t=v(l?.difficulty||"medium"),s=[...u,{question_id:l.question_id,student_answer:o||"",time_spent_seconds:t}],n=[...g,!1];k(n),E(s),b(null),am+1):I(s)}},[x]);const O=r.useCallback(()=>{const t=document.getElementById("assessment-container");t&&(document.fullscreenElement?document.exitFullscreen&&document.exitFullscreen().then(()=>{w(!1)}).catch(s=>{console.error("Exit fullscreen error:",s)}):t.requestFullscreen().then(()=>{w(!0)}).catch(s=>{console.error("Fullscreen error:",s)}))},[]);r.useEffect(()=>{const t=()=>{w(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",t),()=>document.removeEventListener("fullscreenchange",t)},[]);const Q=t=>{b(t)},U=()=>{if(!o)return;c.current&&clearInterval(c.current);const t=v(l?.difficulty||"medium")-x,s=[...g,!0],n=[...u,{question_id:l.question_id,student_answer:o,time_spent_seconds:t}];k(s),E(n),b(null),am+1):I(n)},I=async t=>{_("submitting"),D(null);try{sessionStorage.setItem("mathpulse_diagnostic_responses",JSON.stringify(t))}catch{}try{const s=await ee(T,t);sessionStorage.removeItem("mathpulse_diagnostic"),sessionStorage.removeItem("mathpulse_diagnostic_responses"),_("results");try{const{emitPipelineEvent:n,getStudentContext:m}=await M(async()=>{const{emitPipelineEvent:j,getStudentContext:N}=await import("./pipelineService-h2NDr2Mk.js");return{emitPipelineEvent:j,getStudentContext:N}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),{auth:R}=await M(async()=>{const{auth:j}=await import("./index-BdLfAeGL.js").then(N=>N.b7);return{auth:j}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])),y=m();y&&R.currentUser&&n({student_id:R.currentUser.uid,event_type:"diagnostic",event_data:{overall_score:s.overall_score_percent,mastery_summary:s.mastery_summary},occurred_at:new Date().toISOString(),class_id:y.classId,teacher_id:y.teacherId})}catch{}setTimeout(()=>{B({overallRisk:s.overall_risk,overallScorePercent:s.overall_score_percent,intervention:s.recommended_intervention,xpEarned:s.xp_earned,badgeUnlocked:s.badge_unlocked})},3e3)}catch(s){const n=s instanceof Error?s.message:"Submission failed. Your answers are saved locally.";D(n)}},Y=t=>{const s=Math.floor(t/60),n=t%60;return`${s}:${n.toString().padStart(2,"0")}`},J=["A","B","C","D"];return e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-md flex items-center justify-center p-4 sm:p-6 overflow-hidden",children:e.jsxs("div",{id:"assessment-container",className:"bg-white/95 backdrop-blur-xl border border-white/20 rounded-3xl shadow-[0_0_50px_rgba(0,0,0,0.3)] w-full max-w-4xl h-[95vh] sm:h-[90vh] md:h-[85vh] flex flex-col relative z-10 overflow-hidden transition-all duration-300",children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none z-0 overflow-hidden",children:q.map(t=>e.jsx(i.div,{className:`absolute rounded-full blur-3xl ${t.color.replace("/10","/30")}`,style:{width:t.size*1.5,height:t.size*1.5,left:`${t.x}%`,top:`${t.y}%`},animate:{x:[0,Math.random()*100-50,0],y:[0,Math.random()*100-50,0],scale:[1,1.3,1]},transition:{duration:t.duration,repeat:1/0,ease:"linear",delay:t.delay}},t.id))}),e.jsxs(i.div,{className:"shrink-0 text-white border-b border-white/10 shadow-md relative z-10",style:{backgroundColor:"#9956DE"},children:[e.jsxs("div",{className:"flex items-center justify-between p-4 sm:p-5 md:p-6",children:[e.jsxs("div",{className:"flex-1 min-w-0 mr-2",children:[e.jsx("h2",{className:"text-lg sm:text-xl md:text-2xl font-bold truncate",children:"Diagnostic Assessment"}),e.jsxs("p",{className:"text-white/80 text-xs sm:text-sm font-medium truncate",children:[l.domain," • ",l.difficulty]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:O,className:"w-9 h-9 sm:w-10 sm:h-10 bg-white/20 hover:bg-white/30 rounded-xl flex items-center justify-center transition-colors",title:A?"Exit Fullscreen":"Enter Fullscreen",children:A?e.jsx(le,{size:18}):e.jsx(te,{size:18})}),e.jsx("button",{onClick:L,className:"w-9 h-9 sm:w-10 sm:h-10 bg-white/20 hover:bg-white/30 rounded-xl flex items-center justify-center transition-colors",children:e.jsx(se,{size:20})})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 sm:px-5 md:px-6 pb-3 sm:pb-4 md:pb-5",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"bg-white/20 px-3 py-1 rounded-full flex items-center gap-1",children:[e.jsx(Z,{size:16}),e.jsxs("span",{className:"font-bold text-sm",children:[u.length," / ",d]})]})}),e.jsxs("div",{className:`flex items-center gap-1 px-3 py-1 rounded-full ${x<=10?"bg-red-500/80 animate-pulse":"bg-white/20"}`,children:[e.jsx(ne,{size:16}),e.jsx("span",{className:"font-bold text-sm",children:Y(x)})]})]}),e.jsxs("div",{className:"px-4 sm:px-5 md:px-6 pb-3 sm:pb-4 md:pb-5",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Question ",a+1," of ",d]}),e.jsxs("span",{className:"text-sm font-bold",children:[P,"%"]})]}),e.jsx("div",{className:"flex items-center gap-1",children:f.map((t,s)=>{let n="bg-white/30";return s{const s=l.options[t];if(!s)return null;const n=o===t;let m="bg-[#edf1f7] hover:bg-[#dde3eb] border-[#dde3eb]";return n&&(m="bg-purple-50 border-[#9956DE]"),e.jsx(i.button,{whileHover:{scale:1.01},whileTap:{scale:.99},onClick:()=>Q(t),className:`w-full text-left p-2.5 sm:p-3 md:p-4 rounded-xl border-2 transition-all ${m} cursor-pointer shadow-sm hover:shadow-md flex items-center min-h-[3rem] sm:min-h-[4rem] md:min-h-[5rem]`,children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 w-full min-w-0",children:[e.jsx("div",{className:`w-8 h-8 sm:w-10 sm:h-10 rounded-xl shrink-0 flex items-center justify-center font-bold text-sm sm:text-base ${n?"bg-[#9956DE] text-white shadow-inner":"bg-white text-[#0a1628] shadow-sm"}`,children:t}),e.jsx("span",{className:"font-semibold text-[#0a1628] text-xs sm:text-sm md:text-base break-words",children:s}),n&&e.jsx(re,{size:18,className:"ml-auto text-[#9956DE] flex-shrink-0"})]})},t)})})]},a)})}),e.jsx("div",{className:"p-4 sm:p-5 md:p-6 bg-[#edf1f7] border-t border-[#dde3eb]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm text-[#5a6578]",children:o?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(H,{size:16}),"Ready for the next one!"]}):e.jsx("span",{children:x<=10?`Auto-skipping in ${x}s...`:"Select an answer to continue"})}),e.jsxs(K,{onClick:U,disabled:!o,className:`font-bold px-6 py-2.5 sm:py-3 rounded-xl flex items-center gap-2 transition-all shadow-md hover:shadow-lg text-sm ${o?"bg-[#9956DE] hover:bg-[#8850CE] text-white shadow-[#9956DE]/20":"bg-[#dde3eb] text-slate-500 cursor-not-allowed"}`,children:[a=d*.7?"bg-gradient-to-br from-[#75D06A] to-[#6ED1CF]":"bg-gradient-to-br from-[#FFB356] to-[#FF8B8B]"}`,children:u.length>=d*.7?e.jsx(W,{size:48,className:"text-white"}):e.jsx(X,{size:48,className:"text-white"})}),e.jsx("h2",{className:"text-3xl font-bold font-display text-[#0a1628] mb-2",children:"Assessment Complete!"}),e.jsxs("p",{className:"text-[#5a6578] mb-6",children:["Great job, ",$,"! Your personalized learning path is ready."]}),e.jsxs("div",{className:"bg-gradient-to-br from-[#1FA7E1]/10 to-[#6ED1CF]/10 rounded-2xl p-5 mb-5",children:[e.jsxs("div",{className:"text-sm text-[#5a6578] mb-2",children:["You answered ",u.length," questions"]}),e.jsx("div",{className:"text-xs text-[#5a6578]",children:"Results will be available shortly..."})]}),e.jsx("p",{className:"text-xs text-slate-400 mb-4",children:"Redirecting to dashboard..."})]})})]})})};export{Se as default}; diff --git a/assets/AvatarShop-CnrlXF7V.js b/assets/AvatarShop-CU1RR7LT.js similarity index 98% rename from assets/AvatarShop-CnrlXF7V.js rename to assets/AvatarShop-CU1RR7LT.js index 4fb7d5224a7ad8d277df1d4713d9f0df9dc34427..032239980b728d240f03aa3074e4582f6babd512 100644 --- a/assets/AvatarShop-CnrlXF7V.js +++ b/assets/AvatarShop-CU1RR7LT.js @@ -1,4 +1,4 @@ -import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{e as Ee,L as Pe,g as Ae,f as ze}from"./vendor-radix-C5nwdvGr.js";import{e as Y,u as Te,j as h,L as oe,h as le,m as S,y as Ie,a6 as ie,a7 as E,aP as Me,aQ as _e}from"./index-BvEKrMkD.js";import{u as Ce}from"./useFeatureAccess-BTg5PL53.js";import{T as Re,a as qe,b as Xe}from"./tooltip-DDXcKYaB.js";import{C as Fe}from"./CompositeAvatar-DoKZfi7O.js";import{M as Oe,E as Ue}from"./avatarData-ChByUhv2.js";import{S as P}from"./save-DAHVTL2X.js";import{X as Ve}from"./x-BYtx1i07.js";import{S as Ye}from"./shirt-DFiZ2C4J.js";import{S as $e}from"./sparkles-av0wSNZT.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";/** +import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{e as Ee,L as Pe,g as Ae,f as ze}from"./vendor-radix-C5nwdvGr.js";import{e as Y,u as Te,j as h,L as oe,h as le,m as S,y as Ie,a6 as ie,a7 as E,aP as Me,aQ as _e}from"./index-BdLfAeGL.js";import{u as Ce}from"./useFeatureAccess-BGJy4XRW.js";import{T as Re,a as qe,b as Xe}from"./tooltip-Blvwukwg.js";import{C as Fe}from"./CompositeAvatar-DoKZfi7O.js";import{M as Oe,E as Ue}from"./avatarData-ChByUhv2.js";import{S as P}from"./save-CUEUjfb0.js";import{X as Ve}from"./x-BLhsirCD.js";import{S as Ye}from"./shirt-iZ6vtR5i.js";import{S as $e}from"./sparkles-DnAkO9TX.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ChatMarkdown-Chh6462P.js b/assets/ChatMarkdown-SgVutDBu.js similarity index 97% rename from assets/ChatMarkdown-Chh6462P.js rename to assets/ChatMarkdown-SgVutDBu.js index fde024106916c3abbbb87ff663c27671514597ba..598858cffb00b6b2026c065eda35728dfcf492eb 100644 --- a/assets/ChatMarkdown-Chh6462P.js +++ b/assets/ChatMarkdown-SgVutDBu.js @@ -1,2 +1,2 @@ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-react-B4AQeu28.js","assets/vendor-markdown-CfVKi3_s.css"])))=>i.map(i=>d[i]); -import{b6 as d,_ as c}from"./index-BvEKrMkD.js";import{r as m,j as r}from"./vendor-react-B4AQeu28.js";import{M as h,r as x,a as y}from"./vendor-markdown-yqZQ_iQm.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";let a=null;const p=()=>(a||(a=c(()=>import("./vendor-markdown-yqZQ_iQm.js").then(l=>l.k),__vite__mapDeps([0,1,2]))),a),M=({children:l})=>{if(m.useEffect(()=>{p()},[]),!l||typeof l!="string")return null;const t=d(l);return r.jsx("div",{className:"chat-markdown",children:r.jsx(h,{remarkPlugins:[y],rehypePlugins:[x],components:{a:({href:e,children:s})=>r.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:s}),code:e=>{const{inline:s,className:o,children:n,...i}=e;return r.jsx("code",{className:`${s?"bg-gray-100 dark:bg-gray-800 rounded px-1 py-0.5 text-sm":"block bg-gray-100 dark:bg-gray-900 rounded p-3 overflow-x-auto my-2"} ${o||""}`,...i,children:n})},blockquote:({children:e})=>r.jsx("blockquote",{className:"border-l-4 border-gray-300 dark:border-gray-600 pl-4 italic text-gray-600 dark:text-gray-400 my-2",children:e}),h1:({children:e})=>r.jsx("h1",{className:"text-2xl font-bold my-2",children:e}),h2:({children:e})=>r.jsx("h2",{className:"text-xl font-bold my-2",children:e}),h3:({children:e})=>r.jsx("h3",{className:"text-lg font-bold my-2",children:e}),h4:({children:e})=>r.jsx("h4",{className:"text-base font-bold my-2",children:e}),h5:({children:e})=>r.jsx("h5",{className:"text-sm font-bold my-2",children:e}),h6:({children:e})=>r.jsx("h6",{className:"text-xs font-bold my-2",children:e}),ul:({children:e})=>r.jsx("ul",{className:"list-disc list-inside my-2",children:e}),ol:({children:e})=>r.jsx("ol",{className:"list-decimal list-inside my-2",children:e}),li:({children:e})=>r.jsx("li",{className:"ml-2",children:e}),hr:()=>r.jsx("hr",{className:"my-4 border-t border-gray-300 dark:border-gray-600"}),p:({children:e})=>r.jsx("p",{className:"my-1",children:e})},children:t})})};export{M as default}; +import{b6 as d,_ as c}from"./index-BdLfAeGL.js";import{r as m,j as r}from"./vendor-react-B4AQeu28.js";import{M as h,r as x,a as y}from"./vendor-markdown-yqZQ_iQm.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";let a=null;const p=()=>(a||(a=c(()=>import("./vendor-markdown-yqZQ_iQm.js").then(l=>l.k),__vite__mapDeps([0,1,2]))),a),M=({children:l})=>{if(m.useEffect(()=>{p()},[]),!l||typeof l!="string")return null;const t=d(l);return r.jsx("div",{className:"chat-markdown",children:r.jsx(h,{remarkPlugins:[y],rehypePlugins:[x],components:{a:({href:e,children:s})=>r.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:s}),code:e=>{const{inline:s,className:o,children:n,...i}=e;return r.jsx("code",{className:`${s?"bg-gray-100 dark:bg-gray-800 rounded px-1 py-0.5 text-sm":"block bg-gray-100 dark:bg-gray-900 rounded p-3 overflow-x-auto my-2"} ${o||""}`,...i,children:n})},blockquote:({children:e})=>r.jsx("blockquote",{className:"border-l-4 border-gray-300 dark:border-gray-600 pl-4 italic text-gray-600 dark:text-gray-400 my-2",children:e}),h1:({children:e})=>r.jsx("h1",{className:"text-2xl font-bold my-2",children:e}),h2:({children:e})=>r.jsx("h2",{className:"text-xl font-bold my-2",children:e}),h3:({children:e})=>r.jsx("h3",{className:"text-lg font-bold my-2",children:e}),h4:({children:e})=>r.jsx("h4",{className:"text-base font-bold my-2",children:e}),h5:({children:e})=>r.jsx("h5",{className:"text-sm font-bold my-2",children:e}),h6:({children:e})=>r.jsx("h6",{className:"text-xs font-bold my-2",children:e}),ul:({children:e})=>r.jsx("ul",{className:"list-disc list-inside my-2",children:e}),ol:({children:e})=>r.jsx("ol",{className:"list-decimal list-inside my-2",children:e}),li:({children:e})=>r.jsx("li",{className:"ml-2",children:e}),hr:()=>r.jsx("hr",{className:"my-4 border-t border-gray-300 dark:border-gray-600"}),p:({children:e})=>r.jsx("p",{className:"my-1",children:e})},children:t})})};export{M as default}; diff --git a/assets/CompetencyRadarChart-BIu0jpMm.js b/assets/CompetencyRadarChart-CYjxrfwY.js similarity index 97% rename from assets/CompetencyRadarChart-BIu0jpMm.js rename to assets/CompetencyRadarChart-CYjxrfwY.js index 15db75c0a49133bfeca2f86223db8535df00c238..8820745582184c7f391a7e4f75dc17aff797d908 100644 --- a/assets/CompetencyRadarChart-BIu0jpMm.js +++ b/assets/CompetencyRadarChart-CYjxrfwY.js @@ -1 +1 @@ -import{r as g,j as t}from"./vendor-react-B4AQeu28.js";import{g as A,ad as I,u as B,m as L,B as O,R as W,b as H}from"./index-BvEKrMkD.js";import{collection as R,getDocs as q,query as K,orderBy as U,limit as $,Timestamp as G,getDoc as J,doc as V}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as X,s as Y}from"./subjects-ChEJ6J55.js";import{S as Z}from"./sparkles-av0wSNZT.js";import{R as ee,f as te,g as se,h as ne,i as ae,j as oe,T as re}from"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-DKW3TTRX.js";const P=["#1FA7E1","#9956DE","#75D06A","#FFB356","#7274ED","#FF8B8B","#6ED1CF","#FB96BB"];async function ie(a){try{const r=R(A,"users",a,"quizResults"),d=K(r,U("timestamp","desc"),$(500)),l=await q(d);return l.empty?F(a):l.docs.map(s=>{const e=s.data();return{quizId:s.id,moduleId:e.moduleId||"",subjectId:e.subjectId||"",score:typeof e.score=="number"?e.score:0,totalQuestions:e.totalQuestions||0,correctAnswers:e.correctAnswers||0,questionType:e.questionType||"multiple_choice",timestamp:e.timestamp instanceof G||e.timestamp?.toDate?e.timestamp.toDate():new Date,timeSpent:e.timeSpent||0}})}catch(r){return console.error("[competencyService] fetchQuizResults failed, falling back:",r),F(a)}}async function F(a){const r=await J(V(A,"progress",a));return r.exists()?(r.data().quizAttempts||[]).map((s,e)=>({quizId:String(s.quizId||`attempt-${e}`),moduleId:String(s.moduleId||s.quizId||""),subjectId:String(s.subjectId||""),score:typeof s.score=="number"?s.score:0,totalQuestions:s.totalQuestions||0,correctAnswers:typeof s.correctAnswers=="number"?s.correctAnswers:0,questionType:s.questionType||"multiple_choice",timestamp:s.completedAt?new Date(s.completedAt):new Date,timeSpent:s.timeSpent||0})):[]}async function ce(a){try{const r=R(A,"users",a,"moduleProgress"),d=await q(r);if(d.empty)return{};const l={};return d.forEach(s=>{const e=s.data();l[s.id]={moduleId:s.id,subjectId:e.subjectId||"",sessionsCompleted:e.sessionsCompleted||0,lastActive:e.lastActive?e.lastActive instanceof G?e.lastActive.toDate():new Date(e.lastActive):new Date,moduleTitle:e.moduleTitle||s.id,lessonsCompleted:e.lessonsCompleted||[],quizzesCompleted:e.quizzesCompleted||[]}}),l}catch(r){return console.error("[competencyService] fetchModuleProgress failed:",r),{}}}function _(a,r,d,l){const s=r.filter(p=>p.moduleId===a),e=s.length>0?s.reduce((p,b)=>p+b.score,0)/s.length:0,h=["identification","multiple_choice"],u=s.filter(p=>h.includes(p.questionType)),i=u.length>0?u.reduce((p,b)=>p+b.score,0)/u.length:e*.9,o=["word_problem","equation_based","enumeration"],n=s.filter(p=>o.includes(p.questionType)),c=n.length>0?n.reduce((p,b)=>p+b.score,0)/n.length:e*.85,m=d,f=m?.lessonsCompleted?.length||0,N=m?.quizzesCompleted?.length||0,D=m?.sessionsCompleted||0,y=l.find(p=>p.id===a),x=y?.lessons?.length||1,C=y?.quizzes?.length||1,z=Math.min(100,f/x*100),k=Math.min(100,N/C*100),v=Math.min(100,(z+k+D*5)/2.5);if(s.length<2){const p=v>50?60+v*.3:v*.8;return{overallMastery:e,conceptGrasp:i,application:c,engagement:v,consistency:Math.min(100,p)}}const w=s.map(p=>p.score),M=w.reduce((p,b)=>p+b,0)/w.length,E=w.reduce((p,b)=>p+Math.pow(b-M,2),0)/w.length,j=Math.sqrt(E)/Math.max(M,1),S=Math.max(0,Math.min(100,(1-j)*100));return{overallMastery:Math.round(e),conceptGrasp:Math.round(i),application:Math.round(c),engagement:Math.round(v),consistency:Math.round(S)}}async function le(a){try{const r=R(A,"users",a,"competencyMatrix"),d=await q(r);if(d.empty)return{};const l={};return d.forEach(s=>{const e=s.data();l[s.id]={moduleId:s.id,moduleName:e.moduleName||s.id,overallMastery:e.overallMastery??0,conceptGrasp:e.conceptGrasp??0,application:e.application??0,engagement:e.engagement??0,consistency:e.consistency??0,computedAt:e.computedAt?.toDate?.()||new Date}}),l}catch(r){return console.error("[competencyService] fetchCachedCompetencyMatrix failed:",r),{}}}const Q=[{key:"progress",label:"Overall Mastery"},{key:"concept",label:"Concept Grasp"},{key:"application",label:"Application"},{key:"engagement",label:"Engagement"},{key:"consistency",label:"Consistency"}];function de(a){const[r,d]=g.useState([]),[l,s]=g.useState([]),[e,h]=g.useState("N/A"),[u,i]=g.useState(!0),[o,n]=g.useState(null),[c,m]=g.useState(!1),f=g.useRef(0),N=g.useCallback(async(y,x)=>{if(x!==f.current)return;const z=X(null)[0]??"gen-math",k=Y.find(j=>j.id===z)?.modules||[],v=k.map((j,S)=>({id:j.id,name:j.title.length>15?j.title.substring(0,15).trim()+"...":j.title,color:P[S%P.length]})),w=await le(a);if(x!==f.current)return;if(Object.keys(w).length>0){ue(w,v,d,h),m(!1),i(!1);return}const M=await ie(a),E=await ce(a);if(x!==f.current)return;const T=M.length>0;m(!T),pe(M,E,v,k,d,h),i(!1)},[a]),D=g.useCallback(async()=>{if(!a){i(!1);return}const y=++f.current;i(!0),n(null);try{const x=await new Promise(C=>{const z=I(a,k=>{z(),C(k)})});if(y!==f.current)return;await N(x,y)}catch(x){console.error("[useCompetencyMatrix] Failed to load:",x),y===f.current&&(n("Failed to load competency data. Please try again."),i(!1))}},[a,N]);return g.useEffect(()=>{if(!a)return;const y=I(a,x=>{const C=++f.current;N(x,C)});return()=>y()},[a,N]),{data:r,modulesList:l,topModule:e,loading:u,error:o,isEmpty:c,refresh:D}}function ue(a,r,d,l){let s=-1,e="N/A";const h=Q.map(u=>{const i={metric:u.label,fullMark:100};return r.forEach(o=>{const n=a[o.id];n&&(u.key==="progress"?i[o.id]=n.overallMastery:u.key==="concept"?i[o.id]=n.conceptGrasp:u.key==="application"?i[o.id]=n.application:u.key==="engagement"?i[o.id]=n.engagement:u.key==="consistency"&&(i[o.id]=n.consistency))}),i});r.forEach(u=>{const i=a[u.id];if(i){const o=(i.overallMastery+i.conceptGrasp+i.application+i.engagement+i.consistency)/5;o>s&&(s=o,e=u.name)}}),l(e),d(h)}function pe(a,r,d,l,s,e){let h=-1,u="N/A";const i=Q.map(o=>{const n={metric:o.label,fullMark:100};return l.forEach(c=>{const m=r[c.id],f=_(c.id,a,m??{moduleId:c.id,sessionsCompleted:0,moduleTitle:c.title,lessonsCompleted:[],quizzesCompleted:[]},l);o.key==="progress"?n[c.id]=f.overallMastery:o.key==="concept"?n[c.id]=f.conceptGrasp:o.key==="application"?n[c.id]=f.application:o.key==="engagement"?n[c.id]=f.engagement:o.key==="consistency"&&(n[c.id]=f.consistency)}),n});l.forEach(o=>{const n=r[o.id],c=_(o.id,a,n??{moduleId:o.id,sessionsCompleted:0,moduleTitle:o.title,lessonsCompleted:[],quizzesCompleted:[]},l),m=(c.overallMastery+c.conceptGrasp+c.application+c.engagement+c.consistency)/5;m>h&&(h=m,u=d.find(f=>f.id===o.id)?.name||"N/A")}),e(u),s(i)}const ze=()=>{const{userProfile:a}=B(),{data:r,modulesList:d,topModule:l,loading:s,error:e,isEmpty:h,refresh:u}=de(a?.uid??""),[i,o]=g.useState(!1);return t.jsxs(L.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,ease:[.22,1,.36,1]},className:"relative overflow-hidden bg-white rounded-[16px] border border-slate-200 shadow-sm p-6 lg:p-8 group",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[t.jsx("div",{className:"absolute -right-12 -bottom-12 w-32 h-32 bg-[#9956DE]/5 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between mb-6 relative z-10 gap-4",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("div",{className:"w-10 h-10 rounded-[12px] bg-gradient-to-br from-[#a855f7] to-[#9333ea] flex items-center justify-center shadow-[0_4px_12px_rgba(168,85,247,0.2)]",children:t.jsx(O,{size:20,className:"text-white"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-[15px] font-bold text-slate-900",children:"Competency Matrix"}),t.jsx("p",{className:"text-[12px] text-slate-500",children:"Realtime performance across modules"})]})]}),t.jsxs("div",{className:"flex items-center gap-3",children:[!s&&!h&&!e&&t.jsxs("div",{className:"flex items-center gap-2 bg-[#f5f3ff] border border-[#e0e7ff] px-3 py-1.5 rounded-full",children:[t.jsx(Z,{size:12,className:"text-amber-500"}),t.jsx("span",{className:"text-[11px] font-bold text-[#9956DE] uppercase tracking-wider",children:l})]}),!s&&t.jsx("button",{onClick:u,className:"w-8 h-8 rounded-full bg-white border border-slate-200 flex items-center justify-center hover:bg-[#f5f3ff] hover:border-[#9956DE]/30 transition-colors shadow-sm",title:"Refresh",children:t.jsx(W,{size:13,className:"text-slate-400"})})]})]}),t.jsx("div",{className:"h-[300px] sm:h-[360px] w-full relative z-10",children:s?t.jsx("div",{className:"w-full h-full flex items-center justify-center",children:t.jsxs("div",{className:"flex flex-col items-center gap-3",children:[t.jsx("div",{className:"w-8 h-8 border-4 border-[#9956DE]/20 border-t-[#9956DE] rounded-full animate-spin"}),t.jsx("p",{className:"text-[13px] text-slate-400 font-medium",children:"Analyzing skill vectors..."})]})}):h||e?t.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4",children:[t.jsx("div",{className:"w-14 h-14 rounded-[16px] bg-gradient-to-br from-slate-100 to-slate-50 flex items-center justify-center border border-slate-200",children:t.jsx(H,{size:24,className:"text-slate-400"})}),t.jsxs("div",{className:"text-center",children:[t.jsx("p",{className:"text-[13px] font-semibold text-slate-600 mb-1",children:e?"Unable to load competency data":"No activity yet"}),t.jsx("p",{className:"text-[12px] text-slate-400 max-w-[260px]",children:e||"Complete quizzes and lessons to see your competency matrix here."})]}),e&&t.jsx("button",{onClick:u,className:"px-4 py-2 text-[12px] font-semibold bg-[#9956DE] text-white rounded-full hover:bg-[#8b45d1] transition-colors shadow-md",children:"Try Again"})]}):t.jsx(ee,{width:"100%",height:"100%",children:t.jsxs(te,{cx:"50%",cy:"50%",outerRadius:i?"75%":"70%",data:r,children:[t.jsx(se,{stroke:"#e2e8f0",strokeDasharray:"4 4",polarRadius:[20,40,60,80,100]}),t.jsx(ne,{dataKey:"metric",tick:{fill:"#475569",fontSize:12,fontWeight:600}}),t.jsx(ae,{angle:90,domain:[0,100],tick:{fill:"#94a3b8",fontSize:10},tickCount:6,axisLine:!1}),d.map(n=>t.jsx(oe,{name:n.name,dataKey:n.id,stroke:n.color,strokeWidth:2,fill:n.color,fillOpacity:.3,dot:{r:3,fill:"#fff",stroke:n.color,strokeWidth:2},activeDot:{r:5,fill:n.color,stroke:"#fff",strokeWidth:2},isAnimationActive:!0,animationDuration:1500,animationEasing:"ease-out"},n.id)),t.jsx(re,{cursor:!1,content:({active:n,payload:c})=>n&&c&&c.length?t.jsxs("div",{className:"bg-white/95 backdrop-blur-[12px] shadow-[0_8px_24px_rgba(0,0,0,0.12)] border border-slate-100 rounded-[12px] p-4",children:[t.jsx("p",{className:"font-bold text-slate-800 text-[13px] mb-2",children:c[0].payload.metric}),t.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>t.jsxs("div",{className:"flex items-center justify-between gap-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:m.stroke}}),t.jsx("span",{className:"text-[11px] font-semibold text-slate-600 truncate max-w-[120px]",children:String(m.name)})]}),t.jsxs("span",{className:"text-[13px] font-bold",style:{color:m.stroke},children:[Math.round(m.value),"%"]})]},m.name))})]}):null})]})})}),!s&&!h&&!e&&d.length>0&&t.jsx("div",{className:"flex flex-wrap justify-center items-center gap-3 mt-4 relative z-10",children:d.map(n=>t.jsxs("div",{className:"flex items-center gap-1.5 bg-slate-50 px-2.5 py-1 rounded-full border border-slate-100",children:[t.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:n.color}}),t.jsx("span",{className:"text-[10px] font-bold text-slate-600 uppercase tracking-wider",children:n.name.length>15?n.name.substring(0,12)+"...":n.name})]},n.id))})]})};export{ze as CompetencyRadarChart}; +import{r as g,j as t}from"./vendor-react-B4AQeu28.js";import{g as A,ad as I,u as B,m as L,B as O,R as W,b as H}from"./index-BdLfAeGL.js";import{collection as R,getDocs as q,query as K,orderBy as U,limit as $,Timestamp as G,getDoc as J,doc as V}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as X,s as Y}from"./subjects-Dw9HR29l.js";import{S as Z}from"./sparkles-DnAkO9TX.js";import{R as ee,f as te,g as se,h as ne,i as ae,j as oe,T as re}from"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-Dl7iJ2BC.js";const P=["#1FA7E1","#9956DE","#75D06A","#FFB356","#7274ED","#FF8B8B","#6ED1CF","#FB96BB"];async function ie(a){try{const r=R(A,"users",a,"quizResults"),d=K(r,U("timestamp","desc"),$(500)),l=await q(d);return l.empty?F(a):l.docs.map(s=>{const e=s.data();return{quizId:s.id,moduleId:e.moduleId||"",subjectId:e.subjectId||"",score:typeof e.score=="number"?e.score:0,totalQuestions:e.totalQuestions||0,correctAnswers:e.correctAnswers||0,questionType:e.questionType||"multiple_choice",timestamp:e.timestamp instanceof G||e.timestamp?.toDate?e.timestamp.toDate():new Date,timeSpent:e.timeSpent||0}})}catch(r){return console.error("[competencyService] fetchQuizResults failed, falling back:",r),F(a)}}async function F(a){const r=await J(V(A,"progress",a));return r.exists()?(r.data().quizAttempts||[]).map((s,e)=>({quizId:String(s.quizId||`attempt-${e}`),moduleId:String(s.moduleId||s.quizId||""),subjectId:String(s.subjectId||""),score:typeof s.score=="number"?s.score:0,totalQuestions:s.totalQuestions||0,correctAnswers:typeof s.correctAnswers=="number"?s.correctAnswers:0,questionType:s.questionType||"multiple_choice",timestamp:s.completedAt?new Date(s.completedAt):new Date,timeSpent:s.timeSpent||0})):[]}async function ce(a){try{const r=R(A,"users",a,"moduleProgress"),d=await q(r);if(d.empty)return{};const l={};return d.forEach(s=>{const e=s.data();l[s.id]={moduleId:s.id,subjectId:e.subjectId||"",sessionsCompleted:e.sessionsCompleted||0,lastActive:e.lastActive?e.lastActive instanceof G?e.lastActive.toDate():new Date(e.lastActive):new Date,moduleTitle:e.moduleTitle||s.id,lessonsCompleted:e.lessonsCompleted||[],quizzesCompleted:e.quizzesCompleted||[]}}),l}catch(r){return console.error("[competencyService] fetchModuleProgress failed:",r),{}}}function _(a,r,d,l){const s=r.filter(p=>p.moduleId===a),e=s.length>0?s.reduce((p,b)=>p+b.score,0)/s.length:0,h=["identification","multiple_choice"],u=s.filter(p=>h.includes(p.questionType)),i=u.length>0?u.reduce((p,b)=>p+b.score,0)/u.length:e*.9,o=["word_problem","equation_based","enumeration"],n=s.filter(p=>o.includes(p.questionType)),c=n.length>0?n.reduce((p,b)=>p+b.score,0)/n.length:e*.85,m=d,f=m?.lessonsCompleted?.length||0,N=m?.quizzesCompleted?.length||0,D=m?.sessionsCompleted||0,y=l.find(p=>p.id===a),x=y?.lessons?.length||1,C=y?.quizzes?.length||1,z=Math.min(100,f/x*100),k=Math.min(100,N/C*100),v=Math.min(100,(z+k+D*5)/2.5);if(s.length<2){const p=v>50?60+v*.3:v*.8;return{overallMastery:e,conceptGrasp:i,application:c,engagement:v,consistency:Math.min(100,p)}}const w=s.map(p=>p.score),M=w.reduce((p,b)=>p+b,0)/w.length,E=w.reduce((p,b)=>p+Math.pow(b-M,2),0)/w.length,j=Math.sqrt(E)/Math.max(M,1),S=Math.max(0,Math.min(100,(1-j)*100));return{overallMastery:Math.round(e),conceptGrasp:Math.round(i),application:Math.round(c),engagement:Math.round(v),consistency:Math.round(S)}}async function le(a){try{const r=R(A,"users",a,"competencyMatrix"),d=await q(r);if(d.empty)return{};const l={};return d.forEach(s=>{const e=s.data();l[s.id]={moduleId:s.id,moduleName:e.moduleName||s.id,overallMastery:e.overallMastery??0,conceptGrasp:e.conceptGrasp??0,application:e.application??0,engagement:e.engagement??0,consistency:e.consistency??0,computedAt:e.computedAt?.toDate?.()||new Date}}),l}catch(r){return console.error("[competencyService] fetchCachedCompetencyMatrix failed:",r),{}}}const Q=[{key:"progress",label:"Overall Mastery"},{key:"concept",label:"Concept Grasp"},{key:"application",label:"Application"},{key:"engagement",label:"Engagement"},{key:"consistency",label:"Consistency"}];function de(a){const[r,d]=g.useState([]),[l,s]=g.useState([]),[e,h]=g.useState("N/A"),[u,i]=g.useState(!0),[o,n]=g.useState(null),[c,m]=g.useState(!1),f=g.useRef(0),N=g.useCallback(async(y,x)=>{if(x!==f.current)return;const z=X(null)[0]??"gen-math",k=Y.find(j=>j.id===z)?.modules||[],v=k.map((j,S)=>({id:j.id,name:j.title.length>15?j.title.substring(0,15).trim()+"...":j.title,color:P[S%P.length]})),w=await le(a);if(x!==f.current)return;if(Object.keys(w).length>0){ue(w,v,d,h),m(!1),i(!1);return}const M=await ie(a),E=await ce(a);if(x!==f.current)return;const T=M.length>0;m(!T),pe(M,E,v,k,d,h),i(!1)},[a]),D=g.useCallback(async()=>{if(!a){i(!1);return}const y=++f.current;i(!0),n(null);try{const x=await new Promise(C=>{const z=I(a,k=>{z(),C(k)})});if(y!==f.current)return;await N(x,y)}catch(x){console.error("[useCompetencyMatrix] Failed to load:",x),y===f.current&&(n("Failed to load competency data. Please try again."),i(!1))}},[a,N]);return g.useEffect(()=>{if(!a)return;const y=I(a,x=>{const C=++f.current;N(x,C)});return()=>y()},[a,N]),{data:r,modulesList:l,topModule:e,loading:u,error:o,isEmpty:c,refresh:D}}function ue(a,r,d,l){let s=-1,e="N/A";const h=Q.map(u=>{const i={metric:u.label,fullMark:100};return r.forEach(o=>{const n=a[o.id];n&&(u.key==="progress"?i[o.id]=n.overallMastery:u.key==="concept"?i[o.id]=n.conceptGrasp:u.key==="application"?i[o.id]=n.application:u.key==="engagement"?i[o.id]=n.engagement:u.key==="consistency"&&(i[o.id]=n.consistency))}),i});r.forEach(u=>{const i=a[u.id];if(i){const o=(i.overallMastery+i.conceptGrasp+i.application+i.engagement+i.consistency)/5;o>s&&(s=o,e=u.name)}}),l(e),d(h)}function pe(a,r,d,l,s,e){let h=-1,u="N/A";const i=Q.map(o=>{const n={metric:o.label,fullMark:100};return l.forEach(c=>{const m=r[c.id],f=_(c.id,a,m??{moduleId:c.id,sessionsCompleted:0,moduleTitle:c.title,lessonsCompleted:[],quizzesCompleted:[]},l);o.key==="progress"?n[c.id]=f.overallMastery:o.key==="concept"?n[c.id]=f.conceptGrasp:o.key==="application"?n[c.id]=f.application:o.key==="engagement"?n[c.id]=f.engagement:o.key==="consistency"&&(n[c.id]=f.consistency)}),n});l.forEach(o=>{const n=r[o.id],c=_(o.id,a,n??{moduleId:o.id,sessionsCompleted:0,moduleTitle:o.title,lessonsCompleted:[],quizzesCompleted:[]},l),m=(c.overallMastery+c.conceptGrasp+c.application+c.engagement+c.consistency)/5;m>h&&(h=m,u=d.find(f=>f.id===o.id)?.name||"N/A")}),e(u),s(i)}const ze=()=>{const{userProfile:a}=B(),{data:r,modulesList:d,topModule:l,loading:s,error:e,isEmpty:h,refresh:u}=de(a?.uid??""),[i,o]=g.useState(!1);return t.jsxs(L.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,ease:[.22,1,.36,1]},className:"relative overflow-hidden bg-white rounded-[16px] border border-slate-200 shadow-sm p-6 lg:p-8 group",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[t.jsx("div",{className:"absolute -right-12 -bottom-12 w-32 h-32 bg-[#9956DE]/5 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between mb-6 relative z-10 gap-4",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("div",{className:"w-10 h-10 rounded-[12px] bg-gradient-to-br from-[#a855f7] to-[#9333ea] flex items-center justify-center shadow-[0_4px_12px_rgba(168,85,247,0.2)]",children:t.jsx(O,{size:20,className:"text-white"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-[15px] font-bold text-slate-900",children:"Competency Matrix"}),t.jsx("p",{className:"text-[12px] text-slate-500",children:"Realtime performance across modules"})]})]}),t.jsxs("div",{className:"flex items-center gap-3",children:[!s&&!h&&!e&&t.jsxs("div",{className:"flex items-center gap-2 bg-[#f5f3ff] border border-[#e0e7ff] px-3 py-1.5 rounded-full",children:[t.jsx(Z,{size:12,className:"text-amber-500"}),t.jsx("span",{className:"text-[11px] font-bold text-[#9956DE] uppercase tracking-wider",children:l})]}),!s&&t.jsx("button",{onClick:u,className:"w-8 h-8 rounded-full bg-white border border-slate-200 flex items-center justify-center hover:bg-[#f5f3ff] hover:border-[#9956DE]/30 transition-colors shadow-sm",title:"Refresh",children:t.jsx(W,{size:13,className:"text-slate-400"})})]})]}),t.jsx("div",{className:"h-[300px] sm:h-[360px] w-full relative z-10",children:s?t.jsx("div",{className:"w-full h-full flex items-center justify-center",children:t.jsxs("div",{className:"flex flex-col items-center gap-3",children:[t.jsx("div",{className:"w-8 h-8 border-4 border-[#9956DE]/20 border-t-[#9956DE] rounded-full animate-spin"}),t.jsx("p",{className:"text-[13px] text-slate-400 font-medium",children:"Analyzing skill vectors..."})]})}):h||e?t.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4",children:[t.jsx("div",{className:"w-14 h-14 rounded-[16px] bg-gradient-to-br from-slate-100 to-slate-50 flex items-center justify-center border border-slate-200",children:t.jsx(H,{size:24,className:"text-slate-400"})}),t.jsxs("div",{className:"text-center",children:[t.jsx("p",{className:"text-[13px] font-semibold text-slate-600 mb-1",children:e?"Unable to load competency data":"No activity yet"}),t.jsx("p",{className:"text-[12px] text-slate-400 max-w-[260px]",children:e||"Complete quizzes and lessons to see your competency matrix here."})]}),e&&t.jsx("button",{onClick:u,className:"px-4 py-2 text-[12px] font-semibold bg-[#9956DE] text-white rounded-full hover:bg-[#8b45d1] transition-colors shadow-md",children:"Try Again"})]}):t.jsx(ee,{width:"100%",height:"100%",children:t.jsxs(te,{cx:"50%",cy:"50%",outerRadius:i?"75%":"70%",data:r,children:[t.jsx(se,{stroke:"#e2e8f0",strokeDasharray:"4 4",polarRadius:[20,40,60,80,100]}),t.jsx(ne,{dataKey:"metric",tick:{fill:"#475569",fontSize:12,fontWeight:600}}),t.jsx(ae,{angle:90,domain:[0,100],tick:{fill:"#94a3b8",fontSize:10},tickCount:6,axisLine:!1}),d.map(n=>t.jsx(oe,{name:n.name,dataKey:n.id,stroke:n.color,strokeWidth:2,fill:n.color,fillOpacity:.3,dot:{r:3,fill:"#fff",stroke:n.color,strokeWidth:2},activeDot:{r:5,fill:n.color,stroke:"#fff",strokeWidth:2},isAnimationActive:!0,animationDuration:1500,animationEasing:"ease-out"},n.id)),t.jsx(re,{cursor:!1,content:({active:n,payload:c})=>n&&c&&c.length?t.jsxs("div",{className:"bg-white/95 backdrop-blur-[12px] shadow-[0_8px_24px_rgba(0,0,0,0.12)] border border-slate-100 rounded-[12px] p-4",children:[t.jsx("p",{className:"font-bold text-slate-800 text-[13px] mb-2",children:c[0].payload.metric}),t.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>t.jsxs("div",{className:"flex items-center justify-between gap-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:m.stroke}}),t.jsx("span",{className:"text-[11px] font-semibold text-slate-600 truncate max-w-[120px]",children:String(m.name)})]}),t.jsxs("span",{className:"text-[13px] font-bold",style:{color:m.stroke},children:[Math.round(m.value),"%"]})]},m.name))})]}):null})]})})}),!s&&!h&&!e&&d.length>0&&t.jsx("div",{className:"flex flex-wrap justify-center items-center gap-3 mt-4 relative z-10",children:d.map(n=>t.jsxs("div",{className:"flex items-center gap-1.5 bg-slate-50 px-2.5 py-1 rounded-full border border-slate-100",children:[t.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:n.color}}),t.jsx("span",{className:"text-[10px] font-bold text-slate-600 uppercase tracking-wider",children:n.name.length>15?n.name.substring(0,12)+"...":n.name})]},n.id))})]})};export{ze as CompetencyRadarChart}; diff --git a/assets/ConfirmModal-DE1CbRDa.js b/assets/ConfirmModal-DPzAgSP6.js similarity index 91% rename from assets/ConfirmModal-DE1CbRDa.js rename to assets/ConfirmModal-DPzAgSP6.js index 0ebe86b70c7acc442b1db32c80653c2e4679d9f2..ad6785eb38cf8ea2fb924579b2fd0e8fab8fe5e9 100644 --- a/assets/ConfirmModal-DE1CbRDa.js +++ b/assets/ConfirmModal-DPzAgSP6.js @@ -1 +1 @@ -import{j as e}from"./vendor-react-B4AQeu28.js";import{B as i}from"./button-Bfg1pO9T.js";import{h as u,m as r,y as f}from"./index-BvEKrMkD.js";import{X as y}from"./x-BYtx1i07.js";import{T as j}from"./trash-2-B056YIHV.js";import{L as w}from"./log-out-BDL1J1Fs.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";const O=({isOpen:s,onClose:t,onConfirm:n,title:a,message:l,confirmText:c="Confirm",cancelText:d="Cancel",type:m="warning",icon:x="warning",zIndexClass:g="z-50"})=>{const b=()=>{switch(x){case"logout":return e.jsx(w,{size:32});case"delete":return e.jsx(j,{size:32});case"warning":default:return e.jsx(f,{size:32})}},o=(()=>{switch(m){case"danger":return{iconBg:"bg-red-100",iconColor:"text-red-600",buttonBg:"bg-red-600 hover:bg-red-700",buttonText:"text-white"};case"warning":return{iconBg:"bg-rose-100",iconColor:"text-rose-600",buttonBg:"bg-rose-600 hover:bg-rose-700",buttonText:"text-white"};case"info":default:return{iconBg:"bg-sky-100",iconColor:"text-sky-600",buttonBg:"bg-sky-600 hover:bg-sky-700",buttonText:"text-white"}}})(),p=async()=>{try{await n(),t()}catch{}};return e.jsx(u,{children:s&&e.jsx(e.Fragment,{children:e.jsx(r.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:`fixed inset-0 bg-black/50 backdrop-blur-sm ${g} flex items-center justify-center p-4`,children:e.jsxs(r.div,{initial:{opacity:0,scale:.9,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.9,y:20},transition:{type:"spring",damping:25,stiffness:300},onClick:h=>h.stopPropagation(),className:"bg-[#f7f9fc] rounded-3xl shadow-2xl max-w-md w-full overflow-hidden border border-[#dde3eb]",children:[e.jsx("button",{onClick:t,className:"absolute top-4 right-4 p-2 text-slate-500 hover:text-[#0a1628] hover:bg-[#dde3eb] rounded-xl transition-colors z-10",children:e.jsx(y,{size:20})}),e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(r.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.1,type:"spring",damping:15},className:`w-20 h-20 ${o.iconBg} rounded-full flex items-center justify-center mx-auto mb-6 ${o.iconColor}`,children:b()}),e.jsx("h2",{className:"text-2xl font-display font-bold text-[#0a1628] mb-3",children:a}),e.jsx("p",{className:"text-[#5a6578] mb-8 leading-relaxed",children:l}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(i,{onClick:t,variant:"outline",size:"lg",className:"flex-1 h-12 rounded-xl border-[#dde3eb] hover:border-[#d1cec6] hover:bg-[#edf1f7] font-bold",children:d}),e.jsx(i,{onClick:p,size:"lg",className:`flex-1 h-12 rounded-xl font-bold ${o.buttonBg} ${o.buttonText} transition-colors shadow-lg`,children:c})]})]})]})})})})};export{O as default}; +import{j as e}from"./vendor-react-B4AQeu28.js";import{B as i}from"./button-BbJLXpfi.js";import{h as u,m as r,y as f}from"./index-BdLfAeGL.js";import{X as y}from"./x-BLhsirCD.js";import{T as j}from"./trash-2-f-pq6QuO.js";import{L as w}from"./log-out-CccGdaTy.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";const O=({isOpen:s,onClose:t,onConfirm:n,title:a,message:l,confirmText:c="Confirm",cancelText:d="Cancel",type:m="warning",icon:x="warning",zIndexClass:g="z-50"})=>{const b=()=>{switch(x){case"logout":return e.jsx(w,{size:32});case"delete":return e.jsx(j,{size:32});case"warning":default:return e.jsx(f,{size:32})}},o=(()=>{switch(m){case"danger":return{iconBg:"bg-red-100",iconColor:"text-red-600",buttonBg:"bg-red-600 hover:bg-red-700",buttonText:"text-white"};case"warning":return{iconBg:"bg-rose-100",iconColor:"text-rose-600",buttonBg:"bg-rose-600 hover:bg-rose-700",buttonText:"text-white"};case"info":default:return{iconBg:"bg-sky-100",iconColor:"text-sky-600",buttonBg:"bg-sky-600 hover:bg-sky-700",buttonText:"text-white"}}})(),p=async()=>{try{await n(),t()}catch{}};return e.jsx(u,{children:s&&e.jsx(e.Fragment,{children:e.jsx(r.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:`fixed inset-0 bg-black/50 backdrop-blur-sm ${g} flex items-center justify-center p-4`,children:e.jsxs(r.div,{initial:{opacity:0,scale:.9,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.9,y:20},transition:{type:"spring",damping:25,stiffness:300},onClick:h=>h.stopPropagation(),className:"bg-[#f7f9fc] rounded-3xl shadow-2xl max-w-md w-full overflow-hidden border border-[#dde3eb]",children:[e.jsx("button",{onClick:t,className:"absolute top-4 right-4 p-2 text-slate-500 hover:text-[#0a1628] hover:bg-[#dde3eb] rounded-xl transition-colors z-10",children:e.jsx(y,{size:20})}),e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(r.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.1,type:"spring",damping:15},className:`w-20 h-20 ${o.iconBg} rounded-full flex items-center justify-center mx-auto mb-6 ${o.iconColor}`,children:b()}),e.jsx("h2",{className:"text-2xl font-display font-bold text-[#0a1628] mb-3",children:a}),e.jsx("p",{className:"text-[#5a6578] mb-8 leading-relaxed",children:l}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(i,{onClick:t,variant:"outline",size:"lg",className:"flex-1 h-12 rounded-xl border-[#dde3eb] hover:border-[#d1cec6] hover:bg-[#edf1f7] font-bold",children:d}),e.jsx(i,{onClick:p,size:"lg",className:`flex-1 h-12 rounded-xl font-bold ${o.buttonBg} ${o.buttonText} transition-colors shadow-lg`,children:c})]})]})]})})})})};export{O as default}; diff --git a/assets/DiagnosticBreakdown-KMY-Jwc3.js b/assets/DiagnosticBreakdown-1Ae0p8Ht.js similarity index 97% rename from assets/DiagnosticBreakdown-KMY-Jwc3.js rename to assets/DiagnosticBreakdown-1Ae0p8Ht.js index 2e40397ce7021ed8ee5c8d86bef27e99fb563647..d3e5c2899ee999e8b3932b60a0190e219e1de6ec 100644 --- a/assets/DiagnosticBreakdown-KMY-Jwc3.js +++ b/assets/DiagnosticBreakdown-1Ae0p8Ht.js @@ -1 +1 @@ -import{r as i,j as e}from"./vendor-react-B4AQeu28.js";import{getDoc as y,doc as _}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as k,w as Z,B as H,Z as J,y as C,T as W,r as S,m,h as Y}from"./index-BvEKrMkD.js";import{X as G}from"./x-BYtx1i07.js";import{C as A}from"./clock-0vnF72R6.js";import{L as T,C as K}from"./lightbulb-BpvAgebC.js";import{C as q}from"./circle-check-E415RSic.js";import{C as D}from"./chart-column-DKW3TTRX.js";import{a as O,C as V}from"./chevron-up-CDr90bpM.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const ge=({userId:d,mode:h,isOpen:c=!0,onClose:p})=>{const[o,P]=i.useState([]),[B,$]=i.useState({}),[r,R]=i.useState({}),[a,E]=i.useState(null),[L,x]=i.useState(!0),[Q,j]=i.useState(!0),[g,z]=i.useState(null);i.useEffect(()=>{!d||!c||M()},[d,c]);const M=async()=>{x(!0);try{const s=await y(_(k,"diagnosticResults",d));if(!s.exists()){x(!1);return}const t=s.data(),U=t.responses||[];$(t.domainScores||{}),R(t.riskProfile||{});const b=t.testId;let v={};if(b){const l=await y(_(k,"diagnosticSessions",b));if(l.exists()){const X=l.data();for(const w of X.questions||[])v[w.question_id]=w.question_text}}P(U.map(l=>({...l,question_text:v[l.question_id]}))),x(!1),j(!0);try{const l=await Z("/api/diagnostic/analyze",{method:"POST",body:JSON.stringify({user_id:d})});l.success&&E(l.analysis)}catch(l){console.error("[DiagnosticBreakdown] AI analysis failed:",l)}finally{j(!1)}}catch(s){console.error("[DiagnosticBreakdown] Failed to load data:",s),x(!1),j(!1)}},u=o.filter(s=>s.is_correct).length,n=o.length,f=o.reduce((s,t)=>s+t.time_spent_seconds,0),F=n>0?Math.round(f/n):0,I=n>0?Math.round(u/n*100):0;if(!c)return null;const N=e.jsxs("div",{className:`${h==="fullscreen"?"min-h-screen bg-gradient-to-br from-slate-50 via-white to-indigo-50/30":""} flex flex-col`,children:[e.jsx("div",{className:"top-0 z-10 bg-white border-b border-slate-200/60 px-6 py-4",children:e.jsxs("div",{className:"max-w-6xl mx-auto flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shadow-indigo-200",children:e.jsx(H,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-bold text-slate-900",children:"Diagnostic Assessment Breakdown"}),e.jsx("p",{className:"text-xs text-slate-500",children:"AI-powered analysis of your performance"})]})]}),e.jsx("button",{onClick:p,className:"p-2 hover:bg-slate-100 rounded-xl transition-colors",title:"Close",children:e.jsx(G,{className:"w-5 h-5 text-slate-500"})})]})}),e.jsx("div",{className:"max-w-6xl mx-auto w-full px-6 py-8 space-y-8",children:L?e.jsx("div",{className:"space-y-4",children:[1,2,3].map(s=>e.jsx("div",{className:"h-32 bg-slate-100 rounded-2xl animate-pulse"},s))}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl p-5 text-white shadow-lg shadow-indigo-200/50",children:[e.jsx("p",{className:"text-indigo-200 text-xs font-medium uppercase",children:"Score"}),e.jsxs("p",{className:"text-3xl font-black mt-1",children:[I,"%"]}),e.jsxs("p",{className:"text-indigo-200 text-sm",children:[u,"/",n," correct"]})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(A,{className:"w-4 h-4"})," ",e.jsx("span",{className:"text-xs font-medium uppercase",children:"Avg Time"})]}),e.jsxs("p",{className:"text-2xl font-bold text-slate-800",children:[F,"s"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"per question"})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(J,{className:"w-4 h-4"})," ",e.jsx("span",{className:"text-xs font-medium uppercase",children:"Total Time"})]}),e.jsxs("p",{className:"text-2xl font-bold text-slate-800",children:[Math.floor(f/60),"m ",f%60,"s"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"assessment duration"})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(C,{className:"w-4 h-4"})," ",e.jsx("span",{className:"text-xs font-medium uppercase",children:"Risk"})]}),e.jsx("p",{className:`text-2xl font-bold ${r.overall_risk==="high"||r.overall_risk==="critical"?"text-red-600":r.overall_risk==="moderate"?"text-amber-600":"text-emerald-600"}`,children:(r.overall_risk||"unknown").charAt(0).toUpperCase()+(r.overall_risk||"unknown").slice(1)}),e.jsx("p",{className:"text-xs text-slate-400",children:"risk level"})]})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-4 border-b border-slate-100 bg-gradient-to-r from-amber-50 to-orange-50",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{className:"w-5 h-5 text-amber-500"}),e.jsx("h2",{className:"font-bold text-slate-800",children:"AI Analysis"})]})}),e.jsx("div",{className:"p-6",children:Q?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"h-4 bg-slate-100 rounded animate-pulse w-3/4"}),e.jsx("div",{className:"h-4 bg-slate-100 rounded animate-pulse w-1/2"}),e.jsx("div",{className:"h-4 bg-slate-100 rounded animate-pulse w-5/6"})]}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsx("p",{className:"text-slate-700 leading-relaxed",children:a.overall_summary}),e.jsxs("div",{className:"bg-sky-50 border border-sky-100 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-sky-800 text-sm mb-2 flex items-center gap-2",children:[e.jsx(A,{className:"w-4 h-4"})," Timing Patterns"]}),e.jsx("p",{className:"text-sm text-sky-700",children:a.time_analysis.insight}),a.time_analysis.slow_questions.length>0&&e.jsxs("p",{className:"text-xs text-sky-600 mt-2",children:[e.jsx("span",{className:"font-medium",children:"Took longest on:"})," ",a.time_analysis.slow_questions.join(", ")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.strength_areas.length>0&&e.jsxs("div",{className:"border border-emerald-100 bg-emerald-50/50 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-emerald-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(W,{className:"w-4 h-4"})," Strengths"]}),e.jsx("ul",{className:"space-y-2",children:a.strength_areas.map((s,t)=>e.jsxs("li",{className:"text-sm text-emerald-700 flex items-start gap-2",children:[e.jsx(q,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:[e.jsxs("strong",{children:[s.domain,":"]})," ",s.detail]})]},t))})]}),a.weakness_areas.length>0&&e.jsxs("div",{className:"border border-red-100 bg-red-50/50 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-red-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(S,{className:"w-4 h-4"})," Weak Areas"]}),e.jsx("ul",{className:"space-y-2",children:a.weakness_areas.map((s,t)=>e.jsxs("li",{className:"text-sm text-red-700 flex items-start gap-2",children:[e.jsx(C,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:[e.jsxs("strong",{children:[s.domain,":"]})," ",s.detail]})]},t))})]})]}),a.answer_patterns.common_mistakes.length>0&&e.jsxs("div",{className:"bg-amber-50 border border-amber-100 rounded-xl p-4",children:[e.jsx("h3",{className:"font-semibold text-amber-800 text-sm mb-2",children:"Answer Patterns"}),e.jsx("p",{className:"text-sm text-amber-700 mb-2",children:a.answer_patterns.description}),e.jsx("ul",{className:"space-y-1",children:a.answer_patterns.common_mistakes.map((s,t)=>e.jsxs("li",{className:"text-xs text-amber-600",children:["• ",s]},t))})]}),a.recommendations.length>0&&e.jsxs("div",{className:"bg-indigo-50 border border-indigo-100 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-indigo-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(T,{className:"w-4 h-4"})," Recommendations"]}),e.jsx("ol",{className:"space-y-2",children:a.recommendations.map((s,t)=>e.jsxs("li",{className:"text-sm text-indigo-700",children:[e.jsxs("span",{className:"font-medium",children:[t+1,". ",s.action]}),e.jsxs("span",{className:"text-indigo-500 text-xs ml-2",children:["— ",s.reason]})]},t))})]}),e.jsxs("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-slate-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4"})," Performance by Difficulty"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase font-medium",children:"Easy"}),e.jsx("p",{className:"text-sm font-bold text-slate-700 mt-1",children:a.difficulty_analysis.easy_performance})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase font-medium",children:"Medium"}),e.jsx("p",{className:"text-sm font-bold text-slate-700 mt-1",children:a.difficulty_analysis.medium_performance})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase font-medium",children:"Hard"}),e.jsx("p",{className:"text-sm font-bold text-slate-700 mt-1",children:a.difficulty_analysis.hard_performance})]})]})]})]}):e.jsx("p",{className:"text-slate-500 text-sm",children:"Analysis unavailable."})})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-4 border-b border-slate-100",children:e.jsxs("h2",{className:"font-bold text-slate-800 flex items-center gap-2",children:[e.jsx(D,{className:"w-5 h-5 text-indigo-500"})," Domain Scores"]})}),e.jsx("div",{className:"p-6 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:Object.entries(B).map(([s,t])=>e.jsxs("div",{className:"border border-slate-100 rounded-xl p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 mb-2",children:s}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("span",{className:"text-2xl font-black text-slate-800",children:[t.percentage,"%"]}),e.jsxs("span",{className:"text-xs text-slate-400 mb-1",children:[t.correct,"/",t.total]})]}),e.jsx("div",{className:"mt-2 h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${t.percentage>=80?"bg-emerald-500":t.percentage>=60?"bg-amber-500":"bg-red-500"}`,style:{width:`${t.percentage}%`}})}),e.jsx("p",{className:`text-xs mt-1 font-medium ${t.mastery_level==="mastered"?"text-emerald-600":t.mastery_level==="developing"?"text-amber-600":"text-red-600"}`,children:t.mastery_level})]},s))})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-4 border-b border-slate-100",children:e.jsxs("h2",{className:"font-bold text-slate-800 flex items-center gap-2",children:[e.jsx(S,{className:"w-5 h-5 text-indigo-500"})," Question-by-Question Breakdown"]})}),e.jsx("div",{className:"divide-y divide-slate-50",children:o.map((s,t)=>e.jsxs("div",{className:"px-6 py-3 hover:bg-slate-50/50 transition-colors",children:[e.jsxs("button",{onClick:()=>z(g===t?null:t),className:"w-full flex items-center gap-3 text-left",children:[e.jsx("div",{className:`w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 ${s.is_correct?"bg-emerald-100 text-emerald-600":"bg-red-100 text-red-600"}`,children:s.is_correct?e.jsx(q,{className:"w-4 h-4"}):e.jsx(K,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium text-slate-700 truncate",children:["Q",t+1,". ",s.question_text||`${s.topic} (${s.domain})`]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[e.jsx("span",{className:"text-xs text-slate-400",children:s.difficulty}),e.jsxs("span",{className:"text-xs text-slate-400",children:[s.time_spent_seconds,"s"]}),e.jsx("span",{className:"text-xs text-slate-400",children:s.domain})]})]}),g===t?e.jsx(O,{className:"w-4 h-4 text-slate-400"}):e.jsx(V,{className:"w-4 h-4 text-slate-400"})]}),g===t&&e.jsxs(m.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"ml-10 mt-2 pb-2 space-y-2",children:[s.question_text&&e.jsx("p",{className:"text-sm text-slate-600",children:s.question_text}),e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs",children:[e.jsxs("span",{className:s.is_correct?"text-emerald-600":"text-red-600",children:["Your answer: ",e.jsx("strong",{children:s.student_answer||"—"})]}),!s.is_correct&&e.jsxs("span",{className:"text-emerald-600",children:["Correct: ",e.jsx("strong",{children:s.correct_answer})]}),e.jsxs("span",{className:"text-slate-500",children:["Time: ",s.time_spent_seconds,"s"]}),e.jsxs("span",{className:"text-slate-500",children:["Bloom: ",s.bloom_level]})]})]})]},t))})]}),e.jsx("div",{className:"flex justify-center pb-8",children:e.jsx("button",{onClick:p,className:"px-8 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl shadow-lg shadow-indigo-200 transition-all",children:h==="fullscreen"?"Continue to Dashboard":"Close"})})]})})]});return h==="modal"?e.jsx(Y,{children:c&&e.jsx(m.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",onClick:p,children:e.jsx(m.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"bg-white rounded-2xl shadow-xl w-full max-w-5xl max-h-[90vh] overflow-y-auto will-change-transform",onClick:s=>s.stopPropagation(),children:N})})}):e.jsx(m.div,{initial:{opacity:0},animate:{opacity:1},className:"fixed inset-0 z-50 overflow-y-auto bg-gradient-to-br from-slate-50 via-white to-indigo-50/30",children:N})};export{ge as default}; +import{r as i,j as e}from"./vendor-react-B4AQeu28.js";import{getDoc as y,doc as _}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as k,w as Z,B as H,Z as J,y as C,T as W,r as S,m,h as Y}from"./index-BdLfAeGL.js";import{X as G}from"./x-BLhsirCD.js";import{C as A}from"./clock-CpBwkoND.js";import{L as T,C as K}from"./lightbulb-W3LO7x3u.js";import{C as q}from"./circle-check-CuVe-qlS.js";import{C as D}from"./chart-column-Dl7iJ2BC.js";import{a as O,C as V}from"./chevron-up-uSn_SWll.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const ge=({userId:d,mode:h,isOpen:c=!0,onClose:p})=>{const[o,P]=i.useState([]),[B,$]=i.useState({}),[r,R]=i.useState({}),[a,E]=i.useState(null),[L,x]=i.useState(!0),[Q,j]=i.useState(!0),[g,z]=i.useState(null);i.useEffect(()=>{!d||!c||M()},[d,c]);const M=async()=>{x(!0);try{const s=await y(_(k,"diagnosticResults",d));if(!s.exists()){x(!1);return}const t=s.data(),U=t.responses||[];$(t.domainScores||{}),R(t.riskProfile||{});const b=t.testId;let v={};if(b){const l=await y(_(k,"diagnosticSessions",b));if(l.exists()){const X=l.data();for(const w of X.questions||[])v[w.question_id]=w.question_text}}P(U.map(l=>({...l,question_text:v[l.question_id]}))),x(!1),j(!0);try{const l=await Z("/api/diagnostic/analyze",{method:"POST",body:JSON.stringify({user_id:d})});l.success&&E(l.analysis)}catch(l){console.error("[DiagnosticBreakdown] AI analysis failed:",l)}finally{j(!1)}}catch(s){console.error("[DiagnosticBreakdown] Failed to load data:",s),x(!1),j(!1)}},u=o.filter(s=>s.is_correct).length,n=o.length,f=o.reduce((s,t)=>s+t.time_spent_seconds,0),F=n>0?Math.round(f/n):0,I=n>0?Math.round(u/n*100):0;if(!c)return null;const N=e.jsxs("div",{className:`${h==="fullscreen"?"min-h-screen bg-gradient-to-br from-slate-50 via-white to-indigo-50/30":""} flex flex-col`,children:[e.jsx("div",{className:"top-0 z-10 bg-white border-b border-slate-200/60 px-6 py-4",children:e.jsxs("div",{className:"max-w-6xl mx-auto flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shadow-indigo-200",children:e.jsx(H,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-bold text-slate-900",children:"Diagnostic Assessment Breakdown"}),e.jsx("p",{className:"text-xs text-slate-500",children:"AI-powered analysis of your performance"})]})]}),e.jsx("button",{onClick:p,className:"p-2 hover:bg-slate-100 rounded-xl transition-colors",title:"Close",children:e.jsx(G,{className:"w-5 h-5 text-slate-500"})})]})}),e.jsx("div",{className:"max-w-6xl mx-auto w-full px-6 py-8 space-y-8",children:L?e.jsx("div",{className:"space-y-4",children:[1,2,3].map(s=>e.jsx("div",{className:"h-32 bg-slate-100 rounded-2xl animate-pulse"},s))}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl p-5 text-white shadow-lg shadow-indigo-200/50",children:[e.jsx("p",{className:"text-indigo-200 text-xs font-medium uppercase",children:"Score"}),e.jsxs("p",{className:"text-3xl font-black mt-1",children:[I,"%"]}),e.jsxs("p",{className:"text-indigo-200 text-sm",children:[u,"/",n," correct"]})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(A,{className:"w-4 h-4"})," ",e.jsx("span",{className:"text-xs font-medium uppercase",children:"Avg Time"})]}),e.jsxs("p",{className:"text-2xl font-bold text-slate-800",children:[F,"s"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"per question"})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(J,{className:"w-4 h-4"})," ",e.jsx("span",{className:"text-xs font-medium uppercase",children:"Total Time"})]}),e.jsxs("p",{className:"text-2xl font-bold text-slate-800",children:[Math.floor(f/60),"m ",f%60,"s"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"assessment duration"})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(C,{className:"w-4 h-4"})," ",e.jsx("span",{className:"text-xs font-medium uppercase",children:"Risk"})]}),e.jsx("p",{className:`text-2xl font-bold ${r.overall_risk==="high"||r.overall_risk==="critical"?"text-red-600":r.overall_risk==="moderate"?"text-amber-600":"text-emerald-600"}`,children:(r.overall_risk||"unknown").charAt(0).toUpperCase()+(r.overall_risk||"unknown").slice(1)}),e.jsx("p",{className:"text-xs text-slate-400",children:"risk level"})]})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-4 border-b border-slate-100 bg-gradient-to-r from-amber-50 to-orange-50",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{className:"w-5 h-5 text-amber-500"}),e.jsx("h2",{className:"font-bold text-slate-800",children:"AI Analysis"})]})}),e.jsx("div",{className:"p-6",children:Q?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"h-4 bg-slate-100 rounded animate-pulse w-3/4"}),e.jsx("div",{className:"h-4 bg-slate-100 rounded animate-pulse w-1/2"}),e.jsx("div",{className:"h-4 bg-slate-100 rounded animate-pulse w-5/6"})]}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsx("p",{className:"text-slate-700 leading-relaxed",children:a.overall_summary}),e.jsxs("div",{className:"bg-sky-50 border border-sky-100 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-sky-800 text-sm mb-2 flex items-center gap-2",children:[e.jsx(A,{className:"w-4 h-4"})," Timing Patterns"]}),e.jsx("p",{className:"text-sm text-sky-700",children:a.time_analysis.insight}),a.time_analysis.slow_questions.length>0&&e.jsxs("p",{className:"text-xs text-sky-600 mt-2",children:[e.jsx("span",{className:"font-medium",children:"Took longest on:"})," ",a.time_analysis.slow_questions.join(", ")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.strength_areas.length>0&&e.jsxs("div",{className:"border border-emerald-100 bg-emerald-50/50 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-emerald-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(W,{className:"w-4 h-4"})," Strengths"]}),e.jsx("ul",{className:"space-y-2",children:a.strength_areas.map((s,t)=>e.jsxs("li",{className:"text-sm text-emerald-700 flex items-start gap-2",children:[e.jsx(q,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:[e.jsxs("strong",{children:[s.domain,":"]})," ",s.detail]})]},t))})]}),a.weakness_areas.length>0&&e.jsxs("div",{className:"border border-red-100 bg-red-50/50 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-red-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(S,{className:"w-4 h-4"})," Weak Areas"]}),e.jsx("ul",{className:"space-y-2",children:a.weakness_areas.map((s,t)=>e.jsxs("li",{className:"text-sm text-red-700 flex items-start gap-2",children:[e.jsx(C,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:[e.jsxs("strong",{children:[s.domain,":"]})," ",s.detail]})]},t))})]})]}),a.answer_patterns.common_mistakes.length>0&&e.jsxs("div",{className:"bg-amber-50 border border-amber-100 rounded-xl p-4",children:[e.jsx("h3",{className:"font-semibold text-amber-800 text-sm mb-2",children:"Answer Patterns"}),e.jsx("p",{className:"text-sm text-amber-700 mb-2",children:a.answer_patterns.description}),e.jsx("ul",{className:"space-y-1",children:a.answer_patterns.common_mistakes.map((s,t)=>e.jsxs("li",{className:"text-xs text-amber-600",children:["• ",s]},t))})]}),a.recommendations.length>0&&e.jsxs("div",{className:"bg-indigo-50 border border-indigo-100 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-indigo-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(T,{className:"w-4 h-4"})," Recommendations"]}),e.jsx("ol",{className:"space-y-2",children:a.recommendations.map((s,t)=>e.jsxs("li",{className:"text-sm text-indigo-700",children:[e.jsxs("span",{className:"font-medium",children:[t+1,". ",s.action]}),e.jsxs("span",{className:"text-indigo-500 text-xs ml-2",children:["— ",s.reason]})]},t))})]}),e.jsxs("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:[e.jsxs("h3",{className:"font-semibold text-slate-800 text-sm mb-3 flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4"})," Performance by Difficulty"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase font-medium",children:"Easy"}),e.jsx("p",{className:"text-sm font-bold text-slate-700 mt-1",children:a.difficulty_analysis.easy_performance})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase font-medium",children:"Medium"}),e.jsx("p",{className:"text-sm font-bold text-slate-700 mt-1",children:a.difficulty_analysis.medium_performance})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase font-medium",children:"Hard"}),e.jsx("p",{className:"text-sm font-bold text-slate-700 mt-1",children:a.difficulty_analysis.hard_performance})]})]})]})]}):e.jsx("p",{className:"text-slate-500 text-sm",children:"Analysis unavailable."})})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-4 border-b border-slate-100",children:e.jsxs("h2",{className:"font-bold text-slate-800 flex items-center gap-2",children:[e.jsx(D,{className:"w-5 h-5 text-indigo-500"})," Domain Scores"]})}),e.jsx("div",{className:"p-6 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:Object.entries(B).map(([s,t])=>e.jsxs("div",{className:"border border-slate-100 rounded-xl p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 mb-2",children:s}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("span",{className:"text-2xl font-black text-slate-800",children:[t.percentage,"%"]}),e.jsxs("span",{className:"text-xs text-slate-400 mb-1",children:[t.correct,"/",t.total]})]}),e.jsx("div",{className:"mt-2 h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${t.percentage>=80?"bg-emerald-500":t.percentage>=60?"bg-amber-500":"bg-red-500"}`,style:{width:`${t.percentage}%`}})}),e.jsx("p",{className:`text-xs mt-1 font-medium ${t.mastery_level==="mastered"?"text-emerald-600":t.mastery_level==="developing"?"text-amber-600":"text-red-600"}`,children:t.mastery_level})]},s))})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-4 border-b border-slate-100",children:e.jsxs("h2",{className:"font-bold text-slate-800 flex items-center gap-2",children:[e.jsx(S,{className:"w-5 h-5 text-indigo-500"})," Question-by-Question Breakdown"]})}),e.jsx("div",{className:"divide-y divide-slate-50",children:o.map((s,t)=>e.jsxs("div",{className:"px-6 py-3 hover:bg-slate-50/50 transition-colors",children:[e.jsxs("button",{onClick:()=>z(g===t?null:t),className:"w-full flex items-center gap-3 text-left",children:[e.jsx("div",{className:`w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 ${s.is_correct?"bg-emerald-100 text-emerald-600":"bg-red-100 text-red-600"}`,children:s.is_correct?e.jsx(q,{className:"w-4 h-4"}):e.jsx(K,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium text-slate-700 truncate",children:["Q",t+1,". ",s.question_text||`${s.topic} (${s.domain})`]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[e.jsx("span",{className:"text-xs text-slate-400",children:s.difficulty}),e.jsxs("span",{className:"text-xs text-slate-400",children:[s.time_spent_seconds,"s"]}),e.jsx("span",{className:"text-xs text-slate-400",children:s.domain})]})]}),g===t?e.jsx(O,{className:"w-4 h-4 text-slate-400"}):e.jsx(V,{className:"w-4 h-4 text-slate-400"})]}),g===t&&e.jsxs(m.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"ml-10 mt-2 pb-2 space-y-2",children:[s.question_text&&e.jsx("p",{className:"text-sm text-slate-600",children:s.question_text}),e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs",children:[e.jsxs("span",{className:s.is_correct?"text-emerald-600":"text-red-600",children:["Your answer: ",e.jsx("strong",{children:s.student_answer||"—"})]}),!s.is_correct&&e.jsxs("span",{className:"text-emerald-600",children:["Correct: ",e.jsx("strong",{children:s.correct_answer})]}),e.jsxs("span",{className:"text-slate-500",children:["Time: ",s.time_spent_seconds,"s"]}),e.jsxs("span",{className:"text-slate-500",children:["Bloom: ",s.bloom_level]})]})]})]},t))})]}),e.jsx("div",{className:"flex justify-center pb-8",children:e.jsx("button",{onClick:p,className:"px-8 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl shadow-lg shadow-indigo-200 transition-all",children:h==="fullscreen"?"Continue to Dashboard":"Close"})})]})})]});return h==="modal"?e.jsx(Y,{children:c&&e.jsx(m.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",onClick:p,children:e.jsx(m.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"bg-white rounded-2xl shadow-xl w-full max-w-5xl max-h-[90vh] overflow-y-auto will-change-transform",onClick:s=>s.stopPropagation(),children:N})})}):e.jsx(m.div,{initial:{opacity:0},animate:{opacity:1},className:"fixed inset-0 z-50 overflow-y-auto bg-gradient-to-br from-slate-50 via-white to-indigo-50/30",children:N})};export{ge as default}; diff --git a/assets/FloatingAITutor-CkFvbvHJ.js b/assets/FloatingAITutor-ZRTH3xRj.js similarity index 94% rename from assets/FloatingAITutor-CkFvbvHJ.js rename to assets/FloatingAITutor-ZRTH3xRj.js index 3f65c066903ac1a56aa677995c9569c28547f603..fabaaa38627fa81d6702a073c940a107abd2917b 100644 --- a/assets/FloatingAITutor-CkFvbvHJ.js +++ b/assets/FloatingAITutor-ZRTH3xRj.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css","assets/ChatMarkdown-Chh6462P.js"])))=>i.map(i=>d[i]); -import{g as T,_ as w,aG as O,u as D,m as A,N as P}from"./index-BvEKrMkD.js";import{r as a,j as e}from"./vendor-react-B4AQeu28.js";import{collection as $,query as B,limit as q,orderBy as H,where as V,onSnapshot as F,doc as U,updateDoc as G}from"./vendor-firebase-firestore-CNv3xXal.js";import{M as K}from"./maximize-2-BUGGXJYn.js";import{M as z}from"./minus-DRsrXXF5.js";import{X as C}from"./x-BYtx1i07.js";import{S as W}from"./send-BivcIdIA.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";function X(s,o){const n=$(T,"tutorNudges",s,"nudges"),u=B(n,V("consumed","==",!1),H("createdAt","desc"),q(1));return F(u,d=>{if(d.empty){o(null);return}const h=d.docs[0],m=h.data();o({id:h.id,message:m.message,topic:m.topic,createdAt:m.createdAt?.toDate?.()||new Date,consumed:!1})},()=>o(null))}async function J(s,o){const n=U(T,"tutorNudges",s,"nudges",o);await G(n,{consumed:!0})}const Q="https://deign86-mathpulse-api-v3test.hf.space";async function Y(s){try{const{auth:o}=await w(async()=>{const{auth:u}=await import("./index-BvEKrMkD.js").then(d=>d.b7);return{auth:u}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),n=await o.currentUser?.getIdToken();await fetch(`${Q}/api/pipeline/nudge/${s}`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}}})}catch{}}const Z=a.lazy(()=>w(()=>import("./ChatMarkdown-Chh6462P.js"),__vite__mapDeps([12,0,1,2,3,4,5,6,7,8,9,10,11])));function ee(s){return s?s instanceof Date?s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):typeof s=="object"&&"toDate"in s?s.toDate().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):String(s):""}const xe=({constraintsRef:s,onFullScreen:o})=>{const{activeSessionId:n,setActiveSessionId:u,createNewSession:d,getActiveSession:h,sendMessage:m,isLoading:f}=O(),{currentUser:c,userRole:y}=D(),[i,x]=a.useState(!1),[g,j]=a.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("floating_ai_tutor_minimized")==="1"),[p,v]=a.useState(""),[r,b]=a.useState(null),N=a.useRef(null),k=a.useRef(null);a.useEffect(()=>{if(!c?.uid||y!=="student")return;let t=!1;return X(c.uid,l=>{l&&l.id!==k.current?b(l):(b(null),t||(t=!0,Y(c.uid)))})},[c?.uid,y]),a.useEffect(()=>{typeof window>"u"||window.localStorage.setItem("floating_ai_tutor_minimized",g?"1":"0")},[g]),a.useEffect(()=>{i&&w(async()=>{const{warmupBackend:t}=await import("./index-BvEKrMkD.js").then(l=>l.b8);return{warmupBackend:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({warmupBackend:t})=>{t()}).catch(t=>{console.warn("Floating tutor warmup skipped:",t)})},[i]),a.useEffect(()=>{if(i&&!n){const t=r?r.message:"Hi! I'm your AI math tutor. What would you like to learn about today?",l={id:r?`nudge-${r.id}`:"1",sender:"ai",text:t,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},R=d(l);u(R)}},[i]),a.useEffect(()=>{i&&r&&c?.uid&&(k.current=r.id,J(c.uid,r.id).catch(()=>{}),b(null))},[i,r]);const I=h()?.messages||[],M=()=>{N.current?.scrollIntoView({behavior:"smooth"})};a.useEffect(()=>{M()},[I]);const _=async()=>{if(!p.trim()||!n||f)return;const t=p.trim();v(""),await m(n,t)},E=()=>{o()},S=()=>{x(!1),j(!0)},L=()=>{j(!1)};return e.jsxs("div",{className:"pointer-events-none flex flex-col items-end",children:[e.jsxs("div",{className:`pointer-events-auto mb-4 w-80 bg-[#f7f9fc] rounded-3xl shadow-2xl border border-[#dde3eb] flex flex-col overflow-hidden transition-all duration-300 origin-bottom-right select-none ${i?"opacity-100 scale-100 translate-y-0":"opacity-0 scale-95 translate-y-10 pointer-events-none h-0"}`,style:{"--max-h":i?"32rem":"0",willChange:"transform, opacity"},children:[e.jsxs("div",{className:"bg-gradient-to-r from-sky-600 to-sky-500 p-4 flex items-center justify-between flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-9 h-9 object-contain drop-shadow-md"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-white font-bold text-sm",children:"L.O.L.I."}),e.jsxs("p",{className:"text-sky-100 text-[10px] leading-tight",children:["Logical Operations &",e.jsx("br",{}),"Learning Intelligence"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:E,type:"button","aria-label":"Open fullscreen",className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Open fullscreen",children:e.jsx(K,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",onClick:S,className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Minimize",children:e.jsx(z,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Close chat",onClick:()=>x(!1),className:"p-2 hover:bg-white/20 rounded-lg transition-colors",children:e.jsx(C,{size:16,className:"text-white"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 bg-[#edf1f7]",children:[I.map(t=>e.jsx("div",{className:`flex ${t.sender==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[75%] rounded-2xl px-4 py-2.5 ${t.sender==="user"?"bg-sky-600 text-white":"bg-white text-[#0a1628] shadow-sm border border-[#dde3eb]"}`,children:[t.sender==="user"?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.text}):e.jsx(a.Suspense,{fallback:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.text}),children:e.jsx(Z,{children:t.text})}),e.jsx("p",{className:`text-[10px] mt-1 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:ee(t.timestamp)})]})},t.id)),f&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white text-[#0a1628] shadow-sm border border-[#dde3eb] rounded-2xl px-4 py-2.5 max-w-[75%]",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:150ms]"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:300ms]"})]})})}),e.jsx("div",{ref:N})]}),e.jsx("div",{className:"p-4 border-t border-[#dde3eb] bg-white flex-shrink-0",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{id:"ai-tutor-input",name:"ai-tutor-input","aria-label":"Ask AI tutor a question",type:"text",value:p,onChange:t=>v(t.target.value),onKeyPress:t=>t.key==="Enter"&&_(),placeholder:"Ask me anything...",className:"flex-1 px-4 py-2.5 rounded-xl border border-[#dde3eb] focus:outline-none focus:ring-2 focus:ring-sky-500 text-sm bg-[#f7f9fc]"}),e.jsx("button",{type:"button","aria-label":"Send message",onClick:_,className:"p-2.5 bg-sky-600 hover:bg-sky-700 text-white rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed",disabled:!p.trim()||f,children:e.jsx(W,{size:18})})]})})]}),e.jsx("div",{className:"pointer-events-auto relative self-end",children:g?e.jsx(A.button,{type:"button",onClick:L,whileHover:{scale:1.08},whileTap:{scale:.95},transition:{duration:.15,ease:"easeOut"},className:"h-9 w-9 rounded-full bg-slate-900/85 text-white shadow-lg ring-1 ring-white/20 backdrop-blur-sm flex items-center justify-center","aria-label":"Restore AI tutor launcher",title:"Show AI tutor",style:{willChange:"transform"},children:e.jsx(P,{size:14})}):e.jsxs("div",{className:"relative group",children:[!i&&e.jsxs("div",{className:"absolute right-full mr-4 top-1/2 -translate-y-1/2 px-4 py-2 bg-slate-800 text-white text-sm rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none whitespace-nowrap shadow-xl z-50",children:["Hello! I'm L.O.L.I., how may I help you?",e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -right-1 w-3 h-3 bg-slate-800 rotate-45"})]}),!i&&e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",title:"Minimize",onClick:S,className:"absolute -top-2 -left-2 z-10 h-6 w-6 rounded-full bg-white text-slate-700 border border-slate-200 shadow-md hover:bg-slate-100 transition-colors flex items-center justify-center",children:e.jsx(z,{size:12})}),e.jsxs(A.button,{type:"button",onClick:()=>x(!i),whileHover:{scale:1.1},whileTap:{scale:.9},transition:{duration:.15,ease:"easeOut"},className:"w-16 h-16 bg-gradient-to-br from-sky-600 to-sky-500 rounded-xl shadow-2xl flex items-center justify-center text-white hover:shadow-sky-300/50 transition-all","aria-label":i?"Close AI tutor chat":"Open AI tutor chat",style:{willChange:"transform"},children:[i?e.jsx(C,{size:28}):e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-14 h-14 object-contain drop-shadow-lg"}),!i&&r&&e.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-amber-400 rounded-full border-2 border-white animate-pulse"})]})]})})]})};export{xe as default}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css","assets/ChatMarkdown-SgVutDBu.js"])))=>i.map(i=>d[i]); +import{g as T,_ as w,aG as O,u as D,m as A,N as P}from"./index-BdLfAeGL.js";import{r as a,j as e}from"./vendor-react-B4AQeu28.js";import{collection as $,query as B,limit as q,orderBy as H,where as V,onSnapshot as F,doc as U,updateDoc as G}from"./vendor-firebase-firestore-CNv3xXal.js";import{M as K}from"./maximize-2-C5LwFHUQ.js";import{M as z}from"./minus-rsVFzcwU.js";import{X as C}from"./x-BLhsirCD.js";import{S as W}from"./send-CxDLfaHq.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";function X(s,o){const n=$(T,"tutorNudges",s,"nudges"),u=B(n,V("consumed","==",!1),H("createdAt","desc"),q(1));return F(u,d=>{if(d.empty){o(null);return}const h=d.docs[0],m=h.data();o({id:h.id,message:m.message,topic:m.topic,createdAt:m.createdAt?.toDate?.()||new Date,consumed:!1})},()=>o(null))}async function J(s,o){const n=U(T,"tutorNudges",s,"nudges",o);await G(n,{consumed:!0})}const Q="https://deign86-mathpulse-api-v3test.hf.space";async function Y(s){try{const{auth:o}=await w(async()=>{const{auth:u}=await import("./index-BdLfAeGL.js").then(d=>d.b7);return{auth:u}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),n=await o.currentUser?.getIdToken();await fetch(`${Q}/api/pipeline/nudge/${s}`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}}})}catch{}}const Z=a.lazy(()=>w(()=>import("./ChatMarkdown-SgVutDBu.js"),__vite__mapDeps([12,0,1,2,3,4,5,6,7,8,9,10,11])));function ee(s){return s?s instanceof Date?s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):typeof s=="object"&&"toDate"in s?s.toDate().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):String(s):""}const xe=({constraintsRef:s,onFullScreen:o})=>{const{activeSessionId:n,setActiveSessionId:u,createNewSession:d,getActiveSession:h,sendMessage:m,isLoading:f}=O(),{currentUser:c,userRole:y}=D(),[i,x]=a.useState(!1),[g,j]=a.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("floating_ai_tutor_minimized")==="1"),[p,v]=a.useState(""),[r,b]=a.useState(null),N=a.useRef(null),k=a.useRef(null);a.useEffect(()=>{if(!c?.uid||y!=="student")return;let t=!1;return X(c.uid,l=>{l&&l.id!==k.current?b(l):(b(null),t||(t=!0,Y(c.uid)))})},[c?.uid,y]),a.useEffect(()=>{typeof window>"u"||window.localStorage.setItem("floating_ai_tutor_minimized",g?"1":"0")},[g]),a.useEffect(()=>{i&&w(async()=>{const{warmupBackend:t}=await import("./index-BdLfAeGL.js").then(l=>l.b8);return{warmupBackend:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({warmupBackend:t})=>{t()}).catch(t=>{console.warn("Floating tutor warmup skipped:",t)})},[i]),a.useEffect(()=>{if(i&&!n){const t=r?r.message:"Hi! I'm your AI math tutor. What would you like to learn about today?",l={id:r?`nudge-${r.id}`:"1",sender:"ai",text:t,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},R=d(l);u(R)}},[i]),a.useEffect(()=>{i&&r&&c?.uid&&(k.current=r.id,J(c.uid,r.id).catch(()=>{}),b(null))},[i,r]);const I=h()?.messages||[],M=()=>{N.current?.scrollIntoView({behavior:"smooth"})};a.useEffect(()=>{M()},[I]);const _=async()=>{if(!p.trim()||!n||f)return;const t=p.trim();v(""),await m(n,t)},E=()=>{o()},S=()=>{x(!1),j(!0)},L=()=>{j(!1)};return e.jsxs("div",{className:"pointer-events-none flex flex-col items-end",children:[e.jsxs("div",{className:`pointer-events-auto mb-4 w-80 bg-[#f7f9fc] rounded-3xl shadow-2xl border border-[#dde3eb] flex flex-col overflow-hidden transition-all duration-300 origin-bottom-right select-none ${i?"opacity-100 scale-100 translate-y-0":"opacity-0 scale-95 translate-y-10 pointer-events-none h-0"}`,style:{"--max-h":i?"32rem":"0",willChange:"transform, opacity"},children:[e.jsxs("div",{className:"bg-gradient-to-r from-sky-600 to-sky-500 p-4 flex items-center justify-between flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-9 h-9 object-contain drop-shadow-md"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-white font-bold text-sm",children:"L.O.L.I."}),e.jsxs("p",{className:"text-sky-100 text-[10px] leading-tight",children:["Logical Operations &",e.jsx("br",{}),"Learning Intelligence"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:E,type:"button","aria-label":"Open fullscreen",className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Open fullscreen",children:e.jsx(K,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",onClick:S,className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Minimize",children:e.jsx(z,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Close chat",onClick:()=>x(!1),className:"p-2 hover:bg-white/20 rounded-lg transition-colors",children:e.jsx(C,{size:16,className:"text-white"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 bg-[#edf1f7]",children:[I.map(t=>e.jsx("div",{className:`flex ${t.sender==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[75%] rounded-2xl px-4 py-2.5 ${t.sender==="user"?"bg-sky-600 text-white":"bg-white text-[#0a1628] shadow-sm border border-[#dde3eb]"}`,children:[t.sender==="user"?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.text}):e.jsx(a.Suspense,{fallback:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.text}),children:e.jsx(Z,{children:t.text})}),e.jsx("p",{className:`text-[10px] mt-1 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:ee(t.timestamp)})]})},t.id)),f&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white text-[#0a1628] shadow-sm border border-[#dde3eb] rounded-2xl px-4 py-2.5 max-w-[75%]",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:150ms]"}),e.jsx("div",{className:"w-2 h-2 bg-sky-400 rounded-full animate-bounce [animation-delay:300ms]"})]})})}),e.jsx("div",{ref:N})]}),e.jsx("div",{className:"p-4 border-t border-[#dde3eb] bg-white flex-shrink-0",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{id:"ai-tutor-input",name:"ai-tutor-input","aria-label":"Ask AI tutor a question",type:"text",value:p,onChange:t=>v(t.target.value),onKeyPress:t=>t.key==="Enter"&&_(),placeholder:"Ask me anything...",className:"flex-1 px-4 py-2.5 rounded-xl border border-[#dde3eb] focus:outline-none focus:ring-2 focus:ring-sky-500 text-sm bg-[#f7f9fc]"}),e.jsx("button",{type:"button","aria-label":"Send message",onClick:_,className:"p-2.5 bg-sky-600 hover:bg-sky-700 text-white rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed",disabled:!p.trim()||f,children:e.jsx(W,{size:18})})]})})]}),e.jsx("div",{className:"pointer-events-auto relative self-end",children:g?e.jsx(A.button,{type:"button",onClick:L,whileHover:{scale:1.08},whileTap:{scale:.95},transition:{duration:.15,ease:"easeOut"},className:"h-9 w-9 rounded-full bg-slate-900/85 text-white shadow-lg ring-1 ring-white/20 backdrop-blur-sm flex items-center justify-center","aria-label":"Restore AI tutor launcher",title:"Show AI tutor",style:{willChange:"transform"},children:e.jsx(P,{size:14})}):e.jsxs("div",{className:"relative group",children:[!i&&e.jsxs("div",{className:"absolute right-full mr-4 top-1/2 -translate-y-1/2 px-4 py-2 bg-slate-800 text-white text-sm rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none whitespace-nowrap shadow-xl z-50",children:["Hello! I'm L.O.L.I., how may I help you?",e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -right-1 w-3 h-3 bg-slate-800 rotate-45"})]}),!i&&e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",title:"Minimize",onClick:S,className:"absolute -top-2 -left-2 z-10 h-6 w-6 rounded-full bg-white text-slate-700 border border-slate-200 shadow-md hover:bg-slate-100 transition-colors flex items-center justify-center",children:e.jsx(z,{size:12})}),e.jsxs(A.button,{type:"button",onClick:()=>x(!i),whileHover:{scale:1.1},whileTap:{scale:.9},transition:{duration:.15,ease:"easeOut"},className:"w-16 h-16 bg-gradient-to-br from-sky-600 to-sky-500 rounded-xl shadow-2xl flex items-center justify-center text-white hover:shadow-sky-300/50 transition-all","aria-label":i?"Close AI tutor chat":"Open AI tutor chat",style:{willChange:"transform"},children:[i?e.jsx(C,{size:28}):e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-14 h-14 object-contain drop-shadow-lg"}),!i&&r&&e.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-amber-400 rounded-full border-2 border-white animate-pulse"})]})]})})]})};export{xe as default}; diff --git a/assets/GradesPage-C8P7dxU8.js b/assets/GradesPage-BXZfrLBa.js similarity index 95% rename from assets/GradesPage-C8P7dxU8.js rename to assets/GradesPage-BXZfrLBa.js index 7f21fe31059bc7c93af1c43aba8d92e1abd8fa22..f1a05a77bee6328c94771badd61b28815826347a 100644 --- a/assets/GradesPage-C8P7dxU8.js +++ b/assets/GradesPage-BXZfrLBa.js @@ -1,3 +1,3 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiagnosticBreakdown-KMY-Jwc3.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/index-BvEKrMkD.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css","assets/x-BYtx1i07.js","assets/clock-0vnF72R6.js","assets/lightbulb-BpvAgebC.js","assets/circle-check-E415RSic.js","assets/chart-column-DKW3TTRX.js","assets/chevron-up-CDr90bpM.js"])))=>i.map(i=>d[i]); -import{u as re,aH as le,aI as ne,ad as oe,g as S,H as ie,A as ce,r as O,T as F,B as de,_ as me}from"./index-BvEKrMkD.js";import{r as o,j as e}from"./vendor-react-B4AQeu28.js";import{B as k}from"./button-Bfg1pO9T.js";import{g as xe,S as _,s as pe}from"./subjects-ChEJ6J55.js";import{u as ue}from"./useCurriculum-CSvqmu2B.js";import{getDoc as A,doc as z}from"./vendor-firebase-firestore-CNv3xXal.js";import{D as he}from"./download-BYKPAk50.js";import{C as be}from"./circle-check-E415RSic.js";import{C as ge}from"./circle-alert-fPu7cawt.js";import{F as q}from"./funnel-CAdiZoOH.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-DKW3TTRX.js";const fe=o.lazy(()=>me(()=>import("./DiagnosticBreakdown-KMY-Jwc3.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]))),$e=()=>{const{currentUser:d,userProfile:C}=re(),[u,E]=o.useState("all"),[b,H]=o.useState("all"),[V,w]=o.useState(!0),[g,Y]=o.useState(null),[M,K]=o.useState([]),[m,W]=o.useState(null),[T,v]=o.useState(!1),[p,J]=o.useState(null),L=C?.grade,P=xe(L),R=new Set(P),{isLoading:X}=ue(L);o.useEffect(()=>{},[X]);const D=s=>{if(s==null)return"N/A";const t=s instanceof Date?s:new Date(s);return Number.isNaN(t.getTime())?"N/A":t.toISOString().split("T")[0]};o.useEffect(()=>{if(!d)return;w(!0);const s=le(d.uid,a=>{Y(a),w(!1)}),t=ne(d.uid,a=>{K(a),w(!1)}),r=oe(d.uid,a=>{J(a)});return()=>{s(),t(),r()}},[d]),o.useEffect(()=>{d?.uid&&(async()=>{try{let s=0,t="Unknown",r=[],a="";const l=await A(z(S,"users",d.uid,"dashboardSummary","heroBannerModal"));if(l.exists()){const n=l.data();n.status==="ready"&&(s=n.latestScorePercent||0,t=n.latestRiskLevel||"Unknown",r=n.weaknesses||[],a=n.recommendation||"")}else{const n=await A(z(S,"users",d.uid));if(n.exists()){const i=n.data();(i.initialAssessmentCompleted||i.hasCompletedInitialAssessment)&&(t=i.atRiskSubjects?.length>0?"Moderate":"Low",r=i.atRiskSubjects||[])}}const x=await A(z(S,"diagnosticResults",d.uid,"cache","analysis"));if(x.exists()){const n=x.data(),i=n.recommendations||[];i.length>0&&(a=i.map(c=>c.action).join(". ")+".");const j=n.weakness_areas||[];j.length>0&&(r=j.map(c=>c.domain))}(s>0||t!=="Unknown"||r.length>0)&&W({score:s,riskLevel:t,weaknesses:r,recommendation:a||"Continue with your personalized learning path."})}catch{}})()},[d?.uid]);const N=g?.averageScore?Math.round(g.averageScore):p?.averageScore?Math.round(p.averageScore):0,Z=Math.max(g?.quizzesCompleted??0,p?.quizAttempts?.length??0),ee=N>0?N.toString():"—",se={"gen-math":"indigo","stats-prob":"violet"},$={indigo:{dot:"bg-indigo-500",bar:"bg-indigo-500"},violet:{dot:"bg-violet-500",bar:"bg-violet-500"},fuchsia:{dot:"bg-fuchsia-500",bar:"bg-fuchsia-500"},purple:{dot:"bg-purple-500",bar:"bg-purple-500"},slate:{dot:"bg-slate-500",bar:"bg-slate-500"}},U=_.reduce((s,t)=>(s[t.id]={label:t.name,color:se[t.id]||"slate"},s),{}),h=_.filter(s=>R.has(s.id)).map(s=>s.name),B=Object.entries(p?.subjects??{}).filter(([s])=>R.has(s)).map(([s,t])=>{const r=U[s]||{label:s,color:"slate"},a=(p?.quizAttempts||[]).filter(x=>{const n=t?.modulesProgress||{};return Object.values(n).some(i=>i.quizzesCompleted?.includes(x.quizId))}),l=a.length>0?Math.round(a.reduce((x,n)=>x+n.score,0)/a.length):Math.round(t?.progress??0);return{subject:r.label,average:l,quizzes:a.length||t?.completedModules||0,color:r.color}}),te=P.map(s=>{const t=U[s]||{label:s,color:"slate"},r=g?.subjectPerformance?.[t.label],a=r?.avgScore?Math.round(r.avgScore):0;return{subject:t.label,average:a,quizzes:r?.count||0,color:t.color}}),I=B.length>0?B:te,Q=o.useMemo(()=>{if(!p?.quizAttempts?.length)return[];const s=new Map;return pe.forEach(t=>{const a=_.find(l=>l.id===t.id)?.name||t.title;t.modules.forEach(l=>{l.quizzes.forEach(x=>{s.set(x.id,{title:x.title,subject:a})})})}),p.quizAttempts.map((t,r)=>{const a=s.get(t.quizId),l=t.completedAt instanceof Date?t.completedAt:new Date(t.completedAt);return{id:1e4+r,title:a?.title||t.quizId.replace(/-/g," ").replace(/\b\w/g,x=>x.toUpperCase()),subject:a?.subject||"General Mathematics",score:Math.round(t.score),date:D(l),type:"quiz",status:t.score>=80?"Excellent":t.score>=60?"Passing":"Needs Review",_timestamp:l.getTime()}})},[p?.quizAttempts]),G=o.useMemo(()=>{const s=M.slice().map((a,l)=>({id:l+1,title:a.title||`Assessment ${l+1}`,subject:a.subject||"General",score:a.score,date:a.completedAt?D(a.completedAt.toDate()):"N/A",type:a.type==="practice"?"practice":(a.type==="diagnostic","quiz"),status:a.score>=80?"Excellent":a.score>=60?"Passing":"Needs Review",_timestamp:a.completedAt?.toDate?.()?.getTime()??0})),t=new Set(s.map(a=>a.title.toLowerCase())),r=Q.filter(a=>!t.has(a.title.toLowerCase()));return[...s,...r].sort((a,l)=>(l._timestamp||0)-(a._timestamp||0)).slice(0,20).filter(a=>h.includes(a.subject))},[M,Q,h]),f=G.filter(s=>{if(!h.includes(s.subject))return!1;const t=u==="all"||s.subject===u,r=b==="all"||s.type===b;return t&&r});o.useEffect(()=>{u!=="all"&&(h.includes(u)||E("all"))},[h,u]);const ae=()=>{const s=c=>{const y=String(c??"");return/[",\n]/.test(y)?`"${y.replace(/"/g,'""')}"`:y},t=[],r=C?.name||d?.displayName||d?.email||"Student",a=new Date().toISOString().split("T")[0];t.push("Grade Report"),t.push(`Student,${s(r)}`),t.push(`Export Date,${s(a)}`),t.push(`Subject Filter,${s(u)}`),t.push(`Type Filter,${s(b)}`),t.push(""),t.push("Subject Performance"),t.push("Subject,Average Score"),I.forEach(c=>{t.push([s(c.subject),s(c.average)].join(","))}),t.push(""),t.push("Recent Quizzes"),t.push("Title,Subject,Score,Date,Type,Status"),f.length===0?t.push("No quiz data available for the selected filters"):f.forEach(c=>{t.push([s(c.title),s(c.subject),s(c.score),s(c.date),s(c.type),s(c.status)].join(","))});const l=t.join(` +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiagnosticBreakdown-1Ae0p8Ht.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/index-BdLfAeGL.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css","assets/x-BLhsirCD.js","assets/clock-CpBwkoND.js","assets/lightbulb-W3LO7x3u.js","assets/circle-check-CuVe-qlS.js","assets/chart-column-Dl7iJ2BC.js","assets/chevron-up-uSn_SWll.js"])))=>i.map(i=>d[i]); +import{u as re,aH as le,aI as ne,ad as oe,g as S,H as ie,A as ce,r as O,T as F,B as de,_ as me}from"./index-BdLfAeGL.js";import{r as o,j as e}from"./vendor-react-B4AQeu28.js";import{B as k}from"./button-BbJLXpfi.js";import{g as xe,S as _,s as pe}from"./subjects-Dw9HR29l.js";import{u as ue}from"./useCurriculum-DZL96a-v.js";import{getDoc as A,doc as z}from"./vendor-firebase-firestore-CNv3xXal.js";import{D as he}from"./download-CPe9YOUv.js";import{C as be}from"./circle-check-CuVe-qlS.js";import{C as ge}from"./circle-alert-ByVTnT3r.js";import{F as q}from"./funnel-ijCItoBZ.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-Dl7iJ2BC.js";const fe=o.lazy(()=>me(()=>import("./DiagnosticBreakdown-1Ae0p8Ht.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]))),$e=()=>{const{currentUser:d,userProfile:C}=re(),[u,E]=o.useState("all"),[b,H]=o.useState("all"),[V,w]=o.useState(!0),[g,Y]=o.useState(null),[M,K]=o.useState([]),[m,W]=o.useState(null),[T,v]=o.useState(!1),[p,J]=o.useState(null),L=C?.grade,P=xe(L),R=new Set(P),{isLoading:X}=ue(L);o.useEffect(()=>{},[X]);const D=s=>{if(s==null)return"N/A";const t=s instanceof Date?s:new Date(s);return Number.isNaN(t.getTime())?"N/A":t.toISOString().split("T")[0]};o.useEffect(()=>{if(!d)return;w(!0);const s=le(d.uid,a=>{Y(a),w(!1)}),t=ne(d.uid,a=>{K(a),w(!1)}),r=oe(d.uid,a=>{J(a)});return()=>{s(),t(),r()}},[d]),o.useEffect(()=>{d?.uid&&(async()=>{try{let s=0,t="Unknown",r=[],a="";const l=await A(z(S,"users",d.uid,"dashboardSummary","heroBannerModal"));if(l.exists()){const n=l.data();n.status==="ready"&&(s=n.latestScorePercent||0,t=n.latestRiskLevel||"Unknown",r=n.weaknesses||[],a=n.recommendation||"")}else{const n=await A(z(S,"users",d.uid));if(n.exists()){const i=n.data();(i.initialAssessmentCompleted||i.hasCompletedInitialAssessment)&&(t=i.atRiskSubjects?.length>0?"Moderate":"Low",r=i.atRiskSubjects||[])}}const x=await A(z(S,"diagnosticResults",d.uid,"cache","analysis"));if(x.exists()){const n=x.data(),i=n.recommendations||[];i.length>0&&(a=i.map(c=>c.action).join(". ")+".");const j=n.weakness_areas||[];j.length>0&&(r=j.map(c=>c.domain))}(s>0||t!=="Unknown"||r.length>0)&&W({score:s,riskLevel:t,weaknesses:r,recommendation:a||"Continue with your personalized learning path."})}catch{}})()},[d?.uid]);const N=g?.averageScore?Math.round(g.averageScore):p?.averageScore?Math.round(p.averageScore):0,Z=Math.max(g?.quizzesCompleted??0,p?.quizAttempts?.length??0),ee=N>0?N.toString():"—",se={"gen-math":"indigo","stats-prob":"violet"},$={indigo:{dot:"bg-indigo-500",bar:"bg-indigo-500"},violet:{dot:"bg-violet-500",bar:"bg-violet-500"},fuchsia:{dot:"bg-fuchsia-500",bar:"bg-fuchsia-500"},purple:{dot:"bg-purple-500",bar:"bg-purple-500"},slate:{dot:"bg-slate-500",bar:"bg-slate-500"}},U=_.reduce((s,t)=>(s[t.id]={label:t.name,color:se[t.id]||"slate"},s),{}),h=_.filter(s=>R.has(s.id)).map(s=>s.name),B=Object.entries(p?.subjects??{}).filter(([s])=>R.has(s)).map(([s,t])=>{const r=U[s]||{label:s,color:"slate"},a=(p?.quizAttempts||[]).filter(x=>{const n=t?.modulesProgress||{};return Object.values(n).some(i=>i.quizzesCompleted?.includes(x.quizId))}),l=a.length>0?Math.round(a.reduce((x,n)=>x+n.score,0)/a.length):Math.round(t?.progress??0);return{subject:r.label,average:l,quizzes:a.length||t?.completedModules||0,color:r.color}}),te=P.map(s=>{const t=U[s]||{label:s,color:"slate"},r=g?.subjectPerformance?.[t.label],a=r?.avgScore?Math.round(r.avgScore):0;return{subject:t.label,average:a,quizzes:r?.count||0,color:t.color}}),I=B.length>0?B:te,Q=o.useMemo(()=>{if(!p?.quizAttempts?.length)return[];const s=new Map;return pe.forEach(t=>{const a=_.find(l=>l.id===t.id)?.name||t.title;t.modules.forEach(l=>{l.quizzes.forEach(x=>{s.set(x.id,{title:x.title,subject:a})})})}),p.quizAttempts.map((t,r)=>{const a=s.get(t.quizId),l=t.completedAt instanceof Date?t.completedAt:new Date(t.completedAt);return{id:1e4+r,title:a?.title||t.quizId.replace(/-/g," ").replace(/\b\w/g,x=>x.toUpperCase()),subject:a?.subject||"General Mathematics",score:Math.round(t.score),date:D(l),type:"quiz",status:t.score>=80?"Excellent":t.score>=60?"Passing":"Needs Review",_timestamp:l.getTime()}})},[p?.quizAttempts]),G=o.useMemo(()=>{const s=M.slice().map((a,l)=>({id:l+1,title:a.title||`Assessment ${l+1}`,subject:a.subject||"General",score:a.score,date:a.completedAt?D(a.completedAt.toDate()):"N/A",type:a.type==="practice"?"practice":(a.type==="diagnostic","quiz"),status:a.score>=80?"Excellent":a.score>=60?"Passing":"Needs Review",_timestamp:a.completedAt?.toDate?.()?.getTime()??0})),t=new Set(s.map(a=>a.title.toLowerCase())),r=Q.filter(a=>!t.has(a.title.toLowerCase()));return[...s,...r].sort((a,l)=>(l._timestamp||0)-(a._timestamp||0)).slice(0,20).filter(a=>h.includes(a.subject))},[M,Q,h]),f=G.filter(s=>{if(!h.includes(s.subject))return!1;const t=u==="all"||s.subject===u,r=b==="all"||s.type===b;return t&&r});o.useEffect(()=>{u!=="all"&&(h.includes(u)||E("all"))},[h,u]);const ae=()=>{const s=c=>{const y=String(c??"");return/[",\n]/.test(y)?`"${y.replace(/"/g,'""')}"`:y},t=[],r=C?.name||d?.displayName||d?.email||"Student",a=new Date().toISOString().split("T")[0];t.push("Grade Report"),t.push(`Student,${s(r)}`),t.push(`Export Date,${s(a)}`),t.push(`Subject Filter,${s(u)}`),t.push(`Type Filter,${s(b)}`),t.push(""),t.push("Subject Performance"),t.push("Subject,Average Score"),I.forEach(c=>{t.push([s(c.subject),s(c.average)].join(","))}),t.push(""),t.push("Recent Quizzes"),t.push("Title,Subject,Score,Date,Type,Status"),f.length===0?t.push("No quiz data available for the selected filters"):f.forEach(c=>{t.push([s(c.title),s(c.subject),s(c.score),s(c.date),s(c.type),s(c.status)].join(","))});const l=t.join(` `),x=new Blob([l],{type:"text/csv;charset=utf-8;"}),n=window.URL.createObjectURL(x),i=document.createElement("a"),j=r.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()||"student";i.href=n,i.setAttribute("download",`grade-report-${j}-${a}.csv`),document.body.appendChild(i),i.click(),document.body.removeChild(i),window.URL.revokeObjectURL(n)};return V?e.jsx("div",{className:"p-8 flex justify-center items-center h-full",children:e.jsx("div",{className:"w-10 h-10 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"})}):e.jsxs("div",{className:"p-4 sm:p-6 lg:p-8 space-y-6 lg:space-y-8 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-5 sm:p-6 rounded-[1.5rem] sm:rounded-[2rem] shadow-[0_8px_30px_-12px_rgba(0,0,0,0.06)] border border-slate-50",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-display font-black text-slate-800 tracking-tight",children:"Assessment"}),e.jsx("p",{className:"text-slate-400 font-bold mt-1 text-[13px]",children:"Review your performance across subjects"})]}),e.jsxs("div",{className:"flex gap-3 w-full sm:w-auto",children:[e.jsxs(k,{variant:"outline",className:"flex-1 sm:flex-none border-slate-200 text-slate-500 font-bold rounded-xl h-11 px-5 hover:bg-slate-50 hover:text-slate-700",children:[e.jsx(ie,{className:"w-4 h-4 mr-2 text-slate-400"}),"This Quarter"]}),e.jsxs(k,{className:"flex-1 sm:flex-none bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl h-11 px-5 shadow-[0_8px_20px_-8px_rgba(79,70,229,0.5)] hover:-translate-y-0.5 transition-all",onClick:ae,children:[e.jsx(he,{className:"w-4 h-4 mr-2"}),"Report"]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 sm:gap-6",children:[e.jsxs("div",{className:"bg-white rounded-[1.2rem] sm:rounded-[2rem] border border-slate-100 p-4 sm:p-8 shadow-[0_8px_24px_-10px_rgba(0,0,0,0.05)] relative overflow-hidden group hover:border-indigo-100 transition-colors",children:[e.jsx("div",{className:"absolute -right-6 -top-6 sm:-right-8 sm:-top-8 w-20 h-20 sm:w-32 sm:h-32 bg-indigo-50 rounded-full group-hover:scale-110 transition-transform duration-500"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 bg-indigo-100 text-indigo-600 rounded-xl sm:rounded-2xl flex items-center justify-center mb-3 sm:mb-6 shadow-sm",children:e.jsx(ce,{className:"w-5 h-5 sm:w-7 sm:h-7"})}),e.jsxs("p",{className:"text-slate-400 font-bold text-[9px] sm:text-sm tracking-wider sm:tracking-wide uppercase h-6 sm:h-auto flex items-end sm:block",children:[e.jsx("span",{className:"sm:hidden",children:"GEN. AVE."}),e.jsx("span",{className:"hidden sm:inline",children:"General Average"})]}),e.jsx("div",{className:"flex items-end gap-2 mt-1 sm:mt-2",children:e.jsxs("h3",{className:"text-xl sm:text-4xl font-display font-black text-slate-800",children:[ee,N>0?"%":""]})})]})]}),e.jsxs("div",{className:"bg-white rounded-[1.2rem] sm:rounded-[2rem] border border-slate-100 p-4 sm:p-8 shadow-[0_8px_24px_-10px_rgba(0,0,0,0.05)] relative overflow-hidden group hover:border-emerald-100 transition-colors",children:[e.jsx("div",{className:"absolute -right-6 -top-6 sm:-right-8 sm:-top-8 w-20 h-20 sm:w-32 sm:h-32 bg-emerald-50 rounded-full group-hover:scale-110 transition-transform duration-500"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 bg-emerald-100 text-emerald-600 rounded-xl sm:rounded-2xl flex items-center justify-center mb-3 sm:mb-6 shadow-sm",children:e.jsx(O,{className:"w-5 h-5 sm:w-7 sm:h-7"})}),e.jsxs("p",{className:"text-slate-400 font-bold text-[9px] sm:text-sm tracking-wider sm:tracking-wide uppercase h-6 sm:h-auto flex items-end sm:block",children:[e.jsx("span",{className:"sm:hidden",children:"Weakest"}),e.jsx("span",{className:"hidden sm:inline",children:"Weakest Subject"})]}),e.jsx("div",{className:"flex items-end gap-2 mt-1 sm:mt-2",children:e.jsx("h3",{className:"text-lg sm:text-2xl font-display font-black text-slate-800 truncate",children:m?.weaknesses?.[0]||"—"})})]})]}),e.jsxs("div",{className:"bg-white rounded-[1.2rem] sm:rounded-[2rem] border border-slate-100 p-4 sm:p-8 shadow-[0_8px_24px_-10px_rgba(0,0,0,0.05)] relative overflow-hidden group hover:border-violet-100 transition-colors",children:[e.jsx("div",{className:"absolute -right-6 -top-6 sm:-right-8 sm:-top-8 w-20 h-20 sm:w-32 sm:h-32 bg-violet-50 rounded-full group-hover:scale-110 transition-transform duration-500"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 bg-violet-100 text-violet-600 rounded-xl sm:rounded-2xl flex items-center justify-center mb-3 sm:mb-6 shadow-sm",children:e.jsx(F,{className:"w-5 h-5 sm:w-7 sm:h-7"})}),e.jsxs("p",{className:"text-slate-400 font-bold text-[9px] sm:text-sm tracking-wider sm:tracking-wide uppercase h-6 sm:h-auto flex items-end sm:block",children:[e.jsx("span",{className:"sm:hidden",children:"Quizzes"}),e.jsx("span",{className:"hidden sm:inline",children:"Quizzes Completed"})]}),e.jsx("div",{className:"flex items-end gap-2 mt-1 sm:mt-2",children:e.jsx("h3",{className:"text-xl sm:text-4xl font-display font-black text-slate-800",children:Z})})]})]})]}),m&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6 shadow-sm cursor-pointer hover:shadow-md hover:border-indigo-200 transition-all",onClick:()=>v(!0),role:"button",tabIndex:0,onKeyDown:s=>{s.key==="Enter"&&v(!0)},children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-indigo-100 rounded-xl flex items-center justify-center",children:e.jsx(de,{className:"w-5 h-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-slate-800",children:"Diagnostic Assessment Results"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Your initial competency evaluation"})]})]}),e.jsxs("span",{className:`px-3 py-1 rounded-full text-xs font-bold flex items-center gap-1.5 ${m.riskLevel==="Low"?"bg-emerald-100 text-emerald-700":m.riskLevel==="High"||m.riskLevel==="At Risk"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[m.riskLevel==="Low"?e.jsx(be,{size:12}):e.jsx(ge,{size:12}),m.riskLevel]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[m.score>0&&e.jsxs("div",{className:"bg-slate-50 rounded-xl p-4",children:[e.jsx("p",{className:"text-xs font-bold text-slate-400 uppercase mb-1",children:"Score"}),e.jsxs("p",{className:"text-2xl font-black text-slate-800",children:[m.score,"%"]})]}),m.weaknesses.length>0&&e.jsxs("div",{className:"bg-amber-50 border border-amber-100 rounded-xl p-4",children:[e.jsx("p",{className:"text-xs font-bold text-amber-600 uppercase mb-2",children:"Focus Areas"}),e.jsx("ul",{className:"space-y-1",children:m.weaknesses.map((s,t)=>e.jsxs("li",{className:"text-sm text-amber-800 flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"}),s]},t))})]}),m.recommendation&&e.jsxs("div",{className:"bg-indigo-50 border border-indigo-100 rounded-xl p-4",children:[e.jsx("p",{className:"text-xs font-bold text-indigo-600 uppercase mb-2",children:"Recommendation"}),e.jsx("p",{className:"text-sm text-indigo-800",children:m.recommendation})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-[1.5rem] sm:rounded-[2rem] border border-slate-100 shadow-[0_8px_30px_-12px_rgba(0,0,0,0.06)] overflow-hidden flex flex-col h-full w-full",children:[e.jsxs("div",{className:"p-5 sm:p-8 border-b border-slate-50 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-black text-xl text-slate-800",children:"Recent Assessments"}),e.jsx("p",{className:"text-slate-400 font-bold text-[13px] mt-1",children:"Your latest quiz and practice results"})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 w-full sm:w-auto",children:[e.jsxs("div",{className:"relative flex-1 sm:flex-none",children:[e.jsxs("select",{value:u,onChange:s=>E(s.target.value),className:"appearance-none w-full pl-3 pr-8 py-2.5 border-none bg-slate-50 rounded-xl text-xs sm:text-sm font-bold text-slate-600 focus:ring-2 focus:ring-indigo-500/30 transition-all cursor-pointer min-w-0 sm:min-w-[140px] shadow-sm",children:[e.jsx("option",{value:"all",children:"All Subjects"}),h.map(s=>e.jsx("option",{value:s,children:s},s))]}),e.jsx(q,{className:"w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]}),e.jsxs("div",{className:"relative flex-1 sm:flex-none",children:[e.jsxs("select",{value:b,onChange:s=>H(s.target.value),className:"appearance-none w-full pl-3 pr-8 py-2.5 border-none bg-slate-50 rounded-xl text-xs sm:text-sm font-bold text-slate-600 focus:ring-2 focus:ring-indigo-500/30 transition-all cursor-pointer min-w-0 sm:min-w-[120px] shadow-sm",children:[e.jsx("option",{value:"all",children:"All Types"}),e.jsx("option",{value:"quiz",children:"Quiz"}),e.jsx("option",{value:"practice",children:"Practice"})]}),e.jsx(q,{className:"w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]})]})]}),e.jsx("div",{className:"overflow-x-auto no-scrollbar flex-1 px-4 sm:px-6 pb-4 -mx-4 sm:mx-0",children:e.jsxs("table",{className:"w-full text-left border-separate border-spacing-y-2 mb-4 whitespace-nowrap md:whitespace-normal",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-[11px] font-bold text-slate-400 uppercase tracking-wider border-b border-transparent",children:"Assessment"}),e.jsx("th",{className:"px-4 py-3 text-[11px] font-bold text-slate-400 uppercase tracking-wider border-b border-transparent min-w-[120px]",children:"Subject"}),e.jsx("th",{className:"px-4 py-3 text-[11px] font-bold text-slate-400 uppercase tracking-wider border-b border-transparent",children:"Type"}),e.jsx("th",{className:"px-4 py-3 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-right border-b border-transparent",children:"Score"})]})}),e.jsx("tbody",{children:f.length>0?f.map(s=>e.jsxs("tr",{className:"group hover:bg-slate-50/70 transition-colors",children:[e.jsxs("td",{className:"px-4 py-4 rounded-l-2xl",children:[e.jsx("p",{className:"text-[14px] font-bold text-slate-800",children:s.title}),e.jsx("p",{className:"text-[11px] font-bold text-slate-400 mt-1",children:s.date})]}),e.jsx("td",{className:"px-4 py-4",children:e.jsx("span",{className:"inline-flex flex-col gap-1 items-start",children:e.jsx("span",{className:"text-[13px] font-bold text-slate-600 truncate max-w-[140px] block",children:s.subject})})}),e.jsx("td",{className:"px-4 py-4",children:e.jsx("span",{className:`inline-flex items-center px-3 py-1.5 rounded-lg text-[11px] font-bold uppercase tracking-wide ${s.type==="practice"?"bg-emerald-100/50 text-emerald-600":"bg-indigo-100/50 text-indigo-600"}`,children:s.type==="practice"?"Practice":"Quiz"})}),e.jsx("td",{className:"px-4 py-4 text-right rounded-r-2xl",children:e.jsxs("span",{className:`inline-flex items-center px-3 py-1.5 rounded-xl text-[13px] font-black ${s.score>=80?"bg-emerald-100 text-emerald-700":s.score>=60?"bg-amber-100 text-amber-700":"bg-rose-100 text-rose-700"}`,children:[s.score,"%"]})})]},s.id)):e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-6 py-16 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4",children:e.jsx(O,{className:"w-8 h-8 text-slate-300"})}),e.jsx("p",{className:"text-slate-500 font-bold text-sm",children:"No recent assessments match the selected filters."})]})})})})]})})]})}),e.jsxs("div",{className:"space-y-6 lg:space-y-8 flex flex-col",children:[e.jsxs("div",{className:"bg-white rounded-[1.5rem] sm:rounded-[2rem] border border-slate-100 p-5 sm:p-8 shadow-[0_8px_30px_-12px_rgba(0,0,0,0.06)]",children:[e.jsx("div",{className:"flex items-center justify-between mb-8",children:e.jsx("h3",{className:"font-display font-black text-lg text-slate-800",children:"Subject Performance"})}),e.jsx("div",{className:"space-y-7",children:I.map((s,t)=>{const r=$[s.color]||$.slate;return e.jsxs("div",{className:"group",children:[e.jsxs("div",{className:"flex justify-between items-end mb-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-[14px] font-bold text-slate-800 flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${r.dot} group-hover:scale-125 transition-transform`}),s.subject]}),e.jsxs("p",{className:"text-[11px] text-slate-400 font-bold ml-4 mt-0.5",children:[s.quizzes," activities"]})]}),e.jsxs("span",{className:"text-[15px] font-black text-slate-800",children:[s.average,"%"]})]}),e.jsx("div",{className:"h-2.5 w-full bg-slate-100 rounded-full overflow-hidden shadow-inner",children:e.jsx("div",{className:`h-full rounded-full e-w ${r.bar} shadow-sm relative overflow-hidden transition-all duration-1000`,style:{"--w":`${Math.max(s.average,5)}%`},children:e.jsx("div",{className:"absolute inset-0 bg-white/20 w-1/2 -skew-x-12 translate-x-[-100%] group-hover:animate-[shimmer_1.5s_ease-out]"})})})]},t)})})]}),e.jsxs("div",{className:"relative bg-gradient-to-br from-indigo-600 to-violet-700 rounded-[1.5rem] sm:rounded-[2rem] p-5 sm:p-8 shadow-[0_12px_30px_-10px_rgba(79,70,229,0.5)] text-white overflow-hidden group",children:[e.jsx("div",{className:"absolute top-0 right-0 w-48 h-48 bg-white/10 rounded-full blur-3xl -mt-10 -mr-10 group-hover:bg-white/20 transition-all duration-700 ease-in-out"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-32 h-32 bg-indigo-400/30 rounded-full blur-2xl -mb-10 -ml-10"}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("div",{className:"w-12 h-12 bg-white/10 rounded-2xl flex items-center justify-center mb-5 backdrop-blur-sm border border-white/20 shadow-sm group-hover:scale-110 transition-transform",children:e.jsx(F,{className:"w-6 h-6 text-white"})}),e.jsx("h3",{className:"text-2xl font-display font-black tracking-tight mb-2 leading-tight",children:"Keep up the momentum!"}),e.jsxs("p",{className:"text-white/80 text-[13px] font-medium leading-relaxed mb-8 max-w-[90%]",children:["You've completed ",e.jsx("span",{className:"font-black text-white",children:G.length})," activities recently. Try a practice session to boost your lowest scores."]}),e.jsx(k,{onClick:()=>{sessionStorage.setItem("mathpulse_modules_tab","practice"),window.dispatchEvent(new CustomEvent("mathpulse:navigate",{detail:{tab:"Modules"}}))},className:"w-full bg-white text-indigo-600 hover:bg-slate-50 border-0 font-black h-12 rounded-xl shadow-[0_8px_16px_rgba(0,0,0,0.15)] hover:shadow-[0_8px_24px_rgba(0,0,0,0.2)] hover:-translate-y-0.5 transition-all",children:"Start Practice Session"})]})]})]})]}),T&&d?.uid&&e.jsx(o.Suspense,{fallback:null,children:e.jsx(fe,{userId:d.uid,mode:"modal",isOpen:T,onClose:()=>v(!1)})})]})};export{$e as default}; diff --git a/assets/HeroBanner-Br6C2yH1.js b/assets/HeroBanner-BW-D6-hj.js similarity index 98% rename from assets/HeroBanner-Br6C2yH1.js rename to assets/HeroBanner-BW-D6-hj.js index 009a5bb175e5c08654b01c2e29d11d634db8565b..542ff80a04451c939de171c6cfd7057e26dd5b10 100644 --- a/assets/HeroBanner-Br6C2yH1.js +++ b/assets/HeroBanner-BW-D6-hj.js @@ -1,3 +1,3 @@ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DashboardAvatar-D5djDQQ1.js","assets/vendor-react-B4AQeu28.js","assets/avatarData-ChByUhv2.js"])))=>i.map(i=>d[i]); -import{T as R,g as b,a3 as M,h as _,m as f,a4 as E,A as G,B as S,r as z,Z as Y,a as F,_ as Q}from"./index-BvEKrMkD.js";import{j as e,r as m}from"./vendor-react-B4AQeu28.js";import{D as W,a as q,S as V}from"./dialog-F21mi9j3.js";import{R as K,L as X,C as U,X as Z,Y as O,T as I,e as J}from"./vendor-charts-CAmziV1y.js";import{collection as v,query as w,limit as N,orderBy as k,getDocs as A,getDoc as L,doc as C}from"./vendor-firebase-firestore-CNv3xXal.js";import{X as ee}from"./x-BYtx1i07.js";import{C as H}from"./circle-alert-fPu7cawt.js";import{C as se}from"./circle-check-E415RSic.js";import{S as te}from"./sparkles-av0wSNZT.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-markdown-yqZQ_iQm.js";const ae=({history:s})=>{if(s.length===0)return e.jsxs("div",{className:"text-center py-12 text-slate-400",children:[e.jsx(R,{className:"w-12 h-12 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"Complete more assessments to see your progress history."})]});const a=s.map(r=>({date:new Date(r.completedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"}),score:r.percentage,level:r.proficiencyLevel}));return e.jsx("div",{className:"w-full",children:e.jsx(K,{width:"100%",height:250,children:e.jsxs(X,{data:a,margin:{top:10,right:20,left:0,bottom:5},children:[e.jsx(U,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(Z,{dataKey:"date",tick:{fontSize:12,fill:"#64748b"}}),e.jsx(O,{domain:[0,100],tick:{fontSize:12,fill:"#64748b"}}),e.jsx(I,{contentStyle:{borderRadius:"12px",border:"1px solid #e2e8f0",boxShadow:"0 4px 12px rgba(0,0,0,0.08)"}}),e.jsx(J,{type:"monotone",dataKey:"score",stroke:"#0ea5e9",strokeWidth:3,dot:{fill:"#0ea5e9",strokeWidth:2,r:5},activeDot:{r:7,fill:"#0284c7"}})]})})})};async function re(s){const a=v(b,"assessmentResults",s,"attempts"),r=w(a,k("completedAt","desc"),N(10));return(await A(r)).docs.map(i=>{const n=i.data();return{attemptId:n.attemptId,score:n.score,totalQuestions:n.totalQuestions,percentage:n.percentage,completedAt:n.completedAt?.toDate?.()?.toISOString()||n.completedAt,proficiencyLevel:n.proficiencyLevel}})}async function le(s){const a=v(b,"assessmentResults",s,"attempts"),r=w(a,k("completedAt","desc"),N(1)),c=await A(r);if(c.empty)return null;const n=c.docs[0].data();return{...n,completedAt:n.completedAt?.toDate?.()?.toISOString()||n.completedAt}}const oe={Beginner:"bg-amber-100 text-amber-700 border-amber-300",Developing:"bg-blue-100 text-blue-700 border-blue-300",Proficient:"bg-emerald-100 text-emerald-700 border-emerald-300",Advanced:"bg-violet-100 text-violet-700 border-violet-300"},ne=({result:s})=>e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"bg-gradient-to-br from-sky-500 to-teal-600 rounded-xl p-6 text-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sky-200 text-sm font-medium",children:"Total Score"}),e.jsxs("p",{className:"text-4xl font-bold",children:[s.score,"/",s.totalQuestions]}),e.jsxs("p",{className:"text-sky-200 text-sm mt-1",children:[s.percentage,"% Correct"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sky-200 text-sm font-medium",children:"Proficiency"}),e.jsx("span",{className:`inline-block mt-1 px-3 py-1 rounded-full text-sm font-semibold border ${oe[s.proficiencyLevel]}`,children:s.proficiencyLevel})]})]})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold text-slate-800 mb-3 flex items-center gap-2",children:[e.jsx(S,{className:"w-4 h-4 text-sky-500"}),"Competency Breakdown"]}),e.jsx("div",{className:"space-y-2",children:s.competencyBreakdown.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-slate-50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-slate-700",children:a.topic}),e.jsxs("p",{className:"text-xs text-slate-500",children:[a.correctAnswers,"/",a.totalQuestions," correct"]})]}),e.jsx("div",{className:"w-20 h-2 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${a.accuracyPercent>=70?"bg-emerald-500":"bg-red-400"}`,style:{width:`${a.accuracyPercent}%`}})}),e.jsxs("span",{className:"text-sm font-semibold text-slate-600 w-10 text-right",children:[a.accuracyPercent,"%"]})]},r))})]}),s.aiNarrative&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(te,{className:"w-4 h-4 text-amber-500 mt-0.5 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-amber-800 leading-relaxed",children:s.aiNarrative})]})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold text-slate-800 mb-3 flex items-center gap-2",children:[e.jsx(z,{className:"w-4 h-4 text-sky-500"}),"Question Breakdown"]}),e.jsx("div",{className:"space-y-3",children:s.answers.map((a,r)=>e.jsxs("div",{className:`p-4 rounded-xl border-2 ${a.isCorrect?"border-emerald-200 bg-emerald-50/30":"border-red-200 bg-red-50/30"}`,children:[e.jsxs("p",{className:"text-sm font-medium text-slate-800 mb-2",children:["Q",r+1,". ",a.questionText]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"text-slate-500",children:["Your answer: ",e.jsx("span",{className:a.isCorrect?"text-emerald-600 font-medium":"text-red-500 font-medium",children:a.userAnswer||"—"})]}),!a.isCorrect&&e.jsxs("span",{className:"text-slate-500",children:["Correct: ",e.jsx("span",{className:"text-emerald-600 font-medium",children:a.correctAnswer})]})]}),a.explanation&&e.jsx("p",{className:"text-xs text-slate-500 mt-2 leading-relaxed",children:a.explanation})]},r))})]})]}),ie=({summary:s})=>e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"bg-sky-50 border border-sky-100 rounded-2xl p-4 flex items-center gap-4 flex-1",children:[e.jsxs("div",{className:"w-12 h-12 bg-sky-500 rounded-full flex items-center justify-center text-white font-bold text-lg shadow-sm",children:[s.latestScorePercent,"%"]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-slate-500",children:"Latest Score"}),e.jsx("p",{className:"text-slate-800 font-bold",children:s.headline})]})]}),s.latestRiskLevel&&e.jsxs("div",{className:`px-4 py-2 rounded-full text-sm font-semibold flex items-center gap-2 +import{T as R,g as b,a3 as M,h as _,m as f,a4 as E,A as G,B as S,r as z,Z as Y,a as F,_ as Q}from"./index-BdLfAeGL.js";import{j as e,r as m}from"./vendor-react-B4AQeu28.js";import{D as W,a as q,S as V}from"./dialog-BW6ddbOv.js";import{R as K,L as X,C as U,X as Z,Y as O,T as I,e as J}from"./vendor-charts-CAmziV1y.js";import{collection as v,query as w,limit as N,orderBy as k,getDocs as A,getDoc as L,doc as C}from"./vendor-firebase-firestore-CNv3xXal.js";import{X as ee}from"./x-BLhsirCD.js";import{C as H}from"./circle-alert-ByVTnT3r.js";import{C as se}from"./circle-check-CuVe-qlS.js";import{S as te}from"./sparkles-DnAkO9TX.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-markdown-yqZQ_iQm.js";const ae=({history:s})=>{if(s.length===0)return e.jsxs("div",{className:"text-center py-12 text-slate-400",children:[e.jsx(R,{className:"w-12 h-12 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"Complete more assessments to see your progress history."})]});const a=s.map(r=>({date:new Date(r.completedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"}),score:r.percentage,level:r.proficiencyLevel}));return e.jsx("div",{className:"w-full",children:e.jsx(K,{width:"100%",height:250,children:e.jsxs(X,{data:a,margin:{top:10,right:20,left:0,bottom:5},children:[e.jsx(U,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(Z,{dataKey:"date",tick:{fontSize:12,fill:"#64748b"}}),e.jsx(O,{domain:[0,100],tick:{fontSize:12,fill:"#64748b"}}),e.jsx(I,{contentStyle:{borderRadius:"12px",border:"1px solid #e2e8f0",boxShadow:"0 4px 12px rgba(0,0,0,0.08)"}}),e.jsx(J,{type:"monotone",dataKey:"score",stroke:"#0ea5e9",strokeWidth:3,dot:{fill:"#0ea5e9",strokeWidth:2,r:5},activeDot:{r:7,fill:"#0284c7"}})]})})})};async function re(s){const a=v(b,"assessmentResults",s,"attempts"),r=w(a,k("completedAt","desc"),N(10));return(await A(r)).docs.map(i=>{const n=i.data();return{attemptId:n.attemptId,score:n.score,totalQuestions:n.totalQuestions,percentage:n.percentage,completedAt:n.completedAt?.toDate?.()?.toISOString()||n.completedAt,proficiencyLevel:n.proficiencyLevel}})}async function le(s){const a=v(b,"assessmentResults",s,"attempts"),r=w(a,k("completedAt","desc"),N(1)),c=await A(r);if(c.empty)return null;const n=c.docs[0].data();return{...n,completedAt:n.completedAt?.toDate?.()?.toISOString()||n.completedAt}}const oe={Beginner:"bg-amber-100 text-amber-700 border-amber-300",Developing:"bg-blue-100 text-blue-700 border-blue-300",Proficient:"bg-emerald-100 text-emerald-700 border-emerald-300",Advanced:"bg-violet-100 text-violet-700 border-violet-300"},ne=({result:s})=>e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"bg-gradient-to-br from-sky-500 to-teal-600 rounded-xl p-6 text-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sky-200 text-sm font-medium",children:"Total Score"}),e.jsxs("p",{className:"text-4xl font-bold",children:[s.score,"/",s.totalQuestions]}),e.jsxs("p",{className:"text-sky-200 text-sm mt-1",children:[s.percentage,"% Correct"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sky-200 text-sm font-medium",children:"Proficiency"}),e.jsx("span",{className:`inline-block mt-1 px-3 py-1 rounded-full text-sm font-semibold border ${oe[s.proficiencyLevel]}`,children:s.proficiencyLevel})]})]})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold text-slate-800 mb-3 flex items-center gap-2",children:[e.jsx(S,{className:"w-4 h-4 text-sky-500"}),"Competency Breakdown"]}),e.jsx("div",{className:"space-y-2",children:s.competencyBreakdown.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-slate-50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-slate-700",children:a.topic}),e.jsxs("p",{className:"text-xs text-slate-500",children:[a.correctAnswers,"/",a.totalQuestions," correct"]})]}),e.jsx("div",{className:"w-20 h-2 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${a.accuracyPercent>=70?"bg-emerald-500":"bg-red-400"}`,style:{width:`${a.accuracyPercent}%`}})}),e.jsxs("span",{className:"text-sm font-semibold text-slate-600 w-10 text-right",children:[a.accuracyPercent,"%"]})]},r))})]}),s.aiNarrative&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(te,{className:"w-4 h-4 text-amber-500 mt-0.5 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-amber-800 leading-relaxed",children:s.aiNarrative})]})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold text-slate-800 mb-3 flex items-center gap-2",children:[e.jsx(z,{className:"w-4 h-4 text-sky-500"}),"Question Breakdown"]}),e.jsx("div",{className:"space-y-3",children:s.answers.map((a,r)=>e.jsxs("div",{className:`p-4 rounded-xl border-2 ${a.isCorrect?"border-emerald-200 bg-emerald-50/30":"border-red-200 bg-red-50/30"}`,children:[e.jsxs("p",{className:"text-sm font-medium text-slate-800 mb-2",children:["Q",r+1,". ",a.questionText]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"text-slate-500",children:["Your answer: ",e.jsx("span",{className:a.isCorrect?"text-emerald-600 font-medium":"text-red-500 font-medium",children:a.userAnswer||"—"})]}),!a.isCorrect&&e.jsxs("span",{className:"text-slate-500",children:["Correct: ",e.jsx("span",{className:"text-emerald-600 font-medium",children:a.correctAnswer})]})]}),a.explanation&&e.jsx("p",{className:"text-xs text-slate-500 mt-2 leading-relaxed",children:a.explanation})]},r))})]})]}),ie=({summary:s})=>e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"bg-sky-50 border border-sky-100 rounded-2xl p-4 flex items-center gap-4 flex-1",children:[e.jsxs("div",{className:"w-12 h-12 bg-sky-500 rounded-full flex items-center justify-center text-white font-bold text-lg shadow-sm",children:[s.latestScorePercent,"%"]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-slate-500",children:"Latest Score"}),e.jsx("p",{className:"text-slate-800 font-bold",children:s.headline})]})]}),s.latestRiskLevel&&e.jsxs("div",{className:`px-4 py-2 rounded-full text-sm font-semibold flex items-center gap-2 ${s.latestRiskLevel==="At Risk"?"bg-red-100 text-red-700":s.latestRiskLevel==="Needs Attention"?"bg-amber-100 text-amber-700":"bg-emerald-100 text-emerald-700"}`,children:[s.latestRiskLevel==="At Risk"?e.jsx(V,{className:"w-4 h-4"}):s.latestRiskLevel==="Needs Attention"?e.jsx(H,{className:"w-4 h-4"}):e.jsx(se,{className:"w-4 h-4"}),s.latestRiskLevel]})]}),e.jsx("div",{className:"bg-slate-50 p-5 rounded-2xl border border-slate-100",children:e.jsx("p",{className:"text-slate-700 leading-relaxed",children:s.summary})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.strengths?.length>0&&e.jsxs("div",{className:"border border-emerald-100 bg-emerald-50/30 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-semibold text-emerald-800 mb-3 flex items-center gap-2",children:[e.jsx(R,{className:"w-4 h-4"}),"Strengths"]}),e.jsx("ul",{className:"space-y-2",children:s.strengths.map((a,r)=>e.jsxs("li",{className:"text-sm text-emerald-700 flex items-start gap-2",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 mt-1.5 flex-shrink-0"}),e.jsx("span",{children:a})]},r))})]}),s.weaknesses?.length>0&&e.jsxs("div",{className:"border border-amber-100 bg-amber-50/30 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-semibold text-amber-800 mb-3 flex items-center gap-2",children:[e.jsx(z,{className:"w-4 h-4"}),"Focus Areas"]}),e.jsx("ul",{className:"space-y-2",children:s.weaknesses.map((a,r)=>e.jsxs("li",{className:"text-sm text-amber-700 flex items-start gap-2",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 mt-1.5 flex-shrink-0"}),e.jsx("span",{children:a})]},r))})]})]}),s.recommendation&&e.jsxs("div",{className:"bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl p-5 border border-indigo-100",children:[e.jsxs("h4",{className:"font-semibold text-indigo-900 mb-2 flex items-center gap-2",children:[e.jsx(S,{className:"w-4 h-4 text-indigo-500"}),"Recommended Next Step"]}),e.jsx("p",{className:"text-sm text-indigo-800 leading-relaxed",children:s.recommendation})]})]}),de=({heroBannerSummary:s,latestResult:a,loading:r})=>r?e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-32 bg-slate-200 rounded-xl"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"h-4 bg-slate-200 rounded w-3/4"}),e.jsx("div",{className:"h-4 bg-slate-200 rounded w-1/2"}),e.jsx("div",{className:"h-4 bg-slate-200 rounded w-5/6"})]})]}):!s&&!a?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 bg-sky-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(S,{className:"w-8 h-8 text-sky-500"})}),e.jsx("h3",{className:"text-lg font-bold text-slate-800 mb-2",children:"Let's personalize your learning"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-xs mx-auto",children:"Complete your diagnostic assessment so I can understand your strengths, weak areas, and the best next lessons for you."})]}):s?.status==="ready"?e.jsx(ie,{summary:s}):a?e.jsx(ne,{result:a}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(H,{className:"w-8 h-8 text-amber-500"})}),e.jsx("h3",{className:"text-lg font-bold text-slate-800 mb-2",children:"Your learning summary is being prepared"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-xs mx-auto",children:"Please try opening this again in a moment."})]});async function ce(s){const a=await L(C(b,"competencyProfiles",s)).catch(()=>null);if(a?.exists()){const t=a.data(),l=t.primaryStrength?[t.primaryStrength]:[],o=t.primaryWeakness?[t.primaryWeakness]:[];return{status:"ready",headline:t.overallScore>=70?"Good job — keep it up!":"Let's build your foundation",summary:o.length>0?`Focus on strengthening ${o[0]} to improve your overall performance.`:"Keep practicing to maintain and expand your skills.",strengths:l,weaknesses:o,recommendation:t.suggestedModule?`Start with the ${t.suggestedModule} module.`:"Continue with your personalized learning path.",latestAssessmentId:"",latestScorePercent:t.overallScore||0,latestRiskLevel:t.overallScore>=70?"Low":t.overallScore>=50?"Moderate":"High",updatedAt:t.updatedAt?.toDate?.()||new Date}}const r=await A(w(v(b,"assessments",s,"attempts"),k("completedAt","desc"),N(1))).catch(()=>null);if(r&&!r.empty){const t=r.docs[0].data(),l=t.rawScore||t.overallScorePercent||0,o=t.proficiencyProfile;return{status:"ready",headline:l>=70?"Good job — keep it up!":"Let's build your foundation",summary:o?.weaknesses?.length>0?`Focus on strengthening ${o.weaknesses[0]} to improve.`:l>=70?"You have a solid foundation!":"With practice, you'll build confidence.",strengths:o?.strengths||[],weaknesses:o?.weaknesses||[],recommendation:o?.suggestedStartingModule?`Start with ${o.suggestedStartingModule}.`:"Follow your personalized learning path.",latestAssessmentId:t.assessmentId||"",latestScorePercent:l,latestRiskLevel:l>=70?"Low":l>=50?"Moderate":"High",updatedAt:t.completedAt?.toDate?.()||new Date}}const c=await L(C(b,"diagnosticResults",s)).catch(()=>null);if(c?.exists()){const t=c.data(),l=t.overallScorePercent||t.overall_score_percent||0,o=t.riskProfile?.weak_domains||[];return{status:"ready",headline:l>=70?"Good job — keep it up!":"Let's build your foundation",summary:o.length>0?`Areas to focus on: ${o.join(", ")}.`:"Assessment completed. Follow your learning path.",strengths:[],weaknesses:o,recommendation:t.recommended_intervention||"Continue with your personalized learning path.",latestAssessmentId:"",latestScorePercent:l,latestRiskLevel:t.overall_risk||(l>=70?"Low":"Moderate"),updatedAt:t.completedAt?.toDate?.()||new Date}}const i=await A(w(v(b,"users",s,"assessments"),k("completedAt","desc"),N(5))).catch(()=>null);if(i&&!i.empty){const t=i.docs.map(p=>p.data()),l=t[0],o=l.score||l.scorePercent||0,x=t.length,j=Math.round(t.reduce((p,u)=>p+(u.score||u.scorePercent||0),0)/x);return{status:"ready",headline:o>=70?"Good job — keep it up!":"Let's build your foundation",summary:`You've completed ${x} diagnostic assessment${x>1?"s":""}. Your latest score is ${o}% (average: ${j}%).`,strengths:[],weaknesses:l.risk==="At Risk"||l.risk==="High"?[l.subject||"General Mathematics"]:[],recommendation:"Continue with your personalized learning path to strengthen weak areas.",latestAssessmentId:l.testId||"",latestScorePercent:o,latestRiskLevel:l.risk||(o>=70?"Low":o>=50?"Moderate":"High"),updatedAt:l.completedAt?.toDate?.()||new Date}}const n=await L(C(b,"users",s)).catch(()=>null);if(n?.exists()){const t=n.data();if(t.initialAssessmentCompleted||t.hasCompletedInitialAssessment){const l=t.atRiskSubjects||[];return{status:"ready",headline:"Assessment Complete! ✓",summary:l.length>0?`Areas to focus on: ${l.join(", ")}. Follow your personalized learning path to improve.`:"Your diagnostic assessment is complete. Your personalized learning path is ready.",strengths:[],weaknesses:l,recommendation:"Continue with your recommended lessons to strengthen your skills.",latestAssessmentId:"",latestScorePercent:0,latestRiskLevel:l.length>0?"Moderate":"Low",updatedAt:t.assessmentCompletedAt?.toDate?.()||new Date}}}return null}const me=({isOpen:s,onClose:a,studentId:r,latestResult:c,heroBannerSummary:i})=>{const[n,t]=m.useState("latest"),[l,o]=m.useState(c||null),[x,j]=m.useState([]),[p,u]=m.useState(!1),[g,y]=m.useState(null);m.useEffect(()=>{if(s&&r&&!i){const d=M(r,h=>{y(h)});return()=>d()}},[s,r,i]);const $=i||g;m.useEffect(()=>{s&&r&&(u(!0),(async()=>{try{const[h,T]=await Promise.all([c?Promise.resolve(c):le(r),re(r)]);if(o(h),j(T),!i&&!g){const D=await E(r);if(D)y(D);else{const P=await ce(r);P&&y(P)}}}catch(h){console.error("[AssessmentResultsModal] fetch error:",h)}finally{u(!1)}})())},[s,r,c]);const B=[{key:"latest",label:"Last Results",icon:e.jsx(G,{className:"w-4 h-4"})},{key:"history",label:"History & Trends",icon:e.jsx(R,{className:"w-4 h-4"})}];return e.jsx(W,{open:s,onOpenChange:d=>!d&&a(),children:e.jsxs(q,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0 bg-white rounded-2xl shadow-2xl border-0",children:[e.jsxs("div",{className:"sticky top-0 z-10 bg-white border-b border-slate-200 rounded-t-2xl px-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:"Assessment Results"}),e.jsx("button",{onClick:a,className:"p-1.5 rounded-lg hover:bg-slate-100 transition-colors",children:e.jsx(ee,{className:"w-5 h-5 text-slate-400"})})]}),e.jsx("div",{className:"flex gap-1 bg-slate-100 p-1 rounded-lg",children:B.map(d=>e.jsxs("button",{onClick:()=>t(d.key),className:`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all ${n===d.key?"bg-white text-sky-600 shadow-sm":"text-slate-600 hover:text-slate-800"}`,children:[d.icon,d.label]},d.key))})]}),e.jsx("div",{className:"px-6 py-5",children:e.jsxs(_,{mode:"wait",children:[n==="latest"&&e.jsx(f.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},children:e.jsx(de,{heroBannerSummary:$,latestResult:l,loading:p})},"latest"),n==="history"&&e.jsxs(f.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},children:[e.jsx(ae,{history:x}),x.length>0&&e.jsxs("div",{className:"mt-6 space-y-2",children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:"All Attempts"}),x.map((d,h)=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 rounded-lg",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["Attempt ",x.length-h]}),e.jsx("p",{className:"text-xs text-slate-500",children:new Date(d.completedAt).toLocaleDateString()})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-semibold text-sky-600",children:[d.percentage,"%"]}),e.jsx("p",{className:"text-xs text-slate-500",children:d.proficiencyLevel})]})]},h))]})]},"history")]})})]})})},xe=m.lazy(()=>Q(()=>import("./DashboardAvatar-D5djDQQ1.js"),__vite__mapDeps([0,1,2]))),Ce=({userName:s="Student",userLevel:a=1,avatarLayers:r,onContinueLearning:c,showAssessmentTooltip:i,onOpenAssessment:n,studentId:t,assessmentCompleted:l=!1})=>{const[o,x]=m.useState(!1),[j,p]=m.useState(null);m.useEffect(()=>{if(!o||!t)return;const g=M(t,y=>{p(y)});return()=>g()},[o,t]),m.useEffect(()=>{o||p(null)},[o]);const u=()=>{const g=new Date().getHours();return g<12?"Good Morning":g<18?"Good Afternoon":"Good Evening"};return e.jsxs(f.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.6,ease:[.22,1,.36,1]},className:"relative w-full mt-0 rounded-2xl md:rounded-[2rem] p-5 md:p-6 lg:p-8 bg-gradient-to-br from-white via-sky-50/50 to-white border border-slate-200/80 card-elevated-lg",children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-2xl md:rounded-[2rem] pointer-events-none",children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-sky-400/50 to-transparent"}),e.jsx("div",{className:"absolute top-0 right-0 w-96 h-96 bg-sky-100/40 rounded-full blur-3xl -translate-y-1/2 translate-x-1/4"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-64 h-64 bg-rose-100/30 rounded-full blur-3xl translate-y-1/2 -translate-x-1/4"}),e.jsx("div",{className:"absolute inset-0 bg-dot-pattern opacity-40"})]}),e.jsx("div",{className:"relative z-10 flex flex-col md:flex-row min-h-[140px] lg:min-h-[160px] items-start md:items-center justify-between gap-4 md:gap-6 pb-0",children:e.jsxs("div",{className:"flex-1 w-full md:w-auto min-w-0 pr-0 md:pr-40 lg:pr-[280px] pb-2 md:pb-0 py-1",children:[e.jsxs("div",{className:"flex flex-wrap md:flex-nowrap items-center gap-2 mb-3 md:mb-2",children:[e.jsx("div",{className:"px-3 md:px-4 py-1.5 rounded-full bg-sky-100 border border-sky-200",children:e.jsxs("span",{className:"text-xs md:text-sm font-body font-bold text-sky-700",children:["Level ",a]})}),e.jsxs("div",{className:"px-3 md:px-4 py-1.5 rounded-full bg-rose-50 border border-rose-200",children:[e.jsx(Y,{size:14,className:"inline -mt-0.5 text-rose-500 mr-1"}),e.jsx("span",{className:"text-xs md:text-sm font-body font-bold text-rose-700",children:"Active"})]})]}),e.jsxs("h1",{className:"text-2xl md:text-2xl lg:text-3xl font-display font-black text-[#0a1628] mb-1.5 tracking-tight leading-[1.1]",children:[u(),", ",s,"!"]}),e.jsx("p",{className:"text-slate-500 mb-2 md:mb-1 text-sm md:text-sm font-body font-bold pr-[155px] md:pr-0",children:"Today is a great day to move one step forward in math mastery."}),e.jsx("p",{className:"text-xs md:text-xs text-slate-400 font-body mb-5 md:mb-4 pr-[150px] md:pr-0",children:"Focus on your next recommended lesson and keep your momentum."}),e.jsxs(f.button,{onClick:c,whileHover:{scale:1.03},whileTap:{scale:.97},className:"mt-2 md:mt-2 bg-gradient-to-r from-purple-600 to-[#9956DE] text-white px-5 py-3 md:py-2 rounded-xl font-body font-bold text-base md:text-sm shadow-lg shadow-purple-500/20 hover:shadow-purple-500/30 transition-all flex justify-center md:justify-start items-center gap-2 group w-auto md:w-auto",children:["Continue Learning",e.jsx(F,{size:14,className:"group-hover:translate-x-1 transition-transform"})]})]})}),i&&e.jsx(f.div,{initial:{opacity:0,scale:.9,x:10},animate:{opacity:1,scale:1,x:0},transition:{delay:.5,type:"spring"},onClick:n,className:"absolute hidden md:block right-[150px] lg:right-[250px] bottom-16 lg:bottom-20 z-30 cursor-pointer drop-shadow-lg group",children:e.jsxs("div",{className:"bg-white px-4 py-3 rounded-2xl rounded-br-sm border-2 border-amber-300 relative transition-all group-hover:bg-amber-50 group-hover:border-amber-400 group-hover:-translate-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-amber-500",children:e.jsx(S,{size:16})}),e.jsxs("p",{className:"text-xs lg:text-sm font-bold text-amber-900 leading-tight",children:["Don't forget to take the",e.jsx("br",{}),"Initial Assessment!"]})]}),e.jsx("div",{className:"absolute -right-2 bottom-0 w-4 h-4 bg-white border-2 border-transparent border-r-amber-300 border-b-amber-300 rotate-45 group-hover:bg-amber-50 group-hover:border-r-amber-400 group-hover:border-b-amber-400 transition-colors"})]})}),l&&!i&&e.jsx(f.div,{initial:{opacity:0,scale:.9,x:10},animate:{opacity:1,scale:1,x:0},transition:{delay:.5,type:"spring"},onClick:()=>window.dispatchEvent(new CustomEvent("mathpulse:navigate",{detail:{tab:"Grades"}})),className:"absolute hidden md:block right-[150px] lg:right-[250px] bottom-16 lg:bottom-20 z-30 cursor-pointer drop-shadow-lg group",children:e.jsxs("div",{className:"bg-white px-4 py-3 rounded-2xl rounded-br-sm border-2 border-teal-300 relative transition-all group-hover:bg-teal-50 group-hover:border-teal-400 group-hover:-translate-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 bg-teal-100 rounded-full flex items-center justify-center shrink-0",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"text-teal-600",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsxs("p",{className:"text-xs lg:text-sm font-bold text-teal-900 leading-tight",children:["Assessment Complete!",e.jsx("br",{}),e.jsx("span",{className:"text-[10px] lg:text-[11px] font-normal text-teal-700",children:"View results & history"})]})]}),e.jsx("div",{className:"absolute -right-2 bottom-0 w-4 h-4 bg-white border-2 border-transparent border-r-teal-300 border-b-teal-300 rotate-45 group-hover:bg-teal-50 group-hover:border-r-teal-400 group-hover:border-b-teal-400 transition-colors"})]})}),o&&t&&e.jsx(me,{isOpen:o,onClose:()=>x(!1),studentId:t,heroBannerSummary:j}),e.jsx("div",{className:"absolute right-0 bottom-0 lg:right-10 w-[160px] md:w-[150px] lg:w-[270px] pointer-events-none z-20",style:{clipPath:"inset(-100% -50% 0 -50%)"},children:e.jsx("div",{className:"relative w-full aspect-[4/5] translate-y-[10%] md:translate-y-[21%] lg:translate-y-[19%] drop-shadow-2xl",children:e.jsx(m.Suspense,{fallback:e.jsx("div",{className:"w-full h-full scale-[1.15] md:scale-[1.25] lg:scale-[1.3] origin-bottom"}),children:e.jsx(xe,{layers:r,className:"w-full h-full scale-[1.35] md:scale-[1.25] lg:scale-[1.3] origin-bottom"})})})})]})};export{Ce as default}; diff --git a/assets/InitialAssessmentModal-Cri1vHPb.js b/assets/InitialAssessmentModal-DdNBSpH9.js similarity index 94% rename from assets/InitialAssessmentModal-Cri1vHPb.js rename to assets/InitialAssessmentModal-DdNBSpH9.js index 480088d5b9bca00c4b25d835608efe2ba98e6682..6d212a87cbe30a2bb6dab7f1754a44e328bb6987 100644 --- a/assets/InitialAssessmentModal-Cri1vHPb.js +++ b/assets/InitialAssessmentModal-DdNBSpH9.js @@ -1 +1 @@ -import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{B as j}from"./button-Bfg1pO9T.js";import{g as y}from"./diagnosticService-BvH8S98K.js";import{updateDoc as N,doc as v,serverTimestamp as w}from"./vendor-firebase-firestore-CNv3xXal.js";import{m as o,B as k,y as C,q as L,g as z}from"./index-BvEKrMkD.js";import{X as S}from"./x-BYtx1i07.js";import{C as A}from"./circle-check-big-mtMsU82c.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";const H=({isOpen:n,onClose:d,onDismiss:m,userId:c,strand:x,gradeLevel:p,onAssessmentStart:u,onAssessmentComplete:I})=>{const[t,a]=l.useState(!1),[r,i]=l.useState(null),h=async()=>{a(!0),i(null);try{const s=await y(x,p);sessionStorage.setItem("mathpulse_diagnostic",JSON.stringify({testId:s.test_id,questions:s.questions,totalItems:s.total_items,estimatedMinutes:s.estimated_minutes})),u(s.test_id,s.questions)}catch(s){const b=s instanceof Error?s.message:"Failed to load assessment";i(b),a(!1)}},f=()=>{sessionStorage.setItem("mathpulse_iar_session_dismissed","true"),d()},g=async()=>{try{await N(v(z,"users",c),{assessmentDismissed:!0,assessmentDismissedAt:w()})}catch(s){console.error("[diagnostic] Failed to save dismiss state:",s)}m()};return n?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onClick:s=>s.stopPropagation(),children:e.jsxs(o.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{type:"spring",damping:25,stiffness:200},className:"bg-white rounded-2xl shadow-2xl max-w-[44rem] w-full flex flex-col overflow-hidden pointer-events-auto",onClick:s=>s.stopPropagation(),style:{willChange:"transform, opacity"},children:[e.jsxs("div",{className:"px-5 py-3 border-b border-[#dde3eb] flex items-center justify-between bg-[#edf1f7] flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center text-purple-600",children:e.jsx(k,{size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-bold text-[#0a1628] leading-tight",children:"Initial Assessment"}),e.jsx("p",{className:"text-[11px] text-[#5a6578]",children:"Analyze your strengths & weaknesses"})]})]}),e.jsx("button",{onClick:f,"aria-label":"Close assessment modal",className:"ml-auto w-8 h-8 rounded-lg flex items-center justify-center text-[#5a6578] hover:bg-[#dde3eb] hover:text-[#0a1628] transition-colors",children:e.jsx(S,{size:18})})]}),e.jsx("div",{className:"p-5 text-center space-y-3",children:e.jsxs(o.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},transition:{duration:.3,ease:"easeOut"},children:[e.jsx("div",{className:"w-20 h-20 bg-purple-50 rounded-full flex items-center justify-center mx-auto mb-3",children:e.jsx("svg",{className:"w-9 h-9 text-purple-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 00-2.455 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z"})})}),e.jsx("h3",{className:"text-lg font-bold text-[#0a1628]",children:"Welcome to MathPulse AI!"}),e.jsx("p",{className:"text-[13px] text-[#5a6578] max-w-[24rem] mx-auto leading-relaxed",children:"To personalize your learning path, complete a DepEd competency-based SHS diagnostic (15 items, around 11.6 minutes)."}),e.jsxs("div",{className:"grid grid-cols-2 gap-2.5 max-w-[28rem] mx-auto text-left mt-4",children:[e.jsxs("div",{className:"bg-[#edf1f7] p-2.5 rounded-lg border border-[#dde3eb]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-[13px] text-[#0a1628] mb-1",children:[e.jsx(A,{size:14,className:"text-teal-500"}),"Personalized Path"]}),e.jsx("p",{className:"text-[10px] text-[#5a6578] pl-[18px]",children:"Get recommendations based on your level."})]}),e.jsxs("div",{className:"bg-[#edf1f7] p-2.5 rounded-lg border border-[#dde3eb]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-[13px] text-[#0a1628] mb-1",children:[e.jsx(C,{size:14,className:"text-rose-500"}),"Identify Risks"]}),e.jsx("p",{className:"text-[10px] text-[#5a6578] pl-[18px]",children:"Spot areas that need more attention early."})]})]}),r&&e.jsx("div",{className:"mt-3 p-2.5 bg-red-50 border border-red-200 rounded-lg",children:e.jsx("p",{className:"text-xs text-red-700",children:r})}),e.jsxs("div",{className:"pt-3 space-y-2.5",children:[e.jsx(j,{onClick:h,disabled:t,className:"bg-gradient-to-r from-purple-600 to-purple-500 hover:from-purple-700 hover:to-purple-600 text-white px-5 py-3 rounded-xl text-sm font-bold shadow-lg shadow-purple-200 w-full max-w-[380px] mx-auto",children:t?e.jsxs(e.Fragment,{children:[e.jsx(L,{size:16,className:"animate-spin mr-2"}),"Crafting your assessment..."]}):"Start Assessment"}),t&&e.jsx("p",{className:"text-[10px] text-slate-400 max-w-[24rem] mx-auto text-center leading-relaxed",children:"This may take up to 90 seconds while AI generates your personalized test."}),!t&&e.jsx("button",{onClick:g,disabled:t,className:"block mx-auto text-xs text-slate-500 hover:text-[#5a6578] transition-colors font-medium disabled:opacity-40",children:"Skip for now"})]})]})})]})}):null};export{H as default}; +import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{B as j}from"./button-BbJLXpfi.js";import{g as y}from"./diagnosticService-DmVYM_3F.js";import{updateDoc as N,doc as v,serverTimestamp as w}from"./vendor-firebase-firestore-CNv3xXal.js";import{m as o,B as k,y as C,q as L,g as z}from"./index-BdLfAeGL.js";import{X as S}from"./x-BLhsirCD.js";import{C as A}from"./circle-check-big-B54zXy3k.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";const H=({isOpen:n,onClose:d,onDismiss:m,userId:c,strand:x,gradeLevel:p,onAssessmentStart:u,onAssessmentComplete:I})=>{const[t,a]=l.useState(!1),[r,i]=l.useState(null),h=async()=>{a(!0),i(null);try{const s=await y(x,p);sessionStorage.setItem("mathpulse_diagnostic",JSON.stringify({testId:s.test_id,questions:s.questions,totalItems:s.total_items,estimatedMinutes:s.estimated_minutes})),u(s.test_id,s.questions)}catch(s){const b=s instanceof Error?s.message:"Failed to load assessment";i(b),a(!1)}},f=()=>{sessionStorage.setItem("mathpulse_iar_session_dismissed","true"),d()},g=async()=>{try{await N(v(z,"users",c),{assessmentDismissed:!0,assessmentDismissedAt:w()})}catch(s){console.error("[diagnostic] Failed to save dismiss state:",s)}m()};return n?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onClick:s=>s.stopPropagation(),children:e.jsxs(o.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{type:"spring",damping:25,stiffness:200},className:"bg-white rounded-2xl shadow-2xl max-w-[44rem] w-full flex flex-col overflow-hidden pointer-events-auto",onClick:s=>s.stopPropagation(),style:{willChange:"transform, opacity"},children:[e.jsxs("div",{className:"px-5 py-3 border-b border-[#dde3eb] flex items-center justify-between bg-[#edf1f7] flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center text-purple-600",children:e.jsx(k,{size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-bold text-[#0a1628] leading-tight",children:"Initial Assessment"}),e.jsx("p",{className:"text-[11px] text-[#5a6578]",children:"Analyze your strengths & weaknesses"})]})]}),e.jsx("button",{onClick:f,"aria-label":"Close assessment modal",className:"ml-auto w-8 h-8 rounded-lg flex items-center justify-center text-[#5a6578] hover:bg-[#dde3eb] hover:text-[#0a1628] transition-colors",children:e.jsx(S,{size:18})})]}),e.jsx("div",{className:"p-5 text-center space-y-3",children:e.jsxs(o.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},transition:{duration:.3,ease:"easeOut"},children:[e.jsx("div",{className:"w-20 h-20 bg-purple-50 rounded-full flex items-center justify-center mx-auto mb-3",children:e.jsx("svg",{className:"w-9 h-9 text-purple-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 00-2.455 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z"})})}),e.jsx("h3",{className:"text-lg font-bold text-[#0a1628]",children:"Welcome to MathPulse AI!"}),e.jsx("p",{className:"text-[13px] text-[#5a6578] max-w-[24rem] mx-auto leading-relaxed",children:"To personalize your learning path, complete a DepEd competency-based SHS diagnostic (15 items, around 11.6 minutes)."}),e.jsxs("div",{className:"grid grid-cols-2 gap-2.5 max-w-[28rem] mx-auto text-left mt-4",children:[e.jsxs("div",{className:"bg-[#edf1f7] p-2.5 rounded-lg border border-[#dde3eb]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-[13px] text-[#0a1628] mb-1",children:[e.jsx(A,{size:14,className:"text-teal-500"}),"Personalized Path"]}),e.jsx("p",{className:"text-[10px] text-[#5a6578] pl-[18px]",children:"Get recommendations based on your level."})]}),e.jsxs("div",{className:"bg-[#edf1f7] p-2.5 rounded-lg border border-[#dde3eb]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-[13px] text-[#0a1628] mb-1",children:[e.jsx(C,{size:14,className:"text-rose-500"}),"Identify Risks"]}),e.jsx("p",{className:"text-[10px] text-[#5a6578] pl-[18px]",children:"Spot areas that need more attention early."})]})]}),r&&e.jsx("div",{className:"mt-3 p-2.5 bg-red-50 border border-red-200 rounded-lg",children:e.jsx("p",{className:"text-xs text-red-700",children:r})}),e.jsxs("div",{className:"pt-3 space-y-2.5",children:[e.jsx(j,{onClick:h,disabled:t,className:"bg-gradient-to-r from-purple-600 to-purple-500 hover:from-purple-700 hover:to-purple-600 text-white px-5 py-3 rounded-xl text-sm font-bold shadow-lg shadow-purple-200 w-full max-w-[380px] mx-auto",children:t?e.jsxs(e.Fragment,{children:[e.jsx(L,{size:16,className:"animate-spin mr-2"}),"Crafting your assessment..."]}):"Start Assessment"}),t&&e.jsx("p",{className:"text-[10px] text-slate-400 max-w-[24rem] mx-auto text-center leading-relaxed",children:"This may take up to 90 seconds while AI generates your personalized test."}),!t&&e.jsx("button",{onClick:g,disabled:t,className:"block mx-auto text-xs text-slate-500 hover:text-[#5a6578] transition-colors font-medium disabled:opacity-40",children:"Skip for now"})]})]})})]})}):null};export{H as default}; diff --git a/assets/LeaderboardPage-GVWLWArd.js b/assets/LeaderboardPage-C7BC2ZU8.js similarity index 99% rename from assets/LeaderboardPage-GVWLWArd.js rename to assets/LeaderboardPage-C7BC2ZU8.js index cfea1faa63c43906d8195bec1c948876cb04771f..36740a2c1e1fba964fc800b3558833cd8108ae2a 100644 --- a/assets/LeaderboardPage-GVWLWArd.js +++ b/assets/LeaderboardPage-C7BC2ZU8.js @@ -1,3 +1,3 @@ -import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{aK as O,h as W,m as n,b as y,r as P,A as k,F as m,T as E,q as _,a6 as T,a7 as q,$ as H,u as U,aL as $,R as K,L as G,D as X}from"./index-BvEKrMkD.js";import{X as Q}from"./x-BYtx1i07.js";import{C as V}from"./clock-0vnF72R6.js";import{B as J}from"./badge-check-Dir1sWA0.js";import{u as Z}from"./useFeatureAccess-BTg5PL53.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const ee=({student:s,onClose:f})=>{const[i,u]=l.useState([]),[p,h]=l.useState(!1);if(l.useEffect(()=>{s?.uid&&(h(!0),O(s.uid).then(u).catch(d=>console.error("Failed to load achievements:",d)).finally(()=>h(!1)))},[s?.uid]),!s)return null;const j={trophy:e.jsx(m,{size:24,className:"text-rose-500"}),flame:e.jsx(H,{size:24,className:"text-orange-500"}),star:e.jsx(q,{size:24,className:"text-rose-400"}),"book-open":e.jsx(y,{size:24,className:"text-sky-600"}),"badge-check":e.jsx(J,{size:24,className:"text-emerald-600"}),crown:e.jsx(T,{size:24,className:"text-rose-500"}),target:e.jsx(P,{size:24,className:"text-rose-500"})};return e.jsx(W,{children:e.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4",children:[e.jsx(n.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:f,className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(n.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},className:"relative bg-[#f7f9fc] rounded-2xl shadow-2xl border border-[#dde3eb] w-full max-w-2xl max-h-[90vh] overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-sky-600 to-sky-500 p-8 text-white relative overflow-hidden",children:[e.jsx("div",{className:"accent-line absolute top-0 left-0 right-0"}),e.jsx("button",{onClick:f,className:"absolute top-4 right-4 p-2 hover:bg-slate-100 rounded-xl transition-colors z-10",children:e.jsx(Q,{size:20})}),e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-start gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-24 h-24 bg-white/10 backdrop-blur-sm rounded-2xl flex items-center justify-center text-6xl border border-slate-300",children:s.avatar}),s.isOnline&&e.jsx("div",{className:"absolute -bottom-2 -right-2 w-6 h-6 bg-green-500 rounded-full border-4 border-white"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-3xl font-display font-bold mb-2",children:s.name}),e.jsx("p",{className:"text-slate-500 mb-4",children:s.section}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"bg-slate-100 backdrop-blur-sm rounded-xl px-4 py-2 border border-slate-200",children:[e.jsx("p",{className:"text-xs text-slate-500",children:"Level"}),e.jsx("p",{className:"text-xl font-bold",children:s.level})]}),e.jsxs("div",{className:"bg-slate-100 backdrop-blur-sm rounded-xl px-4 py-2 border border-slate-200",children:[e.jsx("p",{className:"text-xs text-slate-500",children:"Total XP"}),e.jsx("p",{className:"text-xl font-bold",children:s.totalXP})]})]})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-sky-500/5 rounded-full -translate-y-1/2 translate-x-1/2"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-48 h-48 bg-rose-500/5 rounded-full translate-y-1/2 -translate-x-1/2"})]}),e.jsxs("div",{className:"p-6 overflow-y-auto max-h-[calc(90vh-320px)]",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Performance Stats"}),e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(y,{size:24,className:"text-sky-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-[#0a1628]",children:s.stats.quizzesCompleted}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Quizzes"})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(P,{size:24,className:"text-emerald-600 mx-auto mb-2"}),e.jsxs("p",{className:"text-2xl font-bold text-[#0a1628]",children:[s.stats.averageScore,"%"]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Avg Score"})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(k,{size:24,className:"text-rose-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-[#0a1628]",children:s.stats.modulesCompleted}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Modules"})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(V,{size:24,className:"text-rose-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-[#0a1628]",children:s.stats.studyHours}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Hours"})]})]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Rankings"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-rose-50 border border-rose-200 rounded-xl p-4",children:[e.jsx(m,{size:20,className:"text-rose-600 mb-2"}),e.jsxs("p",{className:"text-2xl font-bold text-rose-900",children:["#",s.rank.global]}),e.jsx("p",{className:"text-xs text-rose-700 mt-1 font-body",children:"School"})]}),e.jsxs("div",{className:"bg-sky-50 border border-sky-200 rounded-xl p-4",children:[e.jsx(m,{size:20,className:"text-sky-600 mb-2"}),e.jsxs("p",{className:"text-2xl font-bold text-sky-900",children:["#",s.rank.section]}),e.jsx("p",{className:"text-xs text-sky-700 mt-1 font-body",children:"Section"})]}),e.jsxs("div",{className:"bg-rose-50 border border-rose-200 rounded-xl p-4",children:[e.jsx(m,{size:20,className:"text-rose-600 mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-rose-900",children:s.rank.change>0?e.jsxs("span",{className:"flex items-center gap-1 text-emerald-600",children:[e.jsx(E,{size:20}),"+",s.rank.change]}):s.rank.change<0?e.jsxs("span",{className:"flex items-center gap-1 text-red-600",children:[e.jsx(E,{size:20,className:"rotate-180"}),s.rank.change]}):"0"}),e.jsx("p",{className:"text-xs text-rose-700 mt-1 font-body",children:"This Week"})]})]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Achievements"}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(_,{size:24,className:"text-sky-500 animate-spin"})}):i.length>0?e.jsx("div",{className:"grid grid-cols-3 gap-3",children:i.map(d=>e.jsxs("div",{className:"rounded-xl p-4 text-center transition-all bg-white border-2 border-sky-200",children:[e.jsx("div",{className:"text-3xl mb-2",children:j[d.icon]||e.jsx(k,{size:24,className:"text-slate-500 mx-auto"})}),e.jsx("p",{className:"font-bold text-xs text-[#0a1628] mb-1 font-body",children:d.title}),e.jsx("p",{className:"text-xs text-[#5a6578]",children:d.description})]},d.id))}):e.jsxs("div",{className:"flex flex-col items-center py-8 gap-2",children:[e.jsx(k,{size:32,className:"text-[#d1cec6]"}),e.jsx("p",{className:"text-sm text-[#5a6578] font-body",children:"No achievements unlocked yet"})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Recent Activity"}),e.jsxs("div",{className:"flex flex-col items-center py-8 gap-2",children:[e.jsx(y,{size:32,className:"text-[#d1cec6]"}),e.jsx("p",{className:"text-sm text-[#5a6578] font-body",children:"Activity history coming soon"})]})]})]})]})]})})},fe=({currentUserPhoto:s,onBack:f})=>{const{currentUser:i,userProfile:u}=U(),p=u,{leaderboard:h,loading:j}=Z(i?.uid||null),[d]=l.useState("section"),[g,I]=l.useState("weekly"),[M,z]=l.useState(null),[D,v]=l.useState(!0),[F,S]=l.useState(null),[R,C]=l.useState([]),w=[p?.grade,p?.section].filter(Boolean).join(" - "),N=l.useCallback(async()=>{if(!i){v(!1);return}v(!0),S(null);try{const t=g==="all"?"all":"week",r=await $(i.uid,!1,t,20);if(!r||r.length===0){C([]);return}const x=r.map(a=>({id:a.userId,uid:a.userId,name:a.name,avatar:a.userId===i.uid?s||a.photo||"":a.photo||"",level:a.level,totalXP:a.xp,section:w||"Grade 11 - STEM A",rank:{global:a.rank,section:a.rank,change:0},stats:{quizzesCompleted:0,averageScore:0,modulesCompleted:0,studyHours:0},isOnline:!1,isYou:a.userId===i.uid}));C(x)}catch(t){console.error("Error loading leaderboard:",t),S(t instanceof Error?t.message:"Failed to load leaderboard")}finally{v(!1)}},[i,w,g,s]);l.useEffect(()=>{N()},[N]);const c=(()=>{let t=R;if(d==="section"){const x=w||"";x&&(t=t.filter(a=>a.section===x))}return t.sort((x,a)=>{const B=d==="section"?"section":"global";return(x.rank[B]||999)-(a.rank[B]||999)})})(),A=c.find(t=>t.isYou)?.rank.section||c.length+1,Y=c.length>1?Math.max(10,Math.min(99,100-A/Math.max(1,c.length)*100)):90,o=c.slice(0,3),L=c.slice(3),b=(t,r)=>t?t.startsWith("http")||t.startsWith("data:")?e.jsx("img",{src:t,alt:"Avatar",className:"w-full h-full object-cover rounded-full"}):e.jsx(X,{size:r,className:"text-slate-400 opacity-70"}):e.jsx(X,{size:r,className:"text-slate-400 opacity-70"});return D?e.jsxs("div",{className:"flex flex-col justify-center items-center h-[500px] gap-3",children:[e.jsx(_,{className:"w-8 h-8 animate-spin text-purple-600"}),e.jsx("p",{className:"text-sm text-slate-400 font-medium",children:"Loading leaderboard..."})]}):F?e.jsxs("div",{className:"flex flex-col justify-center items-center h-[500px] gap-4",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(m,{className:"w-7 h-7 text-red-400"})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 mb-1",children:"Couldn't load leaderboard"}),e.jsx("p",{className:"text-xs text-slate-400",children:F})]}),e.jsxs("button",{onClick:N,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 text-white text-sm font-medium rounded-xl hover:bg-purple-700 transition-colors",children:[e.jsx(K,{size:14}),"Try Again"]})]}):j?e.jsxs("div",{className:"flex flex-col justify-center items-center h-[500px] gap-3",children:[e.jsx(_,{className:"w-8 h-8 animate-spin text-purple-600"}),e.jsx("p",{className:"text-sm text-slate-400 font-medium",children:"Loading..."})]}):h?e.jsxs("div",{className:"w-full min-h-screen relative flex flex-col items-center font-body text-white",children:[e.jsxs("div",{className:"absolute inset-x-[-20px] top-0 h-[100vh] min-h-[800px] z-[-1] pointer-events-none overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_50%_100%,#9333ea_0%,#c084fc_40%,transparent_80%)]"}),e.jsx("div",{className:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[250vw] md:w-[200vw] h-[150vh] opacity-75 pointer-events-none",style:{WebkitMaskImage:"radial-gradient(circle at 50% 100%, black 10%, transparent 60%)"},children:e.jsx(n.div,{className:"absolute bottom-0 left-1/2 w-[600vw] h-[600vw] md:w-[400vw] md:h-[400vw]",style:{x:"-50%",y:"50%",originX:.5,originY:.5,background:`repeating-conic-gradient(from 0deg at 50% 50%, +import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{aK as O,h as W,m as n,b as y,r as P,A as k,F as m,T as E,q as _,a6 as T,a7 as q,$ as H,u as U,aL as $,R as K,L as G,D as X}from"./index-BdLfAeGL.js";import{X as Q}from"./x-BLhsirCD.js";import{C as V}from"./clock-CpBwkoND.js";import{B as J}from"./badge-check-4jI3r8US.js";import{u as Z}from"./useFeatureAccess-BGJy4XRW.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const ee=({student:s,onClose:f})=>{const[i,u]=l.useState([]),[p,h]=l.useState(!1);if(l.useEffect(()=>{s?.uid&&(h(!0),O(s.uid).then(u).catch(d=>console.error("Failed to load achievements:",d)).finally(()=>h(!1)))},[s?.uid]),!s)return null;const j={trophy:e.jsx(m,{size:24,className:"text-rose-500"}),flame:e.jsx(H,{size:24,className:"text-orange-500"}),star:e.jsx(q,{size:24,className:"text-rose-400"}),"book-open":e.jsx(y,{size:24,className:"text-sky-600"}),"badge-check":e.jsx(J,{size:24,className:"text-emerald-600"}),crown:e.jsx(T,{size:24,className:"text-rose-500"}),target:e.jsx(P,{size:24,className:"text-rose-500"})};return e.jsx(W,{children:e.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4",children:[e.jsx(n.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:f,className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(n.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},className:"relative bg-[#f7f9fc] rounded-2xl shadow-2xl border border-[#dde3eb] w-full max-w-2xl max-h-[90vh] overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-sky-600 to-sky-500 p-8 text-white relative overflow-hidden",children:[e.jsx("div",{className:"accent-line absolute top-0 left-0 right-0"}),e.jsx("button",{onClick:f,className:"absolute top-4 right-4 p-2 hover:bg-slate-100 rounded-xl transition-colors z-10",children:e.jsx(Q,{size:20})}),e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-start gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-24 h-24 bg-white/10 backdrop-blur-sm rounded-2xl flex items-center justify-center text-6xl border border-slate-300",children:s.avatar}),s.isOnline&&e.jsx("div",{className:"absolute -bottom-2 -right-2 w-6 h-6 bg-green-500 rounded-full border-4 border-white"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-3xl font-display font-bold mb-2",children:s.name}),e.jsx("p",{className:"text-slate-500 mb-4",children:s.section}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"bg-slate-100 backdrop-blur-sm rounded-xl px-4 py-2 border border-slate-200",children:[e.jsx("p",{className:"text-xs text-slate-500",children:"Level"}),e.jsx("p",{className:"text-xl font-bold",children:s.level})]}),e.jsxs("div",{className:"bg-slate-100 backdrop-blur-sm rounded-xl px-4 py-2 border border-slate-200",children:[e.jsx("p",{className:"text-xs text-slate-500",children:"Total XP"}),e.jsx("p",{className:"text-xl font-bold",children:s.totalXP})]})]})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-sky-500/5 rounded-full -translate-y-1/2 translate-x-1/2"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-48 h-48 bg-rose-500/5 rounded-full translate-y-1/2 -translate-x-1/2"})]}),e.jsxs("div",{className:"p-6 overflow-y-auto max-h-[calc(90vh-320px)]",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Performance Stats"}),e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(y,{size:24,className:"text-sky-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-[#0a1628]",children:s.stats.quizzesCompleted}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Quizzes"})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(P,{size:24,className:"text-emerald-600 mx-auto mb-2"}),e.jsxs("p",{className:"text-2xl font-bold text-[#0a1628]",children:[s.stats.averageScore,"%"]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Avg Score"})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(k,{size:24,className:"text-rose-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-[#0a1628]",children:s.stats.modulesCompleted}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Modules"})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-[#dde3eb] p-4 text-center",children:[e.jsx(V,{size:24,className:"text-rose-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-[#0a1628]",children:s.stats.studyHours}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Hours"})]})]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Rankings"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-rose-50 border border-rose-200 rounded-xl p-4",children:[e.jsx(m,{size:20,className:"text-rose-600 mb-2"}),e.jsxs("p",{className:"text-2xl font-bold text-rose-900",children:["#",s.rank.global]}),e.jsx("p",{className:"text-xs text-rose-700 mt-1 font-body",children:"School"})]}),e.jsxs("div",{className:"bg-sky-50 border border-sky-200 rounded-xl p-4",children:[e.jsx(m,{size:20,className:"text-sky-600 mb-2"}),e.jsxs("p",{className:"text-2xl font-bold text-sky-900",children:["#",s.rank.section]}),e.jsx("p",{className:"text-xs text-sky-700 mt-1 font-body",children:"Section"})]}),e.jsxs("div",{className:"bg-rose-50 border border-rose-200 rounded-xl p-4",children:[e.jsx(m,{size:20,className:"text-rose-600 mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-rose-900",children:s.rank.change>0?e.jsxs("span",{className:"flex items-center gap-1 text-emerald-600",children:[e.jsx(E,{size:20}),"+",s.rank.change]}):s.rank.change<0?e.jsxs("span",{className:"flex items-center gap-1 text-red-600",children:[e.jsx(E,{size:20,className:"rotate-180"}),s.rank.change]}):"0"}),e.jsx("p",{className:"text-xs text-rose-700 mt-1 font-body",children:"This Week"})]})]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Achievements"}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(_,{size:24,className:"text-sky-500 animate-spin"})}):i.length>0?e.jsx("div",{className:"grid grid-cols-3 gap-3",children:i.map(d=>e.jsxs("div",{className:"rounded-xl p-4 text-center transition-all bg-white border-2 border-sky-200",children:[e.jsx("div",{className:"text-3xl mb-2",children:j[d.icon]||e.jsx(k,{size:24,className:"text-slate-500 mx-auto"})}),e.jsx("p",{className:"font-bold text-xs text-[#0a1628] mb-1 font-body",children:d.title}),e.jsx("p",{className:"text-xs text-[#5a6578]",children:d.description})]},d.id))}):e.jsxs("div",{className:"flex flex-col items-center py-8 gap-2",children:[e.jsx(k,{size:32,className:"text-[#d1cec6]"}),e.jsx("p",{className:"text-sm text-[#5a6578] font-body",children:"No achievements unlocked yet"})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-bold text-lg text-[#0a1628] mb-4",children:"Recent Activity"}),e.jsxs("div",{className:"flex flex-col items-center py-8 gap-2",children:[e.jsx(y,{size:32,className:"text-[#d1cec6]"}),e.jsx("p",{className:"text-sm text-[#5a6578] font-body",children:"Activity history coming soon"})]})]})]})]})]})})},fe=({currentUserPhoto:s,onBack:f})=>{const{currentUser:i,userProfile:u}=U(),p=u,{leaderboard:h,loading:j}=Z(i?.uid||null),[d]=l.useState("section"),[g,I]=l.useState("weekly"),[M,z]=l.useState(null),[D,v]=l.useState(!0),[F,S]=l.useState(null),[R,C]=l.useState([]),w=[p?.grade,p?.section].filter(Boolean).join(" - "),N=l.useCallback(async()=>{if(!i){v(!1);return}v(!0),S(null);try{const t=g==="all"?"all":"week",r=await $(i.uid,!1,t,20);if(!r||r.length===0){C([]);return}const x=r.map(a=>({id:a.userId,uid:a.userId,name:a.name,avatar:a.userId===i.uid?s||a.photo||"":a.photo||"",level:a.level,totalXP:a.xp,section:w||"Grade 11 - STEM A",rank:{global:a.rank,section:a.rank,change:0},stats:{quizzesCompleted:0,averageScore:0,modulesCompleted:0,studyHours:0},isOnline:!1,isYou:a.userId===i.uid}));C(x)}catch(t){console.error("Error loading leaderboard:",t),S(t instanceof Error?t.message:"Failed to load leaderboard")}finally{v(!1)}},[i,w,g,s]);l.useEffect(()=>{N()},[N]);const c=(()=>{let t=R;if(d==="section"){const x=w||"";x&&(t=t.filter(a=>a.section===x))}return t.sort((x,a)=>{const B=d==="section"?"section":"global";return(x.rank[B]||999)-(a.rank[B]||999)})})(),A=c.find(t=>t.isYou)?.rank.section||c.length+1,Y=c.length>1?Math.max(10,Math.min(99,100-A/Math.max(1,c.length)*100)):90,o=c.slice(0,3),L=c.slice(3),b=(t,r)=>t?t.startsWith("http")||t.startsWith("data:")?e.jsx("img",{src:t,alt:"Avatar",className:"w-full h-full object-cover rounded-full"}):e.jsx(X,{size:r,className:"text-slate-400 opacity-70"}):e.jsx(X,{size:r,className:"text-slate-400 opacity-70"});return D?e.jsxs("div",{className:"flex flex-col justify-center items-center h-[500px] gap-3",children:[e.jsx(_,{className:"w-8 h-8 animate-spin text-purple-600"}),e.jsx("p",{className:"text-sm text-slate-400 font-medium",children:"Loading leaderboard..."})]}):F?e.jsxs("div",{className:"flex flex-col justify-center items-center h-[500px] gap-4",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(m,{className:"w-7 h-7 text-red-400"})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 mb-1",children:"Couldn't load leaderboard"}),e.jsx("p",{className:"text-xs text-slate-400",children:F})]}),e.jsxs("button",{onClick:N,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 text-white text-sm font-medium rounded-xl hover:bg-purple-700 transition-colors",children:[e.jsx(K,{size:14}),"Try Again"]})]}):j?e.jsxs("div",{className:"flex flex-col justify-center items-center h-[500px] gap-3",children:[e.jsx(_,{className:"w-8 h-8 animate-spin text-purple-600"}),e.jsx("p",{className:"text-sm text-slate-400 font-medium",children:"Loading..."})]}):h?e.jsxs("div",{className:"w-full min-h-screen relative flex flex-col items-center font-body text-white",children:[e.jsxs("div",{className:"absolute inset-x-[-20px] top-0 h-[100vh] min-h-[800px] z-[-1] pointer-events-none overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_50%_100%,#9333ea_0%,#c084fc_40%,transparent_80%)]"}),e.jsx("div",{className:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[250vw] md:w-[200vw] h-[150vh] opacity-75 pointer-events-none",style:{WebkitMaskImage:"radial-gradient(circle at 50% 100%, black 10%, transparent 60%)"},children:e.jsx(n.div,{className:"absolute bottom-0 left-1/2 w-[600vw] h-[600vw] md:w-[400vw] md:h-[400vw]",style:{x:"-50%",y:"50%",originX:.5,originY:.5,background:`repeating-conic-gradient(from 0deg at 50% 50%, rgba(255,255,255,0.7) 0deg, rgba(255,255,255,0.7) 6deg, transparent 6deg, transparent 12deg)`},animate:{rotate:360},transition:{duration:160,repeat:1/0,ease:"linear"}})}),e.jsx("div",{className:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[150vw] h-[100vh] bg-[radial-gradient(ellipse_at_50%_100%,#7e22ce_10%,transparent_60%)] mix-blend-overlay"})]}),e.jsx("div",{className:"absolute inset-0 bg-math-pattern opacity-[0.03] mix-blend-overlay pointer-events-none z-[-1]",style:{WebkitMaskImage:"linear-gradient(to bottom, transparent, black 15%)"}}),e.jsxs("div",{className:"relative z-10 w-full px-4 sm:px-8 py-4 md:py-6 flex flex-col items-center",children:[e.jsx("div",{className:"w-full flex justify-center items-center mb-4 mt-2",children:e.jsx("h1",{className:"text-3xl md:text-4xl font-display font-bold tracking-wide text-slate-800 drop-shadow-sm",children:"Leaderboard"})}),e.jsx("div",{className:"bg-slate-800/5 backdrop-blur-md rounded-full p-1 flex gap-1 mb-3 shadow-[inset_0_2px_4px_rgba(0,0,0,0.05)] border border-slate-800/10 w-full max-w-[340px]",children:["daily","weekly","all"].map(t=>e.jsx("button",{onClick:()=>I(t),className:`flex-1 py-1.5 rounded-full text-[13px] md:text-sm font-semibold transition-all capitalize inline-flex justify-center items-center ${g===t?"bg-white text-purple-700 shadow-md border border-white/50 backdrop-blur-lg":"text-slate-600 hover:text-purple-700 hover:bg-white/50"}`,children:t==="all"?"All Time":t},t))}),e.jsxs(n.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"w-full max-w-[420px] mb-4 bg-[#FFB356] p-2.5 md:p-3 rounded-full shadow-lg flex items-center gap-3 relative overflow-hidden ring-1 ring-white/20",children:[e.jsx("div",{className:"absolute inset-0 bg-noise opacity-[0.15] mix-blend-overlay pointer-events-none"}),e.jsx("div",{className:"bg-white/25 backdrop-blur-md px-4 py-2 min-w-[60px] rounded-full flex flex-col items-center justify-center shadow-sm z-10 border border-white/20",children:e.jsxs("span",{className:"text-xl md:text-2xl font-display font-bold text-white leading-none",children:["#",A]})}),e.jsx("div",{className:"z-10 flex-1 pr-2 md:pr-4",children:e.jsxs("p",{className:"font-medium text-white/90 text-sm md:text-[15px] leading-snug text-center",children:["You are doing better than ",e.jsxs("span",{className:"font-black text-white drop-shadow-sm",children:[Math.round(Y),"%"]})," of other players!"]})})]}),e.jsxs("div",{className:"w-full max-w-[1000px] flex items-end justify-center gap-3 md:gap-6 h-[280px] md:h-[310px] relative z-20 mt-8 md:mt-12 mx-auto px-2 sm:px-4 group perspective-1000",children:[e.jsxs(n.div,{initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{delay:.15,type:"spring",stiffness:90},className:"flex flex-col items-center relative z-10 w-[30%] sm:w-[32%] max-w-[280px] mx-1 md:mr-2",children:[e.jsxs("div",{className:"flex flex-col items-center mb-2 md:mb-4 relative z-40 w-full",children:[e.jsx("div",{className:"w-14 h-14 md:w-[72px] md:h-[72px] rounded-full border-[3px] border-[#FF8B8B] bg-[#111827] flex items-center justify-center shadow-[0_0_18px_rgba(255,139,139,0.6)] overflow-hidden",children:b(o[1]?.avatar,26)}),e.jsx("h3",{className:"font-semibold text-white mt-1.5 md:mt-2 text-xs md:text-sm drop-shadow-md w-full text-center pb-1 px-1 whitespace-normal break-words leading-tight relative z-50",children:o[1]?.name||"---"})]}),e.jsxs("div",{className:"w-[90%] relative mt-2",children:[e.jsx("div",{className:"w-full h-10 md:h-14 absolute -bottom-5 md:-bottom-7 bg-[#D96C6A] rounded-[50%] shadow-[0_15px_25px_rgba(0,0,0,0.4)] z-0"}),e.jsx("div",{className:"w-full h-[100px] md:h-[130px] bg-[#D96C6A] relative z-10 flex flex-col items-center justify-start overflow-hidden",children:e.jsx("span",{className:"absolute inset-x-0 top-3 flex items-center justify-center text-[60px] md:text-[80px] font-black text-white/10 drop-shadow",children:"2"})}),e.jsx("div",{className:"w-full h-10 md:h-14 absolute -top-5 md:-top-7 bg-[#FF8B8B] rounded-[50%] z-20 shadow-[0_4px_8px_rgba(0,0,0,0.3)] flex flex-col items-center justify-center",children:e.jsxs("div",{className:"text-black/25 font-black text-[18px] md:text-[26px] transform scale-y-75 uppercase tracking-widest pointer-events-none z-30",children:[o[1]?.totalXP||0," XP"]})})]})]}),e.jsxs(n.div,{initial:{opacity:0,y:60},animate:{opacity:1,y:0},transition:{delay:.05,type:"spring",stiffness:100},className:"flex flex-col items-center relative z-30 w-[38%] sm:w-[40%] max-w-[330px]",children:[e.jsxs("div",{className:"flex flex-col items-center mb-3 md:mb-5 relative z-40 w-full",children:[e.jsx(n.div,{animate:{y:[0,-6,0]},transition:{repeat:1/0,duration:2.2,ease:"easeInOut"},className:"mb-[-10px] z-30",children:e.jsx(T,{size:30,className:"text-yellow-300 fill-yellow-300 drop-shadow-[0_0_12px_rgba(250,204,21,0.9)] md:w-9 md:h-9"})}),e.jsx("div",{className:"w-16 h-16 md:w-[86px] md:h-[86px] rounded-full border-[4px] border-[#fde68a] bg-[#111827] flex items-center justify-center shadow-[0_0_24px_rgba(250,204,21,0.6)] overflow-hidden",children:b(o[0]?.avatar,34)}),e.jsx("h3",{className:"font-semibold text-white mt-1.5 md:mt-2 text-sm md:text-base drop-shadow-md w-full text-center pb-1 px-1 whitespace-normal break-words leading-tight relative z-50",children:o[0]?.name||"---"})]}),e.jsxs("div",{className:"w-[95%] relative mt-2",children:[e.jsx("div",{className:"w-full h-12 md:h-16 absolute -bottom-6 md:-bottom-8 bg-[#6F2BAF] rounded-[50%] shadow-[0_20px_30px_rgba(0,0,0,0.5)] z-0"}),e.jsx("div",{className:"w-full h-[140px] md:h-[180px] bg-[#6F2BAF] relative z-10 flex flex-col items-center justify-start overflow-hidden",children:e.jsx("span",{className:"absolute inset-x-0 top-4 flex items-center justify-center text-[80px] md:text-[110px] font-black text-white/10 drop-shadow",children:"1"})}),e.jsx("div",{className:"w-full h-12 md:h-16 absolute -top-6 md:-top-8 bg-[#9956DE] rounded-[50%] z-20 shadow-[0_5px_12px_rgba(0,0,0,0.4)] flex flex-col items-center justify-center",children:e.jsxs("div",{className:"text-black/25 font-black text-[22px] md:text-[32px] transform scale-y-75 uppercase tracking-widest pointer-events-none z-30",children:[o[0]?.totalXP||0," XP"]})})]})]}),e.jsxs(n.div,{initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{delay:.25,type:"spring",stiffness:90},className:"flex flex-col items-center relative z-10 w-[30%] sm:w-[32%] max-w-[280px] mx-1 md:ml-2",children:[e.jsxs("div",{className:"flex flex-col items-center mb-2 md:mb-4 relative z-40 w-full",children:[e.jsx("div",{className:"w-14 h-14 md:w-[72px] md:h-[72px] rounded-full border-[3px] border-[#FFB356] bg-[#111827] flex items-center justify-center shadow-[0_0_18px_rgba(255,179,86,0.6)] overflow-hidden",children:b(o[2]?.avatar,26)}),e.jsx("h3",{className:"font-semibold text-white mt-1.5 md:mt-2 text-xs md:text-sm drop-shadow-md w-full text-center pb-1 px-1 whitespace-normal break-words leading-tight relative z-50",children:o[2]?.name||"---"})]}),e.jsxs("div",{className:"w-[90%] relative mt-2",children:[e.jsx("div",{className:"w-full h-10 md:h-14 absolute -bottom-5 md:-bottom-7 bg-[#DE7949] rounded-[50%] shadow-[0_15px_25px_rgba(0,0,0,0.4)] z-0"}),e.jsx("div",{className:"w-full h-[75px] md:h-[100px] bg-[#DE7949] relative z-10 flex flex-col items-center justify-start overflow-hidden",children:e.jsx("span",{className:"absolute inset-x-0 top-1 flex items-center justify-center text-[50px] md:text-[70px] font-black text-white/10 drop-shadow",children:"3"})}),e.jsx("div",{className:"w-full h-10 md:h-14 absolute -top-5 md:-top-7 bg-[#FFB356] rounded-[50%] z-20 shadow-[0_4px_8px_rgba(0,0,0,0.3)] flex flex-col items-center justify-center",children:e.jsxs("div",{className:"text-black/25 font-black text-[16px] md:text-[22px] transform scale-y-75 uppercase tracking-widest pointer-events-none z-30",children:[o[2]?.totalXP||0," XP"]})})]})]})]})]}),e.jsxs("div",{className:"w-full flex-grow relative z-20 pt-6 pb-32 px-4 sm:px-10 flex flex-col items-center mt-[-20px] md:mt-[-40px] transition-all duration-300 hover:-translate-y-2 min-h-[50vh] group",children:[e.jsxs("div",{className:"absolute top-0 left-0 right-0 bottom-[-500px] z-[-2] overflow-hidden rounded-t-[2.5rem] pointer-events-none",children:[e.jsx("div",{className:"absolute top-[-5%] left-[-10%] w-[70%] h-[400px] bg-purple-400/30 rounded-full blur-[100px]"}),e.jsx("div",{className:"absolute top-[15%] right-[-5%] w-[60%] h-[350px] bg-amber-300/20 rounded-full blur-[120px]"}),e.jsx("div",{className:"absolute top-[45%] left-[15%] w-[80%] h-[400px] bg-fuchsia-300/20 rounded-full blur-[120px]"})]}),e.jsx("div",{className:"absolute top-0 left-0 right-0 bottom-[-500px] z-[-1] rounded-t-[2.5rem] bg-gradient-to-b from-white/60 to-white/20 backdrop-blur-2xl transition-all duration-300 shadow-[0_-15px_40px_rgba(0,0,0,0.1),inset_0_2px_15px_rgba(255,255,255,0.7),inset_0_1px_1px_rgba(255,255,255,1)] group-hover:shadow-[0_-20px_50px_rgba(0,0,0,0.15),inset_0_2px_15px_rgba(255,255,255,0.8),inset_0_1px_1px_rgba(255,255,255,1)] border-t border-white/80"}),e.jsx("div",{className:"w-12 h-1.5 bg-slate-300/60 rounded-full mb-6 mt-[-10px] shadow-[inset_0_1px_2px_rgba(0,0,0,0.1)] backdrop-blur-md"}),e.jsxs("div",{className:"w-full max-w-4xl space-y-3.5",children:[L.map((t,r)=>{const x=t.rank.global||r+4;return e.jsxs(n.div,{initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{delay:r*.05+.3},onClick:()=>z(t),className:`flex items-center gap-4 p-3.5 md:p-4 rounded-3xl cursor-pointer bg-white border transition-all duration-300 ${t.isYou?"border-[#8B5CF6]/40 shadow-xl shadow-[#8B5CF6]/20 ring-2 ring-[#8B5CF6]/10":"border-slate-100 shadow-[0_12px_25px_rgba(0,0,0,0.08)] hover:shadow-[0_16px_30px_rgba(0,0,0,0.12)]"}`,children:[e.jsx("div",{className:"w-9 h-9 md:w-11 md:h-11 rounded-full border-2 border-slate-100 bg-white flex items-center justify-center font-display font-bold text-slate-500 shadow-sm text-sm",children:x}),e.jsx("div",{className:"w-11 h-11 md:w-14 md:h-14 bg-slate-100 rounded-full flex items-center justify-center text-xl overflow-hidden shadow-sm relative border-[3px] border-[#F1F5F9]",children:b(t.avatar,24)}),e.jsxs("div",{className:"flex-1 flex justify-between items-center pr-2",children:[e.jsx("div",{children:e.jsxs("h4",{className:"font-display font-bold text-[#1E293B] text-[15px] md:text-lg flex items-center gap-2 tracking-wide",children:[t.name,t.isYou&&e.jsx("span",{className:"text-[9px] uppercase tracking-wider bg-[#8B5CF6] text-white px-1.5 py-0.5 rounded font-bold",children:"You"})]})}),e.jsx("div",{children:e.jsxs("p",{className:"text-[13px] md:text-[15px] font-bold text-slate-500 text-right",children:[t.totalXP," ",e.jsx("span",{className:"text-[10px] text-slate-400 font-normal uppercase",children:"XP"})]})})]})]},t.id)}),L.length===0&&e.jsx("div",{className:"text-center py-12",children:e.jsx("p",{className:"text-slate-400 font-medium",children:"No other participants found in this view."})})]})]}),e.jsx(ee,{student:M,onClose:()=>z(null)})]}):e.jsxs("div",{className:"flex flex-col justify-center items-center h-[500px] gap-4",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(G,{className:"w-7 h-7 text-slate-400"})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 mb-1",children:"Leaderboard Locked"}),e.jsx("p",{className:"text-xs text-slate-400",children:"This feature is temporarily unavailable while you focus on your learning."})]})]})};export{fe as default}; diff --git a/assets/LearningPath-BhYUnmrP.js b/assets/LearningPath-BKjN0COS.js similarity index 89% rename from assets/LearningPath-BhYUnmrP.js rename to assets/LearningPath-BKjN0COS.js index 0ae3c3b9180afa30eaf8f00ca5f8cc8e2d6239e7..964e180072b027534fb168c6d851395b28912149 100644 --- a/assets/LearningPath-BhYUnmrP.js +++ b/assets/LearningPath-BKjN0COS.js @@ -1 +1 @@ -import{r as p,d as g,j as r}from"./vendor-react-B4AQeu28.js";import{u as b,ab as j,ac as N,z as k,b as P,a as I}from"./index-BvEKrMkD.js";import{M as v}from"./ModuleFolderCard-CS_0Dtn3.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./useSubjectAvailability-C0TzAHAR.js";import"./deepseekRagService-Bke9fSTt.js";import"./clock-0vnF72R6.js";import"./bell-C57aSZcx.js";import"./info-CMvRmbQw.js";const Y=({onNavigateToModules:m,atRiskSubjects:l=[],priorityTopics:o=[],modules:i})=>{const{userProfile:d}=b(),[x,h]=p.useState(null),a=g.useMemo(()=>{const e=o.length>0?o:l.map(s=>j(s)).filter(s=>s!==null),t=new Set;return e.filter(s=>t.has(s)?!1:(t.add(s),!0))},[o,l]),u=g.useMemo(()=>{if(a.length===0)return i.slice(0,3);const e=new Map(a.map((t,s)=>[N[t],s]));return[...i].sort((t,s)=>{const n=e.get(t.id)??Number.POSITIVE_INFINITY,w=e.get(s.id)??Number.POSITIVE_INFINITY;return n-w}).slice(0,3)},[i,a]);p.useEffect(()=>{d?.uid&&k(d.uid).then(h).catch(console.error)},[d?.uid]);const c=u.slice(0,3).map(e=>{const t=x?.subjects?.[e.subject]?.modulesProgress?.[e.id],s=e.lessons.length,n=t?.progress??(s>0?Math.round((t?.lessonsCompleted?.length||0)/s*100):0);return{...e,progress:n,status:n===100?"Completed":n>0?"In Progress":"Not Started"}}),f=c.some(e=>e.progress>0)?"Continue Learning":"Start Learning";return r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-4 md:mb-6 px-1",children:[r.jsxs("div",{className:"flex items-center gap-2 md:gap-3",children:[r.jsx("div",{className:"w-8 h-8 md:w-10 md:h-10 shrink-0 rounded-xl md:rounded-[14px] bg-indigo-50 border border-indigo-100 flex items-center justify-center text-indigo-500 shadow-inner",children:r.jsx(P,{className:"w-4 h-4 md:w-5 md:h-5",strokeWidth:2.5})}),r.jsx("h2",{className:"font-display font-black text-lg md:text-[24px] text-slate-800 tracking-tight whitespace-nowrap",children:f})]}),r.jsxs("button",{onClick:()=>m?.(),className:"text-primary font-bold text-xs md:text-sm flex shrink-0 items-center gap-1 hover:gap-2 transition-all bg-primary/10 px-3 py-1.5 md:px-4 md:py-2 rounded-lg md:rounded-xl hover:bg-primary/20 whitespace-nowrap",children:["View All ",r.jsx(I,{className:"w-3.5 h-3.5 md:w-4 md:h-4"})]})]}),r.jsx("div",{className:"flex overflow-x-auto snap-x snap-mandatory scrollbar-hide -mx-4 px-4 pb-4 gap-4 md:grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 md:gap-6 md:pb-0 md:mx-0 md:px-0 md:overflow-visible",children:c.map((e,t)=>r.jsx("div",{className:"w-[72vw] max-w-[260px] h-[220px] shrink-0 snap-center md:min-w-0 md:max-w-none md:w-auto md:shrink md:h-auto",children:r.jsx(v,{module:e,index:t,onClick:()=>m?.(e.id),isAtRisk:a.length>0,badgeLabel:e.status!=="Not Started"?e.status:void 0})},e.id))})]})};export{Y as default}; +import{r as p,d as g,j as r}from"./vendor-react-B4AQeu28.js";import{u as b,ab as j,ac as N,z as k,b as P,a as I}from"./index-BdLfAeGL.js";import{M as v}from"./ModuleFolderCard-CXTwxNMY.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./useSubjectAvailability-BUrciGBC.js";import"./deepseekRagService-Bke9fSTt.js";import"./clock-CpBwkoND.js";import"./bell-C5_RRTsA.js";import"./info-D1mJ7S8g.js";const Y=({onNavigateToModules:m,atRiskSubjects:l=[],priorityTopics:o=[],modules:i})=>{const{userProfile:d}=b(),[x,h]=p.useState(null),a=g.useMemo(()=>{const e=o.length>0?o:l.map(s=>j(s)).filter(s=>s!==null),t=new Set;return e.filter(s=>t.has(s)?!1:(t.add(s),!0))},[o,l]),u=g.useMemo(()=>{if(a.length===0)return i.slice(0,3);const e=new Map(a.map((t,s)=>[N[t],s]));return[...i].sort((t,s)=>{const n=e.get(t.id)??Number.POSITIVE_INFINITY,w=e.get(s.id)??Number.POSITIVE_INFINITY;return n-w}).slice(0,3)},[i,a]);p.useEffect(()=>{d?.uid&&k(d.uid).then(h).catch(console.error)},[d?.uid]);const c=u.slice(0,3).map(e=>{const t=x?.subjects?.[e.subject]?.modulesProgress?.[e.id],s=e.lessons.length,n=t?.progress??(s>0?Math.round((t?.lessonsCompleted?.length||0)/s*100):0);return{...e,progress:n,status:n===100?"Completed":n>0?"In Progress":"Not Started"}}),f=c.some(e=>e.progress>0)?"Continue Learning":"Start Learning";return r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-4 md:mb-6 px-1",children:[r.jsxs("div",{className:"flex items-center gap-2 md:gap-3",children:[r.jsx("div",{className:"w-8 h-8 md:w-10 md:h-10 shrink-0 rounded-xl md:rounded-[14px] bg-indigo-50 border border-indigo-100 flex items-center justify-center text-indigo-500 shadow-inner",children:r.jsx(P,{className:"w-4 h-4 md:w-5 md:h-5",strokeWidth:2.5})}),r.jsx("h2",{className:"font-display font-black text-lg md:text-[24px] text-slate-800 tracking-tight whitespace-nowrap",children:f})]}),r.jsxs("button",{onClick:()=>m?.(),className:"text-primary font-bold text-xs md:text-sm flex shrink-0 items-center gap-1 hover:gap-2 transition-all bg-primary/10 px-3 py-1.5 md:px-4 md:py-2 rounded-lg md:rounded-xl hover:bg-primary/20 whitespace-nowrap",children:["View All ",r.jsx(I,{className:"w-3.5 h-3.5 md:w-4 md:h-4"})]})]}),r.jsx("div",{className:"flex overflow-x-auto snap-x snap-mandatory scrollbar-hide -mx-4 px-4 pb-4 gap-4 md:grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 md:gap-6 md:pb-0 md:mx-0 md:px-0 md:overflow-visible",children:c.map((e,t)=>r.jsx("div",{className:"w-[72vw] max-w-[260px] h-[220px] shrink-0 snap-center md:min-w-0 md:max-w-none md:w-auto md:shrink md:h-auto",children:r.jsx(v,{module:e,index:t,onClick:()=>m?.(e.id),isAtRisk:a.length>0,badgeLabel:e.status!=="Not Started"?e.status:void 0})},e.id))})]})};export{Y as default}; diff --git a/assets/LoginPage-B_M2Kx_b.js b/assets/LoginPage-Dp-x74N8.js similarity index 97% rename from assets/LoginPage-B_M2Kx_b.js rename to assets/LoginPage-Dp-x74N8.js index f63bd80ce5156c8bac236e0ebf57af1c75f27fd1..cb290e557fe5069cb9a1178c97437838cddbc059 100644 --- a/assets/LoginPage-B_M2Kx_b.js +++ b/assets/LoginPage-Dp-x74N8.js @@ -1 +1 @@ -import{r as s,j as e}from"./vendor-react-B4AQeu28.js";import{B as je}from"./button-Bfg1pO9T.js";import{I as L}from"./input-B3TmduBc.js";import{m as i,B as we,T as Ne,A as ke,U as Q,L as X,a as K,G as Se,b as Pe,s as ee,c as Ae,d as te}from"./index-BvEKrMkD.js";import{S as Me}from"./sparkles-av0wSNZT.js";import{M as Re}from"./mail-DahQBvd1.js";import{E as Ce,a as Ee}from"./eye-DbYh0OO3.js";import{S as Te}from"./shield-check-X3NwQ434.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";const se="/assets/shader-bg-DA7bEbBA.mp4",Le=[{id:"length",label:"At least 8 characters",test:a=>a.length>=8},{id:"upper-lower",label:"Contains uppercase and lowercase letters",test:a=>/[A-Z]/.test(a)&&/[a-z]/.test(a)},{id:"number",label:"Contains at least one number",test:a=>/\d/.test(a)},{id:"special",label:"Contains at least one special character",test:a=>/[^A-Za-z0-9]/.test(a)}],I="Use at least 8 characters with uppercase, lowercase, number, and special character.",Ie=a=>{const c=typeof a=="object"&&a!==null?a:null,o=a instanceof Error?a.message:"";if(c?.code&&typeof c.code=="string")return{code:c.code.toLowerCase(),message:o};const n=o.match(/auth\/[a-z-]+/i);return{code:n?n[0].toLowerCase():"",message:o}},ze=a=>a.replace(/^Firebase:\s*/i,"").replace(/\s*\(auth\/[a-z-]+\)\.?/i,"").trim(),ae=(a,c)=>{const{code:o,message:n}=Ie(a),h=ze(n);return o==="auth/invalid-credential"||o==="auth/wrong-password"||o==="auth/user-not-found"?"Invalid email or password. Please check your credentials and try again.":o==="auth/email-already-in-use"?"This email is already registered. Please sign in instead.":o==="auth/weak-password"||o==="auth/password-does-not-meet-requirements"?h?`Password does not meet signup requirements. ${h}`:`Password does not meet signup requirements. ${I}`:o==="auth/too-many-requests"?"Access to this account has been temporarily disabled due to many failed login attempts. You can immediately restore it by resetting your password or you can try again later.":o==="auth/network-request-failed"?"Network error. Please check your internet connection and try again.":o.startsWith("auth/")?h||c:n.includes("Firebase:")||n.includes("auth/")?c:n||c},et=()=>{const a={"Grade 11":["Academic","Tech-Pro"]},[c,o]=s.useState(""),[n,h]=s.useState(""),[S,re]=s.useState(!1),[l,z]=s.useState(!1),[P,ie]=s.useState(""),[y,D]=s.useState("student"),[b,De]=s.useState("Grade 11"),[v,B]=s.useState(a["Grade 11"][0]),[_,x]=s.useState(!1),[f,u]=s.useState(null),[oe,le]=s.useState(!1),[ne,ce]=s.useState(!1),[A,de]=s.useState(16),[q,V]=s.useState("primary"),[O,M]=s.useState(0),R=s.useRef(null),C=s.useRef(null),j=oe&&ne,g=s.useRef("primary"),w=s.useRef(0),N=s.useRef(!1),F=1.1,G=.34,U=t=>{const r=Math.max(0,Math.min(1,t));Math.abs(w.current-r)<.02||(w.current=r,M(r))},$=t=>{!Number.isFinite(t)||t<=0||Math.abs(A-t)>.05&&de(t)},E=s.useMemo(()=>Le.map(t=>({...t,met:t.test(n)})),[n]),W=s.useMemo(()=>E.every(t=>t.met),[E]),me=s.useMemo(()=>{if(!l||!f)return!1;const t=f.toLowerCase();return t.includes("password requirements not met")||t.includes("password does not meet")},[f,l]),ue=()=>{const t=R.current?.duration;t&&Number.isFinite(t)&&t>0&&$(t)},pe=()=>{const t=C.current?.duration;t&&Number.isFinite(t)&&t>0&&$(t)};s.useEffect(()=>{if(!j)return;const t=R.current,r=C.current;if(!t||!r)return;let d=!1,m=0;g.current="primary",V("primary"),N.current=!1,w.current=0,M(0),t.loop=!1,r.loop=!1,t.currentTime=0,r.currentTime=0,r.pause(),t.play().catch(()=>{});const k=()=>{if(d)return;const p=g.current==="primary"?t:r,Z=g.current==="primary"?r:t,ge=Number.isFinite(p.duration)&&p.duration>0?p.duration:A,T=Math.max(ge-p.currentTime,0);if(T<=F){N.current||(N.current=!0,Z.currentTime=0,Z.play().catch(()=>{}));const ve=1-T/F;if(U(ve),T<=.03||p.ended){p.pause(),p.currentTime=0;const J=g.current==="primary"?"secondary":"primary";g.current=J,V(J),N.current=!1,w.current=0,M(0)}}else U(0);m=window.requestAnimationFrame(k)};return m=window.requestAnimationFrame(k),()=>{d=!0,m&&window.cancelAnimationFrame(m)}},[A,j]);const Y=j?G*(1-O):0,H=j?G*O:0,xe=q==="primary"?Y:H,ye=q==="secondary"?Y:H;s.useEffect(()=>{const t=a[b]||[];t.length>0&&!t.includes(v)&&B(t[0])},[b,v]);const he=[{label:"Student",role:"student",email:"teststudent@school.edu",password:"TestPass123!",icon:Se,color:"sky"},{label:"Teacher",role:"teacher",email:"testteacher@school.edu",password:"TestPass123!",icon:Pe,color:"emerald"},{label:"Admin",role:"admin",email:"testadmin@school.edu",password:"TestPass123!",icon:Te,color:"rose"}],be=async(t,r,d)=>{u(null),x(!0),o(t),h(r),D(d),z(!1);try{ee(d),await te(t,r)}catch(m){u(ae(m,"Demo sign-in failed. Please try again.")),x(!1)}},fe=async t=>{t.preventDefault(),u(null),x(!0);try{if(l){if(!P.trim()){u("Please enter your name"),x(!1);return}if(y==="student"&&!b){u("Please select a grade level"),x(!1);return}if(y==="admin"){u("Admin account creation is restricted. Please contact an existing administrator."),x(!1);return}if(!W){u(`Password does not meet signup requirements. ${I}`),x(!1);return}ee(y),await Ae(c,n,P,y,y==="student"?{grade:b,section:v}:{department:"Mathematics"})}else await te(c,n)}catch(r){const d=l?`Sign-up failed. ${I}`:"Sign-in failed. Please check your credentials and try again.";u(ae(r,d)),x(!1)}};return e.jsxs("div",{className:"min-h-screen w-full flex items-center justify-center px-4 sm:px-6 py-8 overflow-y-auto relative login-bg",children:[e.jsx("video",{ref:R,autoPlay:!0,muted:!0,playsInline:!0,preload:"auto",onCanPlay:()=>le(!0),onLoadedMetadata:ue,className:"absolute inset-0 w-full h-full object-cover transition-opacity duration-150 e-opacity",style:{"--o":xe},src:se}),e.jsx("video",{ref:C,autoPlay:!0,muted:!0,playsInline:!0,preload:"auto",onCanPlay:()=>ce(!0),onLoadedMetadata:pe,className:"absolute inset-0 w-full h-full object-cover transition-opacity duration-150 e-opacity",style:{"--o":ye},src:se}),e.jsx("div",{className:"absolute inset-0 pointer-events-none login-frost-overlay"}),e.jsx("div",{className:"absolute top-[10%] left-[-10%] w-[60%] h-[60%] rounded-full blur-[140px] pointer-events-none mix-blend-multiply login-orb-purple"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[70%] h-[70%] rounded-full blur-[160px] pointer-events-none mix-blend-multiply login-orb-pink"}),e.jsx("div",{className:"absolute top-[40%] left-[40%] w-[40%] h-[40%] rounded-full blur-[120px] pointer-events-none mix-blend-screen login-orb-blue"}),e.jsx("div",{className:"relative z-10 w-full max-w-6xl mx-auto",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12 items-center",children:[e.jsxs(i.div,{initial:{opacity:0,x:-40},animate:{opacity:1,x:0},transition:{duration:.8,ease:[.22,1,.36,1]},className:"flex flex-col items-center lg:items-start justify-center space-y-5 lg:space-y-8 text-center lg:text-left",children:[e.jsxs(i.div,{className:"flex items-center justify-center lg:justify-start gap-2.5",children:[e.jsx(i.div,{className:"relative flex items-center justify-center drop-shadow-md",children:e.jsx("img",{src:"/mathpulse_final_logo.png",alt:"MathPulse AI Logo",className:"w-10 h-10 lg:w-16 lg:h-16 object-contain flex-shrink-0"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl lg:text-3xl font-display font-black tracking-tight text-slate-900 bg-clip-text text-transparent bg-gradient-to-r from-purple-600 via-pink-600 to-sky-500",children:"MathPulse"}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[e.jsx(Me,{size:12,className:"text-rose-500"}),e.jsx("span",{className:"text-xs text-slate-500 font-body font-medium tracking-wide",children:"Powered by Machine Learning"})]})]})]}),e.jsxs(i.div,{className:"space-y-3 lg:space-y-5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2,duration:.8},children:[e.jsxs("h2",{className:"text-3xl sm:text-4xl lg:text-5xl xl:text-[3.4rem] font-display font-extrabold leading-[1.1] tracking-tight text-slate-900",children:["Transform Your",e.jsx("br",{}),e.jsx("span",{className:"bg-gradient-to-r from-sky-600 via-cyan-500 to-sky-500 bg-clip-text text-transparent",children:"Math Journey"})]}),e.jsx("p",{className:"text-sm lg:text-base text-slate-500 leading-relaxed max-w-md mx-auto lg:mx-0 font-body",children:"AI-powered predictive system designed to identify at-risk students and provide personalized learning recommendations."})]}),e.jsx("div",{className:"grid grid-cols-3 gap-2 lg:gap-3",children:[{icon:we,label:"AI Predictions",desc:"Smart detection",color:"sky"},{icon:Ne,label:"Analytics",desc:"Real-time data",color:"rose"},{icon:ke,label:"Gamified",desc:"Learn & earn",color:"emerald"}].map((t,r)=>{const d=t.icon,m={sky:"border-sky-200/60 hover:border-sky-300",rose:"border-rose-200/60 hover:border-rose-300",emerald:"border-emerald-200/60 hover:border-emerald-300"},k={sky:"text-sky-600",rose:"text-rose-500",emerald:"text-emerald-600"},p={sky:"bg-sky-100",rose:"bg-rose-100",emerald:"bg-emerald-100"};return e.jsxs(i.div,{className:`bg-white/80 backdrop-blur-xl border ${m[t.color]} rounded-xl p-3 lg:p-4 transition-all cursor-pointer group shadow-md shadow-slate-900/[0.04]`,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5+r*.1},whileHover:{scale:1.03,y:-4},children:[e.jsx("div",{className:`w-7 h-7 lg:w-9 lg:h-9 rounded-lg ${p[t.color]} flex items-center justify-center mx-auto lg:mx-0 mb-2 lg:mb-3`,children:e.jsx(d,{size:15,className:k[t.color]})}),e.jsx("h3",{className:"text-xs lg:text-sm font-display font-semibold text-slate-800 mb-0.5",children:t.label}),e.jsx("p",{className:"text-[10px] lg:text-xs text-slate-400 font-body",children:t.desc})]},r)})})]}),e.jsx(i.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.15,ease:[.22,1,.36,1]},className:"relative flex justify-center lg:justify-end",children:e.jsxs("div",{className:"bg-white/85 backdrop-blur-2xl border border-slate-200/60 rounded-3xl p-6 sm:p-7 w-full max-w-md relative overflow-hidden shadow-[0_20px_60px_-15px_rgba(168,85,247,0.15)] max-h-[85vh] overflow-y-auto",children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[3px] bg-gradient-to-r from-purple-500 via-pink-500 to-sky-500"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 w-80 h-80 bg-gradient-to-br from-purple-400/20 to-pink-400/20 rounded-full blur-[60px] pointer-events-none"}),e.jsxs("div",{className:"text-center mb-4 relative",children:[e.jsx(i.h3,{className:"text-2xl font-display font-bold text-slate-900 mb-2",initial:{opacity:0},animate:{opacity:1},transition:{delay:.4},children:l?"Create Account":"Welcome Back"}),e.jsx(i.p,{className:"text-sm text-slate-500 font-body",initial:{opacity:0},animate:{opacity:1},transition:{delay:.5},children:l?"Begin your learning journey":"Sign in to continue learning"})]}),e.jsxs("form",{onSubmit:fe,className:"space-y-3 mb-4 relative",children:[f&&!me&&e.jsx(i.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"bg-rose-50 border border-rose-200 text-rose-600 px-4 py-3 rounded-lg text-sm font-body",children:f}),l&&e.jsxs(i.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Full Name"}),e.jsxs("div",{className:"relative",children:[e.jsx(Q,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(L,{type:"text",placeholder:"Your Name",value:P,onChange:t=>ie(t.target.value),className:"w-full pl-11 pr-4 py-3 rounded-lg bg-slate-100/70 border-slate-200/80 text-slate-900 placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all",required:!0})]})]}),l&&e.jsxs(i.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.45},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Account Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{role:"student",label:"Student"},{role:"teacher",label:"Teacher"}].map(t=>{const r=y===t.role;return e.jsx("button",{type:"button",onClick:()=>D(t.role),className:`rounded-lg border px-3 py-2.5 text-sm font-body font-semibold transition-all ${r?"border-sky-400 bg-sky-50 text-sky-700":"border-slate-200 bg-slate-50 text-slate-500 hover:border-slate-300"}`,children:t.label},t.role)})})]}),l&&y==="student"&&e.jsx(i.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"space-y-3",children:e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Section"}),e.jsxs("div",{className:"relative",children:[e.jsx(Q,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("select",{value:v,onChange:t=>B(t.target.value),className:"w-full pl-11 pr-4 py-2.5 rounded-lg bg-slate-100/70 border border-slate-200/80 text-slate-900 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all appearance-none",required:!0,children:(a[b]||[]).map(t=>e.jsx("option",{value:t,children:t},t))})]})]})}),e.jsxs(i.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.5},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Re,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(L,{type:"email",placeholder:"your.email@school.edu",value:c,onChange:t=>o(t.target.value),className:"w-full pl-11 pr-4 py-3 rounded-lg bg-slate-100/70 border-slate-200/80 text-slate-900 placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all",required:!0})]})]}),e.jsxs(i.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.6},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(X,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(L,{type:S?"text":"password",placeholder:"••••••••",value:n,onChange:t=>h(t.target.value),className:"w-full pl-11 pr-11 py-3 rounded-lg bg-slate-100/70 border-slate-200/80 text-slate-900 placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all",required:!0,minLength:l?8:6}),e.jsx(i.button,{type:"button",onClick:()=>re(!S),className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors",whileTap:{scale:.9},children:S?e.jsx(Ce,{size:16}):e.jsx(Ee,{size:16})})]}),l&&n.length>0&&!W&&e.jsxs("div",{className:"mt-2 rounded-lg border border-sky-100/80 bg-sky-50/70 px-3 py-2",children:[e.jsx("p",{className:"text-[11px] font-body font-semibold uppercase tracking-wider text-slate-600",children:"Password requirements"}),e.jsx("ul",{className:"mt-2 space-y-1",children:E.map(t=>e.jsxs("li",{className:`flex items-center gap-2 text-[11px] font-body ${t.met?"text-emerald-700":"text-slate-500"}`,children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${t.met?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{children:t.label})]},t.id))})]})]}),e.jsx(i.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.7},children:e.jsxs(je,{type:"submit",disabled:_,className:"w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-500 hover:to-pink-400 text-white font-body font-semibold py-3 rounded-xl shadow-lg shadow-purple-600/25 hover:shadow-pink-500/35 hover:scale-[1.02] transition-all text-sm group relative overflow-hidden disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(i.span,{className:"absolute inset-0 bg-gradient-to-r from-white/0 via-white/15 to-white/0",animate:{x:["-100%","100%"]},transition:{duration:3,repeat:1/0,repeatDelay:2}}),e.jsxs("span",{className:"relative flex items-center justify-center gap-2",children:[_?"Please wait...":l?"Create Account":"Sign In",e.jsx(K,{size:16,className:"group-hover:translate-x-1 transition-transform"})]})]})}),e.jsx("div",{className:"text-center",children:e.jsx("button",{type:"button",onClick:()=>{z(!l),u(null)},className:"text-sm text-slate-400 hover:text-sky-500 font-body font-medium transition-colors",children:l?"Already have an account? Sign in":"Don't have an account? Create one"})})]}),!l&&e.jsxs(i.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.85},className:"mb-4 relative",children:[e.jsxs("div",{className:"relative flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"flex-1 h-px bg-slate-200"}),e.jsx("span",{className:"text-[10px] font-body font-semibold text-slate-400 uppercase tracking-widest",children:"Quick Demo Access"}),e.jsx("div",{className:"flex-1 h-px bg-slate-200"})]}),e.jsx("div",{className:"flex flex-col gap-2",children:he.map(t=>{const r=t.icon,d={sky:"bg-sky-100",emerald:"bg-emerald-100",rose:"bg-rose-100"},m={sky:"text-sky-600",emerald:"text-emerald-600",rose:"text-rose-500"};return e.jsxs(i.button,{type:"button",onClick:()=>be(t.email,t.password,t.role),className:"group flex items-center gap-3 w-full px-4 py-2.5 rounded-lg bg-slate-50/80 border border-slate-200/70 hover:border-sky-300 hover:bg-sky-50/80 hover:shadow-sm transition-all text-left",whileHover:{scale:1.01},whileTap:{scale:.99},children:[e.jsx("div",{className:`w-8 h-8 rounded-md flex items-center justify-center shrink-0 ${d[t.color]}`,children:e.jsx(r,{size:15,className:m[t.color]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs font-body font-semibold text-slate-700 group-hover:text-sky-600 transition-colors",children:[t.label," Account"]}),e.jsx("p",{className:"text-[10px] text-slate-400 font-body truncate",children:t.email})]}),e.jsx(K,{size:14,className:"text-slate-300 group-hover:text-sky-500 group-hover:translate-x-0.5 transition-all shrink-0"})]},t.label)})})]}),e.jsxs(i.p,{className:"text-xs text-slate-400 text-center mt-4 font-body relative",initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx(X,{size:10,className:"inline mr-1 -mt-0.5"})," Your data is encrypted and secure"]})]})})]})})]})};export{et as default}; +import{r as s,j as e}from"./vendor-react-B4AQeu28.js";import{B as je}from"./button-BbJLXpfi.js";import{I as L}from"./input-CHfZS1wQ.js";import{m as i,B as we,T as Ne,A as ke,U as Q,L as X,a as K,G as Se,b as Pe,s as ee,c as Ae,d as te}from"./index-BdLfAeGL.js";import{S as Me}from"./sparkles-DnAkO9TX.js";import{M as Re}from"./mail-9RdsJqkx.js";import{E as Ce,a as Ee}from"./eye-8D1uq8DN.js";import{S as Te}from"./shield-check-DqqR-L0T.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";const se="/assets/shader-bg-DA7bEbBA.mp4",Le=[{id:"length",label:"At least 8 characters",test:a=>a.length>=8},{id:"upper-lower",label:"Contains uppercase and lowercase letters",test:a=>/[A-Z]/.test(a)&&/[a-z]/.test(a)},{id:"number",label:"Contains at least one number",test:a=>/\d/.test(a)},{id:"special",label:"Contains at least one special character",test:a=>/[^A-Za-z0-9]/.test(a)}],I="Use at least 8 characters with uppercase, lowercase, number, and special character.",Ie=a=>{const c=typeof a=="object"&&a!==null?a:null,o=a instanceof Error?a.message:"";if(c?.code&&typeof c.code=="string")return{code:c.code.toLowerCase(),message:o};const n=o.match(/auth\/[a-z-]+/i);return{code:n?n[0].toLowerCase():"",message:o}},ze=a=>a.replace(/^Firebase:\s*/i,"").replace(/\s*\(auth\/[a-z-]+\)\.?/i,"").trim(),ae=(a,c)=>{const{code:o,message:n}=Ie(a),h=ze(n);return o==="auth/invalid-credential"||o==="auth/wrong-password"||o==="auth/user-not-found"?"Invalid email or password. Please check your credentials and try again.":o==="auth/email-already-in-use"?"This email is already registered. Please sign in instead.":o==="auth/weak-password"||o==="auth/password-does-not-meet-requirements"?h?`Password does not meet signup requirements. ${h}`:`Password does not meet signup requirements. ${I}`:o==="auth/too-many-requests"?"Access to this account has been temporarily disabled due to many failed login attempts. You can immediately restore it by resetting your password or you can try again later.":o==="auth/network-request-failed"?"Network error. Please check your internet connection and try again.":o.startsWith("auth/")?h||c:n.includes("Firebase:")||n.includes("auth/")?c:n||c},et=()=>{const a={"Grade 11":["Academic","Tech-Pro"]},[c,o]=s.useState(""),[n,h]=s.useState(""),[S,re]=s.useState(!1),[l,z]=s.useState(!1),[P,ie]=s.useState(""),[y,D]=s.useState("student"),[b,De]=s.useState("Grade 11"),[v,B]=s.useState(a["Grade 11"][0]),[_,x]=s.useState(!1),[f,u]=s.useState(null),[oe,le]=s.useState(!1),[ne,ce]=s.useState(!1),[A,de]=s.useState(16),[q,V]=s.useState("primary"),[O,M]=s.useState(0),R=s.useRef(null),C=s.useRef(null),j=oe&&ne,g=s.useRef("primary"),w=s.useRef(0),N=s.useRef(!1),F=1.1,G=.34,U=t=>{const r=Math.max(0,Math.min(1,t));Math.abs(w.current-r)<.02||(w.current=r,M(r))},$=t=>{!Number.isFinite(t)||t<=0||Math.abs(A-t)>.05&&de(t)},E=s.useMemo(()=>Le.map(t=>({...t,met:t.test(n)})),[n]),W=s.useMemo(()=>E.every(t=>t.met),[E]),me=s.useMemo(()=>{if(!l||!f)return!1;const t=f.toLowerCase();return t.includes("password requirements not met")||t.includes("password does not meet")},[f,l]),ue=()=>{const t=R.current?.duration;t&&Number.isFinite(t)&&t>0&&$(t)},pe=()=>{const t=C.current?.duration;t&&Number.isFinite(t)&&t>0&&$(t)};s.useEffect(()=>{if(!j)return;const t=R.current,r=C.current;if(!t||!r)return;let d=!1,m=0;g.current="primary",V("primary"),N.current=!1,w.current=0,M(0),t.loop=!1,r.loop=!1,t.currentTime=0,r.currentTime=0,r.pause(),t.play().catch(()=>{});const k=()=>{if(d)return;const p=g.current==="primary"?t:r,Z=g.current==="primary"?r:t,ge=Number.isFinite(p.duration)&&p.duration>0?p.duration:A,T=Math.max(ge-p.currentTime,0);if(T<=F){N.current||(N.current=!0,Z.currentTime=0,Z.play().catch(()=>{}));const ve=1-T/F;if(U(ve),T<=.03||p.ended){p.pause(),p.currentTime=0;const J=g.current==="primary"?"secondary":"primary";g.current=J,V(J),N.current=!1,w.current=0,M(0)}}else U(0);m=window.requestAnimationFrame(k)};return m=window.requestAnimationFrame(k),()=>{d=!0,m&&window.cancelAnimationFrame(m)}},[A,j]);const Y=j?G*(1-O):0,H=j?G*O:0,xe=q==="primary"?Y:H,ye=q==="secondary"?Y:H;s.useEffect(()=>{const t=a[b]||[];t.length>0&&!t.includes(v)&&B(t[0])},[b,v]);const he=[{label:"Student",role:"student",email:"teststudent@school.edu",password:"TestPass123!",icon:Se,color:"sky"},{label:"Teacher",role:"teacher",email:"testteacher@school.edu",password:"TestPass123!",icon:Pe,color:"emerald"},{label:"Admin",role:"admin",email:"testadmin@school.edu",password:"TestPass123!",icon:Te,color:"rose"}],be=async(t,r,d)=>{u(null),x(!0),o(t),h(r),D(d),z(!1);try{ee(d),await te(t,r)}catch(m){u(ae(m,"Demo sign-in failed. Please try again.")),x(!1)}},fe=async t=>{t.preventDefault(),u(null),x(!0);try{if(l){if(!P.trim()){u("Please enter your name"),x(!1);return}if(y==="student"&&!b){u("Please select a grade level"),x(!1);return}if(y==="admin"){u("Admin account creation is restricted. Please contact an existing administrator."),x(!1);return}if(!W){u(`Password does not meet signup requirements. ${I}`),x(!1);return}ee(y),await Ae(c,n,P,y,y==="student"?{grade:b,section:v}:{department:"Mathematics"})}else await te(c,n)}catch(r){const d=l?`Sign-up failed. ${I}`:"Sign-in failed. Please check your credentials and try again.";u(ae(r,d)),x(!1)}};return e.jsxs("div",{className:"min-h-screen w-full flex items-center justify-center px-4 sm:px-6 py-8 overflow-y-auto relative login-bg",children:[e.jsx("video",{ref:R,autoPlay:!0,muted:!0,playsInline:!0,preload:"auto",onCanPlay:()=>le(!0),onLoadedMetadata:ue,className:"absolute inset-0 w-full h-full object-cover transition-opacity duration-150 e-opacity",style:{"--o":xe},src:se}),e.jsx("video",{ref:C,autoPlay:!0,muted:!0,playsInline:!0,preload:"auto",onCanPlay:()=>ce(!0),onLoadedMetadata:pe,className:"absolute inset-0 w-full h-full object-cover transition-opacity duration-150 e-opacity",style:{"--o":ye},src:se}),e.jsx("div",{className:"absolute inset-0 pointer-events-none login-frost-overlay"}),e.jsx("div",{className:"absolute top-[10%] left-[-10%] w-[60%] h-[60%] rounded-full blur-[140px] pointer-events-none mix-blend-multiply login-orb-purple"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[70%] h-[70%] rounded-full blur-[160px] pointer-events-none mix-blend-multiply login-orb-pink"}),e.jsx("div",{className:"absolute top-[40%] left-[40%] w-[40%] h-[40%] rounded-full blur-[120px] pointer-events-none mix-blend-screen login-orb-blue"}),e.jsx("div",{className:"relative z-10 w-full max-w-6xl mx-auto",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12 items-center",children:[e.jsxs(i.div,{initial:{opacity:0,x:-40},animate:{opacity:1,x:0},transition:{duration:.8,ease:[.22,1,.36,1]},className:"flex flex-col items-center lg:items-start justify-center space-y-5 lg:space-y-8 text-center lg:text-left",children:[e.jsxs(i.div,{className:"flex items-center justify-center lg:justify-start gap-2.5",children:[e.jsx(i.div,{className:"relative flex items-center justify-center drop-shadow-md",children:e.jsx("img",{src:"/mathpulse_final_logo.png",alt:"MathPulse AI Logo",className:"w-10 h-10 lg:w-16 lg:h-16 object-contain flex-shrink-0"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl lg:text-3xl font-display font-black tracking-tight text-slate-900 bg-clip-text text-transparent bg-gradient-to-r from-purple-600 via-pink-600 to-sky-500",children:"MathPulse"}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[e.jsx(Me,{size:12,className:"text-rose-500"}),e.jsx("span",{className:"text-xs text-slate-500 font-body font-medium tracking-wide",children:"Powered by Machine Learning"})]})]})]}),e.jsxs(i.div,{className:"space-y-3 lg:space-y-5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2,duration:.8},children:[e.jsxs("h2",{className:"text-3xl sm:text-4xl lg:text-5xl xl:text-[3.4rem] font-display font-extrabold leading-[1.1] tracking-tight text-slate-900",children:["Transform Your",e.jsx("br",{}),e.jsx("span",{className:"bg-gradient-to-r from-sky-600 via-cyan-500 to-sky-500 bg-clip-text text-transparent",children:"Math Journey"})]}),e.jsx("p",{className:"text-sm lg:text-base text-slate-500 leading-relaxed max-w-md mx-auto lg:mx-0 font-body",children:"AI-powered predictive system designed to identify at-risk students and provide personalized learning recommendations."})]}),e.jsx("div",{className:"grid grid-cols-3 gap-2 lg:gap-3",children:[{icon:we,label:"AI Predictions",desc:"Smart detection",color:"sky"},{icon:Ne,label:"Analytics",desc:"Real-time data",color:"rose"},{icon:ke,label:"Gamified",desc:"Learn & earn",color:"emerald"}].map((t,r)=>{const d=t.icon,m={sky:"border-sky-200/60 hover:border-sky-300",rose:"border-rose-200/60 hover:border-rose-300",emerald:"border-emerald-200/60 hover:border-emerald-300"},k={sky:"text-sky-600",rose:"text-rose-500",emerald:"text-emerald-600"},p={sky:"bg-sky-100",rose:"bg-rose-100",emerald:"bg-emerald-100"};return e.jsxs(i.div,{className:`bg-white/80 backdrop-blur-xl border ${m[t.color]} rounded-xl p-3 lg:p-4 transition-all cursor-pointer group shadow-md shadow-slate-900/[0.04]`,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5+r*.1},whileHover:{scale:1.03,y:-4},children:[e.jsx("div",{className:`w-7 h-7 lg:w-9 lg:h-9 rounded-lg ${p[t.color]} flex items-center justify-center mx-auto lg:mx-0 mb-2 lg:mb-3`,children:e.jsx(d,{size:15,className:k[t.color]})}),e.jsx("h3",{className:"text-xs lg:text-sm font-display font-semibold text-slate-800 mb-0.5",children:t.label}),e.jsx("p",{className:"text-[10px] lg:text-xs text-slate-400 font-body",children:t.desc})]},r)})})]}),e.jsx(i.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.15,ease:[.22,1,.36,1]},className:"relative flex justify-center lg:justify-end",children:e.jsxs("div",{className:"bg-white/85 backdrop-blur-2xl border border-slate-200/60 rounded-3xl p-6 sm:p-7 w-full max-w-md relative overflow-hidden shadow-[0_20px_60px_-15px_rgba(168,85,247,0.15)] max-h-[85vh] overflow-y-auto",children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[3px] bg-gradient-to-r from-purple-500 via-pink-500 to-sky-500"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 w-80 h-80 bg-gradient-to-br from-purple-400/20 to-pink-400/20 rounded-full blur-[60px] pointer-events-none"}),e.jsxs("div",{className:"text-center mb-4 relative",children:[e.jsx(i.h3,{className:"text-2xl font-display font-bold text-slate-900 mb-2",initial:{opacity:0},animate:{opacity:1},transition:{delay:.4},children:l?"Create Account":"Welcome Back"}),e.jsx(i.p,{className:"text-sm text-slate-500 font-body",initial:{opacity:0},animate:{opacity:1},transition:{delay:.5},children:l?"Begin your learning journey":"Sign in to continue learning"})]}),e.jsxs("form",{onSubmit:fe,className:"space-y-3 mb-4 relative",children:[f&&!me&&e.jsx(i.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"bg-rose-50 border border-rose-200 text-rose-600 px-4 py-3 rounded-lg text-sm font-body",children:f}),l&&e.jsxs(i.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Full Name"}),e.jsxs("div",{className:"relative",children:[e.jsx(Q,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(L,{type:"text",placeholder:"Your Name",value:P,onChange:t=>ie(t.target.value),className:"w-full pl-11 pr-4 py-3 rounded-lg bg-slate-100/70 border-slate-200/80 text-slate-900 placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all",required:!0})]})]}),l&&e.jsxs(i.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.45},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Account Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{role:"student",label:"Student"},{role:"teacher",label:"Teacher"}].map(t=>{const r=y===t.role;return e.jsx("button",{type:"button",onClick:()=>D(t.role),className:`rounded-lg border px-3 py-2.5 text-sm font-body font-semibold transition-all ${r?"border-sky-400 bg-sky-50 text-sky-700":"border-slate-200 bg-slate-50 text-slate-500 hover:border-slate-300"}`,children:t.label},t.role)})})]}),l&&y==="student"&&e.jsx(i.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"space-y-3",children:e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Section"}),e.jsxs("div",{className:"relative",children:[e.jsx(Q,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("select",{value:v,onChange:t=>B(t.target.value),className:"w-full pl-11 pr-4 py-2.5 rounded-lg bg-slate-100/70 border border-slate-200/80 text-slate-900 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all appearance-none",required:!0,children:(a[b]||[]).map(t=>e.jsx("option",{value:t,children:t},t))})]})]})}),e.jsxs(i.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.5},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Re,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(L,{type:"email",placeholder:"your.email@school.edu",value:c,onChange:t=>o(t.target.value),className:"w-full pl-11 pr-4 py-3 rounded-lg bg-slate-100/70 border-slate-200/80 text-slate-900 placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all",required:!0})]})]}),e.jsxs(i.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.6},children:[e.jsx("label",{className:"block text-xs font-body font-semibold text-slate-500 mb-2 uppercase tracking-wider",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(X,{size:16,className:"absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(L,{type:S?"text":"password",placeholder:"••••••••",value:n,onChange:t=>h(t.target.value),className:"w-full pl-11 pr-11 py-3 rounded-lg bg-slate-100/70 border-slate-200/80 text-slate-900 placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-400/20 focus:bg-white text-sm font-body transition-all",required:!0,minLength:l?8:6}),e.jsx(i.button,{type:"button",onClick:()=>re(!S),className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors",whileTap:{scale:.9},children:S?e.jsx(Ce,{size:16}):e.jsx(Ee,{size:16})})]}),l&&n.length>0&&!W&&e.jsxs("div",{className:"mt-2 rounded-lg border border-sky-100/80 bg-sky-50/70 px-3 py-2",children:[e.jsx("p",{className:"text-[11px] font-body font-semibold uppercase tracking-wider text-slate-600",children:"Password requirements"}),e.jsx("ul",{className:"mt-2 space-y-1",children:E.map(t=>e.jsxs("li",{className:`flex items-center gap-2 text-[11px] font-body ${t.met?"text-emerald-700":"text-slate-500"}`,children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${t.met?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{children:t.label})]},t.id))})]})]}),e.jsx(i.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.7},children:e.jsxs(je,{type:"submit",disabled:_,className:"w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-500 hover:to-pink-400 text-white font-body font-semibold py-3 rounded-xl shadow-lg shadow-purple-600/25 hover:shadow-pink-500/35 hover:scale-[1.02] transition-all text-sm group relative overflow-hidden disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(i.span,{className:"absolute inset-0 bg-gradient-to-r from-white/0 via-white/15 to-white/0",animate:{x:["-100%","100%"]},transition:{duration:3,repeat:1/0,repeatDelay:2}}),e.jsxs("span",{className:"relative flex items-center justify-center gap-2",children:[_?"Please wait...":l?"Create Account":"Sign In",e.jsx(K,{size:16,className:"group-hover:translate-x-1 transition-transform"})]})]})}),e.jsx("div",{className:"text-center",children:e.jsx("button",{type:"button",onClick:()=>{z(!l),u(null)},className:"text-sm text-slate-400 hover:text-sky-500 font-body font-medium transition-colors",children:l?"Already have an account? Sign in":"Don't have an account? Create one"})})]}),!l&&e.jsxs(i.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.85},className:"mb-4 relative",children:[e.jsxs("div",{className:"relative flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"flex-1 h-px bg-slate-200"}),e.jsx("span",{className:"text-[10px] font-body font-semibold text-slate-400 uppercase tracking-widest",children:"Quick Demo Access"}),e.jsx("div",{className:"flex-1 h-px bg-slate-200"})]}),e.jsx("div",{className:"flex flex-col gap-2",children:he.map(t=>{const r=t.icon,d={sky:"bg-sky-100",emerald:"bg-emerald-100",rose:"bg-rose-100"},m={sky:"text-sky-600",emerald:"text-emerald-600",rose:"text-rose-500"};return e.jsxs(i.button,{type:"button",onClick:()=>be(t.email,t.password,t.role),className:"group flex items-center gap-3 w-full px-4 py-2.5 rounded-lg bg-slate-50/80 border border-slate-200/70 hover:border-sky-300 hover:bg-sky-50/80 hover:shadow-sm transition-all text-left",whileHover:{scale:1.01},whileTap:{scale:.99},children:[e.jsx("div",{className:`w-8 h-8 rounded-md flex items-center justify-center shrink-0 ${d[t.color]}`,children:e.jsx(r,{size:15,className:m[t.color]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs font-body font-semibold text-slate-700 group-hover:text-sky-600 transition-colors",children:[t.label," Account"]}),e.jsx("p",{className:"text-[10px] text-slate-400 font-body truncate",children:t.email})]}),e.jsx(K,{size:14,className:"text-slate-300 group-hover:text-sky-500 group-hover:translate-x-0.5 transition-all shrink-0"})]},t.label)})})]}),e.jsxs(i.p,{className:"text-xs text-slate-400 text-center mt-4 font-body relative",initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx(X,{size:10,className:"inline mr-1 -mt-0.5"})," Your data is encrypted and secure"]})]})})]})})]})};export{et as default}; diff --git a/assets/LogoutActionButton-Cu6gWsBL.js b/assets/LogoutActionButton-Baak8j6y.js similarity index 94% rename from assets/LogoutActionButton-Cu6gWsBL.js rename to assets/LogoutActionButton-Baak8j6y.js index c5c1da8fd5286ca982ee89a63897147364279d7a..cd0a2d53ed054a6137514b690c4daad353bcfc75 100644 --- a/assets/LogoutActionButton-Cu6gWsBL.js +++ b/assets/LogoutActionButton-Baak8j6y.js @@ -1,4 +1,4 @@ -import{e,m as r,o as l}from"./index-BvEKrMkD.js";import{j as t}from"./vendor-react-B4AQeu28.js";import{L as n}from"./log-out-BDL1J1Fs.js";/** +import{e,m as r,o as l}from"./index-BdLfAeGL.js";import{j as t}from"./vendor-react-B4AQeu28.js";import{L as n}from"./log-out-CccGdaTy.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ModuleFolderCard-CS_0Dtn3.js b/assets/ModuleFolderCard-CXTwxNMY.js similarity index 97% rename from assets/ModuleFolderCard-CS_0Dtn3.js rename to assets/ModuleFolderCard-CXTwxNMY.js index b4727444b35a74585434c8c66412bd5c75cfc2f4..255d49f0c55d589bf68afcd4719dd2cd86641714 100644 --- a/assets/ModuleFolderCard-CS_0Dtn3.js +++ b/assets/ModuleFolderCard-CXTwxNMY.js @@ -1,4 +1,4 @@ -import{j as e,r as h}from"./vendor-react-B4AQeu28.js";import{u as j}from"./useSubjectAvailability-C0TzAHAR.js";import{a as y}from"./deepseekRagService-Bke9fSTt.js";import{e as u,m as N,b as k,y as _,G as B}from"./index-BvEKrMkD.js";import{C as z}from"./clock-0vnF72R6.js";import{B as A}from"./bell-C57aSZcx.js";import{I as M}from"./info-CMvRmbQw.js";/** +import{j as e,r as h}from"./vendor-react-B4AQeu28.js";import{u as j}from"./useSubjectAvailability-BUrciGBC.js";import{a as y}from"./deepseekRagService-Bke9fSTt.js";import{e as u,m as N,b as k,y as _,G as B}from"./index-BdLfAeGL.js";import{C as z}from"./clock-CpBwkoND.js";import{B as A}from"./bell-C5_RRTsA.js";import{I as M}from"./info-D1mJ7S8g.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ModulesPage-BgmrOnnq.js b/assets/ModulesPage-DdfzGaQY.js similarity index 93% rename from assets/ModulesPage-BgmrOnnq.js rename to assets/ModulesPage-DdfzGaQY.js index 03271951a15f925dd66475daa32071bc0ff772c8..49e2f5ef5bff6cdede6bc4c69b0275d30f801d85 100644 --- a/assets/ModulesPage-BgmrOnnq.js +++ b/assets/ModulesPage-DdfzGaQY.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{j as e,r as a,b as Et,d as Fe,c as Gs}from"./vendor-react-B4AQeu28.js";import{u as Xs}from"./useQuery-a95tRwQa.js";import{doc as mt,onSnapshot as as,setDoc as Vs,serverTimestamp as Ps,getDoc as Yt,runTransaction as Ys,query as Ks,where as Zs,collection as Js}from"./vendor-firebase-firestore-CNv3xXal.js";import{e as ue,g as Ue,ae as ea,_ as St,m as E,Z as Ke,h as Je,$ as Kt,b as qe,w as rt,a as Ye,r as We,a7 as Tt,C as pt,M as ta,L as rs,T as Lt,u as Ht,A as zt,o as Mt,y as Ls,R as Rt,ad as Zt,af as sa,ag as ms,ah as aa,q as Rs,ai as ra,F as Ds,B as la,aj as na,ak as Is,al as ia,am as oa,an as ca,ab as da,x as ma,ao as xs,ap as xa,aq as us,j as st,G as ua,a9 as pa,ac as ha}from"./index-BvEKrMkD.js";import{M as Jt}from"./ModuleFolderCard-CS_0Dtn3.js";import{B as Oe}from"./button-Bfg1pO9T.js";import{M as fa,r as ba,a as ga}from"./vendor-markdown-yqZQ_iQm.js";import{triggerQuizSubmitted as ya}from"./automationService-Ckfa20vv.js";import{g as wa,h as ja,A as es,V as va,e as Na,P as Dt,a as ka,M as Ca,L as Sa,E as za}from"./quizService-D6WAd8P5.js";import Fs from"./ScientificCalculator-B-rMzwD3.js";import{C as Pt}from"./check-BmWAQELM.js";import{X as Ze}from"./x-BYtx1i07.js";import{C as ht}from"./clock-0vnF72R6.js";import{V as ts,a as ss,M as $s,b as qs}from"./volume-x-C2kyFHU5.js";import{C as ps}from"./chevron-left-DFU37_wB.js";import{C as ut}from"./chevron-right-CbKJd0ln.js";import{C as Wt,L as ct}from"./lightbulb-BpvAgebC.js";import{C as at}from"./circle-check-big-mtMsU82c.js";import{C as Ut}from"./circle-help-DeWZHKak.js";import{logLessonView as _a}from"./trackingService-SBoVE94r.js";import{C as Ma}from"./clipboard-check-jJ306e7q.js";import{s as At,S as hs}from"./subjects-ChEJ6J55.js";import{B as Aa}from"./badge-check-Dir1sWA0.js";import{C as _t}from"./circle-check-E415RSic.js";import{H as Ea}from"./history-uiZLfMqH.js";import{C as Ta}from"./chart-column-DKW3TTRX.js";import{D as Pa}from"./dollar-sign-DWer_VPF.js";import fs from"./confetti.module-C94ZD2ww.js";import{G as La}from"./gift-CL3L8vH3.js";import{u as Ra}from"./useCurriculum-CSvqmu2B.js";import{w as Da}from"./moduleWatchService-Boczzqau.js";import{S as Ia}from"./search-CHZcTJmD.js";import{F as Fa}from"./funnel-CAdiZoOH.js";import{S as $a}from"./sparkles-av0wSNZT.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./useSubjectAvailability-C0TzAHAR.js";import"./deepseekRagService-Bke9fSTt.js";import"./bell-C57aSZcx.js";import"./info-CMvRmbQw.js";import"./chevron-up-CDr90bpM.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{j as e,r as a,b as Et,d as Fe,c as Gs}from"./vendor-react-B4AQeu28.js";import{u as Xs}from"./useQuery-fA8_Syr9.js";import{doc as mt,onSnapshot as as,setDoc as Vs,serverTimestamp as Ps,getDoc as Yt,runTransaction as Ys,query as Ks,where as Zs,collection as Js}from"./vendor-firebase-firestore-CNv3xXal.js";import{e as ue,g as Ue,ae as ea,_ as St,m as E,Z as Ke,h as Je,$ as Kt,b as qe,w as rt,a as Ye,r as We,a7 as Tt,C as pt,M as ta,L as rs,T as Lt,u as Qt,A as zt,o as Mt,y as Ls,R as Rt,ad as Zt,af as sa,ag as ms,ah as aa,q as Rs,ai as ra,F as Ds,B as la,aj as na,ak as Is,al as ia,am as oa,an as ca,ab as da,x as ma,ao as xs,ap as xa,aq as us,j as st,G as ua,a9 as pa,ac as ha}from"./index-BdLfAeGL.js";import{M as Jt}from"./ModuleFolderCard-CXTwxNMY.js";import{B as Oe}from"./button-BbJLXpfi.js";import{M as fa,r as ba,a as ga}from"./vendor-markdown-yqZQ_iQm.js";import{triggerQuizSubmitted as ya}from"./automationService-BoxXP8NH.js";import{g as wa,h as ja,A as es,V as va,e as Na,P as Dt,a as ka,M as Ca,L as Sa,E as za}from"./quizService-DxWImmI3.js";import Fs from"./ScientificCalculator-DQTxoI7Z.js";import{C as Pt}from"./check-DbVe23hB.js";import{X as Ze}from"./x-BLhsirCD.js";import{C as ht}from"./clock-CpBwkoND.js";import{V as ts,a as ss,M as $s,b as qs}from"./volume-x-BfFSlkII.js";import{C as ps}from"./chevron-left-CNwzgiLt.js";import{C as ut}from"./chevron-right-BRRve0zL.js";import{C as Wt,L as ct}from"./lightbulb-W3LO7x3u.js";import{C as at}from"./circle-check-big-B54zXy3k.js";import{C as Ut}from"./circle-help-CZDuv1Gp.js";import{logLessonView as _a}from"./trackingService-DJ3_U-Mf.js";import{C as Ma}from"./clipboard-check-hgJTQlzs.js";import{s as At,S as hs}from"./subjects-Dw9HR29l.js";import{B as Aa}from"./badge-check-4jI3r8US.js";import{C as _t}from"./circle-check-CuVe-qlS.js";import{H as Ea}from"./history-VIZhCw1O.js";import{C as Ta}from"./chart-column-Dl7iJ2BC.js";import{D as Pa}from"./dollar-sign-BFLnKeOT.js";import fs from"./confetti.module-C94ZD2ww.js";import{G as La}from"./gift-CHSGDZhC.js";import{u as Ra}from"./useCurriculum-DZL96a-v.js";import{w as Da}from"./moduleWatchService-Ck2BKbab.js";import{S as Ia}from"./search-gQ2OCqgd.js";import{F as Fa}from"./funnel-ijCItoBZ.js";import{S as $a}from"./sparkles-DnAkO9TX.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./useSubjectAvailability-BUrciGBC.js";import"./deepseekRagService-Bke9fSTt.js";import"./bell-C5_RRTsA.js";import"./info-D1mJ7S8g.js";import"./chevron-up-uSn_SWll.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -14,12 +14,12 @@ import{j as e,r as a,b as Et,d as Fe,c as Gs}from"./vendor-react-B4AQeu28.js";im * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Ha=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],gs=ue("bookmark",Ha);/** + */const Qa=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],gs=ue("bookmark",Qa);/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Qa=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],ys=ue("box",Qa);/** + */const Ha=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],ys=ue("box",Ha);/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -146,9 +146,9 @@ import{j as e,r as a,b as Et,d as Fe,c as Gs}from"./vendor-react-B4AQeu28.js";im height: 10px; animation: confetti-fall linear forwards; } -`,Er=({viewportHeight:t})=>e.jsx("div",{className:"absolute inset-0 pointer-events-none z-[250] overflow-hidden flex justify-between bg-slate-900/5",children:Fe.useMemo(()=>[...Array(40)].map((s,l)=>({id:l,left:`${Math.random()*100}%`,duration:.6+Math.random()*.4,delay:Math.random()*.4})),[t]).map(s=>e.jsx(E.div,{className:"absolute w-0.5 h-16 bg-blue-400/30 rounded-full",style:{left:s.left,top:"-10%"},animate:{y:[0,t*1.2]},transition:{duration:s.duration,ease:"linear",delay:s.delay}},s.id))}),Tr=()=>{const t=Fe.useMemo(()=>[...Array(60)].map((s,l)=>({id:l,left:`${Math.random()*100}%`,backgroundColor:["#75D06A","#6ED1CF","#9956DE","#FB96BB","#FFB356"][l%5],duration:2+Math.random()*2,delay:Math.random()*.5,size:6+Math.random()*8,borderRadius:Math.random()>.5?"50%":"2px"})),[]);return e.jsx("div",{className:"absolute inset-0 pointer-events-none z-[250] overflow-hidden",children:t.map(s=>e.jsx("div",{className:"confetti-piece",style:{left:s.left,top:"-10%",backgroundColor:s.backgroundColor,width:s.size,height:s.size,borderRadius:s.borderRadius,animationDuration:`${s.duration}s`,animationDelay:`${s.delay}s`}},s.id))})},Pr=({viewportHeight:t,viewportWidth:s})=>{const l=Fe.useMemo(()=>[...Array(30)].map((n,i)=>({id:i,xShift:(Math.random()-.5)*s*.8,yShift:(Math.random()-.5)*t*.8,scale:Math.random()*1.5+.5,duration:2+Math.random()*1.5,delay:Math.random()*.35})),[t,s]);return e.jsx("div",{className:"absolute inset-0 pointer-events-none z-[250] overflow-hidden flex items-center justify-center",children:l.map(n=>e.jsx(E.div,{className:"absolute w-2 h-2 bg-amber-400 rounded-full shadow-[0_0_10px_rgba(251,191,36,0.5)]",style:{left:"50%",top:"50%"},animate:{y:[0,n.yShift],x:[0,n.xShift],scale:[0,n.scale,0],opacity:[0,1,0]},transition:{duration:n.duration,ease:"easeOut",delay:n.delay}},n.id))})},ks=({value:t,label:s,delay:l=0,icon:n})=>{const[i,c]=Fe.useState(0);return Fe.useEffect(()=>{if(t<=0)return;const r=1e3,x=30,d=Math.abs(Math.floor(r/x));let h=0;const S=setTimeout(()=>{const m=setInterval(()=>{h+=Math.max(1,Math.floor(t/x)),h>=t?(c(t),clearInterval(m)):c(h)},d);return()=>clearInterval(m)},l);return()=>clearTimeout(S)},[t,l]),t<0?null:e.jsxs(E.div,{initial:{opacity:0,transform:"translateX(-20px)"},animate:{opacity:1,transform:"translateX(0)"},transition:{delay:l/1e3,duration:.5},className:"flex items-center justify-between bg-slate-50 border border-slate-100 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-3 text-slate-500 font-bold uppercase tracking-wider text-[10px]",children:[n,s]}),e.jsxs("div",{className:"text-xl font-black text-purple-600 tabular-nums",children:["+",i]})]})};function Lr(t){if(t.questionType==="multiple_choice"&&t.options&&t.options.length>0){const s=t.options.findIndex(l=>l.trim().toLowerCase()===t.correctAnswer.trim().toLowerCase());return{id:t.id,question:t.question,options:t.options,correctAnswer:s>=0?s:0,correctAnswerText:t.correctAnswer,explanation:t.explanation,questionType:t.questionType,points:t.points,difficulty:t.difficulty,topic:t.topic,bloomLevel:t.bloomLevel}}return{id:t.id,question:t.question,options:[],correctAnswer:-1,correctAnswerText:t.correctAnswer,explanation:t.explanation,questionType:t.questionType,points:t.points,difficulty:t.difficulty,topic:t.topic,bloomLevel:t.bloomLevel}}function Cs(t){return t.replace(/²/g,"^2").replace(/³/g,"^3").replace(/⁻¹/g,"^-1").replace(/⁰/g,"^0").replace(/¹/g,"^1").replace(/⁴/g,"^4").replace(/⁵/g,"^5").replace(/⁶/g,"^6").replace(/⁷/g,"^7").replace(/⁸/g,"^8").replace(/⁹/g,"^9").replace(/π/g,"pi").replace(/√/g,"sqrt").replace(/×/g,"*").replace(/÷/g,"/").replace(/\s+/g,"").toLowerCase().trim()}function Rr(t,s,l){const n=i=>i.trim().toLowerCase().replace(/\s+/g," ");switch(l){case"identification":return n(t)===n(s);case"enumeration":{const i=t.split(",").map(r=>n(r)).filter(Boolean).sort(),c=s.split(",").map(r=>n(r)).filter(Boolean).sort();return JSON.stringify(i)===JSON.stringify(c)}case"word_problem":case"equation_based":{const i=Cs(t),c=Cs(s);if(i===c)return!0;const r=parseFloat(t.replace(/[^\d.\-]/g,"")),x=parseFloat(s.replace(/[^\d.\-]/g,""));return!isNaN(r)&&!isNaN(x)?Math.abs(r-x)<=.01:n(t)===n(s)}default:return n(t)===n(s)}}const Bs=({quiz:t,onClose:s,onComplete:l,onQuizEnd:n,studentId:i,atRiskSubjects:c=[]})=>{const[r,x]=a.useState(0),[d,h]=a.useState(null),[S,m]=a.useState(""),[z,p]=a.useState(!1),[u,k]=a.useState(!1),[f,C]=a.useState(!1),[N,R]=a.useState(0),[T,F]=a.useState(0),[X,Z]=a.useState(1),[Y,te]=a.useState([]),[$,pe]=a.useState([]),[he,ze]=a.useState(Date.now()),[Ce,b]=a.useState(!1),[H,ce]=a.useState(!1),[ae,le]=a.useState(null),[ge,Ne]=a.useState(0),[B,Ee]=a.useState(0),[_e,ye]=a.useState(!1),[fe,Me]=a.useState(!1),[Ae,g]=a.useState(!0),[q,M]=a.useState(!1),[O,I]=a.useState({width:1280,height:720});a.useEffect(()=>{const A=()=>I({width:window.innerWidth,height:window.innerHeight});return A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[]);const[J,be]=a.useState(0),[ke,D]=a.useState({}),[ne,me]=a.useState(!1),[Ge,ft]=a.useState(!1),[bt,De]=a.useState(!1),{totalHintsAvailable:Xe}=Ar(i||null),[et,j]=a.useState(5),[Te,lt]=a.useState(15),Le=et+Xe,[Be,gt]=a.useState(null),[nt,Ve]=a.useState(!1),[it,ot]=a.useState(900*1e3),[o,P]=a.useState([]),[y,L]=a.useState(0),[K,de]=a.useState(null),[ie]=a.useState(()=>t.loadedQuestions&&t.loadedQuestions.length>0?t.loadedQuestions.map(Lr):Array.from({length:t.questions},(A,_)=>({id:`q${_+1}`,question:Dr(t.subject,_),options:Ir(t.subject,_),correctAnswer:Fr(t.subject,_),explanation:$r(t.subject,_,t.difficulty)})));a.useEffect(()=>{D({}),P([]),j(5),lt(15),be(0),R(0),F(0),Z(1)},[t.id]);const xe=ie[r];a.useEffect(()=>{const A=parseInt(t.duration)||10;Ne(A*60);const _=setInterval(()=>{Ne(ee=>ee<=1?(clearInterval(_),w(),0):ee-1)},1e3);return()=>clearInterval(_)},[]),a.useEffect(()=>{Te===0&&!Be&&(gt(Date.now()),Ve(!0))},[Te,Be]),a.useEffect(()=>{if(!nt||!Be)return;const A=setInterval(()=>{const _=Date.now()-Be,ee=Math.max(0,900*1e3-_);ot(ee)},1e3);return()=>clearInterval(A)},[nt,Be]);const[je,He]=a.useState(Array.from({length:15},(A,_)=>({id:_,size:Math.random()*120+40,x:Math.random()*100,y:Math.random()*100,duration:Math.random()*20+15,delay:Math.random()*-20,color:["bg-purple-500/10","bg-blue-500/10","bg-cyan-500/10","bg-emerald-500/10"][Math.floor(Math.random()*4)]}))),we=A=>{if(Ae)try{const _=window.AudioContext||window.webkitAudioContext;if(!_)return;const ee=new _,G=ee.currentTime,V=(Ie,Qe,Re,tt=.1,Pe="sine")=>{const Se=ee.createOscillator(),xt=ee.createGain();Se.type=Pe,Se.frequency.value=Ie,xt.gain.setValueAtTime(0,Qe),xt.gain.linearRampToValueAtTime(tt,Qe+.05),xt.gain.exponentialRampToValueAtTime(.001,Qe+Re),Se.connect(xt),xt.connect(ee.destination),Se.start(Qe),Se.stop(Qe+Re)};A==="correct"?(V(880,G,.1,.1,"sine"),V(1108.73,G+.1,.2,.1,"sine")):A==="incorrect"?(V(300,G,.2,.05,"sawtooth"),V(250,G+.15,.3,.05,"sawtooth")):A==="combo"?(V(440,G,.1,.05,"square"),V(554.37,G+.1,.1,.05,"square"),V(659.25,G+.2,.1,.05,"square"),V(880,G+.3,.4,.05,"square")):A==="complete"&&(V(523.25,G,.1,.1),V(659.25,G+.15,.1,.1),V(783.99,G+.3,.1,.1),V(1046.5,G+.45,.5,.1))}catch{}},w=()=>{b(!0),se()},v=()=>{n?.(t,$),s()},Q=()=>{if(et<=0||u)return;const A=ke[r]||[],_=xe.options.filter(G=>G!==xe.correctAnswerText).filter(G=>!A.includes(G));if(_.length===0)return;const ee=_[Math.floor(Math.random()*_.length)];D(G=>({...G,[r]:[...A,ee]})),j(G=>Math.max(0,G-1)),we("correct")},W=A=>{u||U||(h(A),setTimeout(()=>{re(A)},150))},re=A=>{const _=xe.questionType!=null&&xe.questionType!=="multiple_choice",ee=A!==void 0?A:d;if(_){if(!S.trim())return}else if(ee===null)return;const G=_?Rr(S,xe.correctAnswerText||"",xe.questionType||""):ee===xe.correctAnswer,V=_?S:String(ee),Ie=Math.round((Date.now()-he)/1e3);pe(Se=>[...Se,{questionId:xe.id,answer:V,correct:G,timeSpent:Ie}]);const Qe=[...Y];if(Qe[r]=G?1:0,te(Qe),p(G),k(!0),!G){ft(!0),we("incorrect"),setTimeout(()=>ft(!1),500),lt(Se=>Math.max(0,Se-1)),F(0),Z(1),setTimeout(()=>{ve()},1500);return}we("correct");const tt=(ke[r]||[]).length>0?5:10;be(Se=>Se+tt),R(N+1);const Pe=T+1;F(Pe),Pe===2?de("streak"):Pe===3&&X<2?de("multiplier2"):Pe===5&&X<3&&de("multiplier3"),Pe>0&&Pe%3===0&&we("combo"),Pe>=5?Z(3):Pe>=3?Z(2):Z(1),St(()=>import("./confetti.module-C94ZD2ww.js"),[]).then(Se=>{Se.default({particleCount:30,spread:40,colors:["#75D06A","#6ED1CF"],origin:{y:.6}})}),De(!0),setTimeout(()=>{De(!1),de(null),setTimeout(()=>ve(),300)},1500)},ve=()=>{if(r{const A=Math.round(N/ie.length*100);let _=t.xpReward;A>=90?_=Math.round(_*1.5):A>=80&&(_=Math.round(_*1.25));const ee=parseInt(t.duration)*60;ge>ee*.5&&(_=Math.round(_*1.2)),Ee(_);const G=ee-ge;i&&ya({lrn:i,quizId:t.id,subject:t.subject,score:A,totalQuestions:ie.length,correctAnswers:N,timeSpentSeconds:G}).catch(V=>console.error("[WARN] Automation: quiz pipeline failed:",V)),t.source==="ai_generated"&&i?wa(i,t.id,t.generatedQuizId,t.subject,t.source,A,_,G,$,ie.map(V=>({topic:V.topic||t.subject,difficulty:V.difficulty||"medium",bloomLevel:V.bloomLevel||"understand"}))).catch(V=>console.error("[WARN] Quiz result save failed:",V)):i&&ea(i,t.id,t.subject,A,$.map(V=>({questionId:V.questionId,selectedAnswer:V.answer,isCorrect:V.correct})),G).catch(V=>console.error("[WARN] Practice quiz persist failed:",V)),i&&St(async()=>{const{saveAssessmentResult:V}=await import("./index-BvEKrMkD.js").then(Ie=>Ie.ba);return{saveAssessmentResult:V}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({saveAssessmentResult:V})=>{V({uid:i,testId:t.id,title:t.title||t.id,subject:t.subject||"General Mathematics",type:t.source==="ai_generated"?"quiz":"practice",score:A,totalQuestions:ie.length,risk:A<60?"High":"Low",intervention:"",xpEarned:_,badgeUnlocked:""}).catch(Ie=>console.error("[WARN] Assessment record save failed:",Ie))}),we("complete"),l?.(A,_)},U=y{document.fullscreenElement?(document.exitFullscreen().catch(()=>{}),M(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),M(!0))};if(Ce){const A=Math.round(N/ie.length*100),_=A>=80,ee=A>=50&&A<80,G=A<50,V=document.getElementById("modal-root"),Ie=e.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm",children:[e.jsx("style",{children:Ns}),_&&e.jsx(Tr,{}),ee&&e.jsx(Pr,{viewportHeight:O.height,viewportWidth:O.width}),G&&e.jsx(Er,{viewportHeight:O.height}),e.jsxs(E.div,{initial:{opacity:0,scale:.8,y:40},animate:{opacity:1,scale:1,y:0},transition:{type:"spring",damping:18,stiffness:200},className:"w-full max-w-xs sm:max-w-sm bg-white border-2 border-slate-200 shadow-[0_25px_60px_rgba(0,0,0,0.15)] rounded-[2rem] p-4 sm:p-5 text-center relative z-10",children:[e.jsx(E.div,{initial:{scale:0,rotate:-180},animate:{scale:1,rotate:0},transition:{type:"spring",damping:12,stiffness:150,delay:.2},className:"mb-3",children:e.jsx("img",{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-16 h-16 sm:w-20 sm:h-20 mx-auto drop-shadow-xl animate-mascot-float"})}),e.jsx(E.h2,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.3},className:`text-xl sm:text-2xl font-black uppercase tracking-tight mb-1 drop-shadow-sm ${_?"text-emerald-500":ee?"text-amber-500":"text-rose-500"}`,children:_?"EXCELLENT!":ee?"GOOD JOB!":"KEEP TRYING!"}),e.jsxs("p",{className:"text-slate-400 font-bold text-[10px] mb-3 uppercase tracking-widest",children:["Quiz Complete • Score: ",N,"/",ie.length]}),e.jsx(E.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.4},className:"bg-slate-50/50 rounded-xl p-3 mb-4 border border-slate-100 flex flex-col gap-2",children:e.jsxs("div",{children:[e.jsx("h3",{className:"text-slate-400 text-[9px] font-black uppercase tracking-widest text-left mb-1.5 ml-1",children:"Performance Details"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ks,{value:N,label:"Correct Answers",delay:500,icon:e.jsx(Pt,{className:"h-3 w-3 text-emerald-500"})}),e.jsx(ks,{value:B,label:"Total XP Earned",delay:800,icon:e.jsx(Ke,{className:"h-3 w-3 text-amber-500"})}),e.jsxs(E.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2,duration:.4},className:"flex items-center justify-between pt-1.5 mt-1 border-t border-slate-100",children:[e.jsx("span",{className:"text-slate-400 text-[9px] font-black uppercase tracking-widest",children:"Final Accuracy"}),e.jsxs("span",{className:"text-lg font-black text-slate-800 tabular-nums",children:[A,"%"]})]})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{size:"lg",onClick:()=>{x(0),L(0),h(null),m(""),R(0),F(0),Z(1),te([]),pe([]),be(0),b(!1),k(!1),C(!1),ze(Date.now()),D({}),P([]),me(!1),j(5),ce(!1)},className:"w-full h-10 sm:h-11 rounded-2xl text-xs font-black bg-white hover:bg-slate-50 text-purple-600 border-2 border-purple-100",children:"RETAKE QUIZ"}),e.jsx(Oe,{size:"lg",onClick:v,className:"w-full h-10 sm:h-11 rounded-2xl text-xs font-black bg-purple-600 hover:bg-purple-700 text-white shadow-lg shadow-purple-200",children:"FINISH"})]})]})]});return Et.createPortal(Ie,V)}return e.jsxs(e.Fragment,{children:[e.jsx("style",{children:Ns}),_e&&Et.createPortal(e.jsx(E.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:"fixed right-6 top-1/2 -translate-y-1/2 z-[9999] w-64",children:e.jsxs("div",{className:"bg-white rounded-2xl p-3 border border-slate-200 shadow-[0_10px_40px_rgba(0,0,0,0.3)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("h4",{className:"text-xs font-bold text-[#0a1628] flex items-center gap-2",children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-purple-600",children:[e.jsx("rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}),e.jsx("line",{x1:"8",x2:"16",y1:"6",y2:"6"})]}),"Calculator"]}),e.jsx("button",{onClick:()=>ye(!1),className:"w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 hover:text-slate-800 hover:bg-slate-200 transition-colors",children:e.jsx(Ze,{size:12})})]}),e.jsx(Fs,{isOpen:!0,onClose:()=>ye(!1),inline:!0})]})}),document.getElementById("modal-root")),nt&&Et.createPortal(e.jsx("div",{className:"fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-900/50",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-[2rem] p-6 max-w-xs w-full text-center border-2 border-rose-200 shadow-[0_25px_60px_rgba(0,0,0,0.15)]",children:[e.jsx(E.div,{animate:{scale:[1,1.1,1]},transition:{duration:1,repeat:1/0},className:"text-6xl mb-4",children:e.jsx(nr,{className:"w-10 h-10 text-rose-500"})}),e.jsx("h2",{className:"text-2xl font-black text-slate-800 mb-3",children:"Out of Lives!"}),e.jsx("p",{className:"text-slate-500 text-sm mb-4",children:"Your hearts have run out. You can wait for them to refill or head back and review your lessons in the meantime."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2 text-rose-500 font-bold",children:[e.jsx("img",{src:"/icons/quiz_heart.png",alt:"Hearts",className:"w-5 h-5"}),e.jsx("span",{children:"0 / 15 hearts"})]}),e.jsxs("p",{className:"text-slate-400 text-xs mb-4",children:["Next heart in: ",e.jsxs("span",{className:"font-bold text-slate-600",children:[Math.floor(it/6e4),":",Math.floor(it%6e4/1e3).toString().padStart(2,"0")]})," (15 minutes per heart)"]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{onClick:v,className:"w-full py-3 bg-rose-500 hover:bg-rose-600 text-white font-bold rounded-full",children:"Exit Quiz"}),e.jsx(Oe,{onClick:()=>{Ve(!1)},className:"w-full py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold rounded-full",children:"Review Lessons"})]})]})}),document.getElementById("modal-root")),e.jsx(Je,{children:bt&&z&&e.jsx(E.div,{initial:{opacity:0,scale:.8,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:1.1,filter:"blur(10px)"},transition:{type:"spring",damping:20,stiffness:300},className:"fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[200] pointer-events-none flex flex-col items-center justify-center",children:e.jsxs("div",{className:"bg-white/95 backdrop-blur-xl border border-slate-200 rounded-[2rem] p-6 md:p-8 shadow-[0_30px_80px_rgba(0,0,0,0.15)] flex flex-col items-center min-w-[280px] md:min-w-[320px]",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-24 h-24 md:w-32 md:h-32 mb-4 drop-shadow-[0_10px_20px_rgba(0,0,0,0.15)]"}),e.jsx("h2",{className:"text-3xl md:text-4xl font-black mb-4 uppercase tracking-widest text-emerald-500",children:"Correct!"}),e.jsxs("div",{className:"flex flex-col items-center gap-3 w-full justify-center",children:[e.jsx("div",{className:"flex items-center gap-2 bg-emerald-500/20 text-emerald-400 px-4 py-2 rounded-full font-bold border border-emerald-500/30",children:e.jsxs("span",{children:["+ ",(ke[r]||[]).length>0?5:10," XP"]})}),K==="streak"&&e.jsxs("div",{className:"flex items-center gap-2 bg-orange-500/20 text-orange-400 px-4 py-1.5 rounded-full text-sm font-bold border border-orange-500/30",children:[e.jsx(Kt,{size:14})," Streak Started!"]}),K==="multiplier2"&&e.jsxs("div",{className:"flex items-center gap-2 bg-amber-500/20 text-amber-400 px-4 py-1.5 rounded-full text-sm font-bold border border-amber-500/30",children:[e.jsx(Ke,{size:14})," Multiplier ×2!"]}),K==="multiplier3"&&e.jsxs("div",{className:"flex items-center gap-2 bg-amber-500/20 text-amber-400 px-4 py-1.5 rounded-full text-sm font-bold border border-amber-500/30",children:[e.jsx(Ke,{size:14})," Multiplier ×3!"]})]})]})},"round-result")}),e.jsxs("div",{className:"fixed inset-0 z-[100] h-screen w-full flex flex-col bg-slate-50 overflow-hidden",children:[e.jsxs("header",{className:"relative shrink-0 flex flex-col items-center justify-start px-4 pt-4 sm:pt-6 pb-6 z-[60] shadow-md overflow-hidden bg-gradient-to-r from-purple-600 to-indigo-400 rounded-b-[32px] sm:rounded-b-[40px] min-h-[110px] sm:min-h-[130px]",children:[e.jsxs("div",{className:"absolute inset-0 z-0 pointer-events-none",children:[e.jsx("div",{className:"absolute top-0 left-0 w-64 h-64 bg-white opacity-10 rounded-full -translate-x-1/2 -translate-y-1/2 blur-2xl"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-80 h-80 bg-white opacity-10 rounded-full translate-x-1/3 translate-y-1/3 blur-3xl"})]}),e.jsxs("div",{className:"w-full max-w-7xl flex items-center justify-between relative z-10 mb-3 sm:mb-4 md:mb-6",children:[e.jsx("div",{className:"flex-1 flex items-center gap-1 sm:gap-2",children:e.jsxs("div",{className:"flex items-center gap-1 bg-white/20 px-2 py-1 sm:px-3 sm:py-1.5 rounded-full text-white text-xs sm:text-sm font-bold",children:[e.jsx(ht,{size:14,className:"shrink-0"})," ",qr(ge)]})}),e.jsxs("div",{className:"relative flex items-center justify-center bg-purple-900/40 backdrop-blur-md px-2 sm:px-5 md:px-8 py-2 sm:py-3 rounded-full border border-white/10 gap-1.5 sm:gap-3 md:gap-4 shadow-inner",children:[e.jsx("div",{className:"hidden sm:block w-3 h-3 md:w-4 md:h-4 rounded-full bg-yellow-400 shrink-0 shadow-[0_0_10px_rgba(250,204,21,0.6)]"}),e.jsxs("div",{className:"flex flex-col items-start justify-center",children:[e.jsx("span",{className:"hidden sm:block text-[9px] md:text-[11px] font-black text-purple-200 uppercase tracking-widest leading-none mb-0.5",children:"Try It Yourself!"}),e.jsx("span",{className:"font-bold text-white tracking-wide text-xs sm:text-sm md:text-lg leading-none truncate max-w-[90px] sm:max-w-[180px] md:max-w-[300px]",children:t.title||t.subject})]})]}),e.jsxs("div",{className:"flex-1 flex justify-end gap-1 sm:gap-2 md:gap-3 relative pointer-events-auto",children:[e.jsxs("button",{onClick:()=>g(!Ae),className:"w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:[Ae?e.jsx(ts,{size:16,className:"sm:hidden"}):e.jsx(ss,{size:16,className:"sm:hidden"}),Ae?e.jsx(ts,{size:20,className:"hidden sm:block"}):e.jsx(ss,{size:20,className:"hidden sm:block"})]}),e.jsx("button",{onClick:yt,className:"hidden sm:flex w-10 h-10 md:w-12 md:h-12 rounded-full bg-purple-900/20 text-white items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:q?e.jsx($s,{size:20}):e.jsx(qs,{size:20})}),e.jsxs("button",{onClick:()=>Me(!0),className:"w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:[e.jsx(Ze,{size:18,className:"sm:hidden"}),e.jsx(Ze,{size:20,className:"hidden sm:block"})]})]})]}),e.jsx("div",{className:"w-full max-w-[50rem] flex items-center justify-center px-4 z-10",children:e.jsx("div",{className:"w-full flex items-center gap-2 sm:gap-3",children:ie.map((A,_)=>{let ee=_<=r?"bg-white shadow-[0_0_8px_rgba(255,255,255,0.8)]":"bg-white/20";return e.jsx("div",{className:`h-1.5 sm:h-2 rounded-full flex-1 transition-all ${ee}`},_)})})})]}),e.jsxs("div",{className:"w-full max-w-[54rem] mx-auto shrink-0 flex items-center justify-between px-2 sm:px-4 md:px-6 py-2 sm:py-3 z-[50] relative mt-4 sm:mt-6 md:mt-8",children:[e.jsxs("button",{onClick:()=>L(A=>Math.max(0,A-1)),disabled:y===0,className:`w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 shrink-0 rounded-full flex items-center justify-center shadow-md border-2 transition-all ${y===0?"bg-slate-100 text-slate-400 border-slate-200 cursor-not-allowed":"bg-white text-purple-600 border-purple-100 hover:bg-purple-50 hover:border-purple-200 hover:scale-105 active:scale-95"}`,children:[e.jsx(ps,{size:18,className:"sm:hidden"}),e.jsx(ps,{size:24,className:"hidden sm:block"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5 sm:gap-3 md:gap-5 flex-1 mx-1 sm:mx-2",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 md:gap-3 px-2.5 sm:px-5 md:px-10 py-1.5 sm:py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-rose-500 font-extrabold text-xs sm:text-sm md:text-base",children:[e.jsx("img",{src:"/icons/quiz_heart.png",alt:"Hearts",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," ",Te]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 md:gap-3 px-2.5 sm:px-5 md:px-10 py-1.5 sm:py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-yellow-500 font-extrabold text-xs sm:text-sm md:text-base",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Keys",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," ",et]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-3 md:gap-4 px-2 sm:px-3 py-1 sm:py-1.5 pl-2.5 sm:pl-4 md:pl-6 rounded-full bg-white shadow-md border border-slate-200/60",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 text-orange-500 font-extrabold text-xs sm:text-sm md:text-base",children:[e.jsx("img",{src:"/icons/quiz_streak.png",alt:"Streak",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," ",T]}),e.jsxs("div",{className:"bg-emerald-100 text-emerald-800 px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 rounded-full font-bold text-xs sm:text-sm md:text-base shadow-inner border border-emerald-200/50 whitespace-nowrap",children:["+ ",J," pts"]})]})]}),e.jsxs("button",{onClick:()=>L(A=>Math.min(r,A+1)),disabled:y>=r,className:`w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 shrink-0 rounded-full flex items-center justify-center shadow-md border-2 transition-all ${y>=r?"bg-slate-100 text-slate-400 border-slate-200 cursor-not-allowed":"bg-white text-purple-600 border-purple-100 hover:bg-purple-50 hover:border-purple-200 hover:scale-105 active:scale-95"}`,children:[e.jsx(ut,{size:18,className:"sm:hidden"}),e.jsx(ut,{size:24,className:"hidden sm:block"})]})]}),e.jsx("main",{className:"flex-1 overflow-y-auto w-full px-4 sm:px-6 pt-0 pb-6 flex flex-col items-center relative z-10",children:e.jsxs(E.div,{initial:{opacity:0,x:20},animate:Ge?{x:[-10,10,-10,10,0],scale:[1,1.01,1],opacity:1}:{opacity:1,x:0},className:"w-full max-w-3xl flex flex-col mt-2",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-lg border-t-[6px] border-purple-500 p-4 sm:p-6 md:p-8 text-center flex flex-col items-center mb-4 sm:mb-6 w-full relative overflow-hidden",children:[e.jsxs("div",{className:"bg-slate-100 text-slate-600 px-3 sm:px-4 py-1 sm:py-1.5 rounded-full text-[10px] sm:text-[11px] md:text-xs font-black uppercase tracking-widest mb-3 sm:mb-4 flex items-center shadow-sm",children:["Q",y+1," of ",ie.length]}),e.jsx("h2",{className:"text-base sm:text-xl md:text-2xl font-extrabold text-[#0a1628] leading-tight w-full",children:oe.question.includes("___")?e.jsx("span",{children:oe.question.split("___").map((A,_,ee)=>e.jsxs(Fe.Fragment,{children:[A,_m(G.target.value),onKeyDown:G=>{G.key==="Enter"&&!u&&re()},className:`inline-block w-24 mx-2 border-b-4 outline-none text-center bg-transparent font-bold ${U?"border-slate-300 text-slate-500":"border-[#7C3AED] text-[#7C3AED] focus:border-[#75D06A]"}`})]},_))}):e.jsx(Bt,{children:oe.question})})]}),e.jsxs("div",{className:"w-full flex flex-col items-center",children:[oe.questionType==="multiple_choice"||!oe.questionType?e.jsx("div",{className:"w-full grid grid-cols-1 sm:grid-cols-2 gap-2.5 sm:gap-3 md:gap-5",children:(oe.options||[]).map((A,_)=>{const ee=ke[r]||[],G=ee.includes(A),V=ee.length,Ie=(oe.options||[]).length-1,Qe=Ie>0&&V>=Ie;let Re="bg-white hover:bg-slate-50 border-transparent text-slate-700 hover:border-slate-200",tt=!1;if(Qe){tt=!0;const Pe=oe.options?.[oe.correctAnswer];A===Pe?Re="bg-emerald-50 border-emerald-400 text-emerald-800":$[y]?.answer===String(_)?Re="bg-rose-50 border-rose-400 text-rose-800 opacity-80":Re="bg-slate-100 border-slate-200 text-slate-400 opacity-40 line-through"}else if(G)Re="bg-slate-100 border-slate-200 text-slate-400 opacity-40 line-through cursor-not-allowed";else if(U){const Pe=_===oe.correctAnswer,Se=y===r&&(d===_||ae===_)||y{tt||U||G||W(_)},className:`p-3 sm:p-4 md:p-5 rounded-2xl shadow-sm border-[3px] font-extrabold text-sm sm:text-base md:text-lg text-left transition-all flex items-center justify-between ${Re} ${tt||U||G?"cursor-default":"hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"}`,children:[e.jsx("span",{className:"truncate pr-4",children:e.jsx(Bt,{children:A})}),G&&e.jsx(Wt,{size:20,className:"text-slate-400 shrink-0"}),U&&_===oe.correctAnswer&&e.jsx(at,{size:22,className:"text-emerald-500 shrink-0"}),U&&d===_&&_!==oe.correctAnswer&&e.jsx(Wt,{size:22,className:"text-rose-500 shrink-0"})]},_)})}):e.jsx("div",{className:"w-full max-w-2xl mx-auto flex flex-col gap-4",children:!oe.question.includes("___")&&e.jsx("input",{type:"text",disabled:U,value:y===r?S:"",onChange:A=>m(A.target.value),onKeyDown:A=>{A.key==="Enter"&&!u&&re()},placeholder:"Type your answer here...",className:`w-full p-3 sm:p-4 md:p-5 rounded-2xl border-[3px] font-extrabold text-base sm:text-lg text-center outline-none transition-colors ${U?z?"border-emerald-400 text-emerald-700 bg-emerald-50":"border-rose-400 text-rose-700 bg-rose-50":"border-slate-200 focus:border-[#7C3AED] bg-white text-slate-800"}`})}),U&&f&&e.jsxs("div",{className:"w-full max-w-3xl mt-6 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-[#0a1628]",children:oe.topic||t?.subject||"General Math"}),e.jsxs("p",{className:"text-sm text-slate-500",children:["Question ",y+1," Explanation"]})]}),e.jsx("img",{src:"/icons/default-module-avatar.png",alt:"Module Avatar",className:"w-12 h-12 rounded-full object-cover border-2 border-slate-200"})]}),U&&f&&e.jsx(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"w-full mt-4 space-y-4 max-w-3xl",children:e.jsxs("div",{className:`border-2 rounded-2xl p-5 flex items-start gap-4 ${(y===r?z:$[y]?.correct)?"bg-emerald-50 border-emerald-200":"bg-rose-50 border-rose-200"}`,children:[(y===r?z:$[y]?.correct)?e.jsx(at,{size:28,className:"text-emerald-500 shrink-0 mt-0.5"}):e.jsx(Wt,{size:28,className:"text-rose-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:`font-extrabold text-lg mb-1 ${(y===r?z:$[y]?.correct)?"text-emerald-700":"text-rose-700"}`,children:(y===r?z:$[y]?.correct)?"Correct!":"Incorrect"}),e.jsx("p",{className:`text-base leading-relaxed ${(y===r?z:$[y]?.correct)?"text-emerald-800":"text-rose-800"}`,children:oe.explanation||`Correct Answer: ${oe.correctAnswerText||oe.options?.[oe.correctAnswer]}`})]})]})})]})]},y)}),e.jsx("footer",{className:"shrink-0 relative z-[60] flex flex-col items-center justify-center p-4 sm:p-6 bg-gradient-to-r from-purple-600 to-indigo-400 rounded-t-[32px] sm:rounded-t-[40px] shadow-[0_-10px_40px_rgba(0,0,0,0.15)]",children:(()=>{const A=(ke[r]||[]).length,_=(xe.options||[]).length-1,ee=_>0&&A>=_;return ee||U&&!z?e.jsxs("button",{onClick:ve,className:"bg-orange-500 hover:bg-orange-600 text-white font-extrabold text-sm sm:text-base md:text-lg px-5 sm:px-8 py-3 sm:py-4 rounded-full flex items-center justify-center gap-2 sm:gap-3 shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-all w-full max-w-md mx-auto",children:[r{const V=Le>0&&!u&&!ee;return e.jsxs("button",{onClick:Q,disabled:!V,className:"bg-white hover:bg-slate-50 disabled:opacity-70 disabled:cursor-not-allowed text-slate-700 font-bold px-4 sm:px-6 md:px-8 py-2.5 sm:py-3 md:py-3.5 rounded-full flex items-center gap-1.5 sm:gap-2 text-sm sm:text-base shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Key",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," Hint"]})})(),U&&e.jsxs("button",{onClick:()=>C(!0),className:"bg-white hover:bg-slate-50 text-slate-700 font-bold px-4 sm:px-6 md:px-8 py-2.5 sm:py-3 md:py-3.5 rounded-full flex items-center gap-1.5 sm:gap-2 text-sm sm:text-base shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx(qe,{size:16,className:"sm:hidden"}),e.jsx(qe,{size:20,className:"hidden sm:block"})," Explain"]}),e.jsx("button",{onClick:()=>ye(V=>!V),className:`w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200 ${_e?"bg-purple-100 text-purple-600 border-purple-300":"bg-white hover:bg-slate-50 text-slate-700"}`,children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}),e.jsx("line",{x1:"8",x2:"16",y1:"6",y2:"6"}),e.jsx("path",{d:"M16 10h.01"}),e.jsx("path",{d:"M12 10h.01"}),e.jsx("path",{d:"M8 10h.01"}),e.jsx("path",{d:"M12 14h.01"}),e.jsx("path",{d:"M8 14h.01"}),e.jsx("path",{d:"M12 18h.01"}),e.jsx("path",{d:"M8 18h.01"}),e.jsx("line",{x1:"16",x2:"16",y1:"14",y2:"18"})]})})]}):yL(r),className:"bg-white text-slate-700 font-extrabold text-sm sm:text-base md:text-lg px-4 sm:px-6 md:px-8 py-2.5 sm:py-3 md:py-4 rounded-full inline-flex items-center gap-1.5 sm:gap-2 md:gap-3 shadow-lg hover:bg-slate-50 transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx(ut,{size:16,className:"sm:hidden"}),e.jsx(ut,{size:20,className:"hidden sm:block"}),"Back to Current Question"]}):null})()})]}),fe&&e.jsx("div",{className:"fixed inset-0 z-[300] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-2xl p-6 w-full max-w-[320px] shadow-2xl border border-slate-200 flex flex-col items-center gap-4",children:[e.jsx("h3",{className:"text-lg font-bold text-slate-900 text-center",children:"Leave this quiz?"}),e.jsx("p",{className:"text-sm text-slate-500 text-center",children:"Your progress will be reset and you'll need to start over."}),e.jsxs("div",{className:"w-full flex flex-col gap-2",children:[e.jsx("button",{onClick:()=>Me(!1),className:"w-full py-3 bg-[#9956DE] hover:bg-[#8544c7] text-white font-bold rounded-full transition-colors",children:"Stay"}),e.jsx("button",{onClick:()=>{Me(!1),s()},className:"w-full py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold rounded-full transition-colors",children:"Leave Quiz"})]})]})})]})};function Dr(t,s){const l={"Pre-Calculus":["What is the domain of the function f(x) = √(x - 2)?","Solve for x: 2^x = 16","What is the period of the function y = sin(2x)?","Find the inverse of f(x) = 3x + 5","What is the value of log₂(32)?","Simplify: (x² - 9) / (x - 3)","What is the range of f(x) = |x| - 3?","If f(x) = 2x + 1 and g(x) = x², find f(g(2)).","What is the amplitude of y = 3cos(x)?","Solve: log₃(x) = 4"],"General Mathematics":["Simplify: (2x + 3)(x - 4)","What is 15% of 240?","Solve: 3x + 7 = 22","What is the value of 5! (5 factorial)?","Convert 0.75 to a fraction","What is 25% of 360?","Simplify: 12/18","What is the GCD of 24 and 36?","Convert 3/8 to a decimal","If a shirt costs $40 and is 20% off, what is the sale price?","What is 2/3 + 1/4?","Calculate: 15% tip on a $80 bill","Simplify: 45/60","What fraction is equivalent to 0.125?","If 30% of a number is 45, what is the number?"],"Statistics and Probability":["What is the probability of rolling a 6 on a fair die?","Calculate the mean of: 4, 7, 9, 12, 15","What is the median of: 2, 5, 8, 11, 14?","In a bag with 5 red and 3 blue balls, what is P(red)?","What is the range of: 10, 15, 20, 25, 30?","What is the mode of: 3, 5, 5, 7, 8, 5, 9?","What is the standard deviation concept?","P(A) = 0.3, P(B) = 0.5, events independent. P(A and B) = ?","What is the median of: 4, 7, 10, 13?","How many ways can you arrange 3 books?"],"Basic Calculus":["Find the derivative of f(x) = 3x²","What is the limit of (x² - 4)/(x - 2) as x → 2?","Integrate: ∫ 2x dx","Find f'(x) if f(x) = 5x³ - 2x","What is the derivative of sin(x)?","Find the derivative of f(x) = eˣ + 3x","What is ∫ cos(x) dx?","Find the derivative of f(x) = ln(x)","What is the limit of 1/x as x → ∞?","Find f'(x) if f(x) = x⁴ - 2x² + 1"]},n=Qt(t),i=l[n]||l["General Mathematics"];return i[s%i.length]}function Qt(t){const s=t.toLowerCase();return s.includes("pre-calc")||s.includes("pre calc")||s.includes("precalc")?"Pre-Calculus":s.includes("statistic")||s.includes("probability")?"Statistics and Probability":s.includes("calculus")&&!s.includes("pre")?"Basic Calculus":s.includes("general")||s.includes("math")||s.includes("algebra")||s.includes("fraction")||s.includes("percent")||s.includes("ratio")||s.includes("geometry")?"General Mathematics":s.includes("derivative")||s.includes("integral")||s.includes("limit")?"Basic Calculus":s.includes("trig")||s.includes("function")||s.includes("log")?"Pre-Calculus":s.includes("mean")||s.includes("median")||s.includes("data")?"Statistics and Probability":"General Mathematics"}function Ir(t,s){const l={"Pre-Calculus":[["x ≥ 2","x ≤ 2","x ≥ 0","All real numbers"],["x = 2","x = 4","x = 8","x = 16"],["π","2π","π/2","4π"],["f⁻¹(x) = (x - 5)/3","f⁻¹(x) = 3x - 5","f⁻¹(x) = x/3 - 5","f⁻¹(x) = (x + 5)/3"],["4","5","6","7"],["x + 3","x - 3","x² + 3","(x + 3)(x - 3)"],["y ≥ -3","y ≥ 0","All real numbers","y > -3"],["9","5","7","3"],["1","2","3","1/3"],["12","27","64","81"]],"General Mathematics":[["2x² - 5x - 12","2x² + 5x - 12","2x² - 8x + 12","2x² - 5x + 12"],["36","32","28","24"],["x = 5","x = 4","x = 6","x = 7"],["120","24","60","720"],["3/4","1/2","2/3","4/5"],["90","80","100","72"],["2/3","3/4","4/6","6/9"],["12","6","8","4"],["0.375","0.38","0.35","0.325"],["$32","$28","$30","$36"],["11/12","3/7","5/6","2/3"],["$12","$10","$15","$8"],["3/4","2/3","4/5","9/12"],["1/8","1/4","1/5","1/6"],["150","135","120","160"]],"Statistics and Probability":[["1/6","1/3","1/2","2/3"],["9.4","8.5","10.2","7.8"],["8","9","7","10"],["5/8","3/8","1/2","2/5"],["20","15","25","30"],["5","3","7","8"],["Spread of data from the mean","The highest value","The average","The middle value"],["0.15","0.8","0.35","0.2"],["8.5","7","10","9"],["6","3","9","12"]],"Basic Calculus":[["6x","3x","9x²","6x²"],["4","2","0","undefined"],["x² + C","2x² + C","x²/2 + C","2x + C"],["15x² - 2","15x² - 2x","5x² - 2","15x - 2"],["cos(x)","-cos(x)","tan(x)","-sin(x)"],["eˣ + 3","eˣ + 3x","xeˣ + 3","eˣ"],["sin(x) + C","-sin(x) + C","tan(x) + C","-cos(x) + C"],["1/x","x","ln(x)","-1/x²"],["0","1","∞","undefined"],["4x³ - 4x","4x³ - 2x","x³ - 4x","4x⁴ - 4x²"]]},n=Qt(t),i=l[n]||l["General Mathematics"];return i[s%i.length]}function Fr(t,s){const l={"Pre-Calculus":[0,1,0,0,1,0,0,0,2,3],"General Mathematics":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"Statistics and Probability":[0,0,0,0,0,0,0,0,0,0],"Basic Calculus":[0,0,0,0,0,0,0,0,0,0]},n=Qt(t),i=l[n]||l["General Mathematics"];return i[s%i.length]}function $r(t,s,l){const n={"Pre-Calculus":["The expression under the square root must be non-negative: x - 2 ≥ 0, so x ≥ 2.","Since 2⁴ = 16, we get x = 4.","The period of sin(kx) is 2π/k. Here k = 2, so period = 2π/2 = π.","To find the inverse: y = 3x + 5 → x = 3y + 5 → y = (x - 5)/3.","Since 2⁵ = 32, log₂(32) = 5.","(x² - 9)/(x - 3) = (x+3)(x-3)/(x-3) = x + 3 (for x ≠ 3).","The absolute value |x| ≥ 0 for all x, so |x| - 3 ≥ -3. The range is y ≥ -3.","g(2) = 4, then f(4) = 2(4) + 1 = 9.","The amplitude of y = Acos(x) is |A|. Here A = 3, so amplitude = 3.","log₃(x) = 4 means 3⁴ = x, so x = 81."],"General Mathematics":["(2x + 3)(x - 4) = 2x² - 8x + 3x - 12 = 2x² - 5x - 12","15% of 240 = 0.15 × 240 = 36","3x + 7 = 22 → 3x = 15 → x = 5","5! = 5 × 4 × 3 × 2 × 1 = 120","0.75 = 75/100 = 3/4 after simplifying by dividing both by 25","25% of 360 = 0.25 × 360 = 90","12/18 = (12÷6)/(18÷6) = 2/3","Factors of 24: {1,2,3,4,6,8,12,24}. Factors of 36: {1,2,3,4,6,9,12,18,36}. GCD = 12","3 ÷ 8 = 0.375","20% off $40 = $40 × 0.80 = $32","2/3 + 1/4 = 8/12 + 3/12 = 11/12","15% of $80 = 0.15 × 80 = $12","45/60 = (45÷15)/(60÷15) = 3/4","0.125 = 125/1000 = 1/8","30% × N = 45 → N = 45/0.30 = 150"],"Statistics and Probability":["A fair die has 6 outcomes, each equally likely. P(6) = 1/6.","Mean = (4 + 7 + 9 + 12 + 15) / 5 = 47/5 = 9.4","Sorted: 2, 5, 8, 11, 14. The middle value is 8.","P(red) = 5/(5+3) = 5/8","Range = max - min = 30 - 10 = 20","The value 5 appears 3 times, more than any other value. Mode = 5.","Standard deviation measures how spread out data points are from the mean.","For independent events: P(A and B) = P(A) × P(B) = 0.3 × 0.5 = 0.15","For even-count dataset {4,7,10,13}: median = (7+10)/2 = 8.5","3 books can be arranged in 3! = 3 × 2 × 1 = 6 ways."],"Basic Calculus":["Using the power rule: d/dx[3x²] = 3 × 2x = 6x","Factor: (x²-4)/(x-2) = (x+2)(x-2)/(x-2) = x+2. As x→2: 2+2 = 4","∫ 2x dx = 2 × x²/2 + C = x² + C","f'(x) = 5 × 3x² - 2 = 15x² - 2","The derivative of sin(x) is cos(x). This is a fundamental trigonometric derivative.","d/dx[eˣ + 3x] = eˣ + 3. The derivative of eˣ is eˣ and of 3x is 3.","∫ cos(x) dx = sin(x) + C. Integration is the reverse of differentiation.","The derivative of ln(x) is 1/x. This is a fundamental logarithmic derivative.","As x → ∞, 1/x approaches 0. The function gets infinitely close to zero.","f'(x) = 4x³ - 4x using the power rule on each term."]},i=Qt(t),c=n[i]||n["General Mathematics"];return c[s%c.length]}function qr(t){const s=Math.floor(t/60),l=t%60;return`${s}:${l.toString().padStart(2,"0")}`}async function Xt(t){return rt("/api/try-it-yourself/resolve-question",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Or(t){return rt("/api/try-it-yourself/use-hint",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Br(t){return rt("/api/try-it-yourself/complete-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Hr(t){return rt("/api/try-it-yourself/shadow-retry",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}const Qr=["foundation","application","complexity","gauntlet"],Wr={0:1,1:.7,2:.4,3:.2},Ur=10,Gr=2,Xr=2,Vr=1,Yr=3;function Kr(t,s){const l=Wr[Math.min(t,3)]??.2;return Math.max(Math.round(Ur*l),Gr)}function Zr(t){const s=t.length,l=4;if(t.filter(p=>p.bloomLevel).length0&&k.push(C)}return k}const i=t.filter(p=>p.bloomLevel==="remember"||p.bloomLevel==="understand"),c=t.filter(p=>p.bloomLevel==="apply"),r=t.filter(p=>p.bloomLevel==="analyze"),x=t.filter(p=>p.bloomLevel==="evaluate"),d=t.filter(p=>!p.bloomLevel),h=[],S=[...i,...d];S.length>0&&h.push(S),c.length>0&&h.push(c),r.length>0&&h.push(r),x.length>0&&h.push(x);const m=[];let z=[];for(const p of h)z=[...z,...p],z.length>=l&&(m.push(z),z=[]);return z.length>0&&(m.length>0?m[m.length-1]=[...m[m.length-1],...z]:m.push(z)),m.length>0?m:[t]}function Ss(t){return t==="multiple-choice"?Xr:t==="fill-in-blank"?Vr:null}function Jr(t){const s=t.toLowerCase();return s.includes("geometry")||s.includes("shape")?[Ot,It,qt,ys,Os,fr]:s.includes("algebra")||s.includes("equation")?[Ze,kt,ws,Gt,pt,Ft]:s.includes("calculus")||s.includes("derivative")||s.includes("integral")?[$t,Gt,Lt,pt,kt,ws]:s.includes("statistics")||s.includes("probability")?[We,Lt,ys,It,Ot,qt]:[pt,$t,kt,Ft,Gt,Oa]}let wt=null;function el(){if(wt&&wt.state!=="closed")return wt;const t=window.AudioContext||window.webkitAudioContext;return t?(wt=new t,wt):null}function jt(t,s){if(s)try{const l=el();if(!l)return;l.state==="suspended"&&l.resume();const n=l.currentTime,i=(c,r,x,d=.1,h="sine")=>{const S=l.createOscillator(),m=l.createGain();S.type=h,S.frequency.value=c,m.gain.setValueAtTime(0,r),m.gain.linearRampToValueAtTime(d,r+.05),m.gain.exponentialRampToValueAtTime(.001,r+x),S.connect(m),m.connect(l.destination),S.start(r),S.stop(r+x)};switch(t){case"correct":i(880,n,.1),i(1108.73,n+.1,.2);break;case"incorrect":i(300,n,.2,.05,"sawtooth"),i(250,n+.15,.3,.05,"sawtooth");break;case"streak":i(440,n,.1,.05,"square"),i(554.37,n+.1,.1,.05,"square"),i(659.25,n+.2,.1,.05,"square"),i(880,n+.3,.4,.05,"square");break;case"complete":i(523.25,n,.1),i(659.25,n+.15,.1),i(783.99,n+.3,.1),i(1046.5,n+.45,.5);break;case"hint":i(600,n,.15,.06,"triangle");break}}catch{}}const vt=({label:t,value:s,prefix:l="",suffix:n="",icon:i,delay:c=0,large:r})=>{const[x,d]=Fe.useState(0);return Fe.useEffect(()=>{if(s<=0){d(s);return}const h=setTimeout(()=>{const z=Math.floor(40);let p=0;const u=setInterval(()=>{p+=Math.max(1,Math.floor(s/20)),p>=s?(d(s),clearInterval(u)):d(p)},z)},c);return()=>clearTimeout(h)},[s,c]),e.jsxs(E.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:c/1e3,duration:.4},className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[i," ",t]}),e.jsxs("span",{className:`font-black tabular-nums ${r?"text-2xl text-purple-600":"text-lg text-slate-800"}`,children:[l,x,n]})]})},tl=({questions:t,lessonTitle:s,subject:l,sessionId:n,userId:i,onComplete:c,onBack:r})=>{const x=a.useMemo(()=>Zr(t),[t]),d=x.length,[h,S]=a.useState(0),[m,z]=a.useState(()=>[...x[0]]),[p,u]=a.useState(0),[k,f]=a.useState("playing"),[C,N]=a.useState({}),[R,T]=a.useState(null),[F,X]=a.useState(""),[Z,Y]=a.useState([]),[te,$]=a.useState(!1),[pe,he]=a.useState(!1),[ze,Ce]=a.useState(!1),[b,H]=a.useState(!1),[ce,ae]=a.useState(!1),[le,ge]=a.useState(!1),[Ne,B]=a.useState(!1),[Ee,_e]=a.useState(!1),[ye,fe]=a.useState(!0),[Me,Ae]=a.useState(!1),[g,q]=a.useState(!1),[M,O]=a.useState(0),[I,J]=a.useState(0),[be,ke]=a.useState(0),[D,ne]=a.useState(15),[me,Ge]=a.useState(5),[ft,bt]=a.useState([]),[De,Xe]=a.useState(null);a.useRef(Date.now());const et=a.useRef(null),j=m[p]||null,Te=a.useMemo(()=>Jr(s),[s]),lt={gradient:"bg-gradient-to-br from-[#7274ED] via-[#9956DE] to-[#7274ED]"},Le=a.useCallback(w=>C[w]||{attempts:0,hintsUsed:0,resolved:!1,resolution:null,failedOptions:[],xpAwarded:0},[C]);a.useEffect(()=>{if(j){if(j.type==="multiple-choice"&&j.options){const w=j.options.map((v,Q)=>({id:`${j.id}-${Q}`,text:v}));for(let v=w.length-1;v>0;v--){const Q=Math.floor(Math.random()*(v+1));[w[v],w[Q]]=[w[Q],w[v]]}Y(w)}else Y([]);T(null),X(""),$(!1),he(!1),ge(!1),j.type==="fill-in-blank"&&setTimeout(()=>et.current?.focus(),100)}},[j?.id]);const Be=()=>{document.fullscreenElement?(document.exitFullscreen().catch(()=>{}),Ae(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),Ae(!0))},gt=a.useCallback(()=>{if(!j)return;const w=Le(j.id);if(w.resolved||w.hintsUsed>=(j.hints?.length||0)||me<=0)return;jt("hint",ye),$(!0),Ge(Q=>Q-1);const v=w.hintsUsed+1;N(Q=>({...Q,[j.id]:{...w,hintsUsed:v}})),i&&Or({userId:i,sessionId:n,questionId:String(j.id),currentHintTier:w.hintsUsed}).catch(()=>{})},[j,C,i,n,ye,me,Le]),nt=a.useCallback(()=>{if(!j)return;const w=Le(j.id);if(w.resolved)return;const v=Ss(j.type);v===null||w.attempts({...Q,[j.id]:{...w,resolved:!0,resolution:"revealed",xpAwarded:0}})),J(0),i&&Xt({userId:i,sessionId:n,questionId:String(j.id),resolution:"revealed",attempts:w.attempts,hintsUsed:w.hintsUsed}).catch(()=>{}))},[j,C,i,n,Le]),Ve=a.useCallback(w=>{if(!j||Ee)return;const v=Le(j.id);if(v.resolved)return;let Q="";if(j.type==="fill-in-blank"){if(Q=F.trim(),!Q)return}else if(Q=w||"",!Q)return;_e(!0);const W=v.attempts+1;let re=!1;if(j.type==="fill-in-blank"?re=Q.toLowerCase().replace(/\s+/g,"")===j.correctAnswer.toLowerCase().replace(/\s+/g,""):re=Q===j.correctAnswer,re){const ve=Kr(v.hintsUsed);N(U=>({...U,[j.id]:{...v,attempts:W,resolved:!0,resolution:"correct",xpAwarded:ve}})),O(U=>U+ve);const se=I+1;J(se),ke(U=>Math.max(U,se)),jt(se>=3?"streak":"correct",ye),B(!0),ge(!0),St(()=>import("./confetti.module-C94ZD2ww.js"),[]).then(U=>{U.default({particleCount:30,spread:40,colors:["#75D06A","#6ED1CF"],origin:{y:.6}})}).catch(()=>{}),i&&Xt({userId:i,sessionId:n,questionId:String(j.id),resolution:"correct",attempts:W,hintsUsed:v.hintsUsed}).catch(()=>{}),setTimeout(()=>{ge(!1),_e(!1)},1400)}else{const ve=[...v.failedOptions,Q],se={...v,attempts:W,failedOptions:ve};let U=!1;if(j.type==="multiple-choice"&&j.options?U=j.options.filter(yt=>yt!==j.correctAnswer).every(yt=>ve.includes(yt)):j.type==="true-false"&&(U=!0),U){N(oe=>({...oe,[j.id]:{...se,resolved:!0,resolution:"revealed",xpAwarded:0}})),J(0),ne(oe=>Math.max(0,oe-1)),jt("incorrect",ye),_e(!1),i&&Xt({userId:i,sessionId:n,questionId:String(j.id),resolution:"revealed",attempts:W,hintsUsed:v.hintsUsed}).catch(()=>{});return}N(oe=>({...oe,[j.id]:se})),J(0),ne(oe=>Math.max(0,oe-1)),jt("incorrect",ye),ae(!0),setTimeout(()=>ae(!1),500),j.type==="fill-in-blank"&&X(""),_e(!1)}},[j,C,F,Ee,I,i,n,ye,Le]),it=a.useRef(()=>{}),ot=a.useCallback(()=>{const w=p+1;if(m.slice(w).filter(Q=>!C[Q.id]?.resolved).length===0){const Q=m.filter(W=>!C[W.id]?.resolved);Q.length>0?(z(Q),u(0)):it.current()}else u(w)},[p,m,C]),o=a.useCallback(()=>{const w=x[h]||[];let v=0,Q=0,W=0;const re=[];w.forEach(se=>{const U=C[se.id];U&&(v+=U.xpAwarded,U.resolution==="correct"&&Q++,U.resolution==="revealed"&&W++,U.attempts>=Yr&&re.push(se.topic||se.competencyCode||s))});const ve={phase:Qr[h],questionsCorrect:Q,questionsRevealed:W,xpEarned:v,struggleTopics:[...new Set(re)]};Xe(ve),bt(se=>[...se,ve]),h>=d-1?(f("complete"),jt("complete",ye)):(f("phase-complete"),q(!1))},[h,d,x,C,s,ye]);it.current=o;const P=a.useCallback(async()=>{const w=h+1;if(w>=d){f("complete");return}f("loading-next");const Q=(x[h]||[]).filter(se=>C[se.id]?.resolution==="revealed");let W=[...x[w],...Q];const re=De?.struggleTopics||[];if(re.length>0&&i)try{const se=await Hr({userId:i,sessionId:n,struggleTopics:re,subject:l,count:Math.min(2,re.length)});se.variants?.length&&(W=[...W,...se.variants.map(U=>({id:U.id,type:U.type,question:U.question,options:U.options,correctAnswer:U.correctAnswer,explanation:U.explanation||"",hints:U.hints||[]}))])}catch{}S(w),z(W),u(0);const ve={...C};Q.forEach(se=>{delete ve[se.id]}),N(ve),f("playing")},[h,d,x,De,C,i,n,l]),y=a.useCallback(async()=>{const w=t.map(W=>{const re=C[W.id];return{questionId:String(W.id),resolution:re?.resolution||"correct",attempts:re?.attempts||1,hintsUsed:re?.hintsUsed||0,topic:s}});let v=M;if(i)try{v=(await Br({userId:i,sessionId:n,questionResults:w})).totalXP}catch{}const Q=Object.values(C).filter(W=>W.resolution==="correct").length;c(Math.round(Q/t.length*100),v)},[t,C,M,i,n,s,c]);if(a.useEffect(()=>{const w=v=>{v.key==="Enter"&&j?.type==="fill-in-blank"&&F.trim()&&(v.preventDefault(),Ve())};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[Ve,j,F]),a.useEffect(()=>{(k==="phase-complete"||k==="complete")&&!g&&(q(!0),St(()=>import("./confetti.module-C94ZD2ww.js"),[]).then(w=>{w.default({particleCount:100,spread:80,colors:["#9956DE","#75D06A","#6ED1CF","#FFD700","#FF6B6B"],origin:{y:.35}}),setTimeout(()=>w.default({particleCount:60,spread:100,colors:["#9956DE","#75D06A","#FFD700"],origin:{y:.5,x:.3}}),300),setTimeout(()=>w.default({particleCount:60,spread:100,colors:["#6ED1CF","#FF6B6B","#FFD700"],origin:{y:.5,x:.7}}),600)}).catch(()=>{}))},[k,g]),k==="phase-complete"&&De)return e.jsxs("div",{className:"fixed inset-0 z-[200] flex flex-col items-center justify-center bg-gradient-to-br from-[#e8e0f7] via-[#f0e8ff] to-[#ddd6f3] p-6",children:[e.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden",children:[[Ot,It,qt,kt,Ft,$t].map((w,v)=>e.jsx(E.div,{className:"absolute text-purple-300/30",style:{top:`${10+v*14%80}%`,left:`${5+v*18%85}%`},animate:{y:[0,-15,0],rotate:[0,360]},transition:{duration:4+v,repeat:1/0,ease:"easeInOut",delay:v*.5},children:e.jsx(w,{size:28+v%3*12})},v)),e.jsx("div",{className:"absolute top-0 left-0 w-64 h-64 bg-purple-200 opacity-20 rounded-full -translate-x-1/2 -translate-y-1/2 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-80 h-80 bg-indigo-200 opacity-20 rounded-full translate-x-1/3 translate-y-1/3 blur-3xl"})]}),e.jsxs(E.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",damping:20,stiffness:200},className:"relative z-10 flex flex-col items-center text-center max-w-sm w-full",children:[e.jsx(E.img,{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-36 h-36 sm:w-44 sm:h-44 mb-6 drop-shadow-[0_15px_30px_rgba(0,0,0,0.15)]",initial:{y:-20},animate:{y:[0,-8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsxs("h1",{className:"text-3xl sm:text-4xl font-black text-[#5b3a9e] mb-2 drop-shadow-sm",children:["Phase ",h+1," Complete!"]}),e.jsx("p",{className:"text-purple-500/70 text-sm mb-6",children:"Great work! Keep going."}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-md rounded-2xl p-5 w-full mb-6 border border-purple-200/50 shadow-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Pt,{size:14,className:"text-emerald-500"})," Correct"]}),e.jsx("span",{className:"text-lg font-black text-emerald-600",children:De.questionsCorrect})]}),De.questionsRevealed>0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Ut,{size:14,className:"text-amber-500"})," Revealed"]}),e.jsx("span",{className:"text-lg font-black text-amber-600",children:De.questionsRevealed})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-purple-100",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Ke,{size:14,className:"text-purple-500"})," XP Earned"]}),e.jsxs("span",{className:"text-xl font-black text-purple-600",children:["+",De.xpEarned]})]})]}),e.jsx("div",{className:"flex items-center gap-2 mb-8",children:Array.from({length:d}).map((w,v)=>e.jsx("div",{className:`w-3 h-3 rounded-full transition-all ${v<=h?"bg-purple-500 shadow-[0_0_8px_rgba(153,86,222,0.6)]":"bg-purple-200"}`},v))}),e.jsxs("button",{onClick:P,className:"w-full py-4 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-black text-lg shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-transform mb-3",children:["Continue to Next Phase ",e.jsx(Ye,{size:20,className:"inline ml-2"})]}),e.jsx("button",{onClick:()=>H(!0),className:"text-purple-400 hover:text-purple-600 text-sm font-bold transition-colors",children:"Quit Quiz"})]}),b&&e.jsx("div",{className:"fixed inset-0 z-[220] flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-[2rem] p-6 sm:p-8 max-w-xs w-full shadow-2xl flex flex-col gap-4 text-center",children:[e.jsx("h2",{className:"text-xl font-black text-slate-800",children:"Are you sure you want to leave?"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Your progress won't be saved."}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{onClick:()=>H(!1),className:"w-full py-3 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-bold",children:"Stay"}),e.jsx(Oe,{onClick:r,className:"w-full py-3 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold",children:"Leave"})]})]})})]});if(k==="loading-next")return e.jsx("div",{className:"fixed inset-0 z-[200] flex items-center justify-center bg-gradient-to-br from-[#7274ED] via-[#9956DE] to-[#7274ED]",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 border-4 border-white border-t-transparent rounded-full animate-spin"}),e.jsx("p",{className:"font-bold text-white text-lg",children:"Preparing next phase..."})]})});if(k==="complete"){const w=Object.values(C).filter(W=>W.resolution==="correct").length,v=Object.values(C).filter(W=>W.resolution==="revealed").length,Q=Math.round(w/t.length*100);return e.jsxs("div",{className:"fixed inset-0 z-[200] flex flex-col items-center justify-center bg-gradient-to-br from-[#e8e0f7] via-[#f0e8ff] to-[#ddd6f3] p-6",children:[e.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden",children:[[Ot,It,qt,kt,Ft,$t,Os,We].map((W,re)=>e.jsx(E.div,{className:"absolute text-purple-300/25",style:{top:`${8+re*12%80}%`,left:`${3+re*13%90}%`},animate:{y:[0,-12,0],rotate:[0,360]},transition:{duration:5+re,repeat:1/0,ease:"easeInOut",delay:re*.4},children:e.jsx(W,{size:24+re%4*10})},re)),e.jsx("div",{className:"absolute top-0 right-0 w-72 h-72 bg-purple-200 opacity-20 rounded-full translate-x-1/3 -translate-y-1/3 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-64 h-64 bg-indigo-200 opacity-20 rounded-full -translate-x-1/3 translate-y-1/3 blur-3xl"})]}),e.jsxs(E.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"relative z-10 flex flex-col items-center text-center max-w-sm w-full",children:[e.jsx(E.img,{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-36 h-36 sm:w-44 sm:h-44 mb-6 drop-shadow-[0_15px_30px_rgba(0,0,0,0.15)]",initial:{y:-20},animate:{y:[0,-8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-black text-[#5b3a9e] mb-2",children:"Quiz Complete!"}),e.jsx("p",{className:"text-purple-500/70 text-sm mb-6",children:s}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-md rounded-2xl p-5 w-full mb-6 border border-purple-200/50 shadow-lg space-y-3",children:[e.jsx(vt,{label:"Score",value:Q,suffix:"%",icon:e.jsx(Tt,{size:14,className:"text-purple-500"}),delay:0}),e.jsx(vt,{label:"Correct",value:w,suffix:`/${t.length}`,icon:e.jsx(Pt,{size:14,className:"text-emerald-500"}),delay:200}),v>0&&e.jsx(vt,{label:"Revealed",value:v,icon:e.jsx(Ut,{size:14,className:"text-amber-500"}),delay:400}),e.jsx(vt,{label:"Best Streak",value:be,icon:e.jsx(Kt,{size:14,className:"text-orange-500"}),delay:600}),e.jsx("div",{className:"pt-2 border-t border-purple-100",children:e.jsx(vt,{label:"Total XP",value:M,prefix:"+",icon:e.jsx(Ke,{size:14,className:"text-purple-500"}),delay:800,large:!0})})]}),e.jsx("button",{onClick:y,className:"w-full py-4 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-black text-lg shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-transform",children:"FINISH"})]})]})}const L=j?Le(j.id):null,K=j?Ss(j.type):null,de=K!==null&&(L?.attempts??0)>=K,ie=K===null||!de,xe=!L?.resolved,je=j?.hints?.length??0,He=je-(L?.hintsUsed??0),we=x[h]||[];return we.filter(w=>C[w.id]?.resolved).length,j?e.jsxs(e.Fragment,{children:[ze&&Et.createPortal(e.jsx(E.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:"fixed right-6 top-1/2 -translate-y-1/2 z-[9999] w-64",children:e.jsxs("div",{className:"bg-white rounded-2xl p-3 border border-slate-200 shadow-[0_10px_40px_rgba(0,0,0,0.2)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("h4",{className:"text-xs font-bold text-[#0a1628] flex items-center gap-2",children:[e.jsx(pt,{size:14,className:"text-purple-600"})," Calculator"]}),e.jsx("button",{onClick:()=>Ce(!1),className:"w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 hover:text-slate-800 hover:bg-slate-200 transition-colors",children:e.jsx(Ze,{size:12})})]}),e.jsx(Fs,{isOpen:!0,onClose:()=>Ce(!1),inline:!0})]})}),document.getElementById("modal-root")||document.body),e.jsx(Je,{children:le&&e.jsx(E.div,{initial:{opacity:0,scale:.8,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:1.1,filter:"blur(10px)"},transition:{type:"spring",damping:20,stiffness:300},className:"fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[100] pointer-events-none flex flex-col items-center justify-center",children:e.jsxs("div",{className:"bg-white/95 backdrop-blur-xl border border-slate-200 rounded-[2rem] p-6 md:p-8 shadow-[0_30px_80px_rgba(0,0,0,0.15)] flex flex-col items-center min-w-[280px] md:min-w-[320px]",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-24 h-24 md:w-32 md:h-32 mb-4 drop-shadow-[0_10px_20px_rgba(0,0,0,0.15)]"}),e.jsx("h2",{className:`text-3xl md:text-4xl font-black mb-4 uppercase tracking-widest ${Ne?"text-emerald-500":"text-rose-500"}`,children:Ne?"Correct!":"Incorrect"}),Ne?e.jsxs("div",{className:"flex flex-col items-center gap-3 w-full justify-center",children:[e.jsx("div",{className:"flex items-center gap-2 bg-emerald-500/20 text-emerald-400 px-4 py-2 rounded-full font-bold border border-emerald-500/30",children:e.jsxs("span",{children:["+ ",L?.xpAwarded??10," XP"]})}),I>=3&&e.jsxs("div",{className:"flex items-center gap-2 bg-orange-500/20 text-orange-400 px-4 py-1.5 rounded-full text-sm font-bold border border-orange-500/30",children:[e.jsx(Kt,{size:14})," Streak ×",I,"!"]})]}):e.jsxs("div",{className:"bg-rose-500/20 border border-rose-500/30 text-rose-400 font-bold px-5 py-2 rounded-xl text-center",children:["Correct: ",j.correctAnswer]})]})},"round-result")}),e.jsx(Je,{children:b&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",onClick:()=>H(!1),children:e.jsxs(E.div,{onClick:w=>w.stopPropagation(),initial:{scale:.9,opacity:0,y:20},animate:{scale:1,opacity:1,y:0},exit:{scale:.9,opacity:0,y:20},className:"bg-white rounded-[2rem] p-6 sm:p-8 max-w-xs w-full shadow-2xl flex flex-col gap-4 text-center",children:[e.jsx("h2",{className:"text-xl font-black text-slate-800",children:"Are you sure you want to leave?"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Your progress won't be saved."}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{onClick:()=>H(!1),className:"w-full py-3 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-bold",children:"Stay"}),e.jsx(Oe,{onClick:()=>{H(!1),r()},className:"w-full py-3 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold",children:"Leave"})]})]})})}),e.jsxs("div",{className:"fixed inset-0 z-50 h-screen w-full flex flex-col bg-slate-50 overflow-hidden",children:[e.jsxs("header",{className:`relative shrink-0 flex flex-col items-center justify-start px-4 pt-4 sm:pt-6 pb-6 z-[60] shadow-md overflow-hidden ${lt.gradient} rounded-b-[32px] sm:rounded-b-[40px] min-h-[110px] sm:min-h-[130px]`,children:[e.jsxs("div",{className:"absolute inset-0 z-0 pointer-events-none",children:[e.jsx("div",{className:"absolute top-0 left-0 w-64 h-64 bg-white opacity-10 rounded-full -translate-x-1/2 -translate-y-1/2 blur-2xl"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-80 h-80 bg-white opacity-10 rounded-full translate-x-1/3 translate-y-1/3 blur-3xl"}),Te.map((w,v)=>e.jsx("div",{className:"absolute text-white/10",style:{top:`${10+v*15}%`,left:`${10+v*25%80}%`,transform:`rotate(${v*45}deg) scale(${1+v%3*.2})`},children:e.jsx(w,{size:48+v%2*32})},v))]}),e.jsxs("div",{className:"w-full max-w-7xl flex items-start justify-between relative z-10 mb-4 sm:mb-6",children:[e.jsx("div",{className:"flex-1 pointer-events-none"}),e.jsxs("div",{className:"relative flex items-center justify-center bg-purple-900/40 backdrop-blur-md px-6 sm:px-8 py-3 rounded-full border border-white/10 gap-3 sm:gap-4 shadow-inner",children:[e.jsx("div",{className:"w-3 h-3 sm:w-4 sm:h-4 rounded-full bg-yellow-400 shrink-0 shadow-[0_0_10px_rgba(250,204,21,0.6)]"}),e.jsxs("div",{className:"flex flex-col items-start justify-center",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] font-black text-purple-200 uppercase tracking-widest leading-none mb-1",children:"Try It Yourself!"}),e.jsx("span",{className:"font-bold text-white tracking-wide text-base sm:text-lg leading-none truncate max-w-[200px] sm:max-w-[300px]",children:s})]})]}),e.jsxs("div",{className:"flex-1 flex justify-end gap-2 sm:gap-3 relative pointer-events-auto",children:[e.jsx("button",{onClick:()=>fe(!ye),className:"w-10 h-10 sm:w-12 sm:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:ye?e.jsx(ts,{size:20}):e.jsx(ss,{size:20})}),e.jsx("button",{onClick:Be,className:"hidden sm:flex w-10 h-10 sm:w-12 sm:h-12 rounded-full bg-purple-900/20 text-white items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:Me?e.jsx($s,{size:20}):e.jsx(qs,{size:20})}),e.jsx("button",{onClick:()=>H(!0),className:"w-10 h-10 sm:w-12 sm:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:e.jsx(ta,{size:20})})]})]}),e.jsx("div",{className:"w-full max-w-[50rem] flex items-center justify-center px-4 z-10",children:e.jsx("div",{className:"w-full flex items-center gap-2 sm:gap-3",children:we.map((w,v)=>e.jsx("div",{className:`h-1.5 sm:h-2 rounded-full flex-1 transition-all ${C[w.id]?.resolved?"bg-white shadow-[0_0_8px_rgba(255,255,255,0.8)]":"bg-white/20"}`},w.id))})})]}),e.jsx("div",{className:"w-full max-w-[54rem] mx-auto shrink-0 flex items-center justify-between px-4 sm:px-6 py-2 sm:py-3 z-[50] relative mt-4",children:e.jsxs("div",{className:"flex items-center justify-center gap-3 sm:gap-5 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 px-8 sm:px-10 py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-rose-500 font-extrabold text-sm sm:text-base",children:[e.jsx("img",{src:"/icons/quiz_heart.png",alt:"Hearts",className:"w-5 h-5 object-contain"}),D]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 px-8 sm:px-10 py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-yellow-500 font-extrabold text-sm sm:text-base",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Keys",className:"w-5 h-5 object-contain"}),me]}),e.jsxs("div",{className:"flex items-center gap-3 sm:gap-4 px-3 py-1.5 pl-5 sm:pl-6 rounded-full bg-white shadow-md border border-slate-200/60",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-500 font-extrabold text-sm sm:text-base",children:[e.jsx("img",{src:"/icons/quiz_streak.png",alt:"Streak",className:"w-5 h-5 object-contain"})," ",I]}),e.jsxs("div",{className:"bg-emerald-100 text-emerald-800 px-4 py-1.5 rounded-full font-bold text-sm sm:text-base shadow-inner border border-emerald-200/50",children:["+ ",M," XP"]})]})]})}),e.jsx("main",{className:"flex-1 overflow-y-auto w-full px-4 sm:px-6 pt-0 pb-6 flex flex-col items-center relative z-10",children:e.jsxs(E.div,{initial:{opacity:0,x:20},animate:ce?{x:[-10,10,-10,10,0],scale:[1,1.01,1],opacity:1}:{opacity:1,x:0},className:"w-full max-w-3xl flex flex-col mt-2",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-lg border-t-[6px] border-purple-500 p-6 sm:p-8 text-center flex flex-col items-center mb-6 w-full relative overflow-hidden",children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-extrabold text-[#0a1628] leading-tight w-full",children:e.jsx(Bt,{children:j.question})}),j.type==="fill-in-blank"&&!L?.resolved&&e.jsx("input",{ref:et,type:"text",value:F,onChange:w=>X(w.target.value),placeholder:"Type your answer...",disabled:L?.resolved||Ee,className:"mt-4 w-full max-w-xs mx-auto px-4 py-3 border-b-4 border-[#7C3AED] text-center text-lg font-bold outline-none bg-transparent focus:border-[#75D06A] transition-colors"}),j.type==="fill-in-blank"&&L?.resolved&&e.jsx("div",{className:"mt-4 px-4 py-3 bg-emerald-50 border-2 border-emerald-300 rounded-xl text-emerald-700 font-bold text-lg",children:j.correctAnswer})]}),e.jsxs("div",{className:"w-full flex flex-col items-center",children:[(j.type==="multiple-choice"||j.type==="true-false")&&e.jsx("div",{className:"w-full grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-5",children:(j.type==="true-false"?[{id:"tf-true",text:"True"},{id:"tf-false",text:"False"}]:Z).map(w=>{const v=w.text,Q=L?.failedOptions.includes(v),W=L?.resolved&&L.resolution==="revealed",re=L?.resolved&&L.resolution==="correct",ve=v===j.correctAnswer;let se="bg-white hover:bg-slate-50 border-transparent text-slate-700 hover:border-slate-200";return W||re?ve?se="bg-emerald-50 border-emerald-400 text-emerald-800 shadow-[0_0_15px_rgba(16,185,129,0.2)] scale-[1.02] z-10":Q?se="bg-rose-50 border-rose-400 text-rose-800 opacity-60":se="bg-slate-50 border-slate-200 text-slate-400 opacity-60":Q?se="bg-rose-50 border-rose-400 text-rose-800 opacity-60":R===w.id&&(se="bg-purple-50 border-[#9956DE] text-[#9956DE]"),e.jsxs("button",{disabled:L?.resolved||Q||Ee,onClick:()=>{L?.resolved||Ee||Q||(T(w.id),Ve(v))},className:`p-4 sm:p-5 rounded-2xl shadow-sm border-[3px] font-extrabold text-base sm:text-lg text-left transition-all flex items-center justify-between ${se} ${L?.resolved?"cursor-default":"hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"}`,children:[e.jsx("span",{className:"truncate pr-4",children:e.jsx(Bt,{children:v})}),(W||re)&&ve&&e.jsx(Pt,{size:24,className:"text-emerald-500 shrink-0"}),Q&&e.jsx(Ze,{size:24,className:"text-rose-500 shrink-0"})]},w.id)})}),te&&j.hints&&(L?.hintsUsed??0)>0&&e.jsx(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"w-full mt-6 max-w-3xl",children:e.jsxs("div",{className:"border-2 rounded-2xl p-5 bg-amber-50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ct,{size:18,className:"text-amber-500"}),e.jsxs("span",{className:"font-bold text-amber-700 text-sm",children:["Hints (",L?.hintsUsed,"/",je,")"]})]}),e.jsx("div",{className:"space-y-2",children:j.hints.slice(0,L?.hintsUsed??0).map((w,v)=>e.jsxs("p",{className:"text-sm text-amber-800 leading-relaxed",children:[e.jsxs("span",{className:"font-bold text-amber-600",children:[v+1,"."]})," ",w]},v))})]})}),pe&&L?.resolved&&j.explanation&&e.jsx(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"w-full mt-6 max-w-3xl",children:e.jsxs("div",{className:"border-2 rounded-2xl p-5 flex items-start gap-4 bg-sky-50 border-sky-200",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",className:"w-10 h-10 shrink-0",alt:"AI Explain"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-extrabold text-lg mb-1 text-sky-700",children:"Explanation"}),e.jsx("p",{className:"text-base leading-relaxed text-sky-800",children:j.explanation})]})]})})]})]},j.id)}),e.jsxs("footer",{className:`shrink-0 relative z-[60] flex flex-col items-center justify-center p-4 sm:p-6 ${lt.gradient} rounded-t-[32px] sm:rounded-t-[40px] shadow-[0_-10px_40px_rgba(0,0,0,0.15)]`,children:[e.jsx("div",{className:"absolute inset-0 z-0 pointer-events-none opacity-20",children:Te.slice(0,3).map((w,v)=>e.jsx("div",{className:"absolute text-white",style:{top:`${20+v*20}%`,left:`${20+v*30}%`,transform:`rotate(${v*30}deg) scale(1.5)`},children:e.jsx(w,{size:32})},v))}),e.jsx("div",{className:"relative z-10 flex flex-col gap-3",children:L?.resolved?pe?e.jsxs("button",{onClick:ot,className:"bg-orange-500 hover:bg-orange-600 text-white font-extrabold text-lg px-8 py-4 rounded-full flex items-center justify-center gap-3 shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-all w-full",children:["Next Question ",e.jsx(Ye,{size:24})]}):e.jsxs("div",{className:"flex flex-wrap justify-center gap-3 sm:gap-4",children:[e.jsxs("button",{onClick:()=>{xe||he(!0)},disabled:xe,className:"bg-white hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",className:"w-5 h-5 drop-shadow-sm",alt:"Explain"}),"Explain"]}),e.jsxs("button",{onClick:ot,className:"bg-orange-500 hover:bg-orange-600 text-white font-extrabold text-lg px-8 py-3 sm:py-3.5 rounded-full flex items-center justify-center gap-2 shadow-xl hover:scale-105 active:scale-95",children:["Next Question ",e.jsx(Ye,{size:20})]})]}):e.jsxs("div",{className:"flex flex-wrap justify-center gap-3 sm:gap-4",children:[e.jsxs("button",{onClick:gt,disabled:me<=0||He<=0,className:"bg-white hover:bg-slate-50 disabled:opacity-70 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Hint",className:"w-5 h-5 object-contain"}),"Hint"]}),e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:nt,disabled:ie,className:"bg-white hover:bg-slate-50 disabled:opacity-70 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx(Ut,{size:18,className:"text-purple-500"}),"Reveal"]}),ie&&K!==null&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-1.5 bg-slate-800 text-white text-[11px] rounded-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none font-medium",children:"Reveal locked. Give it another try!"})]}),e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{disabled:!0,className:"bg-white disabled:opacity-50 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg border border-slate-200",children:[e.jsx(rs,{size:16,className:"text-slate-400"}),"Explain"]}),e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-1.5 bg-slate-800 text-white text-[11px] rounded-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none font-medium",children:"Unlocks after you complete or reveal this question"})]}),e.jsx("button",{onClick:()=>Ce(w=>!w),className:`w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200 ${ze?"bg-purple-100 text-purple-600 border-purple-300":"bg-white hover:bg-slate-50 text-slate-700"}`,children:e.jsx(pt,{size:20})}),j.type==="fill-in-blank"&&e.jsxs("button",{onClick:()=>Ve(),disabled:!F.trim()||Ee,className:"bg-orange-500 hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed text-white font-extrabold text-lg px-8 py-3 sm:py-3.5 rounded-full flex items-center justify-center gap-2 shadow-xl hover:scale-105 active:scale-95",children:["Submit ",e.jsx(Ye,{size:20})]})]})})]})]})]}):null},sl=[{id:1,type:"multiple-choice",question:"What is the value of π (pi) to two decimal places?",options:["3.12","3.14","3.16","3.18"],correctAnswer:"3.14",explanation:"π ≈ 3.14159..., so to two decimal places it is 3.14."},{id:2,type:"true-false",question:"The sum of angles in a triangle is 180 degrees.",correctAnswer:"True",explanation:"The interior angles of any Euclidean triangle sum to 180°."},{id:3,type:"fill-in-blank",question:"If 2x + 5 = 13, then x = ___.",correctAnswer:"4",explanation:"2x = 13 - 5 = 8 → x = 4."},{id:4,type:"multiple-choice",question:"Which of the following is a prime number?",options:["9","15","17","21"],correctAnswer:"17",explanation:"17 is only divisible by 1 and itself. 9=3×3, 15=3×5, 21=3×7."},{id:5,type:"true-false",question:"The slope of a horizontal line is zero.",correctAnswer:"True",explanation:"A horizontal line has no rise, so rise/run = 0."},{id:6,type:"fill-in-blank",question:"The square root of 144 is ___.",correctAnswer:"12",explanation:"12 × 12 = 144, so √144 = 12."}];async function al(t){const{lessonTitle:s,topic:l,subjectId:n,competencyCode:i,questionCount:c=6}=t,r=ll(n)||"General Mathematics",x=t.lessonId?Math.abs(t.lessonId.split("").reduce((d,h)=>Math.imul(31,d)+h.charCodeAt(0)|0,0))%1e6:Math.floor(Math.random()*1e6);try{const d=await rt("/api/quiz/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:l||s,subject:r,lessonTitle:s,questionCount:c,questionTypes:["multiple-choice","true-false","fill-in-blank"],difficulty:"medium",competencyCode:i,varianceSeed:x})});return!d.questions||d.questions.length===0?(console.warn("[lessonQuizService] API returned empty questions, using fallback"),zs(c)):d.questions.map(h=>({id:h.id,type:h.type,question:h.question,options:h.options||void 0,correctAnswer:h.correctAnswer,explanation:h.explanation,hints:h.hints||[],bloomLevel:h.bloomLevel||"remember"}))}catch(d){return console.error("[lessonQuizService] Failed to generate quiz via API:",d),console.warn("[lessonQuizService] Using fallback questions"),zs(c)}}function rl(t){return 6}function ll(t){if(!t)return null;const s=t.toLowerCase();return s.includes("gen-math")||s.includes("gen_math")?"General Mathematics":s.includes("stats")||s.includes("prob")?"Statistics and Probability":s.includes("pre-calc")||s.includes("pre_calc")?"Pre-Calculus":s.includes("basic-calc")||s.includes("basic_calc")||s.includes("calculus")?"Basic Calculus":null}function zs(t){const s=[...sl].sort(()=>Math.random()-.5);return s.slice(0,Math.min(t,s.length)).map((l,n)=>({...l,id:n+1}))}const nl="rag_lesson_";function ds(t){return`${nl}${t}`}function il(t){try{const s=sessionStorage.getItem(ds(t));if(s)return JSON.parse(s)}catch{}return null}function ol(t,s){try{sessionStorage.setItem(ds(t),JSON.stringify(s))}catch{}}function cl(t,s,l=!0){const[n,i]=a.useState([]),[c,r]=a.useState(!0),[x,d]=a.useState(null),[h,S]=a.useState([]),[m,z]=a.useState("low"),[p,u]=a.useState(0),[k,f]=a.useState(!1),[C,N]=a.useState(void 0),[R,T]=a.useState(!1),F=a.useCallback(async()=>{if(!l||!t)return;const Z=il(t);if(Z){i(Z.sections),S(Z.sources),z(Z.retrievalBand),u(Z.retrievalConfidence),f(Z.needsReview),N(Z.activeModel),r(!1),d(null),T(!1);return}r(!0),d(null),T(!1);try{const te=(await St(()=>import("./vendor-firebase-auth-T_wvTOvf.js"),__vite__mapDeps([4,3])).then(pe=>pe.getAuth().currentUser))?.uid,$=await ja({...s,lessonId:t,userId:te});i($.sections),S($.sources||[]),z($.retrievalBand),u($.retrievalConfidence),f($.needsReview),N($.activeModel),ol(t,$),d(null),T(!1)}catch(Y){const te=Y.status||Y.response?.status,$=Y.body||Y.response;let pe="Failed to load lesson content.",he=!1;te===404&&$?.error==="no_curriculum_context"?(pe=$.message||"Lesson source PDF not found or not yet ingested.",he=!0):te===401?pe="Please sign in again to access lessons.":navigator.onLine||(pe="No internet connection. Please try again when online.",he=!0),d(pe),T(he),i([])}finally{r(!1)}},[t,l,JSON.stringify(s)]);a.useEffect(()=>{F()},[F]);const X=a.useCallback(()=>{t&&sessionStorage.removeItem(ds(t)),r(!0),d(null),F()},[F,t]);return{sections:n,isLoading:c,error:x,retry:X,sources:h,retrievalBand:m,retrievalConfidence:p,needsReview:k,activeModel:C,isOffline:R}}const Hs=/[=×÷±√∑∫π²³%]/,dl=/^(Definition|Formula|Note|Reminder|Important|Example|Key Concept|Concept|Rule|Theorem|Property|Step)s?\s*:/i;function dt(t){return t.replace(/\b([A-Z][a-zA-Z\s]{2,30}?)\s+(is|are|refers to|defined as|means)\b/g,(s,l,n)=>`**${l.trim()}** ${n}`).replace(/"([^"]{3,40})"/g,(s,l)=>`**${l}**`)}function Vt(t){if(!t?.trim())return null;const s=t.split(` -`),l=[];let n=[],i=[],c=[],r=0;const x=()=>{if(n.length===0)return;const u=n.join(" ").trim();if(!u){n=[];return}const k=u.match(/[^.!?]+[.!?]+["']?/g)||[u],f=[];let C=[],N=0;for(const R of k)C.push(R),N+=R.length,N>220&&(f.push(C),C=[],N=0);C.length&&f.push(C);for(const R of f){const T=dt(R.join(" ").trim());l.push(e.jsx("p",{className:"lesson-body-text text-slate-700 leading-[1.8] text-[1rem] font-body",children:$e(T)},r++))}n=[]},d=()=>{i.length!==0&&(l.push(e.jsx("ul",{className:"space-y-2.5 my-1 pl-1",children:i.map((u,k)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-700 text-[0.95rem] leading-[1.75] font-body",children:[e.jsx("span",{className:"mt-[0.5rem] w-2 h-2 rounded-full bg-[#1a85a4] flex-shrink-0"}),e.jsx("span",{children:$e(dt(u))})]},k))},r++)),i=[])},h=()=>{c.length!==0&&(l.push(e.jsx("ol",{className:"space-y-2.5 my-1 list-none pl-1",children:c.map((u,k)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-700 text-[0.95rem] leading-[1.75] font-body",children:[e.jsx("span",{className:"mt-0.5 min-w-[1.5rem] h-[1.5rem] rounded-full bg-[#1a85a4] text-white text-[0.7rem] font-bold flex items-center justify-center flex-shrink-0",children:k+1}),e.jsx("span",{children:$e(dt(u))})]},k))},r++)),c=[])},S=u=>/^[\-•\*]\s+/.test(u.trim()),m=u=>/^\d+[\.\)]\s+/.test(u.trim()),z=u=>Hs.test(u)&&u.trim().length<120,p=u=>{const k=u.toLowerCase();return/formula|theorem|property|rule/.test(k)?{bg:"bg-amber-50",border:"border-amber-300",text:"text-amber-900",label:"📐"}:/definition|concept|key/.test(k)?{bg:"bg-blue-50",border:"border-blue-300",text:"text-blue-900",label:"📖"}:/note|reminder|important/.test(k)?{bg:"bg-rose-50",border:"border-rose-300",text:"text-rose-900",label:"⚠️"}:/example|step/.test(k)?{bg:"bg-emerald-50",border:"border-emerald-300",text:"text-emerald-900",label:"✏️"}:{bg:"bg-slate-50",border:"border-slate-300",text:"text-slate-800",label:"💡"}};for(const u of s){const k=u.trimEnd(),f=k.trim();if(f===""){d(),h(),x();continue}const C=f.match(dl);if(C){d(),h(),x();const N=C[1],R=f.slice(C[0].length).trim(),T=p(N);l.push(e.jsxs("div",{className:`rounded-xl px-4 py-3.5 border-l-4 ${T.bg} ${T.border} my-1`,children:[e.jsxs("p",{className:`text-[0.75rem] font-black uppercase tracking-widest mb-1.5 ${T.text} opacity-80 font-display`,children:[T.label," ",N]}),e.jsx("p",{className:`text-[0.95rem] leading-[1.75] font-semibold font-body ${T.text}`,children:$e(R)})]},r++));continue}if(S(f)){x(),h(),i.push(f.replace(/^[\-•\*]\s+/,""));continue}if(m(f)){x(),d(),c.push(f.replace(/^\d+[\.\)]\s+/,""));continue}if(z(f)&&!/[a-z]{5,}/.test(f)){d(),h(),x(),l.push(e.jsx("div",{className:"lesson-formula-box my-3",children:f},r++));continue}if(f.endsWith(":")&&f.length<80&&!f.startsWith(" ")){d(),h(),x(),l.push(e.jsx("p",{className:"lesson-section-heading text-[#1a85a4] text-[1.05rem] mt-5 mb-1 border-b-2 border-[#1a85a4]/20 pb-1.5",children:$e(f)},r++));continue}d(),h(),n.push(k)}return d(),h(),x(),e.jsx("div",{className:"space-y-3",children:l})}function $e(t){const s=[],l=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`|==(.+?)==)/g;let n=0,i,c=0;for(;(i=l.exec(t))!==null;)i.index>n&&s.push(e.jsx(Fe.Fragment,{children:t.slice(n,i.index)},c++)),i[2]?s.push(e.jsx("strong",{className:"font-extrabold text-[#1a85a4] bg-[#e0f4fa] px-1 py-0.5 rounded-md font-body",children:i[2]},c++)):i[3]?s.push(e.jsx("em",{className:"italic text-slate-500 font-body",children:i[3]},c++)):i[4]?s.push(e.jsx("code",{className:"px-1.5 py-0.5 bg-slate-100 rounded text-[0.85em] font-mono text-[#e66a5e] border border-slate-200 font-semibold",children:i[4]},c++)):i[5]&&s.push(e.jsx("mark",{className:"bg-[#fff3cd] text-[#92400e] px-1 py-0.5 rounded-md font-bold border-b-2 border-[#fbbf24]",children:i[5]},c++)),n=i.index+i[0].length;return n0?e.jsx(e.Fragment,{children:s}):t}function ml(t){if(!t?.trim())return{welcome:"",objectives:[]};const s=t.split(` -`).map(x=>x.trim()).filter(Boolean),l=/^(\d+[\.\)]\s+|[-•*]\s+|(Identify|Write|Set|Use|Apply|Solve|Compute|Calculate|Determine|Understand|Describe|Explain|Analyze|Evaluate|Create|Define|Distinguish|Compare|Illustrate|Demonstrate|Perform|Simplify|Represent|Model|Interpret|Recognize|Classify|Construct|Derive|Formulate|Graph|Sketch|Verify|Prove|Estimate|Approximate|Convert|Translate|Predict|Justify|Generalize|Extend|Develop|Explore|Investigate|Discover|Observe|Measure|Record|Report|Present|Communicate|Collaborate|Reflect|Review|Summarize|Conclude|Infer|Hypothesize|Test|Experiment|Design|Plan|Implement|Evaluate|Assess|Monitor|Adjust|Improve|Optimize|Innovate|Create|Produce|Publish|Share|Teach|Learn|Practice|Apply|Transfer|Connect|Integrate|Synthesize|Analyze|Evaluate|Create)\b)/i,n=/^(Example:|e\.g\.|For example:|Sample:|\()/i,i=[],c=[];let r=!1;for(let x=0;x0&&t.callouts.map((u,k)=>e.jsxs("div",{className:`lesson-callout-headsup flex items-start gap-3.5 ${u.type==="tip"?"!bg-gradient-to-r !from-emerald-50 !to-teal-50 !border-emerald-400":""}`,children:[e.jsx("div",{className:`w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5 shadow-sm ${u.type==="tip"?"bg-emerald-500":"bg-amber-500"}`,children:e.jsx(ct,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 ${u.type==="tip"?"text-emerald-600":"text-amber-600"}`,children:u.type==="tip"?"✨ Tip":u.type==="important"?"⚠️ Heads Up":"📌 Note"}),e.jsx("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:u.text})]})]},k)),(!t.callouts||t.callouts.length===0)&&e.jsxs("div",{className:"lesson-callout-headsup flex items-start gap-3.5",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-amber-500 flex items-center justify-center flex-shrink-0 mt-0.5 shadow-sm",children:e.jsx(ct,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 text-amber-600",children:"⚠️ Heads Up"}),e.jsxs("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:["This lesson has ",7," sections and takes about 20 minutes to complete. Grab a pen — you might want to take notes along the way!"]})]})]}),z.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(at,{size:20,className:"text-violet-500"}),e.jsx("h3",{className:"lesson-section-heading text-[1.05rem]",style:{color:"#7c3aed"},children:"What you'll learn"})]}),e.jsx("div",{className:"space-y-2.5",children:z.map((u,k)=>{const f=_s[k%_s.length];return e.jsxs("div",{className:`rounded-xl border-2 px-4 py-3.5 flex items-start gap-3.5 ${f.bg} ${f.border} shadow-sm`,children:[e.jsx("span",{className:`mt-0.5 min-w-[1.75rem] h-7 rounded-full ${f.num} text-white text-[0.7rem] font-black flex items-center justify-center flex-shrink-0 shadow-sm`,children:k+1}),e.jsxs("div",{children:[e.jsx("p",{className:`font-body text-[0.95rem] font-semibold leading-snug ${f.text}`,children:$e(dt(u.text))}),u.example&&e.jsx("p",{className:`text-xs mt-1 ${f.ex} font-mono font-semibold`,children:u.example})]})]},k)})})]})]})}case"key_concepts":return e.jsxs("div",{className:"space-y-4",children:[t.content?.trim()?e.jsx("div",{className:"mb-4",children:Vt(t.content)}):e.jsx("p",{className:"text-slate-400 text-sm italic mb-4",children:"Key concepts are being compiled. Review the curriculum sources below for reference material."}),t.callouts&&t.callouts.length>0&&e.jsx("div",{className:"space-y-3",children:t.callouts.map((m,z)=>e.jsxs("div",{className:`rounded-xl border-2 px-5 py-4 flex items-start gap-3.5 shadow-sm ${m.type==="important"?"bg-rose-50 border-rose-300":m.type==="tip"?"bg-emerald-50 border-emerald-300":"bg-amber-50 border-amber-300"}`,children:[e.jsx("div",{className:`w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5 shadow-sm ${m.type==="important"?"bg-rose-500":m.type==="tip"?"bg-emerald-500":"bg-amber-500"}`,children:e.jsx(ct,{size:16,className:"text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:`lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 ${m.type==="important"?"text-rose-500":m.type==="tip"?"text-emerald-600":"text-amber-600"}`,children:m.type==="important"?"🔑 Important":m.type==="tip"?"✨ Tip":"📌 Note"}),e.jsx("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:$e(m.text)})]})]},z))})]});case"video":return e.jsxs("div",{className:"space-y-4",children:[t.content?.trim()?e.jsx("p",{className:"text-slate-600 text-sm",children:t.content}):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"Video explanation loading..."}),e.jsx(va,{videos:t.videos||[],topic:i.title})]});case"worked_examples":return e.jsx("div",{className:"space-y-5",children:t.examples&&t.examples.length>0?t.examples.map((m,z)=>e.jsxs("div",{className:"bg-gradient-to-br from-rose-50 via-orange-50 to-amber-50 rounded-2xl p-5 border-2 border-rose-200 shadow-md",children:[e.jsxs("div",{className:"flex items-start gap-3.5 mb-4",children:[e.jsx("div",{className:"w-10 h-10 bg-gradient-to-br from-rose-500 to-orange-500 rounded-xl flex items-center justify-center flex-shrink-0 shadow-md",children:e.jsx(pt,{size:18,className:"text-white"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] text-rose-400 mb-1",children:["Example ",z+1]}),e.jsx("p",{className:"font-body font-bold text-slate-800 text-[1rem] leading-snug",children:m.problem})]})]}),m.steps.length>0&&e.jsxs("div",{className:"ml-14 space-y-2.5 mb-3",children:[e.jsx("p",{className:"lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] text-slate-400 mb-1.5",children:"Solution"}),m.steps.map((p,u)=>Hs.test(p)&&p.length<100&&!/[a-z]{6,}/.test(p)?e.jsx("div",{className:"lesson-formula-box",children:p},u):e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 min-w-[1.5rem] h-[1.5rem] rounded-full bg-white border-2 border-rose-300 text-rose-500 text-[0.65rem] font-black flex items-center justify-center flex-shrink-0 shadow-sm",children:u+1}),e.jsx("p",{className:"font-body text-slate-700 text-[0.95rem] leading-[1.75]",children:$e(p)})]},u))]}),m.answer&&e.jsxs("div",{className:"ml-14 flex items-center gap-3 mt-3 pt-3 border-t-2 border-rose-200",children:[e.jsx("div",{className:"px-3.5 py-1.5 bg-gradient-to-r from-rose-500 to-orange-500 rounded-lg text-white text-[0.65rem] font-black uppercase tracking-widest flex-shrink-0 shadow-sm",children:"Answer"}),e.jsx("p",{className:"font-body text-slate-800 text-[0.95rem] font-bold",children:m.answer})]})]},z)):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"No worked examples available for this lesson."})});case"important_notes":return e.jsx("div",{className:"space-y-3",children:t.bulletPoints&&t.bulletPoints.length>0?t.bulletPoints.map((m,z)=>{const p=m.match(/^(Note|Important|Remember|Warning|Tip|Key|Formula|Rule)\s*:/i);if(p){const u=p[1],k=m.slice(p[0].length).trim(),f=/note|important|warning|remember/i.test(u);return e.jsxs("div",{className:`rounded-xl px-5 py-4 border-l-4 flex items-start gap-3.5 shadow-sm ${f?"bg-rose-50 border-rose-400":"bg-amber-50 border-amber-400"}`,children:[e.jsx(ct,{size:18,className:`mt-0.5 flex-shrink-0 ${f?"text-rose-500":"text-amber-500"}`}),e.jsxs("div",{children:[e.jsx("p",{className:`lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 ${f?"text-rose-500":"text-amber-600"}`,children:u}),e.jsx("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:$e(dt(k))})]})]},z)}return e.jsxs("div",{className:"flex items-start gap-3.5 p-4 rounded-xl bg-slate-50 border-2 border-slate-200 hover:border-[#1a85a4]/40 hover:bg-[#f0fbff] transition-colors",children:[e.jsx("div",{className:"mt-0.5 w-6 h-6 rounded-full bg-[#1a85a4] flex items-center justify-center flex-shrink-0 shadow-sm",children:e.jsx("span",{className:"text-white text-[0.65rem] font-black",children:z+1})}),e.jsx("p",{className:"font-body text-slate-700 text-[0.95rem] leading-[1.75] font-medium",children:$e(dt(m))})]},z)}):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"No notes available for this lesson."})});case"try_it_yourself":return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-col items-center text-center gap-3 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center shadow-lg",style:{background:"#9956DE"},children:e.jsx(at,{size:32,className:"text-white"})}),e.jsx("h3",{className:"text-xl font-black",style:{color:"#9956DE"},children:"Try It Yourself"}),e.jsx("p",{className:"text-slate-500 text-sm max-w-xs leading-relaxed",children:"Now it's your turn! Try applying what you've learned. You can practice with the exercises at the end of this module."})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-xl px-4 py-3 border",style:{background:"#f5eeff",borderColor:"#d4aaff"},children:[e.jsx(ct,{size:16,className:"mt-0.5 shrink-0",style:{color:"#9956DE"}}),e.jsxs("p",{className:"text-sm",style:{color:"#7a3db8"},children:[e.jsx("span",{className:"font-bold",children:"Tip:"})," Complete the practice quizzes after this lesson to reinforce your learning!"]})]}),c&&e.jsx("div",{className:"bg-white rounded-2xl p-5 border border-slate-200 shadow-sm",children:r?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center",children:e.jsx(at,{size:20,className:"text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-emerald-700",children:["Quiz Complete",typeof x=="number"&&e.jsxs("span",{className:"ml-2 text-emerald-600",children:[x,"%"]})]}),e.jsx("p",{className:"text-xs text-emerald-600/80",children:"Great job! You can now complete this lesson."})]})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-widest mb-1",style:{color:"#9956DE"},children:"Practice Quiz"}),e.jsx("p",{className:"font-bold text-slate-800 text-sm",children:c.title}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[c.questions," questions · ",c.duration]})]}),e.jsx("button",{onClick:d,className:"w-full sm:w-auto px-6 py-2.5 rounded-xl bg-[#1a85a4] text-white text-sm font-black hover:bg-[#126b84] transition-colors shadow-md uppercase tracking-wide",children:"Start Practice"})]})}),!c&&e.jsxs("button",{onClick:S,className:"w-full flex items-center justify-between gap-4 text-white rounded-2xl px-6 py-4 shadow-lg transition-all hover:shadow-xl hover:scale-[1.01] active:scale-[0.99] group",style:{background:"#9956DE"},onMouseEnter:m=>m.currentTarget.style.background="#8744cc",onMouseLeave:m=>m.currentTarget.style.background="#9956DE",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center shrink-0",children:e.jsx(Va,{size:22,className:"text-white"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-black text-sm uppercase tracking-wide",children:"Start Practice Quiz"}),e.jsx("p",{className:"text-white/80 text-xs mt-0.5",children:"10 questions · AI-generated"})]})]}),e.jsx(Ye,{size:20,className:"text-white/80 group-hover:translate-x-1 transition-transform"})]})]});case"summary":return e.jsx("div",{className:"space-y-3",children:t.content?.trim()?Vt(t.content):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"Summary is being prepared. Review the lesson sections above to reinforce your understanding."})});default:return e.jsx("p",{className:"text-slate-500 text-sm italic",children:"Section content not available."})}}const Nt=[{type:"introduction",label:"Intro",helper:"Welcome note",icon:ht,accent:"from-[#1a85a4] to-[#126b84]",tint:"bg-[#1a85a4] text-white border-transparent",tabBg:"bg-[#1a85a4]"},{type:"key_concepts",label:"Concepts",helper:"Core ideas",icon:or,accent:"from-[#fbab41] to-[#e0983a]",tint:"bg-[#fbab41] text-white border-transparent",tabBg:"bg-[#fbab41]"},{type:"video",label:"Video",helper:"Watch and learn",icon:ct,accent:"from-[#e66a5e] to-[#ce5e53]",tint:"bg-[#e66a5e] text-white border-transparent",tabBg:"bg-[#e66a5e]"},{type:"worked_examples",label:"Examples",helper:"Guided solving",icon:Ma,accent:"from-[#7ec16d] to-[#71ad62]",tint:"bg-[#7ec16d] text-white border-transparent",tabBg:"bg-[#7ec16d]"},{type:"important_notes",label:"Notes",helper:"Key reminders",icon:dr,accent:"from-[#9a67d0] to-[#8a5cc0]",tint:"bg-[#9a67d0] text-white border-transparent",tabBg:"bg-[#9a67d0]"},{type:"try_it_yourself",label:"Practice",helper:"Try it yourself",icon:We,accent:"from-[#eb74a6] to-[#d46895]",tint:"bg-[#eb74a6] text-white border-transparent",tabBg:"bg-[#eb74a6]"},{type:"summary",label:"Summary",helper:"Wrap-up",icon:zt,accent:"from-[#48bca6] to-[#40a794]",tint:"bg-[#48bca6] text-white border-transparent",tabBg:"bg-[#48bca6]"}],hl=({lesson:t,lessonCompletionXP:s=10,practiceQuiz:l,practiceQuizCompleted:n=!1,practiceQuizScore:i,initialSection:c=0,nextContentLabel:r,onStartPractice:x,onBack:d,onComplete:h,onProgressUpdate:S,onTryItQuizComplete:m,onContinueLearning:z})=>{const{userProfile:p}=Ht(),[u,k]=a.useState(0),[f,C]=a.useState(1),[N,R]=a.useState(!1),[T,F]=a.useState(null),[X,Z]=a.useState(!1),[Y,te]=a.useState(null),[$,pe]=a.useState(!1),[he]=a.useState(()=>`tiy-${Date.now()}`);a.useEffect(()=>{!X||Y||(pe(!0),al({lessonId:t.id?.toString()||"unknown",lessonTitle:t.title,topic:t.title,subjectId:t.subjectId,competencyCode:t.competencyCode,questionCount:15}).then(D=>te(D)).catch(D=>{console.error("[LessonViewer] Quiz generation failed:",D),Z(!1)}).finally(()=>pe(!1)))},[X,Y,t]);const[ze,Ce]=a.useState(!1),b={topic:t.title,subject:t.subject||"General Mathematics",quarter:t.quarter||1,lessonTitle:t.title,moduleId:t.subjectId,lessonId:t.id,competencyCode:t.competencyCode,learnerLevel:"Grade 11-12",storagePath:t.storagePath},{sections:H,isLoading:ce,error:ae,retry:le,sources:ge,retrievalBand:Ne,activeModel:B,isOffline:Ee}=cl(t.id,b,!0),[_e,ye]=a.useState(null);a.useEffect(()=>{if(H.length>0){const D=H.find(ne=>ne.type==="introduction");if(D?.title){const me=D.title.replace(/^Introduction\s+(to|-|:|—)\s+/i,"").replace(/\s*[-:—]\s*Introduction$/i,"").replace(/\s+Introduction$/i,"").trim();me&&me.toLowerCase()!=="introduction"&&ye(me)}}},[H]),a.useEffect(()=>{H.length>0&&p?.uid&&t.id&&_a(p.uid,t.id,_e||t.title).catch(()=>{})},[H.length,p?.uid,t.id,_e,t.title]);const fe=H.length||Nt.length;if(a.useEffect(()=>{c>=0&&c{const D=H.findIndex(ne=>ne.type==="try_it_yourself");c===-1&&D>=0&&k(D)},[H,c]),a.useEffect(()=>{const D=fe>0?(u+1)/fe*100:0;S?.(D)},[u,fe,S]),ce)return e.jsx(xl,{});if(ae&&H.length===0)return e.jsx(ul,{message:ae,onRetry:le,isOffline:Ee});const Me=String(t.id||"").match(/\d+/);if(Me&&Me[0],X)return $||!Y?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-white rounded-2xl p-6 flex flex-col items-center gap-3 shadow-xl",children:[e.jsx("div",{className:"w-10 h-10 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"}),e.jsx("p",{className:"font-bold text-slate-700",children:"Generating Quiz..."})]})}):e.jsx(tl,{questions:Y,lessonTitle:t.title,subject:t.subject||"General Mathematics",sessionId:he,userId:p?.uid,onBack:()=>{Z(!1),te(null)},onComplete:D=>{m?.(D),Ce(!0),Z(!1),te(null)}});const Ae=H[u]||{type:"introduction",title:"Loading...",content:"Lesson content is loading. Please wait a moment."},g=()=>{uD+1)):(!l||n)&&R(!0)},q=()=>{u>0&&(C(-1),k(D=>D-1))},M=D=>{R(!1),h(void 0,void 0,D)},O=!!(l&&!n||!ze),I=Nt[u]||Nt[0],J=I.icon,be=e.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-slate-50 overflow-hidden font-sans",children:[e.jsx("header",{className:"flex-none bg-transparent px-3 sm:px-6 pt-2 sm:pt-3 md:pt-4 pb-2 sm:pb-3 sm:py-4 relative z-40",children:e.jsxs("div",{className:"max-w-[90rem] mx-auto flex items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx("button",{onClick:d,className:"w-9 h-9 sm:w-10 sm:h-10 rounded-full bg-white border border-slate-200 hover:bg-slate-50 flex items-center justify-center text-slate-600 transition-colors flex-shrink-0 shadow-sm","aria-label":"Go back",children:e.jsx(es,{size:16})}),e.jsxs("div",{className:"min-w-0 flex flex-col justify-center flex-1",children:[e.jsxs("div",{className:"hidden sm:flex items-center gap-1.5 sm:gap-2 text-[9px] sm:text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-0.5",children:[e.jsx(qe,{size:10}),e.jsx("span",{children:"NOTEBOOK"}),B&&e.jsx("span",{className:"text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded font-mono",children:B.split("/").pop()}),Ne==="high"&&e.jsx("span",{className:"text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded text-[10px] font-semibold border border-emerald-200",children:"DepEd Source"})]}),e.jsxs("div",{className:"flex sm:hidden items-center gap-1 text-[9px] font-bold text-slate-400 uppercase tracking-widest mb-0.5",children:[e.jsx(qe,{size:9}),e.jsx("span",{children:"Notebook"}),Ne==="high"&&e.jsx("span",{className:"text-emerald-600 bg-emerald-50 px-1 py-0.5 rounded text-[8px] font-semibold border border-emerald-200 leading-none",children:"DepEd"})]}),e.jsx("h1",{className:"font-bold text-slate-800 text-xs sm:text-sm truncate",children:t.title})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[e.jsxs("div",{className:"text-right hidden sm:block",children:[e.jsx("p",{className:"text-[10px] font-bold text-slate-500 uppercase tracking-wider",children:"Progress"}),e.jsxs("p",{className:"text-sm font-bold text-slate-800",children:[Math.round((u+1)/fe*100),"%"]})]}),e.jsx("div",{className:"w-12 sm:w-24 md:w-32 h-1.5 sm:h-2 bg-slate-200 rounded-full overflow-hidden",children:e.jsx(E.div,{className:"h-full bg-[#7ec16d] rounded-full",animate:{width:`${(u+1)/fe*100}%`},transition:{duration:.25}})})]})]})}),e.jsx("main",{className:"flex-1 overflow-hidden px-2 sm:px-5 pb-2 relative flex justify-center min-h-0",children:e.jsxs("div",{className:"w-full max-w-[90rem] h-full relative flex md:pl-16 pt-10 sm:pt-10 md:pt-0",children:[e.jsx("div",{className:"hidden md:flex absolute left-0 top-8 bottom-8 w-20 flex-col justify-between z-0 py-2",children:Nt.map((D,ne)=>{const me=ne===u,Ge=D.icon;return e.jsxs("button",{onClick:()=>{C(ne>u?1:-1),k(ne)},className:Mt("group relative flex items-center justify-start pl-4 rounded-l-[1.5rem] transition-all duration-300 shadow-sm border-r-0 flex-shrink-0",D.tabBg,me?"w-24 h-20 -translate-x-4 shadow-xl z-20 brightness-105":"w-16 h-16 hover:w-24 hover:h-20 hover:-translate-x-4 hover:brightness-110 opacity-90 hover:opacity-100 z-10"),"aria-label":`Go to ${D.label} section`,children:[e.jsx("div",{className:Mt("transition-all duration-300 rounded-xl",me?"bg-white/30 p-2.5":"bg-white/20 p-2 group-hover:bg-white/30 group-hover:p-2.5"),children:e.jsx(Ge,{size:me?24:20,className:"text-white transition-transform duration-300 group-hover:scale-110"})}),e.jsxs("div",{className:"absolute right-full mr-3 px-3 py-1.5 bg-slate-800 text-white text-xs font-bold rounded-lg opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity whitespace-nowrap z-[100] shadow-xl border border-slate-700/50",children:[e.jsx("div",{className:"absolute top-1/2 -right-1 -translate-y-1/2 w-2 h-2 bg-slate-800 rotate-45 border-r border-t border-slate-700/50"}),D.label]})]},D.type)})}),e.jsx("div",{className:"md:hidden absolute left-0 right-0 top-0 z-30 bg-slate-100/95 backdrop-blur-sm",children:e.jsx("div",{className:"flex gap-0.8 overflow-x-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden px-1",children:Nt.map((D,ne)=>{const me=ne===u,Ge=D.icon;return e.jsxs("button",{onClick:()=>{C(ne>u?1:-1),k(ne)},className:Mt("flex items-center gap-1.5 px-3 py-2 rounded-t-lg transition-all duration-200 shrink-0 text-[11px] font-bold touch-manipulation min-h-[2.5rem]",me?`${D.tabBg} text-white shadow-md`:"bg-slate-200/80 text-slate-500"),children:[e.jsx(Ge,{size:14}),e.jsx("span",{children:D.label})]},D.type)})})}),e.jsxs("div",{className:Mt("flex-1 min-w-0 rounded-none sm:rounded-lg shadow-2xl flex flex-col overflow-visible relative z-10 transition-colors duration-500",I.tabBg),children:[e.jsxs("div",{className:"px-3 sm:px-6 py-2 sm:py-3.5 flex items-center gap-2 sm:gap-4 text-white",children:[e.jsx("div",{className:"bg-white/20 p-1 sm:p-2 rounded-lg sm:rounded-xl shrink-0",children:e.jsx(J,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("h2",{className:"lesson-section-heading text-sm sm:text-xl md:text-2xl truncate",title:Ae.title,children:Ae.title}),e.jsx("p",{className:"text-white/90 text-[10px] sm:text-xs font-medium truncate mt-0.5 font-body",title:t.title,children:t.title})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 bg-[#fdfdfd] rounded-lg sm:rounded-[1.5rem] m-1 mt-0 relative overflow-hidden shadow-inner flex flex-col",children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none opacity-30",style:{backgroundImage:"linear-gradient(transparent 95%, #cbd5e1 95%)",backgroundSize:"100% 40px",backgroundPosition:"0 0"}}),e.jsx("div",{className:"absolute top-0 bottom-0 left-8 sm:left-12 md:left-16 w-[2px] bg-rose-300/60 pointer-events-none z-0"}),e.jsx("div",{className:"relative z-10 flex-1 min-h-0 overflow-y-auto px-3 sm:px-5 md:pl-20 md:pr-10 py-2 sm:py-6",children:e.jsx(Je,{mode:"wait",children:e.jsxs(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},transition:{duration:.2},className:"space-y-4 sm:space-y-6",children:[e.jsx("div",{className:"bg-white/90 backdrop-blur-sm rounded-xl sm:rounded-[1.5rem] p-4 sm:p-6 md:p-8 shadow-sm border border-slate-100/50 font-body",children:e.jsx(pl,{section:Ae,sectionIndex:u,onShowSolution:D=>F(T===D?null:D),expandedIndex:T,lesson:t,practiceQuiz:l,practiceQuizCompleted:n,practiceQuizScore:i,onStartPractice:x,lessonSpecificTopic:_e,onStartTryItQuiz:()=>Z(!0)})}),ge.length>0&&(p?.role==="admin"||p?.role==="teacher")&&e.jsxs("details",{className:"rounded-xl border border-slate-200 bg-white/90 backdrop-blur-sm px-4 py-3 text-xs text-slate-500 shadow-sm",children:[e.jsxs("summary",{className:"cursor-pointer font-semibold text-slate-600 hover:text-slate-800",children:[ge.length," source",ge.length>1?"s":""," used"]}),e.jsx("div",{className:"mt-2 space-y-1 pl-2",children:ge.slice(0,3).map((D,ne)=>e.jsxs("p",{className:"font-mono truncate",children:[D.source_file," p.",D.page," (",Math.round((D.score||0)*100),"%)"]},ne))})]})]},u)})},u)]})]})]})}),e.jsx("footer",{className:"bg-slate-50 border-t border-slate-100 px-3 sm:px-6 flex-shrink-0 relative z-50 w-full flex justify-center items-center py-1.5 sm:py-3",children:e.jsxs("div",{className:"w-full max-w-[90rem] flex flex-col items-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-4 sm:gap-8 w-full md:ml-16",children:[e.jsxs(Oe,{onClick:q,disabled:u===0,variant:"outline",className:"px-4 sm:px-5 py-2 sm:py-2 rounded-full font-bold text-xs sm:text-sm bg-white border-slate-200 text-slate-600 shadow-sm disabled:opacity-40 hover:bg-slate-50 transition-colors flex items-center gap-1 sm:gap-2 min-w-[2.5rem] min-h-[2.5rem] touch-manipulation",children:[e.jsx(es,{size:14}),e.jsx("span",{className:"hidden sm:inline",children:"Previous"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-slate-500 font-bold tabular-nums",children:[u+1," / ",fe]}),e.jsx(Oe,{onClick:g,disabled:u===fe-1&&O,className:"px-5 sm:px-7 py-2 sm:py-2 rounded-full font-bold text-xs sm:text-sm bg-[#7ec16d] text-white hover:bg-[#6ab359] shadow-md transition-colors disabled:opacity-40 flex items-center gap-1 sm:gap-2 min-w-[2.5rem] min-h-[2.5rem] touch-manipulation",children:u===fe-1?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden sm:inline",children:"Complete"}),e.jsx(at,{size:14})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden sm:inline",children:"Next"}),e.jsx(Ye,{size:14})]})})]}),u===fe-1&&O&&e.jsx("p",{className:"text-center text-[10px] sm:text-xs font-semibold text-amber-600 mt-2 sm:mt-3 md:ml-16",children:ze?"Complete the practice quiz first to unlock lesson completion.":"Complete the Try It Yourself quiz first to unlock lesson completion."})]})}),e.jsx(Je,{children:N&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-[100] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-4",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-[2rem] p-8 max-w-sm w-full text-center shadow-2xl",children:[e.jsx("div",{className:"w-20 h-20 bg-[#7ec16d] rounded-full flex items-center justify-center mx-auto mb-5 shadow-lg",children:e.jsx(at,{size:40,className:"text-white"})}),e.jsx("h2",{className:"text-2xl font-black text-slate-800 mb-2",children:"Lesson Complete!"}),e.jsxs("p",{className:"text-slate-500 text-sm mb-6 leading-relaxed",children:["Great job finishing ",e.jsx("strong",{className:"text-slate-700",children:t.title}),"."]}),e.jsxs("div",{className:"bg-emerald-50 rounded-2xl p-4 mb-6 border border-emerald-100",children:[e.jsx("div",{className:"flex items-center justify-center mb-1",children:e.jsx(zt,{className:"text-[#7ec16d]",size:22})}),e.jsx("p",{className:"text-xs text-[#7ec16d] font-bold uppercase tracking-wider mb-0.5",children:"XP Earned"}),e.jsxs("p",{className:"text-3xl font-black text-[#7ec16d]",children:["+",s]})]}),e.jsxs("div",{className:"space-y-2.5",children:[e.jsx("button",{onClick:()=>M(!0),disabled:O,className:"w-full py-3 rounded-xl font-bold text-sm bg-[#1a85a4] text-white hover:bg-[#126b84] transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:r||"Continue to Next Lesson"}),e.jsx("button",{onClick:()=>M(!1),className:"w-full py-3 rounded-xl font-bold text-sm bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors",children:"Back to Modules"})]})]})})})]}),ke=document.getElementById("modal-root")||document.body;return Gs.createPortal(be,ke)},fl={maxRetries:2,timeoutMs:9e4,baseBackoffMs:2e3},Qs=async t=>rt("/api/practice/generate",{method:"POST",body:JSON.stringify(t)},fl),bl=async t=>rt("/api/practice/submit",{method:"POST",body:JSON.stringify(t)}),gl=async t=>rt(`/api/practice/stats/${t}`,{method:"GET"});function yl({userProgress:t,userId:s,subjectId:l,moduleId:n,totalLessons:i,totalQuizzes:c}){const r=a.useMemo(()=>l?t?.subjects?.[l]?.modulesProgress?.[n]??null:null,[t,l,n]),x=a.useMemo(()=>new Set(r?.lessonsCompleted??[]),[r?.lessonsCompleted]),d=a.useMemo(()=>new Set(r?.quizzesCompleted??[]),[r?.quizzesCompleted]),h=a.useMemo(()=>!i&&!c?!1:x.size>=i&&d.size>=c,[x.size,d.size,i,c]),S=a.useCallback(f=>t?.lessons?.[f]??null,[t?.lessons]),m=a.useCallback(f=>t?.lessons?.[f]?.studyMaterialsCompleted===!0,[t?.lessons]),z=a.useCallback(f=>t?.lessons?.[f]?.quizCompleted===!0,[t?.lessons]),p=a.useCallback(f=>t?.lessons?.[f]?.quizScore,[t?.lessons]),u=a.useCallback(async f=>{if(!s)return;const C=mt(Ue,"progress",s);await Vs(C,{[`lessons.${f}.lessonId`]:f,[`lessons.${f}.studyMaterialsCompleted`]:!0,updatedAt:Ps()},{merge:!0})},[s]),k=a.useCallback(f=>{const C=t?.quizAttempts?.filter(R=>R.quizId===f);if(!C?.length)return null;const N=C[C.length-1];return{score:Math.round(N.score/10),total:10}},[t?.quizAttempts]);return{moduleProgress:r,completedLessonIds:x,completedQuizIds:d,isModuleCompleted:h,getLessonProgress:S,isStudyMaterialsCompleted:m,isLessonQuizCompleted:z,getLessonQuizScore:p,markStudyMaterialsComplete:u,getLastQuizScore:k}}const wl=({module:t,onBack:s,onEarnXP:l,isInQuizMode:n=!1,setIsInQuizMode:i})=>{const[r,x]=a.useState(null),{userProfile:d}=Ht(),[h,S]=a.useState(null),[m,z]=a.useState(!1),[p,u]=a.useState(null);a.useEffect(()=>{if(!d?.uid)return;(async()=>{try{const[q,M]=await Promise.all([Yt(mt(Ue,"diagnosticResults",d.uid)),Yt(mt(Ue,"competencyProfiles",d.uid))]),O=q.exists()&&q.data()?.status==="completed",I=M.exists()&&(M.data()?.overallScore??0)>0;z(O||I)}catch{z(!1)}})()},[d?.uid]);const k=a.useRef(l);a.useEffect(()=>{k.current=l},[l]);const f=a.useRef(r);a.useEffect(()=>{f.current=r},[r]),a.useEffect(()=>{try{const g=sessionStorage.getItem(`mathpulse_module_${t.id}_selectedLesson`);if(g){const{lessonId:q}=JSON.parse(g),M=t.lessons.find(O=>O.id===q);M&&x({lesson:M,type:"lesson"})}}catch{}},[]),a.useEffect(()=>{if(r?.type==="lesson"&&r.lesson)try{sessionStorage.setItem(`mathpulse_module_${t.id}_selectedLesson`,JSON.stringify({lessonId:r.lesson.id}))}catch{}else if(r===null)try{sessionStorage.removeItem(`mathpulse_module_${t.id}_selectedLesson`)}catch{}},[r,t.id]);const C=a.useMemo(()=>{const g=Number(t.id.split("-").pop());return Number.isFinite(g)&&g>0?g:1},[t.id]),N=a.useMemo(()=>{const g=t.subjectId;return g||(At.find(M=>M.modules.some(O=>O.id===t.id))?.id??null)},[t.id]),R=["#1FA7E1","#9956DE","#75D06A","#FFB356","#7274ED","#FF8B8B","#6ED1CF","#FB96BB"];a.useMemo(()=>{const g=t.subjectAccentColor;if(g)return g;const M=(N?At.find(I=>I.id===N):null)?.modules?.findIndex(I=>I.id===t.id)??0,O=M>=0?M:0;return R[O%R.length]},[t,t.id,N]),a.useEffect(()=>{if(d?.uid)return Zt(d.uid,S)},[d?.uid]),a.useEffect(()=>{if(!r||r.type!=="quiz"||!d?.uid)return;let g=!1;const M=At.find(O=>O.modules.some(I=>I.id===t.id))?.title??"General Mathematics";return(async()=>{try{const O=await Qs({userId:d.uid,subject:M,competency:r.quiz.title.replace(/^(Practice Quiz|Module Quiz):\s*/i,""),difficulty:r.quiz.type==="module"?"Challenge":"Practice",count:r.quiz.questions||5});if(g)return;const I=O.questions.filter(J=>J.options?.length&&J.correct_index>=0&&J.correct_index({id:J.id||"q-"+be,questionType:"multiple_choice",question:J.question,options:J.options,correctAnswer:J.options[J.correct_index],bloomLevel:J.bloom_level?.toLowerCase()||"understand",difficulty:"medium",topic:r.quiz.title,subject:M,points:10,explanation:J.explanation||""}));u(I)}catch(O){console.error("[ModuleDetailView] Quiz generation failed:",O);const I=r.quiz.questions||5,J=Array.from({length:I}).map((be,ke)=>{const D=Math.floor(Math.random()*20)+2,ne=Math.floor(Math.random()*20)+2,me=(D+ne).toString();return{id:ke+1,type:"multiple-choice",question:`Compute: ${D} + ${ne}`,options:[me,(D*ne).toString(),Math.abs(D-ne).toString(),(D+ne+1).toString()],correctAnswer:me,explanation:`${D} + ${ne} = ${me}`}});g||u(J)}})(),()=>{g=!0}},[r,d?.uid,t.id]);const T=a.useMemo(()=>N?h?.subjects?.[N]?.modulesProgress?.[t.id]??null:null,[t.id,N,h?.subjects]),[F,X]=a.useState(null),Z=a.useMemo(()=>{const g=T?.lessonsCompleted??[];return new Set(g)},[T?.lessonsCompleted]),Y=a.useMemo(()=>{const g=T?.quizzesCompleted??[];return new Set(g)},[T?.quizzesCompleted]),{isModuleCompleted:te,isStudyMaterialsCompleted:$,isLessonQuizCompleted:pe,getLastQuizScore:he,markStudyMaterialsComplete:ze}=yl({userProgress:h,userId:d?.uid,subjectId:N,moduleId:t.id,totalLessons:t.lessons.length,totalQuizzes:t.quizzes.length}),Ce=T?.lessonsCompleted?.length??t.lessons.filter(g=>g.completed).length,b=T?.quizzesCompleted?.length??t.quizzes.filter(g=>g.completed).length,H=T?.progress??t.progress,ce=t.lessons.length+t.quizzes.length,ae=Ce+b;t.lessons.length&&Ce/t.lessons.length*100,t.quizzes.length&&b/t.quizzes.length*100;const le=(g,q)=>{const M=h?.lessons?.[g];if(!M)return q?100:0;if(M.completed)return 100;const O=M.progressPercent??M.score;return typeof O=="number"&&Number.isFinite(O)?Math.max(0,Math.min(100,O)):q?100:0},ge=a.useMemo(()=>{if(!ce)return 0;const g=t.lessons.reduce((M,O)=>{const I=Z.has(O.id)||O.completed;return M+le(O.id,I)},0),q=b*100;return Math.round((g+q)/ce)},[Z,b,t.lessons,t.quizzes.length,ce,h?.lessons]),Ne=ge>0?ge:H,B=a.useMemo(()=>{const g=t.quizzes.find(M=>M.type==="final"||/module\s+quiz|general\s+quiz/i.test(M.title));if(g)return g;const q=t.quizzes.find(M=>M.isStandalone===!0);return q||(t.quizzes.length?t.quizzes[0]:null)},[t.quizzes]),Ee=a.useMemo(()=>{const g=new Map;t.lessons.forEach(M=>{g.set(M.id,[])});const q=t.lessons.length;return q===0||t.quizzes.forEach((M,O)=>{if(B?.id===M.id)return;const I=Math.min(O,q-1),J=t.lessons[I];if(!J)return;const be=g.get(J.id)??[];be.push(M),g.set(J.id,be)}),g},[t.lessons,t.quizzes,B?.id]),_e=a.useMemo(()=>Math.max(1,Math.ceil(t.lessons.length/2)),[t.lessons.length]),ye=a.useCallback(()=>{x(null),X(null)},[]),fe=a.useCallback(()=>{const g=f.current?.type==="lesson"?f.current.lesson:null;if(!g)return;const q={id:`${g.id}-practice`,title:`Practice Quiz: ${g.title}`,questions:rl(),duration:g.duration,completed:!1,locked:!1,type:"practice"};X(g),x({type:"quiz",quiz:q})},[]),Me=a.useCallback((g,q,M)=>{const O=f.current;if(O?.type!=="lesson"||!O.lesson)return;const I=O.lesson,J=10;if(k.current?.(J,`Completed "${I.title}"`),d?.uid&&N&&(async()=>{try{await ze(I.id),await sa(d.uid,N,t.id,I.id,0,J),await ms(d.uid,N,t.id,t.lessons.length,t.quizzes.length)}catch(be){console.error("[LessonComplete] Failed to persist progress:",be)}})(),M){const be=t.lessons.findIndex(ke=>ke.id===I.id);be!==-1&&be0?x({type:"quiz",quiz:t.quizzes[0]}):x(null)}else x(null)},[N,t.id,t.lessons.length,t.quizzes.length]),Ae=a.useCallback(g=>{if(!d?.uid||!f.current||f.current.type!=="lesson")return;const q=f.current.lesson.id;(async()=>{try{await aa(d.uid,q,g)}catch(M){console.warn("[ModuleDetailView] Failed to persist lesson progress:",M)}})()},[d?.uid,t.id]);if(r)if(r.type==="lesson"){const g=Ee.get(r.lesson.id)?.[0]??null,q=g?Y.has(g.id)||g.completed:!1,M=t.lessons.findIndex(I=>I.id===r.lesson.id);let O;if(M!==-1&&M0){const I=t.quizzes[0];I.type==="module"?O="Take Mid-Module Checkpoint":I.type==="final"?O="Take Final Assessment":O="Start Practice Quiz"}return e.jsx(hl,{lesson:r.lesson,lessonCompletionXP:10,practiceQuiz:g,practiceQuizCompleted:q,initialSection:r.returnFromQuiz?-1:0,nextContentLabel:O,onBack:ye,onStartPractice:fe,onProgressUpdate:Ae,onComplete:Me})}else return p?e.jsx(Bs,{quiz:{id:r.quiz.id,title:r.quiz.title,subject:At.find(g=>g.modules.some(q=>q.id===t.id))?.title||"Mathematics",difficulty:"Medium",questions:p.length,duration:r.quiz.duration||"15 min",xpReward:50,type:"practice",completed:r.quiz.completed,locked:!1,loadedQuestions:p,source:"ai_generated"},onClose:()=>{u(null),F?(x({type:"lesson",lesson:F,returnFromQuiz:!0}),X(null)):x(null),i&&i(!1)},onComplete:(g,q)=>{d?.uid&&N&&(async()=>{try{await ra(d.uid,N,t.id,r.quiz.id,g,[],0,q),await ms(d.uid,N,t.id,t.lessons.length,t.quizzes.length),await Zt(d.uid,S)}catch(M){console.warn("[Quiz] Progress persist failed:",M)}l&&l(q??0,"Quiz Complete! +"+(q??0)+" XP")})()},studentId:d?.uid}):e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-white rounded-2xl p-6 flex flex-col items-center gap-3 shadow-xl",children:[e.jsx(Rs,{size:36,className:"animate-spin text-indigo-600"}),e.jsx("p",{className:"font-bold text-slate-700",children:"Generating Quiz..."}),e.jsxs("p",{className:"text-sm text-slate-500",children:["AI is crafting questions for ",r.quiz.title]})]})});return e.jsxs("div",{className:"h-full overflow-y-auto scrollbar-hide px-4 md:px-6 lg:px-10 py-4 md:py-6 lg:py-8 relative",children:[e.jsx("div",{className:"relative mb-4 lg:mb-6 xl:mb-8 w-full lg:w-max",children:e.jsxs("button",{onClick:s,className:"flex items-center gap-2 px-4 py-2.5 rounded-full bg-white/80 backdrop-blur-xl border border-slate-200/60 text-slate-600 hover:text-indigo-600 font-bold text-sm tracking-wide transition-all hover:-translate-x-1 shadow-sm hover:shadow-md",children:[e.jsx(es,{size:18}),"Back"]})}),e.jsxs(E.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},className:`relative mb-6 lg:mb-8 rounded-[2rem] ${t.accentColor} shadow-[0_20px_40px_-15px_rgba(0,0,0,0.3)] shrink-0 overflow-hidden`,children:[e.jsx("div",{className:"absolute inset-0 bg-black/60 pointer-events-none z-0"}),e.jsx("div",{className:"absolute inset-0 opacity-10 pointer-events-none module-detail-grid-pattern"}),e.jsx("div",{className:"absolute top-0 right-0 w-[400px] h-[400px] bg-sky-500/20 blur-[100px] rounded-full pointer-events-none"}),e.jsxs("div",{className:"relative p-5 md:p-6 lg:p-8 flex flex-col md:flex-row md:items-center justify-between gap-3 md:gap-5",children:[e.jsxs("div",{className:"flex-1 text-white",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2 md:mb-2.5",children:[e.jsxs("div",{className:"px-2.5 py-0.5 bg-white/10 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-widest text-[#f8fafc] border border-white/20 shadow-sm flex items-center gap-1",children:[e.jsx(gs,{size:12})," Chapter ",t.id.split("-").pop()||"1"]}),e.jsxs("div",{className:"px-2.5 py-0.5 bg-white/10 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-widest text-emerald-400 border border-emerald-400/30",children:["Lv ",C]})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"flex lg:hidden text-white/80 shrink-0",children:e.jsx(qe,{size:18,strokeWidth:1.5})}),e.jsx("h1",{className:"text-lg md:text-2xl lg:text-3xl font-display font-black text-white tracking-[-0.02em] leading-tight",children:t.title})]}),e.jsx("p",{className:"text-slate-300 text-xs md:text-sm max-w-2xl font-medium leading-relaxed mb-3",children:t.description}),e.jsxs("div",{className:"bg-black/20 backdrop-blur-md rounded-xl p-2 md:p-3 border border-white/10 max-w-xl",children:[e.jsxs("div",{className:"flex justify-between items-end gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(zt,{size:16,className:"text-emerald-400"}),e.jsx("span",{className:"text-[11px] md:text-xs font-black text-white uppercase tracking-wider",children:"Module Mastery"}),te&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/20 border border-emerald-400/30 text-emerald-300 text-[10px] font-bold uppercase tracking-wide",children:[e.jsx(Aa,{size:12})," Completed"]})]}),e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsxs("span",{className:"text-[10px] md:text-xs font-bold text-slate-400",children:[ae,"/",ce]}),e.jsxs("span",{className:"text-base md:text-lg font-black text-white shrink-0 leading-none",children:[Math.round(Ne),"%"]})]})]}),e.jsx("div",{className:"h-2 bg-black/40 rounded-full overflow-hidden shadow-inner ring-1 ring-white/10 p-0.5 mt-2",children:e.jsx(E.div,{initial:{width:0},animate:{width:`${Ne}%`},transition:{duration:1.5,ease:"easeOut",delay:.2},className:`h-full rounded-full relative ${Ne===100?"bg-gradient-to-r from-emerald-400 to-teal-300":t.accentColor}`,children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI4IiBoZWlnaHQ9IjgiPgo8cmVjdCB3aWR0aD0iOCIgaGVpZ2h0PSI4IiBmaWxsPSIjZmZmIiBmaWxsLW9wYWNpdHk9IjAuMSI+PC9yZWN0Pgo8L3N2Zz4=')] opacity-30 mix-blend-overlay"})})})]})]}),e.jsxs("div",{className:"hidden lg:flex w-32 h-32 bg-white/5 rounded-2xl border border-white/10 backdrop-blur-md items-center justify-center transform rotate-[-3deg] shadow-2xl relative group hover:rotate-0 transition-all duration-500 shrink-0",children:[e.jsx("div",{className:`absolute inset-0 opacity-40 rounded-2xl ${t.progress===100?"bg-gradient-to-br from-emerald-400 to-teal-600":t.accentColor}`}),Ne===100?e.jsx(Ds,{size:56,className:"text-white drop-shadow-xl z-10 scale-100 group-hover:scale-110 transition-transform duration-500",strokeWidth:1}):e.jsx(qe,{size:56,className:"text-white drop-shadow-xl z-10 scale-100 group-hover:scale-110 transition-transform duration-500",strokeWidth:1}),e.jsx(E.div,{animate:{y:[-5,5,-5],rotate:[-10,10,-10]},transition:{duration:4,repeat:1/0},className:"absolute top-4 left-4 text-emerald-300 z-20",children:e.jsx(Tt,{size:16,fill:"currentColor"})}),e.jsx(E.div,{animate:{y:[5,-5,5],rotate:[10,-10,10]},transition:{duration:3.5,repeat:1/0},className:"absolute bottom-6 right-4 text-sky-300 z-20",children:e.jsx(js,{size:18})})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto pr-2 pb-8 scrollbar-hide",children:e.jsxs("div",{className:"relative rounded-[2rem] border border-slate-200 bg-white/90 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none bg-[radial-gradient(circle_at_top_right,rgba(153,86,222,0.08),transparent_45%),radial-gradient(circle_at_bottom_left,rgba(31,167,225,0.08),transparent_45%)]"}),e.jsxs("div",{className:"relative z-10 px-4 sm:px-6 md:px-8 py-5 md:py-6 border-b border-slate-200/70 bg-white/70 backdrop-blur-sm flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("h2",{className:"font-display font-black text-xl md:text-2xl text-slate-800 flex items-center gap-3",children:[e.jsx(qe,{size:24,className:"text-sky-500"}),"Study Journey"]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("div",{className:"text-xs md:text-sm font-bold bg-sky-100 text-sky-700 px-3 py-1 rounded-full shadow-sm border border-sky-200/50",children:["Lessons ",Ce,"/",t.lessons.length]}),e.jsxs("div",{className:"text-xs md:text-sm font-bold bg-rose-100 text-rose-700 px-3 py-1 rounded-full shadow-sm border border-rose-200/50",children:["Quizzes ",b,"/",t.quizzes.length]})]})]}),e.jsxs("div",{className:"relative z-10 px-3 md:px-6 lg:px-8 py-4 md:py-6 space-y-4 md:space-y-5",children:[t.lessons.map((g,q)=>{const M=Z.has(g.id)||g.completed,O=le(g.id,M),I=R[q%R.length];return e.jsxs(Fe.Fragment,{children:[e.jsxs(E.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:q*.05},className:`relative rounded-[1.5rem] border overflow-hidden group transition-all duration-500 mb-4 md:mb-6 ${g.locked?"border-slate-200 opacity-65 saturate-50":"border-slate-200/80 hover:border-slate-300 hover:shadow-[0_16px_40px_-15px_rgba(0,0,0,0.12)] hover:-translate-y-0.5"}`,children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[6px] z-20 bg-slate-100 overflow-hidden",children:e.jsx(E.div,{initial:{width:0},animate:{width:`${Math.max(2,O)}%`},transition:{duration:1.2,ease:"easeOut",delay:.1+q*.05},className:"h-full relative",style:{backgroundColor:I},children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI4IiBoZWlnaHQ9IjgiPgo8cmVjdCB3aWR0aD0iOCIgaGVpZ2h0PSI4IiBmaWxsPSIjZmZmIiBmaWxsLW9wYWNpdHk9IjAuMSI+PC9yZWN0Pgo8L3N2Zz4=')] opacity-30 mix-blend-overlay"})})}),e.jsx("div",{className:"absolute inset-0 bg-white transition-opacity duration-500 group-hover:opacity-90",style:{backgroundImage:`linear-gradient(to right, ${I}44 0%, ${I}11 50%, white 100%)`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.2] pointer-events-none",style:{backgroundImage:`radial-gradient(circle at 2px 2px, ${I} 1.5px, transparent 0)`,backgroundSize:"24px 24px"}}),e.jsx("div",{className:"absolute -top-12 -left-10 h-40 w-40 rounded-full blur-[32px] pointer-events-none transition-transform duration-700 group-hover:scale-[1.3] group-hover:translate-x-4",style:{backgroundColor:`${I}22`}}),e.jsx("div",{className:"absolute -bottom-8 right-8 h-32 w-32 rounded-full blur-2xl pointer-events-none transition-transform duration-700 group-hover:scale-125 group-hover:-translate-y-4",style:{backgroundColor:`${I}11`}}),e.jsx("div",{className:"absolute right-4 top-4 opacity-10 pointer-events-none transition-all duration-500 group-hover:rotate-12 group-hover:scale-110 drop-shadow-sm",style:{color:I},children:e.jsx(js,{size:56,strokeWidth:1})}),e.jsx("div",{className:"absolute right-16 bottom-5 opacity-10 pointer-events-none transition-all duration-500 group-hover:-rotate-6 group-hover:-translate-y-2 drop-shadow-sm",style:{color:I},children:e.jsx(qe,{size:40,strokeWidth:1})}),e.jsxs("div",{className:"relative z-10 p-3 md:p-5 pt-5 md:pt-6 space-y-3 md:space-y-4",children:[e.jsxs("button",{type:"button",onClick:()=>!g.locked&&x({lesson:g,type:"lesson"}),className:`w-full text-left flex flex-wrap items-center justify-between gap-2 md:gap-3 rounded-2xl px-3 md:px-5 py-3 md:py-4 transition shadow-sm ${g.locked?"cursor-not-allowed border border-slate-200 bg-white/70":"cursor-pointer bg-white hover:bg-slate-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 md:gap-4 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 md:w-12 md:h-12 rounded-full flex items-center justify-center shrink-0 transition-colors shadow-sm ${g.locked?"bg-slate-100 text-slate-400":M?"text-white ring-2 ring-emerald-400 ring-offset-1":O>0?"text-white ring-2 ring-amber-400 ring-offset-1":"text-white"}`,style:g.locked?{}:M?{backgroundColor:"#10b981"}:{backgroundColor:I},children:g.locked?e.jsx(rs,{size:16}):M?e.jsx(_t,{size:20}):e.jsx(Na,{size:18,className:"ml-0.5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[10px] md:text-[12px] font-black uppercase tracking-wider text-slate-500 mb-0.5",children:["Lesson ",q+1]}),e.jsx("h3",{className:"font-bold text-[14px] md:text-[18px] text-[#0a1628] leading-tight line-clamp-2",children:g.title})]})]}),e.jsx("div",{className:"flex items-center justify-end shrink-0",children:e.jsxs("span",{className:"inline-flex items-center gap-1 text-slate-500 text-[11px] md:text-sm font-semibold bg-slate-100/80 px-2 md:px-3 py-1 md:py-1.5 rounded-lg md:rounded-xl",children:[e.jsx(ht,{size:12}),g.duration]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 md:gap-3 px-0.5 md:px-1",children:[e.jsx("button",{type:"button",onClick:()=>!g.locked&&(x({lesson:g,type:"lesson"}),ze(g.id)),className:`inline-flex items-center gap-1 rounded-full px-3 md:px-4 py-1 md:py-1.5 text-[11px] md:text-[12px] font-bold shadow-sm transition hover:-translate-y-0.5 ${$(g.id)?"bg-emerald-50 border border-emerald-200":"bg-white"}`,style:{color:$(g.id)?"#059669":I},children:$(g.id)?e.jsxs(e.Fragment,{children:[e.jsx(_t,{size:12})," Review"]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:12})," Study Materials"]})}),e.jsx("button",{type:"button",onClick:()=>!g.locked&&(x({lesson:g,type:"lesson"}),fe()),className:`inline-flex items-center gap-1 rounded-full px-3 md:px-4 py-1 md:py-1.5 text-[11px] md:text-[12px] font-bold shadow-sm transition hover:-translate-y-0.5 ${pe(g.id)?"bg-emerald-50 border border-emerald-200":"bg-white"}`,style:{color:pe(g.id)?"#059669":I},children:pe(g.id)?e.jsxs(e.Fragment,{children:[e.jsx(ur,{size:12})," Retry"]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{size:12})," Quiz"]})})]})]})]}),B&&q===_e-1&&e.jsxs(E.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.15+q*.03},className:"mt-4 md:mt-6 mb-4 md:mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2 md:gap-4 mb-4 md:mb-6",children:[e.jsx("div",{className:"flex-1 h-px bg-slate-200"}),e.jsx("span",{className:"text-[10px] md:text-xs font-bold text-indigo-400 uppercase tracking-widest text-center",children:"mid-module checkpoint"}),e.jsx("div",{className:"flex-1 h-px bg-slate-200"})]}),e.jsxs("div",{className:"relative rounded-[1.5rem] bg-[#533ab6] p-3 md:p-5 shadow-lg overflow-hidden group transition-all hover:shadow-xl hover:-translate-y-1",children:[e.jsx("div",{className:"absolute right-2 md:right-10 top-1/2 -translate-y-1/2 text-white/5 text-[80px] md:text-[140px] font-black font-display pointer-events-none group-hover:scale-110 transition-transform duration-500",children:"?"}),e.jsxs("div",{className:"relative z-10 flex flex-wrap items-center gap-3 md:gap-5",children:[e.jsx("div",{className:"w-12 h-12 md:w-14 md:h-14 rounded-[12px] md:rounded-[14px] bg-white/10 backdrop-blur-md border border-white/10 shrink-0 flex items-center justify-center shadow-inner",children:e.jsx(We,{size:22,className:"text-rose-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[9px] md:text-[11px] font-black uppercase tracking-widest text-[#a3b1ee] mb-0.5 md:mb-1 drop-shadow-sm",children:"COMPETENCY CHECK · General Quiz"}),e.jsx("h3",{className:"font-display font-medium text-[16px] md:text-[22px] text-white leading-tight mb-1 md:mb-2 tracking-tight",children:B.title}),e.jsxs("p",{className:"text-[11px] md:text-xs font-semibold text-white/80 flex flex-wrap items-center gap-2 md:gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Dt,{size:11})," ",B.questions," Qs"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ht,{size:11})," ",B.duration]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 drop-shadow-md",children:[e.jsx(Ke,{size:11,className:"fill-amber-300"})," +50 XP"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 self-center shrink-0",children:[m&&(Y.has(B.id)||B.completed)&&he(B.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 text-[11px] md:text-xs font-bold",children:[e.jsx(Tt,{size:12,fill:"currentColor"})," Last: ",he(B.id).score,"/",he(B.id).total]}),e.jsx("button",{type:"button",onClick:()=>!B.locked&&(x({quiz:B,type:"quiz"}),i&&i(!0)),className:`px-4 md:px-6 py-2 md:py-2.5 rounded-xl text-[11px] md:text-sm font-bold tracking-wider transition-all backdrop-blur-sm ${B.locked?"bg-white/5 text-white/30 border border-white/10 cursor-not-allowed":m&&(Y.has(B.id)||B.completed)?"bg-white/20 text-white border border-white/40 hover:bg-white/30 shadow-sm":"bg-transparent text-white border border-white/40 hover:bg-white/10 shadow-sm"}`,children:m&&(Y.has(B.id)||B.completed)?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Rt,{size:12})," Retake"]}):"START"})]})]})]})]})]},g.id)}),t.lessons.length===0&&B&&e.jsxs("div",{className:"relative rounded-[1.5rem] bg-[#533ab6] p-5 shadow-lg overflow-hidden group",children:[e.jsx("div",{className:"absolute right-4 md:right-10 top-1/2 -translate-y-1/2 text-white/5 text-[140px] font-black font-display pointer-events-none group-hover:scale-110 transition-transform duration-500",children:"?"}),e.jsxs("div",{className:"relative z-10 flex flex-wrap items-center justify-between gap-4 md:gap-5",children:[e.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[e.jsx("div",{className:"w-14 h-14 rounded-[14px] bg-white/10 backdrop-blur-md border border-white/10 shrink-0 flex items-center justify-center shadow-inner",children:e.jsx(We,{size:28,className:"text-rose-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] md:text-[11px] font-black uppercase tracking-widest text-[#a3b1ee] mb-1 drop-shadow-sm",children:"COMPETENCY CHECK · General Quiz"}),e.jsx("h3",{className:"font-display font-medium text-[20px] md:text-[22px] text-white leading-tight mb-2 tracking-tight",children:B.title}),e.jsxs("p",{className:"text-xs font-semibold text-white/80 flex items-center gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Dt,{size:12})," ",B.questions," Qs"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ht,{size:12})," ",B.duration]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 drop-shadow-md",children:[e.jsx(Ke,{size:12,className:"fill-amber-300"})," +50 XP"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 self-center shrink-0",children:[m&&(Y.has(B.id)||B.completed)&&he(B.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 text-[11px] md:text-xs font-bold",children:[e.jsx(Tt,{size:12,fill:"currentColor"})," Last: ",he(B.id).score,"/",he(B.id).total]}),e.jsx("button",{type:"button",onClick:()=>!B.locked&&(x({quiz:B,type:"quiz"}),i&&i(!0)),className:`px-6 py-2.5 rounded-xl text-xs md:text-sm font-bold tracking-wider transition-all backdrop-blur-sm ${B.locked?"bg-white/5 text-white/30 border border-white/10 cursor-not-allowed":m&&(Y.has(B.id)||B.completed)?"bg-white/20 text-white border border-white/40 hover:bg-white/30 shadow-sm":"bg-transparent text-white border border-white/40 hover:bg-white/10 shadow-sm"}`,children:m&&(Y.has(B.id)||B.completed)?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Rt,{size:12})," Retake"]}):"START"})]})]})]})]})]})})]})},jl={"Patterns, Relations, and Functions":{icon:Lt,bg:"bg-indigo-500"},"Financial Mathematics":{icon:Pa,bg:"bg-emerald-500"},"Logic and Mathematical Reasoning":{icon:la,bg:"bg-purple-500"},"Random Variables":{icon:er,bg:"bg-orange-500"},"Normal Distribution":{icon:Ta,bg:"bg-sky-500"},"Sampling and Estimation":{icon:Za,bg:"bg-teal-500"},"Hypothesis Testing":{icon:ar,bg:"bg-rose-500"},"Correlation and Regression":{icon:Ga,bg:"bg-amber-500"}};function vl(t){return jl[t]||{icon:Dt,bg:"bg-slate-500"}}const Nl=({userId:t,onStartQuiz:s,searchQuery:l="",allowedSubjectIds:n,atRiskTopics:i=[]})=>{const{userProfile:c}=Ht(),[r,x]=a.useState("all"),[d,h]=a.useState("Medium"),[S,m]=a.useState("all"),[z,p]=a.useState(null),[u,k]=a.useState(!1),[f,C]=a.useState(null),[N,R]=a.useState(null),T=a.useMemo(()=>!n||n.length===0?hs:hs.filter(b=>n.includes(b.id)),[n]),F=a.useMemo(()=>T.flatMap(b=>b.topics.map(H=>({id:H.id,name:H.name,unit:H.unit,subject:b.name,subjectId:b.id}))),[T]);a.useEffect(()=>{t&&(k(!0),gl(t).then(p).catch(console.error).finally(()=>k(!1)))},[t]);const X=`mathpulse_practice_completed_${t}`,[Z,Y]=a.useState(0);a.useEffect(()=>{const b=()=>Y(ae=>ae+1),H=ae=>{ae.key===X&&Y(le=>le+1)},ce=()=>Y(ae=>ae+1);return window.addEventListener("focus",b),window.addEventListener("storage",H),window.addEventListener("practice-completion-updated",ce),()=>{window.removeEventListener("focus",b),window.removeEventListener("storage",H),window.removeEventListener("practice-completion-updated",ce)}},[X]);const te=a.useMemo(()=>{try{const b=localStorage.getItem(X);if(b)return new Map(JSON.parse(b))}catch{}return new Map},[X,Z]),$=a.useMemo(()=>F.filter(b=>{const H=r==="all"||b.subject===r,ce=!l||b.name.toLowerCase().includes(l.toLowerCase())||b.unit.toLowerCase().includes(l.toLowerCase())||b.subject.toLowerCase().includes(l.toLowerCase());let ae=!0;return S==="completed"?ae=te.has(b.name.toLowerCase()):S==="recommended"&&(ae=i.some(le=>b.name.toLowerCase().includes(le.toLowerCase())||le.toLowerCase().includes(b.name.toLowerCase()))),H&&ce&&ae}),[F,r,l,S,te,i]),pe=z?.quizzesCompleted??0,he=z?.totalXPEarned??c?.totalXP??0,ze=z?.averageScore??0,Ce=a.useCallback(async b=>{if(!(!t||f)){C(b.id);try{const H={Easy:"Practice",Medium:"Challenge",Hard:"Mastery"},ce=await Qs({userId:t,subject:b.subject,competency:b.name,difficulty:H[d],count:5}),ae={id:ce.session_id,title:`Practice Quiz: ${b.name} (AI)`,subject:b.subject,difficulty:d,questions:ce.questions.length,duration:"10 min",xpReward:d==="Hard"?75:d==="Medium"?50:25,type:"practice",loadedQuestions:ce.questions.map(le=>({id:le.id,questionType:"multiple_choice",question:le.question,options:le.options,correctAnswer:le.options[le.correct_index],bloomLevel:["remember","understand","apply","analyze"].includes(le.bloomsLevel?.toLowerCase()||"")?le.bloomsLevel.toLowerCase():"understand",difficulty:d.toLowerCase(),topic:b.name,subject:b.subject,points:10,explanation:le.explanation})),generatedQuizId:ce.session_id,source:"ai_generated",completed:!1,locked:!1};s?.(ae)}catch(H){console.error("Failed to generate practice quiz:",H)}finally{C(null)}}},[t,d,f,s]);return e.jsxs("div",{className:"px-4 sm:px-6 xl:px-10 py-4 sm:py-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 sm:gap-4 mb-6",children:[e.jsxs(E.div,{whileHover:{scale:1.02},className:"bg-gradient-to-br from-sky-700 to-sky-500 rounded-xl sm:rounded-2xl p-3 sm:p-5 text-white shadow-lg",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between mb-1 sm:mb-3 gap-1 sm:gap-0",children:[e.jsxs("div",{className:"w-8 h-8 sm:w-12 sm:h-12 bg-white/20 rounded-lg sm:rounded-xl flex items-center justify-center shrink-0",children:[e.jsx(zt,{size:16,className:"sm:hidden"}),e.jsx(zt,{size:24,className:"hidden sm:block"})]}),e.jsx("span",{className:"text-xl sm:text-3xl font-bold",children:pe})]}),e.jsx("p",{className:"text-[10px] sm:text-sm font-medium text-sky-100 leading-tight",children:"Quizzes Completed"})]}),e.jsxs(E.div,{whileHover:{scale:1.02},className:"bg-gradient-to-br from-rose-500 to-rose-600 rounded-xl sm:rounded-2xl p-3 sm:p-5 text-white shadow-lg",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between mb-1 sm:mb-3 gap-1 sm:gap-0",children:[e.jsxs("div",{className:"w-8 h-8 sm:w-12 sm:h-12 bg-white/20 rounded-lg sm:rounded-xl flex items-center justify-center shrink-0",children:[e.jsx(Ke,{size:16,className:"sm:hidden"}),e.jsx(Ke,{size:24,className:"hidden sm:block"})]}),e.jsx("span",{className:"text-xl sm:text-3xl font-bold",children:he.toLocaleString()})]}),e.jsx("p",{className:"text-[10px] sm:text-sm font-medium text-cyan-100 leading-tight",children:"Total XP Earned"})]}),e.jsxs(E.div,{whileHover:{scale:1.02},className:"bg-gradient-to-br from-indigo-600 to-indigo-700 rounded-xl sm:rounded-2xl p-3 sm:p-5 text-white shadow-lg",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between mb-1 sm:mb-3 gap-1 sm:gap-0",children:[e.jsxs("div",{className:"w-8 h-8 sm:w-12 sm:h-12 bg-white/20 rounded-lg sm:rounded-xl flex items-center justify-center shrink-0",children:[e.jsx(We,{size:16,className:"sm:hidden"}),e.jsx(We,{size:24,className:"hidden sm:block"})]}),e.jsxs("span",{className:"text-xl sm:text-3xl font-bold",children:[Math.round(ze),"%"]})]}),e.jsx("p",{className:"text-[10px] sm:text-sm font-medium text-sky-100 leading-tight",children:"Average Score"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 mb-6",children:[e.jsxs("select",{value:r,onChange:b=>x(b.target.value),className:"w-full sm:w-auto px-3 sm:px-4 py-2 sm:py-2.5 bg-white border-2 border-[#dde3eb] rounded-xl text-xs sm:text-sm font-bold text-[#0a1628] focus:border-indigo-600 focus:outline-none",children:[e.jsx("option",{value:"all",children:"All Subjects"}),T.map(b=>e.jsx("option",{value:b.name,children:b.name},b.id))]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 bg-white rounded-xl p-1 shadow-sm",children:[e.jsx("span",{className:"px-2 text-xs font-bold text-slate-400",children:"Difficulty:"}),["Easy","Medium","Hard"].map(b=>e.jsx("button",{onClick:()=>h(b),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all whitespace-nowrap ${d===b?b==="Easy"?"bg-green-500 text-white shadow-sm":b==="Medium"?"bg-orange-500 text-white shadow-sm":"bg-red-500 text-white shadow-sm":"text-[#5a6578] hover:bg-[#edf1f7]"}`,children:b},b))]}),e.jsx("div",{className:"flex items-center gap-1.5 sm:gap-2 bg-white rounded-xl p-1 shadow-sm",children:[["all","All"],["completed","Completed"],["recommended","Recommended"]].map(([b,H])=>e.jsx("button",{onClick:()=>m(b),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all whitespace-nowrap ${S===b?b==="completed"?"bg-emerald-500 text-white shadow-sm":b==="recommended"?"bg-purple-500 text-white shadow-sm":"bg-indigo-500 text-white shadow-sm":"text-[#5a6578] hover:bg-[#edf1f7]"}`,children:H},b))})]}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-white rounded-2xl p-6 flex flex-col items-center gap-3 shadow-xl",children:[e.jsx(Rs,{size:36,className:"animate-spin text-indigo-600"}),e.jsx("p",{className:"font-bold text-slate-700",children:"Generating Quiz..."}),e.jsx("p",{className:"text-sm text-slate-500",children:"AI is crafting questions from curriculum"})]})}),e.jsxs("div",{className:"pr-2 pb-4 rounded-[2rem] border border-slate-200 shadow-inner relative",style:{backgroundImage:"radial-gradient(#CBD5E1 1px, transparent 1px)",backgroundSize:"24px 24px",backgroundPosition:"-12px -12px",backgroundColor:"#FAFAFA"},children:[e.jsx("div",{className:"absolute left-12 top-0 bottom-0 w-0.5 bg-rose-200/60 pointer-events-none z-0"}),e.jsx("div",{className:"absolute left-[54px] top-0 bottom-0 w-px bg-rose-100/40 pointer-events-none z-0"}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-5 p-4 md:p-6 relative z-10",children:$.map((b,H)=>e.jsx(E.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:H*.03},onClick:()=>Ce(b),className:`bg-white/90 backdrop-blur-sm rounded-2xl p-4 md:p-5 border-2 relative select-none transition-all duration-300 ${f===b.id?"border-indigo-300 opacity-80 cursor-wait":f?"border-slate-200 opacity-60 cursor-not-allowed":"border-slate-200 shadow-sm hover:border-indigo-300 hover:shadow-md cursor-pointer"} group`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3 md:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 md:gap-4 flex-1",children:[(()=>{const{icon:ce,bg:ae}=vl(b.unit);return e.jsxs("div",{className:`w-10 h-10 md:w-12 md:h-12 rounded-xl flex items-center justify-center shrink-0 shadow-sm transform group-hover:rotate-3 transition-transform ${ae} text-white relative`,children:[e.jsx(ce,{size:18}),te.has(b.name.toLowerCase())&&e.jsx("div",{className:"absolute -top-1 -right-1 w-4 h-4 bg-emerald-500 rounded-full flex items-center justify-center border-2 border-white",children:e.jsx(at,{size:10,className:"text-white"})})]})})(),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-1",children:[e.jsxs("span",{className:`px-2 py-0.5 rounded-[6px] text-[9px] md:text-[10px] font-black uppercase tracking-wider ${d==="Easy"?"bg-green-100 text-green-700":d==="Medium"?"bg-orange-100 text-orange-700":"bg-red-100 text-red-700"}`,children:["AI ","•"," ",d]}),te.has(b.name.toLowerCase())&&e.jsxs("span",{className:"px-2 py-0.5 rounded-[6px] text-[9px] md:text-[10px] font-black uppercase tracking-wider bg-emerald-100 text-emerald-700",children:["Best: ",te.get(b.name.toLowerCase())?.bestScore,"%"]}),e.jsx("span",{className:"w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-emerald-500 animate-pulse"})]}),e.jsx("h3",{className:"font-bold text-[14px] md:text-[16px] leading-tight mb-1 md:mb-1.5 text-[#0a1628] transition-colors",children:b.name}),e.jsxs("p",{className:"text-[11px] md:text-[12px] text-slate-500 mb-1.5 line-clamp-1",children:[b.subject," — ",b.unit]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:gap-3 text-[11px] md:text-[12px] font-bold text-slate-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qe,{size:12})," 5 Qs"]}),e.jsx("span",{className:"hidden sm:inline",children:"•"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ht,{size:12})," 10 min"]}),e.jsx("span",{className:"hidden sm:inline",children:"•"}),e.jsxs("span",{className:"flex items-center gap-1 text-rose-500",children:[e.jsx(Ds,{size:12})," +",d==="Hard"?75:d==="Medium"?50:25," XP"]})]})]})]}),e.jsxs("div",{className:"shrink-0 flex flex-col items-center gap-1.5",children:[e.jsx("div",{className:`px-3 py-1.5 md:px-4 md:py-2 rounded-xl text-[11px] md:text-[12px] font-black uppercase tracking-wider shadow-sm transition-all ${f===b.id?"bg-indigo-100 text-indigo-600":te.has(b.name.toLowerCase())?"bg-orange-500 text-white group-hover:bg-orange-600 shadow-orange-200":"bg-indigo-500 text-white group-hover:bg-indigo-600 shadow-indigo-200"}`,children:f===b.id?"Loading...":te.has(b.name.toLowerCase())?"Retry":"Start"}),te.has(b.name.toLowerCase())&&e.jsxs("button",{onClick:ce=>{ce.stopPropagation();const ae=te.get(b.name.toLowerCase());R({topic:b.name,items:ae?.history||[]})},className:"flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-bold text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-colors",children:[e.jsx(Ea,{size:11})," History"]})]})]})},b.id))}),$.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-slate-500 relative z-10",children:[e.jsx(We,{size:48,className:"mb-3"}),e.jsx("p",{className:"font-medium",children:"No topics found"}),e.jsx("p",{className:"text-sm",children:"Try adjusting your filters or search query"})]})]}),e.jsx(Je,{children:N&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onClick:()=>R(null),children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.9,opacity:0},onClick:b=>b.stopPropagation(),className:"bg-white rounded-2xl p-6 max-w-md w-full shadow-2xl max-h-[80vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-black text-slate-800",children:"Quiz History"}),e.jsx("button",{onClick:()=>R(null),className:"p-1.5 rounded-full hover:bg-slate-100",children:e.jsx(Ze,{size:18,className:"text-slate-400"})})]}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:N.topic}),N.items.length===0?e.jsx("p",{className:"text-center text-slate-400 py-8 text-sm",children:"No history found for this topic."}):e.jsx("div",{className:"space-y-3",children:N.items.map((b,H)=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 rounded-xl border border-slate-100",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-slate-700",children:new Date(b.date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsxs("p",{className:"text-xs text-slate-400",children:[b.difficulty," difficulty"]})]}),e.jsxs("div",{className:`text-lg font-black ${b.score>=80?"text-emerald-600":b.score>=50?"text-amber-600":"text-rose-600"}`,children:[b.score,"%"]})]},H))})]})})})]})},kl=` +`,Er=({viewportHeight:t})=>e.jsx("div",{className:"absolute inset-0 pointer-events-none z-[250] overflow-hidden flex justify-between bg-slate-900/5",children:Fe.useMemo(()=>[...Array(40)].map((s,l)=>({id:l,left:`${Math.random()*100}%`,duration:.6+Math.random()*.4,delay:Math.random()*.4})),[t]).map(s=>e.jsx(E.div,{className:"absolute w-0.5 h-16 bg-blue-400/30 rounded-full",style:{left:s.left,top:"-10%"},animate:{y:[0,t*1.2]},transition:{duration:s.duration,ease:"linear",delay:s.delay}},s.id))}),Tr=()=>{const t=Fe.useMemo(()=>[...Array(60)].map((s,l)=>({id:l,left:`${Math.random()*100}%`,backgroundColor:["#75D06A","#6ED1CF","#9956DE","#FB96BB","#FFB356"][l%5],duration:2+Math.random()*2,delay:Math.random()*.5,size:6+Math.random()*8,borderRadius:Math.random()>.5?"50%":"2px"})),[]);return e.jsx("div",{className:"absolute inset-0 pointer-events-none z-[250] overflow-hidden",children:t.map(s=>e.jsx("div",{className:"confetti-piece",style:{left:s.left,top:"-10%",backgroundColor:s.backgroundColor,width:s.size,height:s.size,borderRadius:s.borderRadius,animationDuration:`${s.duration}s`,animationDelay:`${s.delay}s`}},s.id))})},Pr=({viewportHeight:t,viewportWidth:s})=>{const l=Fe.useMemo(()=>[...Array(30)].map((n,i)=>({id:i,xShift:(Math.random()-.5)*s*.8,yShift:(Math.random()-.5)*t*.8,scale:Math.random()*1.5+.5,duration:2+Math.random()*1.5,delay:Math.random()*.35})),[t,s]);return e.jsx("div",{className:"absolute inset-0 pointer-events-none z-[250] overflow-hidden flex items-center justify-center",children:l.map(n=>e.jsx(E.div,{className:"absolute w-2 h-2 bg-amber-400 rounded-full shadow-[0_0_10px_rgba(251,191,36,0.5)]",style:{left:"50%",top:"50%"},animate:{y:[0,n.yShift],x:[0,n.xShift],scale:[0,n.scale,0],opacity:[0,1,0]},transition:{duration:n.duration,ease:"easeOut",delay:n.delay}},n.id))})},ks=({value:t,label:s,delay:l=0,icon:n})=>{const[i,c]=Fe.useState(0);return Fe.useEffect(()=>{if(t<=0)return;const r=1e3,x=30,d=Math.abs(Math.floor(r/x));let h=0;const S=setTimeout(()=>{const m=setInterval(()=>{h+=Math.max(1,Math.floor(t/x)),h>=t?(c(t),clearInterval(m)):c(h)},d);return()=>clearInterval(m)},l);return()=>clearTimeout(S)},[t,l]),t<0?null:e.jsxs(E.div,{initial:{opacity:0,transform:"translateX(-20px)"},animate:{opacity:1,transform:"translateX(0)"},transition:{delay:l/1e3,duration:.5},className:"flex items-center justify-between bg-slate-50 border border-slate-100 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-3 text-slate-500 font-bold uppercase tracking-wider text-[10px]",children:[n,s]}),e.jsxs("div",{className:"text-xl font-black text-purple-600 tabular-nums",children:["+",i]})]})};function Lr(t){if(t.questionType==="multiple_choice"&&t.options&&t.options.length>0){const s=t.options.findIndex(l=>l.trim().toLowerCase()===t.correctAnswer.trim().toLowerCase());return{id:t.id,question:t.question,options:t.options,correctAnswer:s>=0?s:0,correctAnswerText:t.correctAnswer,explanation:t.explanation,questionType:t.questionType,points:t.points,difficulty:t.difficulty,topic:t.topic,bloomLevel:t.bloomLevel}}return{id:t.id,question:t.question,options:[],correctAnswer:-1,correctAnswerText:t.correctAnswer,explanation:t.explanation,questionType:t.questionType,points:t.points,difficulty:t.difficulty,topic:t.topic,bloomLevel:t.bloomLevel}}function Cs(t){return t.replace(/²/g,"^2").replace(/³/g,"^3").replace(/⁻¹/g,"^-1").replace(/⁰/g,"^0").replace(/¹/g,"^1").replace(/⁴/g,"^4").replace(/⁵/g,"^5").replace(/⁶/g,"^6").replace(/⁷/g,"^7").replace(/⁸/g,"^8").replace(/⁹/g,"^9").replace(/π/g,"pi").replace(/√/g,"sqrt").replace(/×/g,"*").replace(/÷/g,"/").replace(/\s+/g,"").toLowerCase().trim()}function Rr(t,s,l){const n=i=>i.trim().toLowerCase().replace(/\s+/g," ");switch(l){case"identification":return n(t)===n(s);case"enumeration":{const i=t.split(",").map(r=>n(r)).filter(Boolean).sort(),c=s.split(",").map(r=>n(r)).filter(Boolean).sort();return JSON.stringify(i)===JSON.stringify(c)}case"word_problem":case"equation_based":{const i=Cs(t),c=Cs(s);if(i===c)return!0;const r=parseFloat(t.replace(/[^\d.\-]/g,"")),x=parseFloat(s.replace(/[^\d.\-]/g,""));return!isNaN(r)&&!isNaN(x)?Math.abs(r-x)<=.01:n(t)===n(s)}default:return n(t)===n(s)}}const Bs=({quiz:t,onClose:s,onComplete:l,onQuizEnd:n,studentId:i,atRiskSubjects:c=[]})=>{const[r,x]=a.useState(0),[d,h]=a.useState(null),[S,m]=a.useState(""),[z,p]=a.useState(!1),[u,k]=a.useState(!1),[f,C]=a.useState(!1),[N,R]=a.useState(0),[T,F]=a.useState(0),[X,Z]=a.useState(1),[Y,te]=a.useState([]),[$,pe]=a.useState([]),[he,ze]=a.useState(Date.now()),[Ce,b]=a.useState(!1),[Q,ce]=a.useState(!1),[ae,le]=a.useState(null),[ge,Ne]=a.useState(0),[B,Ee]=a.useState(0),[_e,ye]=a.useState(!1),[fe,Me]=a.useState(!1),[Ae,g]=a.useState(!0),[q,M]=a.useState(!1),[O,I]=a.useState({width:1280,height:720});a.useEffect(()=>{const A=()=>I({width:window.innerWidth,height:window.innerHeight});return A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[]);const[J,be]=a.useState(0),[ke,D]=a.useState({}),[ne,me]=a.useState(!1),[Ge,ft]=a.useState(!1),[bt,De]=a.useState(!1),{totalHintsAvailable:Xe}=Ar(i||null),[et,j]=a.useState(5),[Te,lt]=a.useState(15),Le=et+Xe,[Be,gt]=a.useState(null),[nt,Ve]=a.useState(!1),[it,ot]=a.useState(900*1e3),[o,P]=a.useState([]),[y,L]=a.useState(0),[K,de]=a.useState(null),[ie]=a.useState(()=>t.loadedQuestions&&t.loadedQuestions.length>0?t.loadedQuestions.map(Lr):Array.from({length:t.questions},(A,_)=>({id:`q${_+1}`,question:Dr(t.subject,_),options:Ir(t.subject,_),correctAnswer:Fr(t.subject,_),explanation:$r(t.subject,_,t.difficulty)})));a.useEffect(()=>{D({}),P([]),j(5),lt(15),be(0),R(0),F(0),Z(1)},[t.id]);const xe=ie[r];a.useEffect(()=>{const A=parseInt(t.duration)||10;Ne(A*60);const _=setInterval(()=>{Ne(ee=>ee<=1?(clearInterval(_),w(),0):ee-1)},1e3);return()=>clearInterval(_)},[]),a.useEffect(()=>{Te===0&&!Be&&(gt(Date.now()),Ve(!0))},[Te,Be]),a.useEffect(()=>{if(!nt||!Be)return;const A=setInterval(()=>{const _=Date.now()-Be,ee=Math.max(0,900*1e3-_);ot(ee)},1e3);return()=>clearInterval(A)},[nt,Be]);const[je,Qe]=a.useState(Array.from({length:15},(A,_)=>({id:_,size:Math.random()*120+40,x:Math.random()*100,y:Math.random()*100,duration:Math.random()*20+15,delay:Math.random()*-20,color:["bg-purple-500/10","bg-blue-500/10","bg-cyan-500/10","bg-emerald-500/10"][Math.floor(Math.random()*4)]}))),we=A=>{if(Ae)try{const _=window.AudioContext||window.webkitAudioContext;if(!_)return;const ee=new _,G=ee.currentTime,V=(Ie,He,Re,tt=.1,Pe="sine")=>{const Se=ee.createOscillator(),xt=ee.createGain();Se.type=Pe,Se.frequency.value=Ie,xt.gain.setValueAtTime(0,He),xt.gain.linearRampToValueAtTime(tt,He+.05),xt.gain.exponentialRampToValueAtTime(.001,He+Re),Se.connect(xt),xt.connect(ee.destination),Se.start(He),Se.stop(He+Re)};A==="correct"?(V(880,G,.1,.1,"sine"),V(1108.73,G+.1,.2,.1,"sine")):A==="incorrect"?(V(300,G,.2,.05,"sawtooth"),V(250,G+.15,.3,.05,"sawtooth")):A==="combo"?(V(440,G,.1,.05,"square"),V(554.37,G+.1,.1,.05,"square"),V(659.25,G+.2,.1,.05,"square"),V(880,G+.3,.4,.05,"square")):A==="complete"&&(V(523.25,G,.1,.1),V(659.25,G+.15,.1,.1),V(783.99,G+.3,.1,.1),V(1046.5,G+.45,.5,.1))}catch{}},w=()=>{b(!0),se()},v=()=>{n?.(t,$),s()},H=()=>{if(et<=0||u)return;const A=ke[r]||[],_=xe.options.filter(G=>G!==xe.correctAnswerText).filter(G=>!A.includes(G));if(_.length===0)return;const ee=_[Math.floor(Math.random()*_.length)];D(G=>({...G,[r]:[...A,ee]})),j(G=>Math.max(0,G-1)),we("correct")},W=A=>{u||U||(h(A),setTimeout(()=>{re(A)},150))},re=A=>{const _=xe.questionType!=null&&xe.questionType!=="multiple_choice",ee=A!==void 0?A:d;if(_){if(!S.trim())return}else if(ee===null)return;const G=_?Rr(S,xe.correctAnswerText||"",xe.questionType||""):ee===xe.correctAnswer,V=_?S:String(ee),Ie=Math.round((Date.now()-he)/1e3);pe(Se=>[...Se,{questionId:xe.id,answer:V,correct:G,timeSpent:Ie}]);const He=[...Y];if(He[r]=G?1:0,te(He),p(G),k(!0),!G){ft(!0),we("incorrect"),setTimeout(()=>ft(!1),500),lt(Se=>Math.max(0,Se-1)),F(0),Z(1),setTimeout(()=>{ve()},1500);return}we("correct");const tt=(ke[r]||[]).length>0?5:10;be(Se=>Se+tt),R(N+1);const Pe=T+1;F(Pe),Pe===2?de("streak"):Pe===3&&X<2?de("multiplier2"):Pe===5&&X<3&&de("multiplier3"),Pe>0&&Pe%3===0&&we("combo"),Pe>=5?Z(3):Pe>=3?Z(2):Z(1),St(()=>import("./confetti.module-C94ZD2ww.js"),[]).then(Se=>{Se.default({particleCount:30,spread:40,colors:["#75D06A","#6ED1CF"],origin:{y:.6}})}),De(!0),setTimeout(()=>{De(!1),de(null),setTimeout(()=>ve(),300)},1500)},ve=()=>{if(r{const A=Math.round(N/ie.length*100);let _=t.xpReward;A>=90?_=Math.round(_*1.5):A>=80&&(_=Math.round(_*1.25));const ee=parseInt(t.duration)*60;ge>ee*.5&&(_=Math.round(_*1.2)),Ee(_);const G=ee-ge;i&&ya({lrn:i,quizId:t.id,subject:t.subject,score:A,totalQuestions:ie.length,correctAnswers:N,timeSpentSeconds:G}).catch(V=>console.error("[WARN] Automation: quiz pipeline failed:",V)),t.source==="ai_generated"&&i?wa(i,t.id,t.generatedQuizId,t.subject,t.source,A,_,G,$,ie.map(V=>({topic:V.topic||t.subject,difficulty:V.difficulty||"medium",bloomLevel:V.bloomLevel||"understand"}))).catch(V=>console.error("[WARN] Quiz result save failed:",V)):i&&ea(i,t.id,t.subject,A,$.map(V=>({questionId:V.questionId,selectedAnswer:V.answer,isCorrect:V.correct})),G).catch(V=>console.error("[WARN] Practice quiz persist failed:",V)),i&&St(async()=>{const{saveAssessmentResult:V}=await import("./index-BdLfAeGL.js").then(Ie=>Ie.ba);return{saveAssessmentResult:V}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({saveAssessmentResult:V})=>{V({uid:i,testId:t.id,title:t.title||t.id,subject:t.subject||"General Mathematics",type:t.source==="ai_generated"?"quiz":"practice",score:A,totalQuestions:ie.length,risk:A<60?"High":"Low",intervention:"",xpEarned:_,badgeUnlocked:""}).catch(Ie=>console.error("[WARN] Assessment record save failed:",Ie))}),we("complete"),l?.(A,_)},U=y{document.fullscreenElement?(document.exitFullscreen().catch(()=>{}),M(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),M(!0))};if(Ce){const A=Math.round(N/ie.length*100),_=A>=80,ee=A>=50&&A<80,G=A<50,V=document.getElementById("modal-root"),Ie=e.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm",children:[e.jsx("style",{children:Ns}),_&&e.jsx(Tr,{}),ee&&e.jsx(Pr,{viewportHeight:O.height,viewportWidth:O.width}),G&&e.jsx(Er,{viewportHeight:O.height}),e.jsxs(E.div,{initial:{opacity:0,scale:.8,y:40},animate:{opacity:1,scale:1,y:0},transition:{type:"spring",damping:18,stiffness:200},className:"w-full max-w-xs sm:max-w-sm bg-white border-2 border-slate-200 shadow-[0_25px_60px_rgba(0,0,0,0.15)] rounded-[2rem] p-4 sm:p-5 text-center relative z-10",children:[e.jsx(E.div,{initial:{scale:0,rotate:-180},animate:{scale:1,rotate:0},transition:{type:"spring",damping:12,stiffness:150,delay:.2},className:"mb-3",children:e.jsx("img",{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-16 h-16 sm:w-20 sm:h-20 mx-auto drop-shadow-xl animate-mascot-float"})}),e.jsx(E.h2,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.3},className:`text-xl sm:text-2xl font-black uppercase tracking-tight mb-1 drop-shadow-sm ${_?"text-emerald-500":ee?"text-amber-500":"text-rose-500"}`,children:_?"EXCELLENT!":ee?"GOOD JOB!":"KEEP TRYING!"}),e.jsxs("p",{className:"text-slate-400 font-bold text-[10px] mb-3 uppercase tracking-widest",children:["Quiz Complete • Score: ",N,"/",ie.length]}),e.jsx(E.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.4},className:"bg-slate-50/50 rounded-xl p-3 mb-4 border border-slate-100 flex flex-col gap-2",children:e.jsxs("div",{children:[e.jsx("h3",{className:"text-slate-400 text-[9px] font-black uppercase tracking-widest text-left mb-1.5 ml-1",children:"Performance Details"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ks,{value:N,label:"Correct Answers",delay:500,icon:e.jsx(Pt,{className:"h-3 w-3 text-emerald-500"})}),e.jsx(ks,{value:B,label:"Total XP Earned",delay:800,icon:e.jsx(Ke,{className:"h-3 w-3 text-amber-500"})}),e.jsxs(E.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2,duration:.4},className:"flex items-center justify-between pt-1.5 mt-1 border-t border-slate-100",children:[e.jsx("span",{className:"text-slate-400 text-[9px] font-black uppercase tracking-widest",children:"Final Accuracy"}),e.jsxs("span",{className:"text-lg font-black text-slate-800 tabular-nums",children:[A,"%"]})]})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{size:"lg",onClick:()=>{x(0),L(0),h(null),m(""),R(0),F(0),Z(1),te([]),pe([]),be(0),b(!1),k(!1),C(!1),ze(Date.now()),D({}),P([]),me(!1),j(5),ce(!1)},className:"w-full h-10 sm:h-11 rounded-2xl text-xs font-black bg-white hover:bg-slate-50 text-purple-600 border-2 border-purple-100",children:"RETAKE QUIZ"}),e.jsx(Oe,{size:"lg",onClick:v,className:"w-full h-10 sm:h-11 rounded-2xl text-xs font-black bg-purple-600 hover:bg-purple-700 text-white shadow-lg shadow-purple-200",children:"FINISH"})]})]})]});return Et.createPortal(Ie,V)}return e.jsxs(e.Fragment,{children:[e.jsx("style",{children:Ns}),_e&&Et.createPortal(e.jsx(E.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:"fixed right-6 top-1/2 -translate-y-1/2 z-[9999] w-64",children:e.jsxs("div",{className:"bg-white rounded-2xl p-3 border border-slate-200 shadow-[0_10px_40px_rgba(0,0,0,0.3)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("h4",{className:"text-xs font-bold text-[#0a1628] flex items-center gap-2",children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-purple-600",children:[e.jsx("rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}),e.jsx("line",{x1:"8",x2:"16",y1:"6",y2:"6"})]}),"Calculator"]}),e.jsx("button",{onClick:()=>ye(!1),className:"w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 hover:text-slate-800 hover:bg-slate-200 transition-colors",children:e.jsx(Ze,{size:12})})]}),e.jsx(Fs,{isOpen:!0,onClose:()=>ye(!1),inline:!0})]})}),document.getElementById("modal-root")),nt&&Et.createPortal(e.jsx("div",{className:"fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-900/50",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-[2rem] p-6 max-w-xs w-full text-center border-2 border-rose-200 shadow-[0_25px_60px_rgba(0,0,0,0.15)]",children:[e.jsx(E.div,{animate:{scale:[1,1.1,1]},transition:{duration:1,repeat:1/0},className:"text-6xl mb-4",children:e.jsx(nr,{className:"w-10 h-10 text-rose-500"})}),e.jsx("h2",{className:"text-2xl font-black text-slate-800 mb-3",children:"Out of Lives!"}),e.jsx("p",{className:"text-slate-500 text-sm mb-4",children:"Your hearts have run out. You can wait for them to refill or head back and review your lessons in the meantime."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2 text-rose-500 font-bold",children:[e.jsx("img",{src:"/icons/quiz_heart.png",alt:"Hearts",className:"w-5 h-5"}),e.jsx("span",{children:"0 / 15 hearts"})]}),e.jsxs("p",{className:"text-slate-400 text-xs mb-4",children:["Next heart in: ",e.jsxs("span",{className:"font-bold text-slate-600",children:[Math.floor(it/6e4),":",Math.floor(it%6e4/1e3).toString().padStart(2,"0")]})," (15 minutes per heart)"]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{onClick:v,className:"w-full py-3 bg-rose-500 hover:bg-rose-600 text-white font-bold rounded-full",children:"Exit Quiz"}),e.jsx(Oe,{onClick:()=>{Ve(!1)},className:"w-full py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold rounded-full",children:"Review Lessons"})]})]})}),document.getElementById("modal-root")),e.jsx(Je,{children:bt&&z&&e.jsx(E.div,{initial:{opacity:0,scale:.8,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:1.1,filter:"blur(10px)"},transition:{type:"spring",damping:20,stiffness:300},className:"fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[200] pointer-events-none flex flex-col items-center justify-center",children:e.jsxs("div",{className:"bg-white/95 backdrop-blur-xl border border-slate-200 rounded-[2rem] p-6 md:p-8 shadow-[0_30px_80px_rgba(0,0,0,0.15)] flex flex-col items-center min-w-[280px] md:min-w-[320px]",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-24 h-24 md:w-32 md:h-32 mb-4 drop-shadow-[0_10px_20px_rgba(0,0,0,0.15)]"}),e.jsx("h2",{className:"text-3xl md:text-4xl font-black mb-4 uppercase tracking-widest text-emerald-500",children:"Correct!"}),e.jsxs("div",{className:"flex flex-col items-center gap-3 w-full justify-center",children:[e.jsx("div",{className:"flex items-center gap-2 bg-emerald-500/20 text-emerald-400 px-4 py-2 rounded-full font-bold border border-emerald-500/30",children:e.jsxs("span",{children:["+ ",(ke[r]||[]).length>0?5:10," XP"]})}),K==="streak"&&e.jsxs("div",{className:"flex items-center gap-2 bg-orange-500/20 text-orange-400 px-4 py-1.5 rounded-full text-sm font-bold border border-orange-500/30",children:[e.jsx(Kt,{size:14})," Streak Started!"]}),K==="multiplier2"&&e.jsxs("div",{className:"flex items-center gap-2 bg-amber-500/20 text-amber-400 px-4 py-1.5 rounded-full text-sm font-bold border border-amber-500/30",children:[e.jsx(Ke,{size:14})," Multiplier ×2!"]}),K==="multiplier3"&&e.jsxs("div",{className:"flex items-center gap-2 bg-amber-500/20 text-amber-400 px-4 py-1.5 rounded-full text-sm font-bold border border-amber-500/30",children:[e.jsx(Ke,{size:14})," Multiplier ×3!"]})]})]})},"round-result")}),e.jsxs("div",{className:"fixed inset-0 z-[100] h-screen w-full flex flex-col bg-slate-50 overflow-hidden",children:[e.jsxs("header",{className:"relative shrink-0 flex flex-col items-center justify-start px-4 pt-4 sm:pt-6 pb-6 z-[60] shadow-md overflow-hidden bg-gradient-to-r from-purple-600 to-indigo-400 rounded-b-[32px] sm:rounded-b-[40px] min-h-[110px] sm:min-h-[130px]",children:[e.jsxs("div",{className:"absolute inset-0 z-0 pointer-events-none",children:[e.jsx("div",{className:"absolute top-0 left-0 w-64 h-64 bg-white opacity-10 rounded-full -translate-x-1/2 -translate-y-1/2 blur-2xl"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-80 h-80 bg-white opacity-10 rounded-full translate-x-1/3 translate-y-1/3 blur-3xl"})]}),e.jsxs("div",{className:"w-full max-w-7xl flex items-center justify-between relative z-10 mb-3 sm:mb-4 md:mb-6",children:[e.jsx("div",{className:"flex-1 flex items-center gap-1 sm:gap-2",children:e.jsxs("div",{className:"flex items-center gap-1 bg-white/20 px-2 py-1 sm:px-3 sm:py-1.5 rounded-full text-white text-xs sm:text-sm font-bold",children:[e.jsx(ht,{size:14,className:"shrink-0"})," ",qr(ge)]})}),e.jsxs("div",{className:"relative flex items-center justify-center bg-purple-900/40 backdrop-blur-md px-2 sm:px-5 md:px-8 py-2 sm:py-3 rounded-full border border-white/10 gap-1.5 sm:gap-3 md:gap-4 shadow-inner",children:[e.jsx("div",{className:"hidden sm:block w-3 h-3 md:w-4 md:h-4 rounded-full bg-yellow-400 shrink-0 shadow-[0_0_10px_rgba(250,204,21,0.6)]"}),e.jsxs("div",{className:"flex flex-col items-start justify-center",children:[e.jsx("span",{className:"hidden sm:block text-[9px] md:text-[11px] font-black text-purple-200 uppercase tracking-widest leading-none mb-0.5",children:"Try It Yourself!"}),e.jsx("span",{className:"font-bold text-white tracking-wide text-xs sm:text-sm md:text-lg leading-none truncate max-w-[90px] sm:max-w-[180px] md:max-w-[300px]",children:t.title||t.subject})]})]}),e.jsxs("div",{className:"flex-1 flex justify-end gap-1 sm:gap-2 md:gap-3 relative pointer-events-auto",children:[e.jsxs("button",{onClick:()=>g(!Ae),className:"w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:[Ae?e.jsx(ts,{size:16,className:"sm:hidden"}):e.jsx(ss,{size:16,className:"sm:hidden"}),Ae?e.jsx(ts,{size:20,className:"hidden sm:block"}):e.jsx(ss,{size:20,className:"hidden sm:block"})]}),e.jsx("button",{onClick:yt,className:"hidden sm:flex w-10 h-10 md:w-12 md:h-12 rounded-full bg-purple-900/20 text-white items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:q?e.jsx($s,{size:20}):e.jsx(qs,{size:20})}),e.jsxs("button",{onClick:()=>Me(!0),className:"w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:[e.jsx(Ze,{size:18,className:"sm:hidden"}),e.jsx(Ze,{size:20,className:"hidden sm:block"})]})]})]}),e.jsx("div",{className:"w-full max-w-[50rem] flex items-center justify-center px-4 z-10",children:e.jsx("div",{className:"w-full flex items-center gap-2 sm:gap-3",children:ie.map((A,_)=>{let ee=_<=r?"bg-white shadow-[0_0_8px_rgba(255,255,255,0.8)]":"bg-white/20";return e.jsx("div",{className:`h-1.5 sm:h-2 rounded-full flex-1 transition-all ${ee}`},_)})})})]}),e.jsxs("div",{className:"w-full max-w-[54rem] mx-auto shrink-0 flex items-center justify-between px-2 sm:px-4 md:px-6 py-2 sm:py-3 z-[50] relative mt-4 sm:mt-6 md:mt-8",children:[e.jsxs("button",{onClick:()=>L(A=>Math.max(0,A-1)),disabled:y===0,className:`w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 shrink-0 rounded-full flex items-center justify-center shadow-md border-2 transition-all ${y===0?"bg-slate-100 text-slate-400 border-slate-200 cursor-not-allowed":"bg-white text-purple-600 border-purple-100 hover:bg-purple-50 hover:border-purple-200 hover:scale-105 active:scale-95"}`,children:[e.jsx(ps,{size:18,className:"sm:hidden"}),e.jsx(ps,{size:24,className:"hidden sm:block"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5 sm:gap-3 md:gap-5 flex-1 mx-1 sm:mx-2",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 md:gap-3 px-2.5 sm:px-5 md:px-10 py-1.5 sm:py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-rose-500 font-extrabold text-xs sm:text-sm md:text-base",children:[e.jsx("img",{src:"/icons/quiz_heart.png",alt:"Hearts",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," ",Te]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 md:gap-3 px-2.5 sm:px-5 md:px-10 py-1.5 sm:py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-yellow-500 font-extrabold text-xs sm:text-sm md:text-base",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Keys",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," ",et]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-3 md:gap-4 px-2 sm:px-3 py-1 sm:py-1.5 pl-2.5 sm:pl-4 md:pl-6 rounded-full bg-white shadow-md border border-slate-200/60",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 text-orange-500 font-extrabold text-xs sm:text-sm md:text-base",children:[e.jsx("img",{src:"/icons/quiz_streak.png",alt:"Streak",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," ",T]}),e.jsxs("div",{className:"bg-emerald-100 text-emerald-800 px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 rounded-full font-bold text-xs sm:text-sm md:text-base shadow-inner border border-emerald-200/50 whitespace-nowrap",children:["+ ",J," pts"]})]})]}),e.jsxs("button",{onClick:()=>L(A=>Math.min(r,A+1)),disabled:y>=r,className:`w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 shrink-0 rounded-full flex items-center justify-center shadow-md border-2 transition-all ${y>=r?"bg-slate-100 text-slate-400 border-slate-200 cursor-not-allowed":"bg-white text-purple-600 border-purple-100 hover:bg-purple-50 hover:border-purple-200 hover:scale-105 active:scale-95"}`,children:[e.jsx(ut,{size:18,className:"sm:hidden"}),e.jsx(ut,{size:24,className:"hidden sm:block"})]})]}),e.jsx("main",{className:"flex-1 overflow-y-auto w-full px-4 sm:px-6 pt-0 pb-6 flex flex-col items-center relative z-10",children:e.jsxs(E.div,{initial:{opacity:0,x:20},animate:Ge?{x:[-10,10,-10,10,0],scale:[1,1.01,1],opacity:1}:{opacity:1,x:0},className:"w-full max-w-3xl flex flex-col mt-2",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-lg border-t-[6px] border-purple-500 p-4 sm:p-6 md:p-8 text-center flex flex-col items-center mb-4 sm:mb-6 w-full relative overflow-hidden",children:[e.jsxs("div",{className:"bg-slate-100 text-slate-600 px-3 sm:px-4 py-1 sm:py-1.5 rounded-full text-[10px] sm:text-[11px] md:text-xs font-black uppercase tracking-widest mb-3 sm:mb-4 flex items-center shadow-sm",children:["Q",y+1," of ",ie.length]}),e.jsx("h2",{className:"text-base sm:text-xl md:text-2xl font-extrabold text-[#0a1628] leading-tight w-full",children:oe.question.includes("___")?e.jsx("span",{children:oe.question.split("___").map((A,_,ee)=>e.jsxs(Fe.Fragment,{children:[A,_m(G.target.value),onKeyDown:G=>{G.key==="Enter"&&!u&&re()},className:`inline-block w-24 mx-2 border-b-4 outline-none text-center bg-transparent font-bold ${U?"border-slate-300 text-slate-500":"border-[#7C3AED] text-[#7C3AED] focus:border-[#75D06A]"}`})]},_))}):e.jsx(Bt,{children:oe.question})})]}),e.jsxs("div",{className:"w-full flex flex-col items-center",children:[oe.questionType==="multiple_choice"||!oe.questionType?e.jsx("div",{className:"w-full grid grid-cols-1 sm:grid-cols-2 gap-2.5 sm:gap-3 md:gap-5",children:(oe.options||[]).map((A,_)=>{const ee=ke[r]||[],G=ee.includes(A),V=ee.length,Ie=(oe.options||[]).length-1,He=Ie>0&&V>=Ie;let Re="bg-white hover:bg-slate-50 border-transparent text-slate-700 hover:border-slate-200",tt=!1;if(He){tt=!0;const Pe=oe.options?.[oe.correctAnswer];A===Pe?Re="bg-emerald-50 border-emerald-400 text-emerald-800":$[y]?.answer===String(_)?Re="bg-rose-50 border-rose-400 text-rose-800 opacity-80":Re="bg-slate-100 border-slate-200 text-slate-400 opacity-40 line-through"}else if(G)Re="bg-slate-100 border-slate-200 text-slate-400 opacity-40 line-through cursor-not-allowed";else if(U){const Pe=_===oe.correctAnswer,Se=y===r&&(d===_||ae===_)||y{tt||U||G||W(_)},className:`p-3 sm:p-4 md:p-5 rounded-2xl shadow-sm border-[3px] font-extrabold text-sm sm:text-base md:text-lg text-left transition-all flex items-center justify-between ${Re} ${tt||U||G?"cursor-default":"hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"}`,children:[e.jsx("span",{className:"truncate pr-4",children:e.jsx(Bt,{children:A})}),G&&e.jsx(Wt,{size:20,className:"text-slate-400 shrink-0"}),U&&_===oe.correctAnswer&&e.jsx(at,{size:22,className:"text-emerald-500 shrink-0"}),U&&d===_&&_!==oe.correctAnswer&&e.jsx(Wt,{size:22,className:"text-rose-500 shrink-0"})]},_)})}):e.jsx("div",{className:"w-full max-w-2xl mx-auto flex flex-col gap-4",children:!oe.question.includes("___")&&e.jsx("input",{type:"text",disabled:U,value:y===r?S:"",onChange:A=>m(A.target.value),onKeyDown:A=>{A.key==="Enter"&&!u&&re()},placeholder:"Type your answer here...",className:`w-full p-3 sm:p-4 md:p-5 rounded-2xl border-[3px] font-extrabold text-base sm:text-lg text-center outline-none transition-colors ${U?z?"border-emerald-400 text-emerald-700 bg-emerald-50":"border-rose-400 text-rose-700 bg-rose-50":"border-slate-200 focus:border-[#7C3AED] bg-white text-slate-800"}`})}),U&&f&&e.jsxs("div",{className:"w-full max-w-3xl mt-6 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-[#0a1628]",children:oe.topic||t?.subject||"General Math"}),e.jsxs("p",{className:"text-sm text-slate-500",children:["Question ",y+1," Explanation"]})]}),e.jsx("img",{src:"/icons/default-module-avatar.png",alt:"Module Avatar",className:"w-12 h-12 rounded-full object-cover border-2 border-slate-200"})]}),U&&f&&e.jsx(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"w-full mt-4 space-y-4 max-w-3xl",children:e.jsxs("div",{className:`border-2 rounded-2xl p-5 flex items-start gap-4 ${(y===r?z:$[y]?.correct)?"bg-emerald-50 border-emerald-200":"bg-rose-50 border-rose-200"}`,children:[(y===r?z:$[y]?.correct)?e.jsx(at,{size:28,className:"text-emerald-500 shrink-0 mt-0.5"}):e.jsx(Wt,{size:28,className:"text-rose-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:`font-extrabold text-lg mb-1 ${(y===r?z:$[y]?.correct)?"text-emerald-700":"text-rose-700"}`,children:(y===r?z:$[y]?.correct)?"Correct!":"Incorrect"}),e.jsx("p",{className:`text-base leading-relaxed ${(y===r?z:$[y]?.correct)?"text-emerald-800":"text-rose-800"}`,children:oe.explanation||`Correct Answer: ${oe.correctAnswerText||oe.options?.[oe.correctAnswer]}`})]})]})})]})]},y)}),e.jsx("footer",{className:"shrink-0 relative z-[60] flex flex-col items-center justify-center p-4 sm:p-6 bg-gradient-to-r from-purple-600 to-indigo-400 rounded-t-[32px] sm:rounded-t-[40px] shadow-[0_-10px_40px_rgba(0,0,0,0.15)]",children:(()=>{const A=(ke[r]||[]).length,_=(xe.options||[]).length-1,ee=_>0&&A>=_;return ee||U&&!z?e.jsxs("button",{onClick:ve,className:"bg-orange-500 hover:bg-orange-600 text-white font-extrabold text-sm sm:text-base md:text-lg px-5 sm:px-8 py-3 sm:py-4 rounded-full flex items-center justify-center gap-2 sm:gap-3 shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-all w-full max-w-md mx-auto",children:[r{const V=Le>0&&!u&&!ee;return e.jsxs("button",{onClick:H,disabled:!V,className:"bg-white hover:bg-slate-50 disabled:opacity-70 disabled:cursor-not-allowed text-slate-700 font-bold px-4 sm:px-6 md:px-8 py-2.5 sm:py-3 md:py-3.5 rounded-full flex items-center gap-1.5 sm:gap-2 text-sm sm:text-base shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Key",className:"w-4 h-4 sm:w-5 sm:h-5 object-contain"})," Hint"]})})(),U&&e.jsxs("button",{onClick:()=>C(!0),className:"bg-white hover:bg-slate-50 text-slate-700 font-bold px-4 sm:px-6 md:px-8 py-2.5 sm:py-3 md:py-3.5 rounded-full flex items-center gap-1.5 sm:gap-2 text-sm sm:text-base shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx(qe,{size:16,className:"sm:hidden"}),e.jsx(qe,{size:20,className:"hidden sm:block"})," Explain"]}),e.jsx("button",{onClick:()=>ye(V=>!V),className:`w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200 ${_e?"bg-purple-100 text-purple-600 border-purple-300":"bg-white hover:bg-slate-50 text-slate-700"}`,children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}),e.jsx("line",{x1:"8",x2:"16",y1:"6",y2:"6"}),e.jsx("path",{d:"M16 10h.01"}),e.jsx("path",{d:"M12 10h.01"}),e.jsx("path",{d:"M8 10h.01"}),e.jsx("path",{d:"M12 14h.01"}),e.jsx("path",{d:"M8 14h.01"}),e.jsx("path",{d:"M12 18h.01"}),e.jsx("path",{d:"M8 18h.01"}),e.jsx("line",{x1:"16",x2:"16",y1:"14",y2:"18"})]})})]}):yL(r),className:"bg-white text-slate-700 font-extrabold text-sm sm:text-base md:text-lg px-4 sm:px-6 md:px-8 py-2.5 sm:py-3 md:py-4 rounded-full inline-flex items-center gap-1.5 sm:gap-2 md:gap-3 shadow-lg hover:bg-slate-50 transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx(ut,{size:16,className:"sm:hidden"}),e.jsx(ut,{size:20,className:"hidden sm:block"}),"Back to Current Question"]}):null})()})]}),fe&&e.jsx("div",{className:"fixed inset-0 z-[300] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-2xl p-6 w-full max-w-[320px] shadow-2xl border border-slate-200 flex flex-col items-center gap-4",children:[e.jsx("h3",{className:"text-lg font-bold text-slate-900 text-center",children:"Leave this quiz?"}),e.jsx("p",{className:"text-sm text-slate-500 text-center",children:"Your progress will be reset and you'll need to start over."}),e.jsxs("div",{className:"w-full flex flex-col gap-2",children:[e.jsx("button",{onClick:()=>Me(!1),className:"w-full py-3 bg-[#9956DE] hover:bg-[#8544c7] text-white font-bold rounded-full transition-colors",children:"Stay"}),e.jsx("button",{onClick:()=>{Me(!1),s()},className:"w-full py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold rounded-full transition-colors",children:"Leave Quiz"})]})]})})]})};function Dr(t,s){const l={"Pre-Calculus":["What is the domain of the function f(x) = √(x - 2)?","Solve for x: 2^x = 16","What is the period of the function y = sin(2x)?","Find the inverse of f(x) = 3x + 5","What is the value of log₂(32)?","Simplify: (x² - 9) / (x - 3)","What is the range of f(x) = |x| - 3?","If f(x) = 2x + 1 and g(x) = x², find f(g(2)).","What is the amplitude of y = 3cos(x)?","Solve: log₃(x) = 4"],"General Mathematics":["Simplify: (2x + 3)(x - 4)","What is 15% of 240?","Solve: 3x + 7 = 22","What is the value of 5! (5 factorial)?","Convert 0.75 to a fraction","What is 25% of 360?","Simplify: 12/18","What is the GCD of 24 and 36?","Convert 3/8 to a decimal","If a shirt costs $40 and is 20% off, what is the sale price?","What is 2/3 + 1/4?","Calculate: 15% tip on a $80 bill","Simplify: 45/60","What fraction is equivalent to 0.125?","If 30% of a number is 45, what is the number?"],"Statistics and Probability":["What is the probability of rolling a 6 on a fair die?","Calculate the mean of: 4, 7, 9, 12, 15","What is the median of: 2, 5, 8, 11, 14?","In a bag with 5 red and 3 blue balls, what is P(red)?","What is the range of: 10, 15, 20, 25, 30?","What is the mode of: 3, 5, 5, 7, 8, 5, 9?","What is the standard deviation concept?","P(A) = 0.3, P(B) = 0.5, events independent. P(A and B) = ?","What is the median of: 4, 7, 10, 13?","How many ways can you arrange 3 books?"],"Basic Calculus":["Find the derivative of f(x) = 3x²","What is the limit of (x² - 4)/(x - 2) as x → 2?","Integrate: ∫ 2x dx","Find f'(x) if f(x) = 5x³ - 2x","What is the derivative of sin(x)?","Find the derivative of f(x) = eˣ + 3x","What is ∫ cos(x) dx?","Find the derivative of f(x) = ln(x)","What is the limit of 1/x as x → ∞?","Find f'(x) if f(x) = x⁴ - 2x² + 1"]},n=Ht(t),i=l[n]||l["General Mathematics"];return i[s%i.length]}function Ht(t){const s=t.toLowerCase();return s.includes("pre-calc")||s.includes("pre calc")||s.includes("precalc")?"Pre-Calculus":s.includes("statistic")||s.includes("probability")?"Statistics and Probability":s.includes("calculus")&&!s.includes("pre")?"Basic Calculus":s.includes("general")||s.includes("math")||s.includes("algebra")||s.includes("fraction")||s.includes("percent")||s.includes("ratio")||s.includes("geometry")?"General Mathematics":s.includes("derivative")||s.includes("integral")||s.includes("limit")?"Basic Calculus":s.includes("trig")||s.includes("function")||s.includes("log")?"Pre-Calculus":s.includes("mean")||s.includes("median")||s.includes("data")?"Statistics and Probability":"General Mathematics"}function Ir(t,s){const l={"Pre-Calculus":[["x ≥ 2","x ≤ 2","x ≥ 0","All real numbers"],["x = 2","x = 4","x = 8","x = 16"],["π","2π","π/2","4π"],["f⁻¹(x) = (x - 5)/3","f⁻¹(x) = 3x - 5","f⁻¹(x) = x/3 - 5","f⁻¹(x) = (x + 5)/3"],["4","5","6","7"],["x + 3","x - 3","x² + 3","(x + 3)(x - 3)"],["y ≥ -3","y ≥ 0","All real numbers","y > -3"],["9","5","7","3"],["1","2","3","1/3"],["12","27","64","81"]],"General Mathematics":[["2x² - 5x - 12","2x² + 5x - 12","2x² - 8x + 12","2x² - 5x + 12"],["36","32","28","24"],["x = 5","x = 4","x = 6","x = 7"],["120","24","60","720"],["3/4","1/2","2/3","4/5"],["90","80","100","72"],["2/3","3/4","4/6","6/9"],["12","6","8","4"],["0.375","0.38","0.35","0.325"],["$32","$28","$30","$36"],["11/12","3/7","5/6","2/3"],["$12","$10","$15","$8"],["3/4","2/3","4/5","9/12"],["1/8","1/4","1/5","1/6"],["150","135","120","160"]],"Statistics and Probability":[["1/6","1/3","1/2","2/3"],["9.4","8.5","10.2","7.8"],["8","9","7","10"],["5/8","3/8","1/2","2/5"],["20","15","25","30"],["5","3","7","8"],["Spread of data from the mean","The highest value","The average","The middle value"],["0.15","0.8","0.35","0.2"],["8.5","7","10","9"],["6","3","9","12"]],"Basic Calculus":[["6x","3x","9x²","6x²"],["4","2","0","undefined"],["x² + C","2x² + C","x²/2 + C","2x + C"],["15x² - 2","15x² - 2x","5x² - 2","15x - 2"],["cos(x)","-cos(x)","tan(x)","-sin(x)"],["eˣ + 3","eˣ + 3x","xeˣ + 3","eˣ"],["sin(x) + C","-sin(x) + C","tan(x) + C","-cos(x) + C"],["1/x","x","ln(x)","-1/x²"],["0","1","∞","undefined"],["4x³ - 4x","4x³ - 2x","x³ - 4x","4x⁴ - 4x²"]]},n=Ht(t),i=l[n]||l["General Mathematics"];return i[s%i.length]}function Fr(t,s){const l={"Pre-Calculus":[0,1,0,0,1,0,0,0,2,3],"General Mathematics":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"Statistics and Probability":[0,0,0,0,0,0,0,0,0,0],"Basic Calculus":[0,0,0,0,0,0,0,0,0,0]},n=Ht(t),i=l[n]||l["General Mathematics"];return i[s%i.length]}function $r(t,s,l){const n={"Pre-Calculus":["The expression under the square root must be non-negative: x - 2 ≥ 0, so x ≥ 2.","Since 2⁴ = 16, we get x = 4.","The period of sin(kx) is 2π/k. Here k = 2, so period = 2π/2 = π.","To find the inverse: y = 3x + 5 → x = 3y + 5 → y = (x - 5)/3.","Since 2⁵ = 32, log₂(32) = 5.","(x² - 9)/(x - 3) = (x+3)(x-3)/(x-3) = x + 3 (for x ≠ 3).","The absolute value |x| ≥ 0 for all x, so |x| - 3 ≥ -3. The range is y ≥ -3.","g(2) = 4, then f(4) = 2(4) + 1 = 9.","The amplitude of y = Acos(x) is |A|. Here A = 3, so amplitude = 3.","log₃(x) = 4 means 3⁴ = x, so x = 81."],"General Mathematics":["(2x + 3)(x - 4) = 2x² - 8x + 3x - 12 = 2x² - 5x - 12","15% of 240 = 0.15 × 240 = 36","3x + 7 = 22 → 3x = 15 → x = 5","5! = 5 × 4 × 3 × 2 × 1 = 120","0.75 = 75/100 = 3/4 after simplifying by dividing both by 25","25% of 360 = 0.25 × 360 = 90","12/18 = (12÷6)/(18÷6) = 2/3","Factors of 24: {1,2,3,4,6,8,12,24}. Factors of 36: {1,2,3,4,6,9,12,18,36}. GCD = 12","3 ÷ 8 = 0.375","20% off $40 = $40 × 0.80 = $32","2/3 + 1/4 = 8/12 + 3/12 = 11/12","15% of $80 = 0.15 × 80 = $12","45/60 = (45÷15)/(60÷15) = 3/4","0.125 = 125/1000 = 1/8","30% × N = 45 → N = 45/0.30 = 150"],"Statistics and Probability":["A fair die has 6 outcomes, each equally likely. P(6) = 1/6.","Mean = (4 + 7 + 9 + 12 + 15) / 5 = 47/5 = 9.4","Sorted: 2, 5, 8, 11, 14. The middle value is 8.","P(red) = 5/(5+3) = 5/8","Range = max - min = 30 - 10 = 20","The value 5 appears 3 times, more than any other value. Mode = 5.","Standard deviation measures how spread out data points are from the mean.","For independent events: P(A and B) = P(A) × P(B) = 0.3 × 0.5 = 0.15","For even-count dataset {4,7,10,13}: median = (7+10)/2 = 8.5","3 books can be arranged in 3! = 3 × 2 × 1 = 6 ways."],"Basic Calculus":["Using the power rule: d/dx[3x²] = 3 × 2x = 6x","Factor: (x²-4)/(x-2) = (x+2)(x-2)/(x-2) = x+2. As x→2: 2+2 = 4","∫ 2x dx = 2 × x²/2 + C = x² + C","f'(x) = 5 × 3x² - 2 = 15x² - 2","The derivative of sin(x) is cos(x). This is a fundamental trigonometric derivative.","d/dx[eˣ + 3x] = eˣ + 3. The derivative of eˣ is eˣ and of 3x is 3.","∫ cos(x) dx = sin(x) + C. Integration is the reverse of differentiation.","The derivative of ln(x) is 1/x. This is a fundamental logarithmic derivative.","As x → ∞, 1/x approaches 0. The function gets infinitely close to zero.","f'(x) = 4x³ - 4x using the power rule on each term."]},i=Ht(t),c=n[i]||n["General Mathematics"];return c[s%c.length]}function qr(t){const s=Math.floor(t/60),l=t%60;return`${s}:${l.toString().padStart(2,"0")}`}async function Xt(t){return rt("/api/try-it-yourself/resolve-question",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Or(t){return rt("/api/try-it-yourself/use-hint",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Br(t){return rt("/api/try-it-yourself/complete-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Qr(t){return rt("/api/try-it-yourself/shadow-retry",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}const Hr=["foundation","application","complexity","gauntlet"],Wr={0:1,1:.7,2:.4,3:.2},Ur=10,Gr=2,Xr=2,Vr=1,Yr=3;function Kr(t,s){const l=Wr[Math.min(t,3)]??.2;return Math.max(Math.round(Ur*l),Gr)}function Zr(t){const s=t.length,l=4;if(t.filter(p=>p.bloomLevel).length0&&k.push(C)}return k}const i=t.filter(p=>p.bloomLevel==="remember"||p.bloomLevel==="understand"),c=t.filter(p=>p.bloomLevel==="apply"),r=t.filter(p=>p.bloomLevel==="analyze"),x=t.filter(p=>p.bloomLevel==="evaluate"),d=t.filter(p=>!p.bloomLevel),h=[],S=[...i,...d];S.length>0&&h.push(S),c.length>0&&h.push(c),r.length>0&&h.push(r),x.length>0&&h.push(x);const m=[];let z=[];for(const p of h)z=[...z,...p],z.length>=l&&(m.push(z),z=[]);return z.length>0&&(m.length>0?m[m.length-1]=[...m[m.length-1],...z]:m.push(z)),m.length>0?m:[t]}function Ss(t){return t==="multiple-choice"?Xr:t==="fill-in-blank"?Vr:null}function Jr(t){const s=t.toLowerCase();return s.includes("geometry")||s.includes("shape")?[Ot,It,qt,ys,Os,fr]:s.includes("algebra")||s.includes("equation")?[Ze,kt,ws,Gt,pt,Ft]:s.includes("calculus")||s.includes("derivative")||s.includes("integral")?[$t,Gt,Lt,pt,kt,ws]:s.includes("statistics")||s.includes("probability")?[We,Lt,ys,It,Ot,qt]:[pt,$t,kt,Ft,Gt,Oa]}let wt=null;function el(){if(wt&&wt.state!=="closed")return wt;const t=window.AudioContext||window.webkitAudioContext;return t?(wt=new t,wt):null}function jt(t,s){if(s)try{const l=el();if(!l)return;l.state==="suspended"&&l.resume();const n=l.currentTime,i=(c,r,x,d=.1,h="sine")=>{const S=l.createOscillator(),m=l.createGain();S.type=h,S.frequency.value=c,m.gain.setValueAtTime(0,r),m.gain.linearRampToValueAtTime(d,r+.05),m.gain.exponentialRampToValueAtTime(.001,r+x),S.connect(m),m.connect(l.destination),S.start(r),S.stop(r+x)};switch(t){case"correct":i(880,n,.1),i(1108.73,n+.1,.2);break;case"incorrect":i(300,n,.2,.05,"sawtooth"),i(250,n+.15,.3,.05,"sawtooth");break;case"streak":i(440,n,.1,.05,"square"),i(554.37,n+.1,.1,.05,"square"),i(659.25,n+.2,.1,.05,"square"),i(880,n+.3,.4,.05,"square");break;case"complete":i(523.25,n,.1),i(659.25,n+.15,.1),i(783.99,n+.3,.1),i(1046.5,n+.45,.5);break;case"hint":i(600,n,.15,.06,"triangle");break}}catch{}}const vt=({label:t,value:s,prefix:l="",suffix:n="",icon:i,delay:c=0,large:r})=>{const[x,d]=Fe.useState(0);return Fe.useEffect(()=>{if(s<=0){d(s);return}const h=setTimeout(()=>{const z=Math.floor(40);let p=0;const u=setInterval(()=>{p+=Math.max(1,Math.floor(s/20)),p>=s?(d(s),clearInterval(u)):d(p)},z)},c);return()=>clearTimeout(h)},[s,c]),e.jsxs(E.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:c/1e3,duration:.4},className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[i," ",t]}),e.jsxs("span",{className:`font-black tabular-nums ${r?"text-2xl text-purple-600":"text-lg text-slate-800"}`,children:[l,x,n]})]})},tl=({questions:t,lessonTitle:s,subject:l,sessionId:n,userId:i,onComplete:c,onBack:r})=>{const x=a.useMemo(()=>Zr(t),[t]),d=x.length,[h,S]=a.useState(0),[m,z]=a.useState(()=>[...x[0]]),[p,u]=a.useState(0),[k,f]=a.useState("playing"),[C,N]=a.useState({}),[R,T]=a.useState(null),[F,X]=a.useState(""),[Z,Y]=a.useState([]),[te,$]=a.useState(!1),[pe,he]=a.useState(!1),[ze,Ce]=a.useState(!1),[b,Q]=a.useState(!1),[ce,ae]=a.useState(!1),[le,ge]=a.useState(!1),[Ne,B]=a.useState(!1),[Ee,_e]=a.useState(!1),[ye,fe]=a.useState(!0),[Me,Ae]=a.useState(!1),[g,q]=a.useState(!1),[M,O]=a.useState(0),[I,J]=a.useState(0),[be,ke]=a.useState(0),[D,ne]=a.useState(15),[me,Ge]=a.useState(5),[ft,bt]=a.useState([]),[De,Xe]=a.useState(null);a.useRef(Date.now());const et=a.useRef(null),j=m[p]||null,Te=a.useMemo(()=>Jr(s),[s]),lt={gradient:"bg-gradient-to-br from-[#7274ED] via-[#9956DE] to-[#7274ED]"},Le=a.useCallback(w=>C[w]||{attempts:0,hintsUsed:0,resolved:!1,resolution:null,failedOptions:[],xpAwarded:0},[C]);a.useEffect(()=>{if(j){if(j.type==="multiple-choice"&&j.options){const w=j.options.map((v,H)=>({id:`${j.id}-${H}`,text:v}));for(let v=w.length-1;v>0;v--){const H=Math.floor(Math.random()*(v+1));[w[v],w[H]]=[w[H],w[v]]}Y(w)}else Y([]);T(null),X(""),$(!1),he(!1),ge(!1),j.type==="fill-in-blank"&&setTimeout(()=>et.current?.focus(),100)}},[j?.id]);const Be=()=>{document.fullscreenElement?(document.exitFullscreen().catch(()=>{}),Ae(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),Ae(!0))},gt=a.useCallback(()=>{if(!j)return;const w=Le(j.id);if(w.resolved||w.hintsUsed>=(j.hints?.length||0)||me<=0)return;jt("hint",ye),$(!0),Ge(H=>H-1);const v=w.hintsUsed+1;N(H=>({...H,[j.id]:{...w,hintsUsed:v}})),i&&Or({userId:i,sessionId:n,questionId:String(j.id),currentHintTier:w.hintsUsed}).catch(()=>{})},[j,C,i,n,ye,me,Le]),nt=a.useCallback(()=>{if(!j)return;const w=Le(j.id);if(w.resolved)return;const v=Ss(j.type);v===null||w.attempts({...H,[j.id]:{...w,resolved:!0,resolution:"revealed",xpAwarded:0}})),J(0),i&&Xt({userId:i,sessionId:n,questionId:String(j.id),resolution:"revealed",attempts:w.attempts,hintsUsed:w.hintsUsed}).catch(()=>{}))},[j,C,i,n,Le]),Ve=a.useCallback(w=>{if(!j||Ee)return;const v=Le(j.id);if(v.resolved)return;let H="";if(j.type==="fill-in-blank"){if(H=F.trim(),!H)return}else if(H=w||"",!H)return;_e(!0);const W=v.attempts+1;let re=!1;if(j.type==="fill-in-blank"?re=H.toLowerCase().replace(/\s+/g,"")===j.correctAnswer.toLowerCase().replace(/\s+/g,""):re=H===j.correctAnswer,re){const ve=Kr(v.hintsUsed);N(U=>({...U,[j.id]:{...v,attempts:W,resolved:!0,resolution:"correct",xpAwarded:ve}})),O(U=>U+ve);const se=I+1;J(se),ke(U=>Math.max(U,se)),jt(se>=3?"streak":"correct",ye),B(!0),ge(!0),St(()=>import("./confetti.module-C94ZD2ww.js"),[]).then(U=>{U.default({particleCount:30,spread:40,colors:["#75D06A","#6ED1CF"],origin:{y:.6}})}).catch(()=>{}),i&&Xt({userId:i,sessionId:n,questionId:String(j.id),resolution:"correct",attempts:W,hintsUsed:v.hintsUsed}).catch(()=>{}),setTimeout(()=>{ge(!1),_e(!1)},1400)}else{const ve=[...v.failedOptions,H],se={...v,attempts:W,failedOptions:ve};let U=!1;if(j.type==="multiple-choice"&&j.options?U=j.options.filter(yt=>yt!==j.correctAnswer).every(yt=>ve.includes(yt)):j.type==="true-false"&&(U=!0),U){N(oe=>({...oe,[j.id]:{...se,resolved:!0,resolution:"revealed",xpAwarded:0}})),J(0),ne(oe=>Math.max(0,oe-1)),jt("incorrect",ye),_e(!1),i&&Xt({userId:i,sessionId:n,questionId:String(j.id),resolution:"revealed",attempts:W,hintsUsed:v.hintsUsed}).catch(()=>{});return}N(oe=>({...oe,[j.id]:se})),J(0),ne(oe=>Math.max(0,oe-1)),jt("incorrect",ye),ae(!0),setTimeout(()=>ae(!1),500),j.type==="fill-in-blank"&&X(""),_e(!1)}},[j,C,F,Ee,I,i,n,ye,Le]),it=a.useRef(()=>{}),ot=a.useCallback(()=>{const w=p+1;if(m.slice(w).filter(H=>!C[H.id]?.resolved).length===0){const H=m.filter(W=>!C[W.id]?.resolved);H.length>0?(z(H),u(0)):it.current()}else u(w)},[p,m,C]),o=a.useCallback(()=>{const w=x[h]||[];let v=0,H=0,W=0;const re=[];w.forEach(se=>{const U=C[se.id];U&&(v+=U.xpAwarded,U.resolution==="correct"&&H++,U.resolution==="revealed"&&W++,U.attempts>=Yr&&re.push(se.topic||se.competencyCode||s))});const ve={phase:Hr[h],questionsCorrect:H,questionsRevealed:W,xpEarned:v,struggleTopics:[...new Set(re)]};Xe(ve),bt(se=>[...se,ve]),h>=d-1?(f("complete"),jt("complete",ye)):(f("phase-complete"),q(!1))},[h,d,x,C,s,ye]);it.current=o;const P=a.useCallback(async()=>{const w=h+1;if(w>=d){f("complete");return}f("loading-next");const H=(x[h]||[]).filter(se=>C[se.id]?.resolution==="revealed");let W=[...x[w],...H];const re=De?.struggleTopics||[];if(re.length>0&&i)try{const se=await Qr({userId:i,sessionId:n,struggleTopics:re,subject:l,count:Math.min(2,re.length)});se.variants?.length&&(W=[...W,...se.variants.map(U=>({id:U.id,type:U.type,question:U.question,options:U.options,correctAnswer:U.correctAnswer,explanation:U.explanation||"",hints:U.hints||[]}))])}catch{}S(w),z(W),u(0);const ve={...C};H.forEach(se=>{delete ve[se.id]}),N(ve),f("playing")},[h,d,x,De,C,i,n,l]),y=a.useCallback(async()=>{const w=t.map(W=>{const re=C[W.id];return{questionId:String(W.id),resolution:re?.resolution||"correct",attempts:re?.attempts||1,hintsUsed:re?.hintsUsed||0,topic:s}});let v=M;if(i)try{v=(await Br({userId:i,sessionId:n,questionResults:w})).totalXP}catch{}const H=Object.values(C).filter(W=>W.resolution==="correct").length;c(Math.round(H/t.length*100),v)},[t,C,M,i,n,s,c]);if(a.useEffect(()=>{const w=v=>{v.key==="Enter"&&j?.type==="fill-in-blank"&&F.trim()&&(v.preventDefault(),Ve())};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[Ve,j,F]),a.useEffect(()=>{(k==="phase-complete"||k==="complete")&&!g&&(q(!0),St(()=>import("./confetti.module-C94ZD2ww.js"),[]).then(w=>{w.default({particleCount:100,spread:80,colors:["#9956DE","#75D06A","#6ED1CF","#FFD700","#FF6B6B"],origin:{y:.35}}),setTimeout(()=>w.default({particleCount:60,spread:100,colors:["#9956DE","#75D06A","#FFD700"],origin:{y:.5,x:.3}}),300),setTimeout(()=>w.default({particleCount:60,spread:100,colors:["#6ED1CF","#FF6B6B","#FFD700"],origin:{y:.5,x:.7}}),600)}).catch(()=>{}))},[k,g]),k==="phase-complete"&&De)return e.jsxs("div",{className:"fixed inset-0 z-[200] flex flex-col items-center justify-center bg-gradient-to-br from-[#e8e0f7] via-[#f0e8ff] to-[#ddd6f3] p-6",children:[e.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden",children:[[Ot,It,qt,kt,Ft,$t].map((w,v)=>e.jsx(E.div,{className:"absolute text-purple-300/30",style:{top:`${10+v*14%80}%`,left:`${5+v*18%85}%`},animate:{y:[0,-15,0],rotate:[0,360]},transition:{duration:4+v,repeat:1/0,ease:"easeInOut",delay:v*.5},children:e.jsx(w,{size:28+v%3*12})},v)),e.jsx("div",{className:"absolute top-0 left-0 w-64 h-64 bg-purple-200 opacity-20 rounded-full -translate-x-1/2 -translate-y-1/2 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-80 h-80 bg-indigo-200 opacity-20 rounded-full translate-x-1/3 translate-y-1/3 blur-3xl"})]}),e.jsxs(E.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",damping:20,stiffness:200},className:"relative z-10 flex flex-col items-center text-center max-w-sm w-full",children:[e.jsx(E.img,{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-36 h-36 sm:w-44 sm:h-44 mb-6 drop-shadow-[0_15px_30px_rgba(0,0,0,0.15)]",initial:{y:-20},animate:{y:[0,-8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsxs("h1",{className:"text-3xl sm:text-4xl font-black text-[#5b3a9e] mb-2 drop-shadow-sm",children:["Phase ",h+1," Complete!"]}),e.jsx("p",{className:"text-purple-500/70 text-sm mb-6",children:"Great work! Keep going."}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-md rounded-2xl p-5 w-full mb-6 border border-purple-200/50 shadow-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Pt,{size:14,className:"text-emerald-500"})," Correct"]}),e.jsx("span",{className:"text-lg font-black text-emerald-600",children:De.questionsCorrect})]}),De.questionsRevealed>0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Ut,{size:14,className:"text-amber-500"})," Revealed"]}),e.jsx("span",{className:"text-lg font-black text-amber-600",children:De.questionsRevealed})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-purple-100",children:[e.jsxs("span",{className:"text-slate-500 text-xs font-bold uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Ke,{size:14,className:"text-purple-500"})," XP Earned"]}),e.jsxs("span",{className:"text-xl font-black text-purple-600",children:["+",De.xpEarned]})]})]}),e.jsx("div",{className:"flex items-center gap-2 mb-8",children:Array.from({length:d}).map((w,v)=>e.jsx("div",{className:`w-3 h-3 rounded-full transition-all ${v<=h?"bg-purple-500 shadow-[0_0_8px_rgba(153,86,222,0.6)]":"bg-purple-200"}`},v))}),e.jsxs("button",{onClick:P,className:"w-full py-4 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-black text-lg shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-transform mb-3",children:["Continue to Next Phase ",e.jsx(Ye,{size:20,className:"inline ml-2"})]}),e.jsx("button",{onClick:()=>Q(!0),className:"text-purple-400 hover:text-purple-600 text-sm font-bold transition-colors",children:"Quit Quiz"})]}),b&&e.jsx("div",{className:"fixed inset-0 z-[220] flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-[2rem] p-6 sm:p-8 max-w-xs w-full shadow-2xl flex flex-col gap-4 text-center",children:[e.jsx("h2",{className:"text-xl font-black text-slate-800",children:"Are you sure you want to leave?"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Your progress won't be saved."}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{onClick:()=>Q(!1),className:"w-full py-3 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-bold",children:"Stay"}),e.jsx(Oe,{onClick:r,className:"w-full py-3 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold",children:"Leave"})]})]})})]});if(k==="loading-next")return e.jsx("div",{className:"fixed inset-0 z-[200] flex items-center justify-center bg-gradient-to-br from-[#7274ED] via-[#9956DE] to-[#7274ED]",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 border-4 border-white border-t-transparent rounded-full animate-spin"}),e.jsx("p",{className:"font-bold text-white text-lg",children:"Preparing next phase..."})]})});if(k==="complete"){const w=Object.values(C).filter(W=>W.resolution==="correct").length,v=Object.values(C).filter(W=>W.resolution==="revealed").length,H=Math.round(w/t.length*100);return e.jsxs("div",{className:"fixed inset-0 z-[200] flex flex-col items-center justify-center bg-gradient-to-br from-[#e8e0f7] via-[#f0e8ff] to-[#ddd6f3] p-6",children:[e.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden",children:[[Ot,It,qt,kt,Ft,$t,Os,We].map((W,re)=>e.jsx(E.div,{className:"absolute text-purple-300/25",style:{top:`${8+re*12%80}%`,left:`${3+re*13%90}%`},animate:{y:[0,-12,0],rotate:[0,360]},transition:{duration:5+re,repeat:1/0,ease:"easeInOut",delay:re*.4},children:e.jsx(W,{size:24+re%4*10})},re)),e.jsx("div",{className:"absolute top-0 right-0 w-72 h-72 bg-purple-200 opacity-20 rounded-full translate-x-1/3 -translate-y-1/3 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-64 h-64 bg-indigo-200 opacity-20 rounded-full -translate-x-1/3 translate-y-1/3 blur-3xl"})]}),e.jsxs(E.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"relative z-10 flex flex-col items-center text-center max-w-sm w-full",children:[e.jsx(E.img,{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-36 h-36 sm:w-44 sm:h-44 mb-6 drop-shadow-[0_15px_30px_rgba(0,0,0,0.15)]",initial:{y:-20},animate:{y:[0,-8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-black text-[#5b3a9e] mb-2",children:"Quiz Complete!"}),e.jsx("p",{className:"text-purple-500/70 text-sm mb-6",children:s}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-md rounded-2xl p-5 w-full mb-6 border border-purple-200/50 shadow-lg space-y-3",children:[e.jsx(vt,{label:"Score",value:H,suffix:"%",icon:e.jsx(Tt,{size:14,className:"text-purple-500"}),delay:0}),e.jsx(vt,{label:"Correct",value:w,suffix:`/${t.length}`,icon:e.jsx(Pt,{size:14,className:"text-emerald-500"}),delay:200}),v>0&&e.jsx(vt,{label:"Revealed",value:v,icon:e.jsx(Ut,{size:14,className:"text-amber-500"}),delay:400}),e.jsx(vt,{label:"Best Streak",value:be,icon:e.jsx(Kt,{size:14,className:"text-orange-500"}),delay:600}),e.jsx("div",{className:"pt-2 border-t border-purple-100",children:e.jsx(vt,{label:"Total XP",value:M,prefix:"+",icon:e.jsx(Ke,{size:14,className:"text-purple-500"}),delay:800,large:!0})})]}),e.jsx("button",{onClick:y,className:"w-full py-4 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-black text-lg shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-transform",children:"FINISH"})]})]})}const L=j?Le(j.id):null,K=j?Ss(j.type):null,de=K!==null&&(L?.attempts??0)>=K,ie=K===null||!de,xe=!L?.resolved,je=j?.hints?.length??0,Qe=je-(L?.hintsUsed??0),we=x[h]||[];return we.filter(w=>C[w.id]?.resolved).length,j?e.jsxs(e.Fragment,{children:[ze&&Et.createPortal(e.jsx(E.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:"fixed right-6 top-1/2 -translate-y-1/2 z-[9999] w-64",children:e.jsxs("div",{className:"bg-white rounded-2xl p-3 border border-slate-200 shadow-[0_10px_40px_rgba(0,0,0,0.2)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("h4",{className:"text-xs font-bold text-[#0a1628] flex items-center gap-2",children:[e.jsx(pt,{size:14,className:"text-purple-600"})," Calculator"]}),e.jsx("button",{onClick:()=>Ce(!1),className:"w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 hover:text-slate-800 hover:bg-slate-200 transition-colors",children:e.jsx(Ze,{size:12})})]}),e.jsx(Fs,{isOpen:!0,onClose:()=>Ce(!1),inline:!0})]})}),document.getElementById("modal-root")||document.body),e.jsx(Je,{children:le&&e.jsx(E.div,{initial:{opacity:0,scale:.8,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:1.1,filter:"blur(10px)"},transition:{type:"spring",damping:20,stiffness:300},className:"fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[100] pointer-events-none flex flex-col items-center justify-center",children:e.jsxs("div",{className:"bg-white/95 backdrop-blur-xl border border-slate-200 rounded-[2rem] p-6 md:p-8 shadow-[0_30px_80px_rgba(0,0,0,0.15)] flex flex-col items-center min-w-[280px] md:min-w-[320px]",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",alt:"Mascot",className:"w-24 h-24 md:w-32 md:h-32 mb-4 drop-shadow-[0_10px_20px_rgba(0,0,0,0.15)]"}),e.jsx("h2",{className:`text-3xl md:text-4xl font-black mb-4 uppercase tracking-widest ${Ne?"text-emerald-500":"text-rose-500"}`,children:Ne?"Correct!":"Incorrect"}),Ne?e.jsxs("div",{className:"flex flex-col items-center gap-3 w-full justify-center",children:[e.jsx("div",{className:"flex items-center gap-2 bg-emerald-500/20 text-emerald-400 px-4 py-2 rounded-full font-bold border border-emerald-500/30",children:e.jsxs("span",{children:["+ ",L?.xpAwarded??10," XP"]})}),I>=3&&e.jsxs("div",{className:"flex items-center gap-2 bg-orange-500/20 text-orange-400 px-4 py-1.5 rounded-full text-sm font-bold border border-orange-500/30",children:[e.jsx(Kt,{size:14})," Streak ×",I,"!"]})]}):e.jsxs("div",{className:"bg-rose-500/20 border border-rose-500/30 text-rose-400 font-bold px-5 py-2 rounded-xl text-center",children:["Correct: ",j.correctAnswer]})]})},"round-result")}),e.jsx(Je,{children:b&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",onClick:()=>Q(!1),children:e.jsxs(E.div,{onClick:w=>w.stopPropagation(),initial:{scale:.9,opacity:0,y:20},animate:{scale:1,opacity:1,y:0},exit:{scale:.9,opacity:0,y:20},className:"bg-white rounded-[2rem] p-6 sm:p-8 max-w-xs w-full shadow-2xl flex flex-col gap-4 text-center",children:[e.jsx("h2",{className:"text-xl font-black text-slate-800",children:"Are you sure you want to leave?"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Your progress won't be saved."}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Oe,{onClick:()=>Q(!1),className:"w-full py-3 rounded-full bg-[#9956DE] hover:bg-[#8544c7] text-white font-bold",children:"Stay"}),e.jsx(Oe,{onClick:()=>{Q(!1),r()},className:"w-full py-3 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold",children:"Leave"})]})]})})}),e.jsxs("div",{className:"fixed inset-0 z-50 h-screen w-full flex flex-col bg-slate-50 overflow-hidden",children:[e.jsxs("header",{className:`relative shrink-0 flex flex-col items-center justify-start px-4 pt-4 sm:pt-6 pb-6 z-[60] shadow-md overflow-hidden ${lt.gradient} rounded-b-[32px] sm:rounded-b-[40px] min-h-[110px] sm:min-h-[130px]`,children:[e.jsxs("div",{className:"absolute inset-0 z-0 pointer-events-none",children:[e.jsx("div",{className:"absolute top-0 left-0 w-64 h-64 bg-white opacity-10 rounded-full -translate-x-1/2 -translate-y-1/2 blur-2xl"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-80 h-80 bg-white opacity-10 rounded-full translate-x-1/3 translate-y-1/3 blur-3xl"}),Te.map((w,v)=>e.jsx("div",{className:"absolute text-white/10",style:{top:`${10+v*15}%`,left:`${10+v*25%80}%`,transform:`rotate(${v*45}deg) scale(${1+v%3*.2})`},children:e.jsx(w,{size:48+v%2*32})},v))]}),e.jsxs("div",{className:"w-full max-w-7xl flex items-start justify-between relative z-10 mb-4 sm:mb-6",children:[e.jsx("div",{className:"flex-1 pointer-events-none"}),e.jsxs("div",{className:"relative flex items-center justify-center bg-purple-900/40 backdrop-blur-md px-6 sm:px-8 py-3 rounded-full border border-white/10 gap-3 sm:gap-4 shadow-inner",children:[e.jsx("div",{className:"w-3 h-3 sm:w-4 sm:h-4 rounded-full bg-yellow-400 shrink-0 shadow-[0_0_10px_rgba(250,204,21,0.6)]"}),e.jsxs("div",{className:"flex flex-col items-start justify-center",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] font-black text-purple-200 uppercase tracking-widest leading-none mb-1",children:"Try It Yourself!"}),e.jsx("span",{className:"font-bold text-white tracking-wide text-base sm:text-lg leading-none truncate max-w-[200px] sm:max-w-[300px]",children:s})]})]}),e.jsxs("div",{className:"flex-1 flex justify-end gap-2 sm:gap-3 relative pointer-events-auto",children:[e.jsx("button",{onClick:()=>fe(!ye),className:"w-10 h-10 sm:w-12 sm:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:ye?e.jsx(ts,{size:20}):e.jsx(ss,{size:20})}),e.jsx("button",{onClick:Be,className:"hidden sm:flex w-10 h-10 sm:w-12 sm:h-12 rounded-full bg-purple-900/20 text-white items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:Me?e.jsx($s,{size:20}):e.jsx(qs,{size:20})}),e.jsx("button",{onClick:()=>Q(!0),className:"w-10 h-10 sm:w-12 sm:h-12 rounded-full bg-purple-900/20 text-white flex items-center justify-center hover:bg-purple-900/40 transition-colors shadow-sm border border-white/10",children:e.jsx(ta,{size:20})})]})]}),e.jsx("div",{className:"w-full max-w-[50rem] flex items-center justify-center px-4 z-10",children:e.jsx("div",{className:"w-full flex items-center gap-2 sm:gap-3",children:we.map((w,v)=>e.jsx("div",{className:`h-1.5 sm:h-2 rounded-full flex-1 transition-all ${C[w.id]?.resolved?"bg-white shadow-[0_0_8px_rgba(255,255,255,0.8)]":"bg-white/20"}`},w.id))})})]}),e.jsx("div",{className:"w-full max-w-[54rem] mx-auto shrink-0 flex items-center justify-between px-4 sm:px-6 py-2 sm:py-3 z-[50] relative mt-4",children:e.jsxs("div",{className:"flex items-center justify-center gap-3 sm:gap-5 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 px-8 sm:px-10 py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-rose-500 font-extrabold text-sm sm:text-base",children:[e.jsx("img",{src:"/icons/quiz_heart.png",alt:"Hearts",className:"w-5 h-5 object-contain"}),D]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 px-8 sm:px-10 py-2 rounded-full bg-white shadow-md border border-slate-200/60 text-yellow-500 font-extrabold text-sm sm:text-base",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Keys",className:"w-5 h-5 object-contain"}),me]}),e.jsxs("div",{className:"flex items-center gap-3 sm:gap-4 px-3 py-1.5 pl-5 sm:pl-6 rounded-full bg-white shadow-md border border-slate-200/60",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-500 font-extrabold text-sm sm:text-base",children:[e.jsx("img",{src:"/icons/quiz_streak.png",alt:"Streak",className:"w-5 h-5 object-contain"})," ",I]}),e.jsxs("div",{className:"bg-emerald-100 text-emerald-800 px-4 py-1.5 rounded-full font-bold text-sm sm:text-base shadow-inner border border-emerald-200/50",children:["+ ",M," XP"]})]})]})}),e.jsx("main",{className:"flex-1 overflow-y-auto w-full px-4 sm:px-6 pt-0 pb-6 flex flex-col items-center relative z-10",children:e.jsxs(E.div,{initial:{opacity:0,x:20},animate:ce?{x:[-10,10,-10,10,0],scale:[1,1.01,1],opacity:1}:{opacity:1,x:0},className:"w-full max-w-3xl flex flex-col mt-2",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-lg border-t-[6px] border-purple-500 p-6 sm:p-8 text-center flex flex-col items-center mb-6 w-full relative overflow-hidden",children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-extrabold text-[#0a1628] leading-tight w-full",children:e.jsx(Bt,{children:j.question})}),j.type==="fill-in-blank"&&!L?.resolved&&e.jsx("input",{ref:et,type:"text",value:F,onChange:w=>X(w.target.value),placeholder:"Type your answer...",disabled:L?.resolved||Ee,className:"mt-4 w-full max-w-xs mx-auto px-4 py-3 border-b-4 border-[#7C3AED] text-center text-lg font-bold outline-none bg-transparent focus:border-[#75D06A] transition-colors"}),j.type==="fill-in-blank"&&L?.resolved&&e.jsx("div",{className:"mt-4 px-4 py-3 bg-emerald-50 border-2 border-emerald-300 rounded-xl text-emerald-700 font-bold text-lg",children:j.correctAnswer})]}),e.jsxs("div",{className:"w-full flex flex-col items-center",children:[(j.type==="multiple-choice"||j.type==="true-false")&&e.jsx("div",{className:"w-full grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-5",children:(j.type==="true-false"?[{id:"tf-true",text:"True"},{id:"tf-false",text:"False"}]:Z).map(w=>{const v=w.text,H=L?.failedOptions.includes(v),W=L?.resolved&&L.resolution==="revealed",re=L?.resolved&&L.resolution==="correct",ve=v===j.correctAnswer;let se="bg-white hover:bg-slate-50 border-transparent text-slate-700 hover:border-slate-200";return W||re?ve?se="bg-emerald-50 border-emerald-400 text-emerald-800 shadow-[0_0_15px_rgba(16,185,129,0.2)] scale-[1.02] z-10":H?se="bg-rose-50 border-rose-400 text-rose-800 opacity-60":se="bg-slate-50 border-slate-200 text-slate-400 opacity-60":H?se="bg-rose-50 border-rose-400 text-rose-800 opacity-60":R===w.id&&(se="bg-purple-50 border-[#9956DE] text-[#9956DE]"),e.jsxs("button",{disabled:L?.resolved||H||Ee,onClick:()=>{L?.resolved||Ee||H||(T(w.id),Ve(v))},className:`p-4 sm:p-5 rounded-2xl shadow-sm border-[3px] font-extrabold text-base sm:text-lg text-left transition-all flex items-center justify-between ${se} ${L?.resolved?"cursor-default":"hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"}`,children:[e.jsx("span",{className:"truncate pr-4",children:e.jsx(Bt,{children:v})}),(W||re)&&ve&&e.jsx(Pt,{size:24,className:"text-emerald-500 shrink-0"}),H&&e.jsx(Ze,{size:24,className:"text-rose-500 shrink-0"})]},w.id)})}),te&&j.hints&&(L?.hintsUsed??0)>0&&e.jsx(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"w-full mt-6 max-w-3xl",children:e.jsxs("div",{className:"border-2 rounded-2xl p-5 bg-amber-50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ct,{size:18,className:"text-amber-500"}),e.jsxs("span",{className:"font-bold text-amber-700 text-sm",children:["Hints (",L?.hintsUsed,"/",je,")"]})]}),e.jsx("div",{className:"space-y-2",children:j.hints.slice(0,L?.hintsUsed??0).map((w,v)=>e.jsxs("p",{className:"text-sm text-amber-800 leading-relaxed",children:[e.jsxs("span",{className:"font-bold text-amber-600",children:[v+1,"."]})," ",w]},v))})]})}),pe&&L?.resolved&&j.explanation&&e.jsx(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"w-full mt-6 max-w-3xl",children:e.jsxs("div",{className:"border-2 rounded-2xl p-5 flex items-start gap-4 bg-sky-50 border-sky-200",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",className:"w-10 h-10 shrink-0",alt:"AI Explain"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-extrabold text-lg mb-1 text-sky-700",children:"Explanation"}),e.jsx("p",{className:"text-base leading-relaxed text-sky-800",children:j.explanation})]})]})})]})]},j.id)}),e.jsxs("footer",{className:`shrink-0 relative z-[60] flex flex-col items-center justify-center p-4 sm:p-6 ${lt.gradient} rounded-t-[32px] sm:rounded-t-[40px] shadow-[0_-10px_40px_rgba(0,0,0,0.15)]`,children:[e.jsx("div",{className:"absolute inset-0 z-0 pointer-events-none opacity-20",children:Te.slice(0,3).map((w,v)=>e.jsx("div",{className:"absolute text-white",style:{top:`${20+v*20}%`,left:`${20+v*30}%`,transform:`rotate(${v*30}deg) scale(1.5)`},children:e.jsx(w,{size:32})},v))}),e.jsx("div",{className:"relative z-10 flex flex-col gap-3",children:L?.resolved?pe?e.jsxs("button",{onClick:ot,className:"bg-orange-500 hover:bg-orange-600 text-white font-extrabold text-lg px-8 py-4 rounded-full flex items-center justify-center gap-3 shadow-xl hover:scale-[1.02] active:scale-[0.98] transition-all w-full",children:["Next Question ",e.jsx(Ye,{size:24})]}):e.jsxs("div",{className:"flex flex-wrap justify-center gap-3 sm:gap-4",children:[e.jsxs("button",{onClick:()=>{xe||he(!0)},disabled:xe,className:"bg-white hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx("img",{src:"/mascot/modules_avatar.png",className:"w-5 h-5 drop-shadow-sm",alt:"Explain"}),"Explain"]}),e.jsxs("button",{onClick:ot,className:"bg-orange-500 hover:bg-orange-600 text-white font-extrabold text-lg px-8 py-3 sm:py-3.5 rounded-full flex items-center justify-center gap-2 shadow-xl hover:scale-105 active:scale-95",children:["Next Question ",e.jsx(Ye,{size:20})]})]}):e.jsxs("div",{className:"flex flex-wrap justify-center gap-3 sm:gap-4",children:[e.jsxs("button",{onClick:gt,disabled:me<=0||Qe<=0,className:"bg-white hover:bg-slate-50 disabled:opacity-70 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx("img",{src:"/icons/quiz_key.png",alt:"Hint",className:"w-5 h-5 object-contain"}),"Hint"]}),e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:nt,disabled:ie,className:"bg-white hover:bg-slate-50 disabled:opacity-70 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200",children:[e.jsx(Ut,{size:18,className:"text-purple-500"}),"Reveal"]}),ie&&K!==null&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-1.5 bg-slate-800 text-white text-[11px] rounded-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none font-medium",children:"Reveal locked. Give it another try!"})]}),e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{disabled:!0,className:"bg-white disabled:opacity-50 disabled:cursor-not-allowed text-slate-700 font-bold px-6 sm:px-8 py-3 sm:py-3.5 rounded-full flex items-center gap-2 shadow-lg border border-slate-200",children:[e.jsx(rs,{size:16,className:"text-slate-400"}),"Explain"]}),e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-1.5 bg-slate-800 text-white text-[11px] rounded-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none font-medium",children:"Unlocks after you complete or reveal this question"})]}),e.jsx("button",{onClick:()=>Ce(w=>!w),className:`w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center shadow-lg transition-transform hover:scale-105 active:scale-95 border border-slate-200 ${ze?"bg-purple-100 text-purple-600 border-purple-300":"bg-white hover:bg-slate-50 text-slate-700"}`,children:e.jsx(pt,{size:20})}),j.type==="fill-in-blank"&&e.jsxs("button",{onClick:()=>Ve(),disabled:!F.trim()||Ee,className:"bg-orange-500 hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed text-white font-extrabold text-lg px-8 py-3 sm:py-3.5 rounded-full flex items-center justify-center gap-2 shadow-xl hover:scale-105 active:scale-95",children:["Submit ",e.jsx(Ye,{size:20})]})]})})]})]})]}):null},sl=[{id:1,type:"multiple-choice",question:"What is the value of π (pi) to two decimal places?",options:["3.12","3.14","3.16","3.18"],correctAnswer:"3.14",explanation:"π ≈ 3.14159..., so to two decimal places it is 3.14."},{id:2,type:"true-false",question:"The sum of angles in a triangle is 180 degrees.",correctAnswer:"True",explanation:"The interior angles of any Euclidean triangle sum to 180°."},{id:3,type:"fill-in-blank",question:"If 2x + 5 = 13, then x = ___.",correctAnswer:"4",explanation:"2x = 13 - 5 = 8 → x = 4."},{id:4,type:"multiple-choice",question:"Which of the following is a prime number?",options:["9","15","17","21"],correctAnswer:"17",explanation:"17 is only divisible by 1 and itself. 9=3×3, 15=3×5, 21=3×7."},{id:5,type:"true-false",question:"The slope of a horizontal line is zero.",correctAnswer:"True",explanation:"A horizontal line has no rise, so rise/run = 0."},{id:6,type:"fill-in-blank",question:"The square root of 144 is ___.",correctAnswer:"12",explanation:"12 × 12 = 144, so √144 = 12."}];async function al(t){const{lessonTitle:s,topic:l,subjectId:n,competencyCode:i,questionCount:c=6}=t,r=ll(n)||"General Mathematics",x=t.lessonId?Math.abs(t.lessonId.split("").reduce((d,h)=>Math.imul(31,d)+h.charCodeAt(0)|0,0))%1e6:Math.floor(Math.random()*1e6);try{const d=await rt("/api/quiz/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:l||s,subject:r,lessonTitle:s,questionCount:c,questionTypes:["multiple-choice","true-false","fill-in-blank"],difficulty:"medium",competencyCode:i,varianceSeed:x})});return!d.questions||d.questions.length===0?(console.warn("[lessonQuizService] API returned empty questions, using fallback"),zs(c)):d.questions.map(h=>({id:h.id,type:h.type,question:h.question,options:h.options||void 0,correctAnswer:h.correctAnswer,explanation:h.explanation,hints:h.hints||[],bloomLevel:h.bloomLevel||"remember"}))}catch(d){return console.error("[lessonQuizService] Failed to generate quiz via API:",d),console.warn("[lessonQuizService] Using fallback questions"),zs(c)}}function rl(t){return 6}function ll(t){if(!t)return null;const s=t.toLowerCase();return s.includes("gen-math")||s.includes("gen_math")?"General Mathematics":s.includes("stats")||s.includes("prob")?"Statistics and Probability":s.includes("pre-calc")||s.includes("pre_calc")?"Pre-Calculus":s.includes("basic-calc")||s.includes("basic_calc")||s.includes("calculus")?"Basic Calculus":null}function zs(t){const s=[...sl].sort(()=>Math.random()-.5);return s.slice(0,Math.min(t,s.length)).map((l,n)=>({...l,id:n+1}))}const nl="rag_lesson_";function ds(t){return`${nl}${t}`}function il(t){try{const s=sessionStorage.getItem(ds(t));if(s)return JSON.parse(s)}catch{}return null}function ol(t,s){try{sessionStorage.setItem(ds(t),JSON.stringify(s))}catch{}}function cl(t,s,l=!0){const[n,i]=a.useState([]),[c,r]=a.useState(!0),[x,d]=a.useState(null),[h,S]=a.useState([]),[m,z]=a.useState("low"),[p,u]=a.useState(0),[k,f]=a.useState(!1),[C,N]=a.useState(void 0),[R,T]=a.useState(!1),F=a.useCallback(async()=>{if(!l||!t)return;const Z=il(t);if(Z){i(Z.sections),S(Z.sources),z(Z.retrievalBand),u(Z.retrievalConfidence),f(Z.needsReview),N(Z.activeModel),r(!1),d(null),T(!1);return}r(!0),d(null),T(!1);try{const te=(await St(()=>import("./vendor-firebase-auth-T_wvTOvf.js"),__vite__mapDeps([4,3])).then(pe=>pe.getAuth().currentUser))?.uid,$=await ja({...s,lessonId:t,userId:te});i($.sections),S($.sources||[]),z($.retrievalBand),u($.retrievalConfidence),f($.needsReview),N($.activeModel),ol(t,$),d(null),T(!1)}catch(Y){const te=Y.status||Y.response?.status,$=Y.body||Y.response;let pe="Failed to load lesson content.",he=!1;te===404&&$?.error==="no_curriculum_context"?(pe=$.message||"Lesson source PDF not found or not yet ingested.",he=!0):te===401?pe="Please sign in again to access lessons.":navigator.onLine||(pe="No internet connection. Please try again when online.",he=!0),d(pe),T(he),i([])}finally{r(!1)}},[t,l,JSON.stringify(s)]);a.useEffect(()=>{F()},[F]);const X=a.useCallback(()=>{t&&sessionStorage.removeItem(ds(t)),r(!0),d(null),F()},[F,t]);return{sections:n,isLoading:c,error:x,retry:X,sources:h,retrievalBand:m,retrievalConfidence:p,needsReview:k,activeModel:C,isOffline:R}}const Qs=/[=×÷±√∑∫π²³%]/,dl=/^(Definition|Formula|Note|Reminder|Important|Example|Key Concept|Concept|Rule|Theorem|Property|Step)s?\s*:/i;function dt(t){return t.replace(/\b([A-Z][a-zA-Z\s]{2,30}?)\s+(is|are|refers to|defined as|means)\b/g,(s,l,n)=>`**${l.trim()}** ${n}`).replace(/"([^"]{3,40})"/g,(s,l)=>`**${l}**`)}function Vt(t){if(!t?.trim())return null;const s=t.split(` +`),l=[];let n=[],i=[],c=[],r=0;const x=()=>{if(n.length===0)return;const u=n.join(" ").trim();if(!u){n=[];return}const k=u.match(/[^.!?]+[.!?]+["']?/g)||[u],f=[];let C=[],N=0;for(const R of k)C.push(R),N+=R.length,N>220&&(f.push(C),C=[],N=0);C.length&&f.push(C);for(const R of f){const T=dt(R.join(" ").trim());l.push(e.jsx("p",{className:"lesson-body-text text-slate-700 leading-[1.8] text-[1rem] font-body",children:$e(T)},r++))}n=[]},d=()=>{i.length!==0&&(l.push(e.jsx("ul",{className:"space-y-2.5 my-1 pl-1",children:i.map((u,k)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-700 text-[0.95rem] leading-[1.75] font-body",children:[e.jsx("span",{className:"mt-[0.5rem] w-2 h-2 rounded-full bg-[#1a85a4] flex-shrink-0"}),e.jsx("span",{children:$e(dt(u))})]},k))},r++)),i=[])},h=()=>{c.length!==0&&(l.push(e.jsx("ol",{className:"space-y-2.5 my-1 list-none pl-1",children:c.map((u,k)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-700 text-[0.95rem] leading-[1.75] font-body",children:[e.jsx("span",{className:"mt-0.5 min-w-[1.5rem] h-[1.5rem] rounded-full bg-[#1a85a4] text-white text-[0.7rem] font-bold flex items-center justify-center flex-shrink-0",children:k+1}),e.jsx("span",{children:$e(dt(u))})]},k))},r++)),c=[])},S=u=>/^[\-•\*]\s+/.test(u.trim()),m=u=>/^\d+[\.\)]\s+/.test(u.trim()),z=u=>Qs.test(u)&&u.trim().length<120,p=u=>{const k=u.toLowerCase();return/formula|theorem|property|rule/.test(k)?{bg:"bg-amber-50",border:"border-amber-300",text:"text-amber-900",label:"📐"}:/definition|concept|key/.test(k)?{bg:"bg-blue-50",border:"border-blue-300",text:"text-blue-900",label:"📖"}:/note|reminder|important/.test(k)?{bg:"bg-rose-50",border:"border-rose-300",text:"text-rose-900",label:"⚠️"}:/example|step/.test(k)?{bg:"bg-emerald-50",border:"border-emerald-300",text:"text-emerald-900",label:"✏️"}:{bg:"bg-slate-50",border:"border-slate-300",text:"text-slate-800",label:"💡"}};for(const u of s){const k=u.trimEnd(),f=k.trim();if(f===""){d(),h(),x();continue}const C=f.match(dl);if(C){d(),h(),x();const N=C[1],R=f.slice(C[0].length).trim(),T=p(N);l.push(e.jsxs("div",{className:`rounded-xl px-4 py-3.5 border-l-4 ${T.bg} ${T.border} my-1`,children:[e.jsxs("p",{className:`text-[0.75rem] font-black uppercase tracking-widest mb-1.5 ${T.text} opacity-80 font-display`,children:[T.label," ",N]}),e.jsx("p",{className:`text-[0.95rem] leading-[1.75] font-semibold font-body ${T.text}`,children:$e(R)})]},r++));continue}if(S(f)){x(),h(),i.push(f.replace(/^[\-•\*]\s+/,""));continue}if(m(f)){x(),d(),c.push(f.replace(/^\d+[\.\)]\s+/,""));continue}if(z(f)&&!/[a-z]{5,}/.test(f)){d(),h(),x(),l.push(e.jsx("div",{className:"lesson-formula-box my-3",children:f},r++));continue}if(f.endsWith(":")&&f.length<80&&!f.startsWith(" ")){d(),h(),x(),l.push(e.jsx("p",{className:"lesson-section-heading text-[#1a85a4] text-[1.05rem] mt-5 mb-1 border-b-2 border-[#1a85a4]/20 pb-1.5",children:$e(f)},r++));continue}d(),h(),n.push(k)}return d(),h(),x(),e.jsx("div",{className:"space-y-3",children:l})}function $e(t){const s=[],l=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`|==(.+?)==)/g;let n=0,i,c=0;for(;(i=l.exec(t))!==null;)i.index>n&&s.push(e.jsx(Fe.Fragment,{children:t.slice(n,i.index)},c++)),i[2]?s.push(e.jsx("strong",{className:"font-extrabold text-[#1a85a4] bg-[#e0f4fa] px-1 py-0.5 rounded-md font-body",children:i[2]},c++)):i[3]?s.push(e.jsx("em",{className:"italic text-slate-500 font-body",children:i[3]},c++)):i[4]?s.push(e.jsx("code",{className:"px-1.5 py-0.5 bg-slate-100 rounded text-[0.85em] font-mono text-[#e66a5e] border border-slate-200 font-semibold",children:i[4]},c++)):i[5]&&s.push(e.jsx("mark",{className:"bg-[#fff3cd] text-[#92400e] px-1 py-0.5 rounded-md font-bold border-b-2 border-[#fbbf24]",children:i[5]},c++)),n=i.index+i[0].length;return n0?e.jsx(e.Fragment,{children:s}):t}function ml(t){if(!t?.trim())return{welcome:"",objectives:[]};const s=t.split(` +`).map(x=>x.trim()).filter(Boolean),l=/^(\d+[\.\)]\s+|[-•*]\s+|(Identify|Write|Set|Use|Apply|Solve|Compute|Calculate|Determine|Understand|Describe|Explain|Analyze|Evaluate|Create|Define|Distinguish|Compare|Illustrate|Demonstrate|Perform|Simplify|Represent|Model|Interpret|Recognize|Classify|Construct|Derive|Formulate|Graph|Sketch|Verify|Prove|Estimate|Approximate|Convert|Translate|Predict|Justify|Generalize|Extend|Develop|Explore|Investigate|Discover|Observe|Measure|Record|Report|Present|Communicate|Collaborate|Reflect|Review|Summarize|Conclude|Infer|Hypothesize|Test|Experiment|Design|Plan|Implement|Evaluate|Assess|Monitor|Adjust|Improve|Optimize|Innovate|Create|Produce|Publish|Share|Teach|Learn|Practice|Apply|Transfer|Connect|Integrate|Synthesize|Analyze|Evaluate|Create)\b)/i,n=/^(Example:|e\.g\.|For example:|Sample:|\()/i,i=[],c=[];let r=!1;for(let x=0;x0&&t.callouts.map((u,k)=>e.jsxs("div",{className:`lesson-callout-headsup flex items-start gap-3.5 ${u.type==="tip"?"!bg-gradient-to-r !from-emerald-50 !to-teal-50 !border-emerald-400":""}`,children:[e.jsx("div",{className:`w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5 shadow-sm ${u.type==="tip"?"bg-emerald-500":"bg-amber-500"}`,children:e.jsx(ct,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 ${u.type==="tip"?"text-emerald-600":"text-amber-600"}`,children:u.type==="tip"?"✨ Tip":u.type==="important"?"⚠️ Heads Up":"📌 Note"}),e.jsx("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:u.text})]})]},k)),(!t.callouts||t.callouts.length===0)&&e.jsxs("div",{className:"lesson-callout-headsup flex items-start gap-3.5",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-amber-500 flex items-center justify-center flex-shrink-0 mt-0.5 shadow-sm",children:e.jsx(ct,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 text-amber-600",children:"⚠️ Heads Up"}),e.jsxs("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:["This lesson has ",7," sections and takes about 20 minutes to complete. Grab a pen — you might want to take notes along the way!"]})]})]}),z.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(at,{size:20,className:"text-violet-500"}),e.jsx("h3",{className:"lesson-section-heading text-[1.05rem]",style:{color:"#7c3aed"},children:"What you'll learn"})]}),e.jsx("div",{className:"space-y-2.5",children:z.map((u,k)=>{const f=_s[k%_s.length];return e.jsxs("div",{className:`rounded-xl border-2 px-4 py-3.5 flex items-start gap-3.5 ${f.bg} ${f.border} shadow-sm`,children:[e.jsx("span",{className:`mt-0.5 min-w-[1.75rem] h-7 rounded-full ${f.num} text-white text-[0.7rem] font-black flex items-center justify-center flex-shrink-0 shadow-sm`,children:k+1}),e.jsxs("div",{children:[e.jsx("p",{className:`font-body text-[0.95rem] font-semibold leading-snug ${f.text}`,children:$e(dt(u.text))}),u.example&&e.jsx("p",{className:`text-xs mt-1 ${f.ex} font-mono font-semibold`,children:u.example})]})]},k)})})]})]})}case"key_concepts":return e.jsxs("div",{className:"space-y-4",children:[t.content?.trim()?e.jsx("div",{className:"mb-4",children:Vt(t.content)}):e.jsx("p",{className:"text-slate-400 text-sm italic mb-4",children:"Key concepts are being compiled. Review the curriculum sources below for reference material."}),t.callouts&&t.callouts.length>0&&e.jsx("div",{className:"space-y-3",children:t.callouts.map((m,z)=>e.jsxs("div",{className:`rounded-xl border-2 px-5 py-4 flex items-start gap-3.5 shadow-sm ${m.type==="important"?"bg-rose-50 border-rose-300":m.type==="tip"?"bg-emerald-50 border-emerald-300":"bg-amber-50 border-amber-300"}`,children:[e.jsx("div",{className:`w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5 shadow-sm ${m.type==="important"?"bg-rose-500":m.type==="tip"?"bg-emerald-500":"bg-amber-500"}`,children:e.jsx(ct,{size:16,className:"text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:`lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 ${m.type==="important"?"text-rose-500":m.type==="tip"?"text-emerald-600":"text-amber-600"}`,children:m.type==="important"?"🔑 Important":m.type==="tip"?"✨ Tip":"📌 Note"}),e.jsx("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:$e(m.text)})]})]},z))})]});case"video":return e.jsxs("div",{className:"space-y-4",children:[t.content?.trim()?e.jsx("p",{className:"text-slate-600 text-sm",children:t.content}):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"Video explanation loading..."}),e.jsx(va,{videos:t.videos||[],topic:i.title})]});case"worked_examples":return e.jsx("div",{className:"space-y-5",children:t.examples&&t.examples.length>0?t.examples.map((m,z)=>e.jsxs("div",{className:"bg-gradient-to-br from-rose-50 via-orange-50 to-amber-50 rounded-2xl p-5 border-2 border-rose-200 shadow-md",children:[e.jsxs("div",{className:"flex items-start gap-3.5 mb-4",children:[e.jsx("div",{className:"w-10 h-10 bg-gradient-to-br from-rose-500 to-orange-500 rounded-xl flex items-center justify-center flex-shrink-0 shadow-md",children:e.jsx(pt,{size:18,className:"text-white"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] text-rose-400 mb-1",children:["Example ",z+1]}),e.jsx("p",{className:"font-body font-bold text-slate-800 text-[1rem] leading-snug",children:m.problem})]})]}),m.steps.length>0&&e.jsxs("div",{className:"ml-14 space-y-2.5 mb-3",children:[e.jsx("p",{className:"lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] text-slate-400 mb-1.5",children:"Solution"}),m.steps.map((p,u)=>Qs.test(p)&&p.length<100&&!/[a-z]{6,}/.test(p)?e.jsx("div",{className:"lesson-formula-box",children:p},u):e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 min-w-[1.5rem] h-[1.5rem] rounded-full bg-white border-2 border-rose-300 text-rose-500 text-[0.65rem] font-black flex items-center justify-center flex-shrink-0 shadow-sm",children:u+1}),e.jsx("p",{className:"font-body text-slate-700 text-[0.95rem] leading-[1.75]",children:$e(p)})]},u))]}),m.answer&&e.jsxs("div",{className:"ml-14 flex items-center gap-3 mt-3 pt-3 border-t-2 border-rose-200",children:[e.jsx("div",{className:"px-3.5 py-1.5 bg-gradient-to-r from-rose-500 to-orange-500 rounded-lg text-white text-[0.65rem] font-black uppercase tracking-widest flex-shrink-0 shadow-sm",children:"Answer"}),e.jsx("p",{className:"font-body text-slate-800 text-[0.95rem] font-bold",children:m.answer})]})]},z)):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"No worked examples available for this lesson."})});case"important_notes":return e.jsx("div",{className:"space-y-3",children:t.bulletPoints&&t.bulletPoints.length>0?t.bulletPoints.map((m,z)=>{const p=m.match(/^(Note|Important|Remember|Warning|Tip|Key|Formula|Rule)\s*:/i);if(p){const u=p[1],k=m.slice(p[0].length).trim(),f=/note|important|warning|remember/i.test(u);return e.jsxs("div",{className:`rounded-xl px-5 py-4 border-l-4 flex items-start gap-3.5 shadow-sm ${f?"bg-rose-50 border-rose-400":"bg-amber-50 border-amber-400"}`,children:[e.jsx(ct,{size:18,className:`mt-0.5 flex-shrink-0 ${f?"text-rose-500":"text-amber-500"}`}),e.jsxs("div",{children:[e.jsx("p",{className:`lesson-section-heading text-[0.65rem] uppercase tracking-[0.2em] mb-1 ${f?"text-rose-500":"text-amber-600"}`,children:u}),e.jsx("p",{className:"font-body text-[0.95rem] text-slate-700 leading-[1.75] font-medium",children:$e(dt(k))})]})]},z)}return e.jsxs("div",{className:"flex items-start gap-3.5 p-4 rounded-xl bg-slate-50 border-2 border-slate-200 hover:border-[#1a85a4]/40 hover:bg-[#f0fbff] transition-colors",children:[e.jsx("div",{className:"mt-0.5 w-6 h-6 rounded-full bg-[#1a85a4] flex items-center justify-center flex-shrink-0 shadow-sm",children:e.jsx("span",{className:"text-white text-[0.65rem] font-black",children:z+1})}),e.jsx("p",{className:"font-body text-slate-700 text-[0.95rem] leading-[1.75] font-medium",children:$e(dt(m))})]},z)}):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"No notes available for this lesson."})});case"try_it_yourself":return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-col items-center text-center gap-3 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center shadow-lg",style:{background:"#9956DE"},children:e.jsx(at,{size:32,className:"text-white"})}),e.jsx("h3",{className:"text-xl font-black",style:{color:"#9956DE"},children:"Try It Yourself"}),e.jsx("p",{className:"text-slate-500 text-sm max-w-xs leading-relaxed",children:"Now it's your turn! Try applying what you've learned. You can practice with the exercises at the end of this module."})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-xl px-4 py-3 border",style:{background:"#f5eeff",borderColor:"#d4aaff"},children:[e.jsx(ct,{size:16,className:"mt-0.5 shrink-0",style:{color:"#9956DE"}}),e.jsxs("p",{className:"text-sm",style:{color:"#7a3db8"},children:[e.jsx("span",{className:"font-bold",children:"Tip:"})," Complete the practice quizzes after this lesson to reinforce your learning!"]})]}),c&&e.jsx("div",{className:"bg-white rounded-2xl p-5 border border-slate-200 shadow-sm",children:r?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center",children:e.jsx(at,{size:20,className:"text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-emerald-700",children:["Quiz Complete",typeof x=="number"&&e.jsxs("span",{className:"ml-2 text-emerald-600",children:[x,"%"]})]}),e.jsx("p",{className:"text-xs text-emerald-600/80",children:"Great job! You can now complete this lesson."})]})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-widest mb-1",style:{color:"#9956DE"},children:"Practice Quiz"}),e.jsx("p",{className:"font-bold text-slate-800 text-sm",children:c.title}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[c.questions," questions · ",c.duration]})]}),e.jsx("button",{onClick:d,className:"w-full sm:w-auto px-6 py-2.5 rounded-xl bg-[#1a85a4] text-white text-sm font-black hover:bg-[#126b84] transition-colors shadow-md uppercase tracking-wide",children:"Start Practice"})]})}),!c&&e.jsxs("button",{onClick:S,className:"w-full flex items-center justify-between gap-4 text-white rounded-2xl px-6 py-4 shadow-lg transition-all hover:shadow-xl hover:scale-[1.01] active:scale-[0.99] group",style:{background:"#9956DE"},onMouseEnter:m=>m.currentTarget.style.background="#8744cc",onMouseLeave:m=>m.currentTarget.style.background="#9956DE",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center shrink-0",children:e.jsx(Va,{size:22,className:"text-white"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-black text-sm uppercase tracking-wide",children:"Start Practice Quiz"}),e.jsx("p",{className:"text-white/80 text-xs mt-0.5",children:"10 questions · AI-generated"})]})]}),e.jsx(Ye,{size:20,className:"text-white/80 group-hover:translate-x-1 transition-transform"})]})]});case"summary":return e.jsx("div",{className:"space-y-3",children:t.content?.trim()?Vt(t.content):e.jsx("p",{className:"text-slate-400 text-sm italic",children:"Summary is being prepared. Review the lesson sections above to reinforce your understanding."})});default:return e.jsx("p",{className:"text-slate-500 text-sm italic",children:"Section content not available."})}}const Nt=[{type:"introduction",label:"Intro",helper:"Welcome note",icon:ht,accent:"from-[#1a85a4] to-[#126b84]",tint:"bg-[#1a85a4] text-white border-transparent",tabBg:"bg-[#1a85a4]"},{type:"key_concepts",label:"Concepts",helper:"Core ideas",icon:or,accent:"from-[#fbab41] to-[#e0983a]",tint:"bg-[#fbab41] text-white border-transparent",tabBg:"bg-[#fbab41]"},{type:"video",label:"Video",helper:"Watch and learn",icon:ct,accent:"from-[#e66a5e] to-[#ce5e53]",tint:"bg-[#e66a5e] text-white border-transparent",tabBg:"bg-[#e66a5e]"},{type:"worked_examples",label:"Examples",helper:"Guided solving",icon:Ma,accent:"from-[#7ec16d] to-[#71ad62]",tint:"bg-[#7ec16d] text-white border-transparent",tabBg:"bg-[#7ec16d]"},{type:"important_notes",label:"Notes",helper:"Key reminders",icon:dr,accent:"from-[#9a67d0] to-[#8a5cc0]",tint:"bg-[#9a67d0] text-white border-transparent",tabBg:"bg-[#9a67d0]"},{type:"try_it_yourself",label:"Practice",helper:"Try it yourself",icon:We,accent:"from-[#eb74a6] to-[#d46895]",tint:"bg-[#eb74a6] text-white border-transparent",tabBg:"bg-[#eb74a6]"},{type:"summary",label:"Summary",helper:"Wrap-up",icon:zt,accent:"from-[#48bca6] to-[#40a794]",tint:"bg-[#48bca6] text-white border-transparent",tabBg:"bg-[#48bca6]"}],hl=({lesson:t,lessonCompletionXP:s=10,practiceQuiz:l,practiceQuizCompleted:n=!1,practiceQuizScore:i,initialSection:c=0,nextContentLabel:r,onStartPractice:x,onBack:d,onComplete:h,onProgressUpdate:S,onTryItQuizComplete:m,onContinueLearning:z})=>{const{userProfile:p}=Qt(),[u,k]=a.useState(0),[f,C]=a.useState(1),[N,R]=a.useState(!1),[T,F]=a.useState(null),[X,Z]=a.useState(!1),[Y,te]=a.useState(null),[$,pe]=a.useState(!1),[he]=a.useState(()=>`tiy-${Date.now()}`);a.useEffect(()=>{!X||Y||(pe(!0),al({lessonId:t.id?.toString()||"unknown",lessonTitle:t.title,topic:t.title,subjectId:t.subjectId,competencyCode:t.competencyCode,questionCount:15}).then(D=>te(D)).catch(D=>{console.error("[LessonViewer] Quiz generation failed:",D),Z(!1)}).finally(()=>pe(!1)))},[X,Y,t]);const[ze,Ce]=a.useState(!1),b={topic:t.title,subject:t.subject||"General Mathematics",quarter:t.quarter||1,lessonTitle:t.title,moduleId:t.subjectId,lessonId:t.id,competencyCode:t.competencyCode,learnerLevel:"Grade 11-12",storagePath:t.storagePath},{sections:Q,isLoading:ce,error:ae,retry:le,sources:ge,retrievalBand:Ne,activeModel:B,isOffline:Ee}=cl(t.id,b,!0),[_e,ye]=a.useState(null);a.useEffect(()=>{if(Q.length>0){const D=Q.find(ne=>ne.type==="introduction");if(D?.title){const me=D.title.replace(/^Introduction\s+(to|-|:|—)\s+/i,"").replace(/\s*[-:—]\s*Introduction$/i,"").replace(/\s+Introduction$/i,"").trim();me&&me.toLowerCase()!=="introduction"&&ye(me)}}},[Q]),a.useEffect(()=>{Q.length>0&&p?.uid&&t.id&&_a(p.uid,t.id,_e||t.title).catch(()=>{})},[Q.length,p?.uid,t.id,_e,t.title]);const fe=Q.length||Nt.length;if(a.useEffect(()=>{c>=0&&c{const D=Q.findIndex(ne=>ne.type==="try_it_yourself");c===-1&&D>=0&&k(D)},[Q,c]),a.useEffect(()=>{const D=fe>0?(u+1)/fe*100:0;S?.(D)},[u,fe,S]),ce)return e.jsx(xl,{});if(ae&&Q.length===0)return e.jsx(ul,{message:ae,onRetry:le,isOffline:Ee});const Me=String(t.id||"").match(/\d+/);if(Me&&Me[0],X)return $||!Y?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-white rounded-2xl p-6 flex flex-col items-center gap-3 shadow-xl",children:[e.jsx("div",{className:"w-10 h-10 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"}),e.jsx("p",{className:"font-bold text-slate-700",children:"Generating Quiz..."})]})}):e.jsx(tl,{questions:Y,lessonTitle:t.title,subject:t.subject||"General Mathematics",sessionId:he,userId:p?.uid,onBack:()=>{Z(!1),te(null)},onComplete:D=>{m?.(D),Ce(!0),Z(!1),te(null)}});const Ae=Q[u]||{type:"introduction",title:"Loading...",content:"Lesson content is loading. Please wait a moment."},g=()=>{uD+1)):(!l||n)&&R(!0)},q=()=>{u>0&&(C(-1),k(D=>D-1))},M=D=>{R(!1),h(void 0,void 0,D)},O=!!(l&&!n||!ze),I=Nt[u]||Nt[0],J=I.icon,be=e.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-slate-50 overflow-hidden font-sans",children:[e.jsx("header",{className:"flex-none bg-transparent px-3 sm:px-6 pt-2 sm:pt-3 md:pt-4 pb-2 sm:pb-3 sm:py-4 relative z-40",children:e.jsxs("div",{className:"max-w-[90rem] mx-auto flex items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx("button",{onClick:d,className:"w-9 h-9 sm:w-10 sm:h-10 rounded-full bg-white border border-slate-200 hover:bg-slate-50 flex items-center justify-center text-slate-600 transition-colors flex-shrink-0 shadow-sm","aria-label":"Go back",children:e.jsx(es,{size:16})}),e.jsxs("div",{className:"min-w-0 flex flex-col justify-center flex-1",children:[e.jsxs("div",{className:"hidden sm:flex items-center gap-1.5 sm:gap-2 text-[9px] sm:text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-0.5",children:[e.jsx(qe,{size:10}),e.jsx("span",{children:"NOTEBOOK"}),B&&e.jsx("span",{className:"text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded font-mono",children:B.split("/").pop()}),Ne==="high"&&e.jsx("span",{className:"text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded text-[10px] font-semibold border border-emerald-200",children:"DepEd Source"})]}),e.jsxs("div",{className:"flex sm:hidden items-center gap-1 text-[9px] font-bold text-slate-400 uppercase tracking-widest mb-0.5",children:[e.jsx(qe,{size:9}),e.jsx("span",{children:"Notebook"}),Ne==="high"&&e.jsx("span",{className:"text-emerald-600 bg-emerald-50 px-1 py-0.5 rounded text-[8px] font-semibold border border-emerald-200 leading-none",children:"DepEd"})]}),e.jsx("h1",{className:"font-bold text-slate-800 text-xs sm:text-sm truncate",children:t.title})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[e.jsxs("div",{className:"text-right hidden sm:block",children:[e.jsx("p",{className:"text-[10px] font-bold text-slate-500 uppercase tracking-wider",children:"Progress"}),e.jsxs("p",{className:"text-sm font-bold text-slate-800",children:[Math.round((u+1)/fe*100),"%"]})]}),e.jsx("div",{className:"w-12 sm:w-24 md:w-32 h-1.5 sm:h-2 bg-slate-200 rounded-full overflow-hidden",children:e.jsx(E.div,{className:"h-full bg-[#7ec16d] rounded-full",animate:{width:`${(u+1)/fe*100}%`},transition:{duration:.25}})})]})]})}),e.jsx("main",{className:"flex-1 overflow-hidden px-2 sm:px-5 pb-2 relative flex justify-center min-h-0",children:e.jsxs("div",{className:"w-full max-w-[90rem] h-full relative flex md:pl-16 pt-10 sm:pt-10 md:pt-0",children:[e.jsx("div",{className:"hidden md:flex absolute left-0 top-8 bottom-8 w-20 flex-col justify-between z-0 py-2",children:Nt.map((D,ne)=>{const me=ne===u,Ge=D.icon;return e.jsxs("button",{onClick:()=>{C(ne>u?1:-1),k(ne)},className:Mt("group relative flex items-center justify-start pl-4 rounded-l-[1.5rem] transition-all duration-300 shadow-sm border-r-0 flex-shrink-0",D.tabBg,me?"w-24 h-20 -translate-x-4 shadow-xl z-20 brightness-105":"w-16 h-16 hover:w-24 hover:h-20 hover:-translate-x-4 hover:brightness-110 opacity-90 hover:opacity-100 z-10"),"aria-label":`Go to ${D.label} section`,children:[e.jsx("div",{className:Mt("transition-all duration-300 rounded-xl",me?"bg-white/30 p-2.5":"bg-white/20 p-2 group-hover:bg-white/30 group-hover:p-2.5"),children:e.jsx(Ge,{size:me?24:20,className:"text-white transition-transform duration-300 group-hover:scale-110"})}),e.jsxs("div",{className:"absolute right-full mr-3 px-3 py-1.5 bg-slate-800 text-white text-xs font-bold rounded-lg opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity whitespace-nowrap z-[100] shadow-xl border border-slate-700/50",children:[e.jsx("div",{className:"absolute top-1/2 -right-1 -translate-y-1/2 w-2 h-2 bg-slate-800 rotate-45 border-r border-t border-slate-700/50"}),D.label]})]},D.type)})}),e.jsx("div",{className:"md:hidden absolute left-0 right-0 top-0 z-30 bg-slate-100/95 backdrop-blur-sm",children:e.jsx("div",{className:"flex gap-0.8 overflow-x-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden px-1",children:Nt.map((D,ne)=>{const me=ne===u,Ge=D.icon;return e.jsxs("button",{onClick:()=>{C(ne>u?1:-1),k(ne)},className:Mt("flex items-center gap-1.5 px-3 py-2 rounded-t-lg transition-all duration-200 shrink-0 text-[11px] font-bold touch-manipulation min-h-[2.5rem]",me?`${D.tabBg} text-white shadow-md`:"bg-slate-200/80 text-slate-500"),children:[e.jsx(Ge,{size:14}),e.jsx("span",{children:D.label})]},D.type)})})}),e.jsxs("div",{className:Mt("flex-1 min-w-0 rounded-none sm:rounded-lg shadow-2xl flex flex-col overflow-visible relative z-10 transition-colors duration-500",I.tabBg),children:[e.jsxs("div",{className:"px-3 sm:px-6 py-2 sm:py-3.5 flex items-center gap-2 sm:gap-4 text-white",children:[e.jsx("div",{className:"bg-white/20 p-1 sm:p-2 rounded-lg sm:rounded-xl shrink-0",children:e.jsx(J,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("h2",{className:"lesson-section-heading text-sm sm:text-xl md:text-2xl truncate",title:Ae.title,children:Ae.title}),e.jsx("p",{className:"text-white/90 text-[10px] sm:text-xs font-medium truncate mt-0.5 font-body",title:t.title,children:t.title})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 bg-[#fdfdfd] rounded-lg sm:rounded-[1.5rem] m-1 mt-0 relative overflow-hidden shadow-inner flex flex-col",children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none opacity-30",style:{backgroundImage:"linear-gradient(transparent 95%, #cbd5e1 95%)",backgroundSize:"100% 40px",backgroundPosition:"0 0"}}),e.jsx("div",{className:"absolute top-0 bottom-0 left-8 sm:left-12 md:left-16 w-[2px] bg-rose-300/60 pointer-events-none z-0"}),e.jsx("div",{className:"relative z-10 flex-1 min-h-0 overflow-y-auto px-3 sm:px-5 md:pl-20 md:pr-10 py-2 sm:py-6",children:e.jsx(Je,{mode:"wait",children:e.jsxs(E.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},transition:{duration:.2},className:"space-y-4 sm:space-y-6",children:[e.jsx("div",{className:"bg-white/90 backdrop-blur-sm rounded-xl sm:rounded-[1.5rem] p-4 sm:p-6 md:p-8 shadow-sm border border-slate-100/50 font-body",children:e.jsx(pl,{section:Ae,sectionIndex:u,onShowSolution:D=>F(T===D?null:D),expandedIndex:T,lesson:t,practiceQuiz:l,practiceQuizCompleted:n,practiceQuizScore:i,onStartPractice:x,lessonSpecificTopic:_e,onStartTryItQuiz:()=>Z(!0)})}),ge.length>0&&(p?.role==="admin"||p?.role==="teacher")&&e.jsxs("details",{className:"rounded-xl border border-slate-200 bg-white/90 backdrop-blur-sm px-4 py-3 text-xs text-slate-500 shadow-sm",children:[e.jsxs("summary",{className:"cursor-pointer font-semibold text-slate-600 hover:text-slate-800",children:[ge.length," source",ge.length>1?"s":""," used"]}),e.jsx("div",{className:"mt-2 space-y-1 pl-2",children:ge.slice(0,3).map((D,ne)=>e.jsxs("p",{className:"font-mono truncate",children:[D.source_file," p.",D.page," (",Math.round((D.score||0)*100),"%)"]},ne))})]})]},u)})},u)]})]})]})}),e.jsx("footer",{className:"bg-slate-50 border-t border-slate-100 px-3 sm:px-6 flex-shrink-0 relative z-50 w-full flex justify-center items-center py-1.5 sm:py-3",children:e.jsxs("div",{className:"w-full max-w-[90rem] flex flex-col items-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-4 sm:gap-8 w-full md:ml-16",children:[e.jsxs(Oe,{onClick:q,disabled:u===0,variant:"outline",className:"px-4 sm:px-5 py-2 sm:py-2 rounded-full font-bold text-xs sm:text-sm bg-white border-slate-200 text-slate-600 shadow-sm disabled:opacity-40 hover:bg-slate-50 transition-colors flex items-center gap-1 sm:gap-2 min-w-[2.5rem] min-h-[2.5rem] touch-manipulation",children:[e.jsx(es,{size:14}),e.jsx("span",{className:"hidden sm:inline",children:"Previous"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-slate-500 font-bold tabular-nums",children:[u+1," / ",fe]}),e.jsx(Oe,{onClick:g,disabled:u===fe-1&&O,className:"px-5 sm:px-7 py-2 sm:py-2 rounded-full font-bold text-xs sm:text-sm bg-[#7ec16d] text-white hover:bg-[#6ab359] shadow-md transition-colors disabled:opacity-40 flex items-center gap-1 sm:gap-2 min-w-[2.5rem] min-h-[2.5rem] touch-manipulation",children:u===fe-1?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden sm:inline",children:"Complete"}),e.jsx(at,{size:14})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden sm:inline",children:"Next"}),e.jsx(Ye,{size:14})]})})]}),u===fe-1&&O&&e.jsx("p",{className:"text-center text-[10px] sm:text-xs font-semibold text-amber-600 mt-2 sm:mt-3 md:ml-16",children:ze?"Complete the practice quiz first to unlock lesson completion.":"Complete the Try It Yourself quiz first to unlock lesson completion."})]})}),e.jsx(Je,{children:N&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-[100] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-4",children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"bg-white rounded-[2rem] p-8 max-w-sm w-full text-center shadow-2xl",children:[e.jsx("div",{className:"w-20 h-20 bg-[#7ec16d] rounded-full flex items-center justify-center mx-auto mb-5 shadow-lg",children:e.jsx(at,{size:40,className:"text-white"})}),e.jsx("h2",{className:"text-2xl font-black text-slate-800 mb-2",children:"Lesson Complete!"}),e.jsxs("p",{className:"text-slate-500 text-sm mb-6 leading-relaxed",children:["Great job finishing ",e.jsx("strong",{className:"text-slate-700",children:t.title}),"."]}),e.jsxs("div",{className:"bg-emerald-50 rounded-2xl p-4 mb-6 border border-emerald-100",children:[e.jsx("div",{className:"flex items-center justify-center mb-1",children:e.jsx(zt,{className:"text-[#7ec16d]",size:22})}),e.jsx("p",{className:"text-xs text-[#7ec16d] font-bold uppercase tracking-wider mb-0.5",children:"XP Earned"}),e.jsxs("p",{className:"text-3xl font-black text-[#7ec16d]",children:["+",s]})]}),e.jsxs("div",{className:"space-y-2.5",children:[e.jsx("button",{onClick:()=>M(!0),disabled:O,className:"w-full py-3 rounded-xl font-bold text-sm bg-[#1a85a4] text-white hover:bg-[#126b84] transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:r||"Continue to Next Lesson"}),e.jsx("button",{onClick:()=>M(!1),className:"w-full py-3 rounded-xl font-bold text-sm bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors",children:"Back to Modules"})]})]})})})]}),ke=document.getElementById("modal-root")||document.body;return Gs.createPortal(be,ke)},fl={maxRetries:2,timeoutMs:9e4,baseBackoffMs:2e3},Hs=async t=>rt("/api/practice/generate",{method:"POST",body:JSON.stringify(t)},fl),bl=async t=>rt("/api/practice/submit",{method:"POST",body:JSON.stringify(t)}),gl=async t=>rt(`/api/practice/stats/${t}`,{method:"GET"});function yl({userProgress:t,userId:s,subjectId:l,moduleId:n,totalLessons:i,totalQuizzes:c}){const r=a.useMemo(()=>l?t?.subjects?.[l]?.modulesProgress?.[n]??null:null,[t,l,n]),x=a.useMemo(()=>new Set(r?.lessonsCompleted??[]),[r?.lessonsCompleted]),d=a.useMemo(()=>new Set(r?.quizzesCompleted??[]),[r?.quizzesCompleted]),h=a.useMemo(()=>!i&&!c?!1:x.size>=i&&d.size>=c,[x.size,d.size,i,c]),S=a.useCallback(f=>t?.lessons?.[f]??null,[t?.lessons]),m=a.useCallback(f=>t?.lessons?.[f]?.studyMaterialsCompleted===!0,[t?.lessons]),z=a.useCallback(f=>t?.lessons?.[f]?.quizCompleted===!0,[t?.lessons]),p=a.useCallback(f=>t?.lessons?.[f]?.quizScore,[t?.lessons]),u=a.useCallback(async f=>{if(!s)return;const C=mt(Ue,"progress",s);await Vs(C,{[`lessons.${f}.lessonId`]:f,[`lessons.${f}.studyMaterialsCompleted`]:!0,updatedAt:Ps()},{merge:!0})},[s]),k=a.useCallback(f=>{const C=t?.quizAttempts?.filter(R=>R.quizId===f);if(!C?.length)return null;const N=C[C.length-1];return{score:Math.round(N.score/10),total:10}},[t?.quizAttempts]);return{moduleProgress:r,completedLessonIds:x,completedQuizIds:d,isModuleCompleted:h,getLessonProgress:S,isStudyMaterialsCompleted:m,isLessonQuizCompleted:z,getLessonQuizScore:p,markStudyMaterialsComplete:u,getLastQuizScore:k}}const wl=({module:t,onBack:s,onEarnXP:l,isInQuizMode:n=!1,setIsInQuizMode:i})=>{const[r,x]=a.useState(null),{userProfile:d}=Qt(),[h,S]=a.useState(null),[m,z]=a.useState(!1),[p,u]=a.useState(null);a.useEffect(()=>{if(!d?.uid)return;(async()=>{try{const[q,M]=await Promise.all([Yt(mt(Ue,"diagnosticResults",d.uid)),Yt(mt(Ue,"competencyProfiles",d.uid))]),O=q.exists()&&q.data()?.status==="completed",I=M.exists()&&(M.data()?.overallScore??0)>0;z(O||I)}catch{z(!1)}})()},[d?.uid]);const k=a.useRef(l);a.useEffect(()=>{k.current=l},[l]);const f=a.useRef(r);a.useEffect(()=>{f.current=r},[r]),a.useEffect(()=>{try{const g=sessionStorage.getItem(`mathpulse_module_${t.id}_selectedLesson`);if(g){const{lessonId:q}=JSON.parse(g),M=t.lessons.find(O=>O.id===q);M&&x({lesson:M,type:"lesson"})}}catch{}},[]),a.useEffect(()=>{if(r?.type==="lesson"&&r.lesson)try{sessionStorage.setItem(`mathpulse_module_${t.id}_selectedLesson`,JSON.stringify({lessonId:r.lesson.id}))}catch{}else if(r===null)try{sessionStorage.removeItem(`mathpulse_module_${t.id}_selectedLesson`)}catch{}},[r,t.id]);const C=a.useMemo(()=>{const g=Number(t.id.split("-").pop());return Number.isFinite(g)&&g>0?g:1},[t.id]),N=a.useMemo(()=>{const g=t.subjectId;return g||(At.find(M=>M.modules.some(O=>O.id===t.id))?.id??null)},[t.id]),R=["#1FA7E1","#9956DE","#75D06A","#FFB356","#7274ED","#FF8B8B","#6ED1CF","#FB96BB"];a.useMemo(()=>{const g=t.subjectAccentColor;if(g)return g;const M=(N?At.find(I=>I.id===N):null)?.modules?.findIndex(I=>I.id===t.id)??0,O=M>=0?M:0;return R[O%R.length]},[t,t.id,N]),a.useEffect(()=>{if(d?.uid)return Zt(d.uid,S)},[d?.uid]),a.useEffect(()=>{if(!r||r.type!=="quiz"||!d?.uid)return;let g=!1;const M=At.find(O=>O.modules.some(I=>I.id===t.id))?.title??"General Mathematics";return(async()=>{try{const O=await Hs({userId:d.uid,subject:M,competency:r.quiz.title.replace(/^(Practice Quiz|Module Quiz):\s*/i,""),difficulty:r.quiz.type==="module"?"Challenge":"Practice",count:r.quiz.questions||5});if(g)return;const I=O.questions.filter(J=>J.options?.length&&J.correct_index>=0&&J.correct_index({id:J.id||"q-"+be,questionType:"multiple_choice",question:J.question,options:J.options,correctAnswer:J.options[J.correct_index],bloomLevel:J.bloom_level?.toLowerCase()||"understand",difficulty:"medium",topic:r.quiz.title,subject:M,points:10,explanation:J.explanation||""}));u(I)}catch(O){console.error("[ModuleDetailView] Quiz generation failed:",O);const I=r.quiz.questions||5,J=Array.from({length:I}).map((be,ke)=>{const D=Math.floor(Math.random()*20)+2,ne=Math.floor(Math.random()*20)+2,me=(D+ne).toString();return{id:ke+1,type:"multiple-choice",question:`Compute: ${D} + ${ne}`,options:[me,(D*ne).toString(),Math.abs(D-ne).toString(),(D+ne+1).toString()],correctAnswer:me,explanation:`${D} + ${ne} = ${me}`}});g||u(J)}})(),()=>{g=!0}},[r,d?.uid,t.id]);const T=a.useMemo(()=>N?h?.subjects?.[N]?.modulesProgress?.[t.id]??null:null,[t.id,N,h?.subjects]),[F,X]=a.useState(null),Z=a.useMemo(()=>{const g=T?.lessonsCompleted??[];return new Set(g)},[T?.lessonsCompleted]),Y=a.useMemo(()=>{const g=T?.quizzesCompleted??[];return new Set(g)},[T?.quizzesCompleted]),{isModuleCompleted:te,isStudyMaterialsCompleted:$,isLessonQuizCompleted:pe,getLastQuizScore:he,markStudyMaterialsComplete:ze}=yl({userProgress:h,userId:d?.uid,subjectId:N,moduleId:t.id,totalLessons:t.lessons.length,totalQuizzes:t.quizzes.length}),Ce=T?.lessonsCompleted?.length??t.lessons.filter(g=>g.completed).length,b=T?.quizzesCompleted?.length??t.quizzes.filter(g=>g.completed).length,Q=T?.progress??t.progress,ce=t.lessons.length+t.quizzes.length,ae=Ce+b;t.lessons.length&&Ce/t.lessons.length*100,t.quizzes.length&&b/t.quizzes.length*100;const le=(g,q)=>{const M=h?.lessons?.[g];if(!M)return q?100:0;if(M.completed)return 100;const O=M.progressPercent??M.score;return typeof O=="number"&&Number.isFinite(O)?Math.max(0,Math.min(100,O)):q?100:0},ge=a.useMemo(()=>{if(!ce)return 0;const g=t.lessons.reduce((M,O)=>{const I=Z.has(O.id)||O.completed;return M+le(O.id,I)},0),q=b*100;return Math.round((g+q)/ce)},[Z,b,t.lessons,t.quizzes.length,ce,h?.lessons]),Ne=ge>0?ge:Q,B=a.useMemo(()=>{const g=t.quizzes.find(M=>M.type==="final"||/module\s+quiz|general\s+quiz/i.test(M.title));if(g)return g;const q=t.quizzes.find(M=>M.isStandalone===!0);return q||(t.quizzes.length?t.quizzes[0]:null)},[t.quizzes]),Ee=a.useMemo(()=>{const g=new Map;t.lessons.forEach(M=>{g.set(M.id,[])});const q=t.lessons.length;return q===0||t.quizzes.forEach((M,O)=>{if(B?.id===M.id)return;const I=Math.min(O,q-1),J=t.lessons[I];if(!J)return;const be=g.get(J.id)??[];be.push(M),g.set(J.id,be)}),g},[t.lessons,t.quizzes,B?.id]),_e=a.useMemo(()=>Math.max(1,Math.ceil(t.lessons.length/2)),[t.lessons.length]),ye=a.useCallback(()=>{x(null),X(null)},[]),fe=a.useCallback(()=>{const g=f.current?.type==="lesson"?f.current.lesson:null;if(!g)return;const q={id:`${g.id}-practice`,title:`Practice Quiz: ${g.title}`,questions:rl(),duration:g.duration,completed:!1,locked:!1,type:"practice"};X(g),x({type:"quiz",quiz:q})},[]),Me=a.useCallback((g,q,M)=>{const O=f.current;if(O?.type!=="lesson"||!O.lesson)return;const I=O.lesson,J=10;if(k.current?.(J,`Completed "${I.title}"`),d?.uid&&N&&(async()=>{try{await ze(I.id),await sa(d.uid,N,t.id,I.id,0,J),await ms(d.uid,N,t.id,t.lessons.length,t.quizzes.length)}catch(be){console.error("[LessonComplete] Failed to persist progress:",be)}})(),M){const be=t.lessons.findIndex(ke=>ke.id===I.id);be!==-1&&be0?x({type:"quiz",quiz:t.quizzes[0]}):x(null)}else x(null)},[N,t.id,t.lessons.length,t.quizzes.length]),Ae=a.useCallback(g=>{if(!d?.uid||!f.current||f.current.type!=="lesson")return;const q=f.current.lesson.id;(async()=>{try{await aa(d.uid,q,g)}catch(M){console.warn("[ModuleDetailView] Failed to persist lesson progress:",M)}})()},[d?.uid,t.id]);if(r)if(r.type==="lesson"){const g=Ee.get(r.lesson.id)?.[0]??null,q=g?Y.has(g.id)||g.completed:!1,M=t.lessons.findIndex(I=>I.id===r.lesson.id);let O;if(M!==-1&&M0){const I=t.quizzes[0];I.type==="module"?O="Take Mid-Module Checkpoint":I.type==="final"?O="Take Final Assessment":O="Start Practice Quiz"}return e.jsx(hl,{lesson:r.lesson,lessonCompletionXP:10,practiceQuiz:g,practiceQuizCompleted:q,initialSection:r.returnFromQuiz?-1:0,nextContentLabel:O,onBack:ye,onStartPractice:fe,onProgressUpdate:Ae,onComplete:Me})}else return p?e.jsx(Bs,{quiz:{id:r.quiz.id,title:r.quiz.title,subject:At.find(g=>g.modules.some(q=>q.id===t.id))?.title||"Mathematics",difficulty:"Medium",questions:p.length,duration:r.quiz.duration||"15 min",xpReward:50,type:"practice",completed:r.quiz.completed,locked:!1,loadedQuestions:p,source:"ai_generated"},onClose:()=>{u(null),F?(x({type:"lesson",lesson:F,returnFromQuiz:!0}),X(null)):x(null),i&&i(!1)},onComplete:(g,q)=>{d?.uid&&N&&(async()=>{try{await ra(d.uid,N,t.id,r.quiz.id,g,[],0,q),await ms(d.uid,N,t.id,t.lessons.length,t.quizzes.length),await Zt(d.uid,S)}catch(M){console.warn("[Quiz] Progress persist failed:",M)}l&&l(q??0,"Quiz Complete! +"+(q??0)+" XP")})()},studentId:d?.uid}):e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-white rounded-2xl p-6 flex flex-col items-center gap-3 shadow-xl",children:[e.jsx(Rs,{size:36,className:"animate-spin text-indigo-600"}),e.jsx("p",{className:"font-bold text-slate-700",children:"Generating Quiz..."}),e.jsxs("p",{className:"text-sm text-slate-500",children:["AI is crafting questions for ",r.quiz.title]})]})});return e.jsxs("div",{className:"h-full overflow-y-auto scrollbar-hide px-4 md:px-6 lg:px-10 py-4 md:py-6 lg:py-8 relative",children:[e.jsx("div",{className:"relative mb-4 lg:mb-6 xl:mb-8 w-full lg:w-max",children:e.jsxs("button",{onClick:s,className:"flex items-center gap-2 px-4 py-2.5 rounded-full bg-white/80 backdrop-blur-xl border border-slate-200/60 text-slate-600 hover:text-indigo-600 font-bold text-sm tracking-wide transition-all hover:-translate-x-1 shadow-sm hover:shadow-md",children:[e.jsx(es,{size:18}),"Back"]})}),e.jsxs(E.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},className:`relative mb-6 lg:mb-8 rounded-[2rem] ${t.accentColor} shadow-[0_20px_40px_-15px_rgba(0,0,0,0.3)] shrink-0 overflow-hidden`,children:[e.jsx("div",{className:"absolute inset-0 bg-black/60 pointer-events-none z-0"}),e.jsx("div",{className:"absolute inset-0 opacity-10 pointer-events-none module-detail-grid-pattern"}),e.jsx("div",{className:"absolute top-0 right-0 w-[400px] h-[400px] bg-sky-500/20 blur-[100px] rounded-full pointer-events-none"}),e.jsxs("div",{className:"relative p-5 md:p-6 lg:p-8 flex flex-col md:flex-row md:items-center justify-between gap-3 md:gap-5",children:[e.jsxs("div",{className:"flex-1 text-white",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2 md:mb-2.5",children:[e.jsxs("div",{className:"px-2.5 py-0.5 bg-white/10 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-widest text-[#f8fafc] border border-white/20 shadow-sm flex items-center gap-1",children:[e.jsx(gs,{size:12})," Chapter ",t.id.split("-").pop()||"1"]}),e.jsxs("div",{className:"px-2.5 py-0.5 bg-white/10 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-widest text-emerald-400 border border-emerald-400/30",children:["Lv ",C]})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"flex lg:hidden text-white/80 shrink-0",children:e.jsx(qe,{size:18,strokeWidth:1.5})}),e.jsx("h1",{className:"text-lg md:text-2xl lg:text-3xl font-display font-black text-white tracking-[-0.02em] leading-tight",children:t.title})]}),e.jsx("p",{className:"text-slate-300 text-xs md:text-sm max-w-2xl font-medium leading-relaxed mb-3",children:t.description}),e.jsxs("div",{className:"bg-black/20 backdrop-blur-md rounded-xl p-2 md:p-3 border border-white/10 max-w-xl",children:[e.jsxs("div",{className:"flex justify-between items-end gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(zt,{size:16,className:"text-emerald-400"}),e.jsx("span",{className:"text-[11px] md:text-xs font-black text-white uppercase tracking-wider",children:"Module Mastery"}),te&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/20 border border-emerald-400/30 text-emerald-300 text-[10px] font-bold uppercase tracking-wide",children:[e.jsx(Aa,{size:12})," Completed"]})]}),e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsxs("span",{className:"text-[10px] md:text-xs font-bold text-slate-400",children:[ae,"/",ce]}),e.jsxs("span",{className:"text-base md:text-lg font-black text-white shrink-0 leading-none",children:[Math.round(Ne),"%"]})]})]}),e.jsx("div",{className:"h-2 bg-black/40 rounded-full overflow-hidden shadow-inner ring-1 ring-white/10 p-0.5 mt-2",children:e.jsx(E.div,{initial:{width:0},animate:{width:`${Ne}%`},transition:{duration:1.5,ease:"easeOut",delay:.2},className:`h-full rounded-full relative ${Ne===100?"bg-gradient-to-r from-emerald-400 to-teal-300":t.accentColor}`,children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI4IiBoZWlnaHQ9IjgiPgo8cmVjdCB3aWR0aD0iOCIgaGVpZ2h0PSI4IiBmaWxsPSIjZmZmIiBmaWxsLW9wYWNpdHk9IjAuMSI+PC9yZWN0Pgo8L3N2Zz4=')] opacity-30 mix-blend-overlay"})})})]})]}),e.jsxs("div",{className:"hidden lg:flex w-32 h-32 bg-white/5 rounded-2xl border border-white/10 backdrop-blur-md items-center justify-center transform rotate-[-3deg] shadow-2xl relative group hover:rotate-0 transition-all duration-500 shrink-0",children:[e.jsx("div",{className:`absolute inset-0 opacity-40 rounded-2xl ${t.progress===100?"bg-gradient-to-br from-emerald-400 to-teal-600":t.accentColor}`}),Ne===100?e.jsx(Ds,{size:56,className:"text-white drop-shadow-xl z-10 scale-100 group-hover:scale-110 transition-transform duration-500",strokeWidth:1}):e.jsx(qe,{size:56,className:"text-white drop-shadow-xl z-10 scale-100 group-hover:scale-110 transition-transform duration-500",strokeWidth:1}),e.jsx(E.div,{animate:{y:[-5,5,-5],rotate:[-10,10,-10]},transition:{duration:4,repeat:1/0},className:"absolute top-4 left-4 text-emerald-300 z-20",children:e.jsx(Tt,{size:16,fill:"currentColor"})}),e.jsx(E.div,{animate:{y:[5,-5,5],rotate:[10,-10,10]},transition:{duration:3.5,repeat:1/0},className:"absolute bottom-6 right-4 text-sky-300 z-20",children:e.jsx(js,{size:18})})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto pr-2 pb-8 scrollbar-hide",children:e.jsxs("div",{className:"relative rounded-[2rem] border border-slate-200 bg-white/90 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none bg-[radial-gradient(circle_at_top_right,rgba(153,86,222,0.08),transparent_45%),radial-gradient(circle_at_bottom_left,rgba(31,167,225,0.08),transparent_45%)]"}),e.jsxs("div",{className:"relative z-10 px-4 sm:px-6 md:px-8 py-5 md:py-6 border-b border-slate-200/70 bg-white/70 backdrop-blur-sm flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("h2",{className:"font-display font-black text-xl md:text-2xl text-slate-800 flex items-center gap-3",children:[e.jsx(qe,{size:24,className:"text-sky-500"}),"Study Journey"]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("div",{className:"text-xs md:text-sm font-bold bg-sky-100 text-sky-700 px-3 py-1 rounded-full shadow-sm border border-sky-200/50",children:["Lessons ",Ce,"/",t.lessons.length]}),e.jsxs("div",{className:"text-xs md:text-sm font-bold bg-rose-100 text-rose-700 px-3 py-1 rounded-full shadow-sm border border-rose-200/50",children:["Quizzes ",b,"/",t.quizzes.length]})]})]}),e.jsxs("div",{className:"relative z-10 px-3 md:px-6 lg:px-8 py-4 md:py-6 space-y-4 md:space-y-5",children:[t.lessons.map((g,q)=>{const M=Z.has(g.id)||g.completed,O=le(g.id,M),I=R[q%R.length];return e.jsxs(Fe.Fragment,{children:[e.jsxs(E.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:q*.05},className:`relative rounded-[1.5rem] border overflow-hidden group transition-all duration-500 mb-4 md:mb-6 ${g.locked?"border-slate-200 opacity-65 saturate-50":"border-slate-200/80 hover:border-slate-300 hover:shadow-[0_16px_40px_-15px_rgba(0,0,0,0.12)] hover:-translate-y-0.5"}`,children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[6px] z-20 bg-slate-100 overflow-hidden",children:e.jsx(E.div,{initial:{width:0},animate:{width:`${Math.max(2,O)}%`},transition:{duration:1.2,ease:"easeOut",delay:.1+q*.05},className:"h-full relative",style:{backgroundColor:I},children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI4IiBoZWlnaHQ9IjgiPgo8cmVjdCB3aWR0aD0iOCIgaGVpZ2h0PSI4IiBmaWxsPSIjZmZmIiBmaWxsLW9wYWNpdHk9IjAuMSI+PC9yZWN0Pgo8L3N2Zz4=')] opacity-30 mix-blend-overlay"})})}),e.jsx("div",{className:"absolute inset-0 bg-white transition-opacity duration-500 group-hover:opacity-90",style:{backgroundImage:`linear-gradient(to right, ${I}44 0%, ${I}11 50%, white 100%)`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.2] pointer-events-none",style:{backgroundImage:`radial-gradient(circle at 2px 2px, ${I} 1.5px, transparent 0)`,backgroundSize:"24px 24px"}}),e.jsx("div",{className:"absolute -top-12 -left-10 h-40 w-40 rounded-full blur-[32px] pointer-events-none transition-transform duration-700 group-hover:scale-[1.3] group-hover:translate-x-4",style:{backgroundColor:`${I}22`}}),e.jsx("div",{className:"absolute -bottom-8 right-8 h-32 w-32 rounded-full blur-2xl pointer-events-none transition-transform duration-700 group-hover:scale-125 group-hover:-translate-y-4",style:{backgroundColor:`${I}11`}}),e.jsx("div",{className:"absolute right-4 top-4 opacity-10 pointer-events-none transition-all duration-500 group-hover:rotate-12 group-hover:scale-110 drop-shadow-sm",style:{color:I},children:e.jsx(js,{size:56,strokeWidth:1})}),e.jsx("div",{className:"absolute right-16 bottom-5 opacity-10 pointer-events-none transition-all duration-500 group-hover:-rotate-6 group-hover:-translate-y-2 drop-shadow-sm",style:{color:I},children:e.jsx(qe,{size:40,strokeWidth:1})}),e.jsxs("div",{className:"relative z-10 p-3 md:p-5 pt-5 md:pt-6 space-y-3 md:space-y-4",children:[e.jsxs("button",{type:"button",onClick:()=>!g.locked&&x({lesson:g,type:"lesson"}),className:`w-full text-left flex flex-wrap items-center justify-between gap-2 md:gap-3 rounded-2xl px-3 md:px-5 py-3 md:py-4 transition shadow-sm ${g.locked?"cursor-not-allowed border border-slate-200 bg-white/70":"cursor-pointer bg-white hover:bg-slate-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 md:gap-4 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 md:w-12 md:h-12 rounded-full flex items-center justify-center shrink-0 transition-colors shadow-sm ${g.locked?"bg-slate-100 text-slate-400":M?"text-white ring-2 ring-emerald-400 ring-offset-1":O>0?"text-white ring-2 ring-amber-400 ring-offset-1":"text-white"}`,style:g.locked?{}:M?{backgroundColor:"#10b981"}:{backgroundColor:I},children:g.locked?e.jsx(rs,{size:16}):M?e.jsx(_t,{size:20}):e.jsx(Na,{size:18,className:"ml-0.5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[10px] md:text-[12px] font-black uppercase tracking-wider text-slate-500 mb-0.5",children:["Lesson ",q+1]}),e.jsx("h3",{className:"font-bold text-[14px] md:text-[18px] text-[#0a1628] leading-tight line-clamp-2",children:g.title})]})]}),e.jsx("div",{className:"flex items-center justify-end shrink-0",children:e.jsxs("span",{className:"inline-flex items-center gap-1 text-slate-500 text-[11px] md:text-sm font-semibold bg-slate-100/80 px-2 md:px-3 py-1 md:py-1.5 rounded-lg md:rounded-xl",children:[e.jsx(ht,{size:12}),g.duration]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 md:gap-3 px-0.5 md:px-1",children:[e.jsx("button",{type:"button",onClick:()=>!g.locked&&(x({lesson:g,type:"lesson"}),ze(g.id)),className:`inline-flex items-center gap-1 rounded-full px-3 md:px-4 py-1 md:py-1.5 text-[11px] md:text-[12px] font-bold shadow-sm transition hover:-translate-y-0.5 ${$(g.id)?"bg-emerald-50 border border-emerald-200":"bg-white"}`,style:{color:$(g.id)?"#059669":I},children:$(g.id)?e.jsxs(e.Fragment,{children:[e.jsx(_t,{size:12})," Review"]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:12})," Study Materials"]})}),e.jsx("button",{type:"button",onClick:()=>!g.locked&&(x({lesson:g,type:"lesson"}),fe()),className:`inline-flex items-center gap-1 rounded-full px-3 md:px-4 py-1 md:py-1.5 text-[11px] md:text-[12px] font-bold shadow-sm transition hover:-translate-y-0.5 ${pe(g.id)?"bg-emerald-50 border border-emerald-200":"bg-white"}`,style:{color:pe(g.id)?"#059669":I},children:pe(g.id)?e.jsxs(e.Fragment,{children:[e.jsx(ur,{size:12})," Retry"]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{size:12})," Quiz"]})})]})]})]}),B&&q===_e-1&&e.jsxs(E.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.15+q*.03},className:"mt-4 md:mt-6 mb-4 md:mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2 md:gap-4 mb-4 md:mb-6",children:[e.jsx("div",{className:"flex-1 h-px bg-slate-200"}),e.jsx("span",{className:"text-[10px] md:text-xs font-bold text-indigo-400 uppercase tracking-widest text-center",children:"mid-module checkpoint"}),e.jsx("div",{className:"flex-1 h-px bg-slate-200"})]}),e.jsxs("div",{className:"relative rounded-[1.5rem] bg-[#533ab6] p-3 md:p-5 shadow-lg overflow-hidden group transition-all hover:shadow-xl hover:-translate-y-1",children:[e.jsx("div",{className:"absolute right-2 md:right-10 top-1/2 -translate-y-1/2 text-white/5 text-[80px] md:text-[140px] font-black font-display pointer-events-none group-hover:scale-110 transition-transform duration-500",children:"?"}),e.jsxs("div",{className:"relative z-10 flex flex-wrap items-center gap-3 md:gap-5",children:[e.jsx("div",{className:"w-12 h-12 md:w-14 md:h-14 rounded-[12px] md:rounded-[14px] bg-white/10 backdrop-blur-md border border-white/10 shrink-0 flex items-center justify-center shadow-inner",children:e.jsx(We,{size:22,className:"text-rose-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[9px] md:text-[11px] font-black uppercase tracking-widest text-[#a3b1ee] mb-0.5 md:mb-1 drop-shadow-sm",children:"COMPETENCY CHECK · General Quiz"}),e.jsx("h3",{className:"font-display font-medium text-[16px] md:text-[22px] text-white leading-tight mb-1 md:mb-2 tracking-tight",children:B.title}),e.jsxs("p",{className:"text-[11px] md:text-xs font-semibold text-white/80 flex flex-wrap items-center gap-2 md:gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Dt,{size:11})," ",B.questions," Qs"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ht,{size:11})," ",B.duration]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 drop-shadow-md",children:[e.jsx(Ke,{size:11,className:"fill-amber-300"})," +50 XP"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 self-center shrink-0",children:[m&&(Y.has(B.id)||B.completed)&&he(B.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 text-[11px] md:text-xs font-bold",children:[e.jsx(Tt,{size:12,fill:"currentColor"})," Last: ",he(B.id).score,"/",he(B.id).total]}),e.jsx("button",{type:"button",onClick:()=>!B.locked&&(x({quiz:B,type:"quiz"}),i&&i(!0)),className:`px-4 md:px-6 py-2 md:py-2.5 rounded-xl text-[11px] md:text-sm font-bold tracking-wider transition-all backdrop-blur-sm ${B.locked?"bg-white/5 text-white/30 border border-white/10 cursor-not-allowed":m&&(Y.has(B.id)||B.completed)?"bg-white/20 text-white border border-white/40 hover:bg-white/30 shadow-sm":"bg-transparent text-white border border-white/40 hover:bg-white/10 shadow-sm"}`,children:m&&(Y.has(B.id)||B.completed)?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Rt,{size:12})," Retake"]}):"START"})]})]})]})]})]},g.id)}),t.lessons.length===0&&B&&e.jsxs("div",{className:"relative rounded-[1.5rem] bg-[#533ab6] p-5 shadow-lg overflow-hidden group",children:[e.jsx("div",{className:"absolute right-4 md:right-10 top-1/2 -translate-y-1/2 text-white/5 text-[140px] font-black font-display pointer-events-none group-hover:scale-110 transition-transform duration-500",children:"?"}),e.jsxs("div",{className:"relative z-10 flex flex-wrap items-center justify-between gap-4 md:gap-5",children:[e.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[e.jsx("div",{className:"w-14 h-14 rounded-[14px] bg-white/10 backdrop-blur-md border border-white/10 shrink-0 flex items-center justify-center shadow-inner",children:e.jsx(We,{size:28,className:"text-rose-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] md:text-[11px] font-black uppercase tracking-widest text-[#a3b1ee] mb-1 drop-shadow-sm",children:"COMPETENCY CHECK · General Quiz"}),e.jsx("h3",{className:"font-display font-medium text-[20px] md:text-[22px] text-white leading-tight mb-2 tracking-tight",children:B.title}),e.jsxs("p",{className:"text-xs font-semibold text-white/80 flex items-center gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Dt,{size:12})," ",B.questions," Qs"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ht,{size:12})," ",B.duration]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 drop-shadow-md",children:[e.jsx(Ke,{size:12,className:"fill-amber-300"})," +50 XP"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 self-center shrink-0",children:[m&&(Y.has(B.id)||B.completed)&&he(B.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-300 text-[11px] md:text-xs font-bold",children:[e.jsx(Tt,{size:12,fill:"currentColor"})," Last: ",he(B.id).score,"/",he(B.id).total]}),e.jsx("button",{type:"button",onClick:()=>!B.locked&&(x({quiz:B,type:"quiz"}),i&&i(!0)),className:`px-6 py-2.5 rounded-xl text-xs md:text-sm font-bold tracking-wider transition-all backdrop-blur-sm ${B.locked?"bg-white/5 text-white/30 border border-white/10 cursor-not-allowed":m&&(Y.has(B.id)||B.completed)?"bg-white/20 text-white border border-white/40 hover:bg-white/30 shadow-sm":"bg-transparent text-white border border-white/40 hover:bg-white/10 shadow-sm"}`,children:m&&(Y.has(B.id)||B.completed)?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Rt,{size:12})," Retake"]}):"START"})]})]})]})]})]})})]})},jl={"Patterns, Relations, and Functions":{icon:Lt,bg:"bg-indigo-500"},"Financial Mathematics":{icon:Pa,bg:"bg-emerald-500"},"Logic and Mathematical Reasoning":{icon:la,bg:"bg-purple-500"},"Random Variables":{icon:er,bg:"bg-orange-500"},"Normal Distribution":{icon:Ta,bg:"bg-sky-500"},"Sampling and Estimation":{icon:Za,bg:"bg-teal-500"},"Hypothesis Testing":{icon:ar,bg:"bg-rose-500"},"Correlation and Regression":{icon:Ga,bg:"bg-amber-500"}};function vl(t){return jl[t]||{icon:Dt,bg:"bg-slate-500"}}const Nl=({userId:t,onStartQuiz:s,searchQuery:l="",allowedSubjectIds:n,atRiskTopics:i=[]})=>{const{userProfile:c}=Qt(),[r,x]=a.useState("all"),[d,h]=a.useState("Medium"),[S,m]=a.useState("all"),[z,p]=a.useState(null),[u,k]=a.useState(!1),[f,C]=a.useState(null),[N,R]=a.useState(null),T=a.useMemo(()=>!n||n.length===0?hs:hs.filter(b=>n.includes(b.id)),[n]),F=a.useMemo(()=>T.flatMap(b=>b.topics.map(Q=>({id:Q.id,name:Q.name,unit:Q.unit,subject:b.name,subjectId:b.id}))),[T]);a.useEffect(()=>{t&&(k(!0),gl(t).then(p).catch(console.error).finally(()=>k(!1)))},[t]);const X=`mathpulse_practice_completed_${t}`,[Z,Y]=a.useState(0);a.useEffect(()=>{const b=()=>Y(ae=>ae+1),Q=ae=>{ae.key===X&&Y(le=>le+1)},ce=()=>Y(ae=>ae+1);return window.addEventListener("focus",b),window.addEventListener("storage",Q),window.addEventListener("practice-completion-updated",ce),()=>{window.removeEventListener("focus",b),window.removeEventListener("storage",Q),window.removeEventListener("practice-completion-updated",ce)}},[X]);const te=a.useMemo(()=>{try{const b=localStorage.getItem(X);if(b)return new Map(JSON.parse(b))}catch{}return new Map},[X,Z]),$=a.useMemo(()=>F.filter(b=>{const Q=r==="all"||b.subject===r,ce=!l||b.name.toLowerCase().includes(l.toLowerCase())||b.unit.toLowerCase().includes(l.toLowerCase())||b.subject.toLowerCase().includes(l.toLowerCase());let ae=!0;return S==="completed"?ae=te.has(b.name.toLowerCase()):S==="recommended"&&(ae=i.some(le=>b.name.toLowerCase().includes(le.toLowerCase())||le.toLowerCase().includes(b.name.toLowerCase()))),Q&&ce&&ae}),[F,r,l,S,te,i]),pe=z?.quizzesCompleted??0,he=z?.totalXPEarned??c?.totalXP??0,ze=z?.averageScore??0,Ce=a.useCallback(async b=>{if(!(!t||f)){C(b.id);try{const Q={Easy:"Practice",Medium:"Challenge",Hard:"Mastery"},ce=await Hs({userId:t,subject:b.subject,competency:b.name,difficulty:Q[d],count:5}),ae={id:ce.session_id,title:`Practice Quiz: ${b.name} (AI)`,subject:b.subject,difficulty:d,questions:ce.questions.length,duration:"10 min",xpReward:d==="Hard"?75:d==="Medium"?50:25,type:"practice",loadedQuestions:ce.questions.map(le=>({id:le.id,questionType:"multiple_choice",question:le.question,options:le.options,correctAnswer:le.options[le.correct_index],bloomLevel:["remember","understand","apply","analyze"].includes(le.bloomsLevel?.toLowerCase()||"")?le.bloomsLevel.toLowerCase():"understand",difficulty:d.toLowerCase(),topic:b.name,subject:b.subject,points:10,explanation:le.explanation})),generatedQuizId:ce.session_id,source:"ai_generated",completed:!1,locked:!1};s?.(ae)}catch(Q){console.error("Failed to generate practice quiz:",Q)}finally{C(null)}}},[t,d,f,s]);return e.jsxs("div",{className:"px-4 sm:px-6 xl:px-10 py-4 sm:py-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 sm:gap-4 mb-6",children:[e.jsxs(E.div,{whileHover:{scale:1.02},className:"bg-gradient-to-br from-sky-700 to-sky-500 rounded-xl sm:rounded-2xl p-3 sm:p-5 text-white shadow-lg",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between mb-1 sm:mb-3 gap-1 sm:gap-0",children:[e.jsxs("div",{className:"w-8 h-8 sm:w-12 sm:h-12 bg-white/20 rounded-lg sm:rounded-xl flex items-center justify-center shrink-0",children:[e.jsx(zt,{size:16,className:"sm:hidden"}),e.jsx(zt,{size:24,className:"hidden sm:block"})]}),e.jsx("span",{className:"text-xl sm:text-3xl font-bold",children:pe})]}),e.jsx("p",{className:"text-[10px] sm:text-sm font-medium text-sky-100 leading-tight",children:"Quizzes Completed"})]}),e.jsxs(E.div,{whileHover:{scale:1.02},className:"bg-gradient-to-br from-rose-500 to-rose-600 rounded-xl sm:rounded-2xl p-3 sm:p-5 text-white shadow-lg",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between mb-1 sm:mb-3 gap-1 sm:gap-0",children:[e.jsxs("div",{className:"w-8 h-8 sm:w-12 sm:h-12 bg-white/20 rounded-lg sm:rounded-xl flex items-center justify-center shrink-0",children:[e.jsx(Ke,{size:16,className:"sm:hidden"}),e.jsx(Ke,{size:24,className:"hidden sm:block"})]}),e.jsx("span",{className:"text-xl sm:text-3xl font-bold",children:he.toLocaleString()})]}),e.jsx("p",{className:"text-[10px] sm:text-sm font-medium text-cyan-100 leading-tight",children:"Total XP Earned"})]}),e.jsxs(E.div,{whileHover:{scale:1.02},className:"bg-gradient-to-br from-indigo-600 to-indigo-700 rounded-xl sm:rounded-2xl p-3 sm:p-5 text-white shadow-lg",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between mb-1 sm:mb-3 gap-1 sm:gap-0",children:[e.jsxs("div",{className:"w-8 h-8 sm:w-12 sm:h-12 bg-white/20 rounded-lg sm:rounded-xl flex items-center justify-center shrink-0",children:[e.jsx(We,{size:16,className:"sm:hidden"}),e.jsx(We,{size:24,className:"hidden sm:block"})]}),e.jsxs("span",{className:"text-xl sm:text-3xl font-bold",children:[Math.round(ze),"%"]})]}),e.jsx("p",{className:"text-[10px] sm:text-sm font-medium text-sky-100 leading-tight",children:"Average Score"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 mb-6",children:[e.jsxs("select",{value:r,onChange:b=>x(b.target.value),className:"w-full sm:w-auto px-3 sm:px-4 py-2 sm:py-2.5 bg-white border-2 border-[#dde3eb] rounded-xl text-xs sm:text-sm font-bold text-[#0a1628] focus:border-indigo-600 focus:outline-none",children:[e.jsx("option",{value:"all",children:"All Subjects"}),T.map(b=>e.jsx("option",{value:b.name,children:b.name},b.id))]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 bg-white rounded-xl p-1 shadow-sm",children:[e.jsx("span",{className:"px-2 text-xs font-bold text-slate-400",children:"Difficulty:"}),["Easy","Medium","Hard"].map(b=>e.jsx("button",{onClick:()=>h(b),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all whitespace-nowrap ${d===b?b==="Easy"?"bg-green-500 text-white shadow-sm":b==="Medium"?"bg-orange-500 text-white shadow-sm":"bg-red-500 text-white shadow-sm":"text-[#5a6578] hover:bg-[#edf1f7]"}`,children:b},b))]}),e.jsx("div",{className:"flex items-center gap-1.5 sm:gap-2 bg-white rounded-xl p-1 shadow-sm",children:[["all","All"],["completed","Completed"],["recommended","Recommended"]].map(([b,Q])=>e.jsx("button",{onClick:()=>m(b),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all whitespace-nowrap ${S===b?b==="completed"?"bg-emerald-500 text-white shadow-sm":b==="recommended"?"bg-purple-500 text-white shadow-sm":"bg-indigo-500 text-white shadow-sm":"text-[#5a6578] hover:bg-[#edf1f7]"}`,children:Q},b))})]}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-white rounded-2xl p-6 flex flex-col items-center gap-3 shadow-xl",children:[e.jsx(Rs,{size:36,className:"animate-spin text-indigo-600"}),e.jsx("p",{className:"font-bold text-slate-700",children:"Generating Quiz..."}),e.jsx("p",{className:"text-sm text-slate-500",children:"AI is crafting questions from curriculum"})]})}),e.jsxs("div",{className:"pr-2 pb-4 rounded-[2rem] border border-slate-200 shadow-inner relative",style:{backgroundImage:"radial-gradient(#CBD5E1 1px, transparent 1px)",backgroundSize:"24px 24px",backgroundPosition:"-12px -12px",backgroundColor:"#FAFAFA"},children:[e.jsx("div",{className:"absolute left-12 top-0 bottom-0 w-0.5 bg-rose-200/60 pointer-events-none z-0"}),e.jsx("div",{className:"absolute left-[54px] top-0 bottom-0 w-px bg-rose-100/40 pointer-events-none z-0"}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-5 p-4 md:p-6 relative z-10",children:$.map((b,Q)=>e.jsx(E.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:Q*.03},onClick:()=>Ce(b),className:`bg-white/90 backdrop-blur-sm rounded-2xl p-4 md:p-5 border-2 relative select-none transition-all duration-300 ${f===b.id?"border-indigo-300 opacity-80 cursor-wait":f?"border-slate-200 opacity-60 cursor-not-allowed":"border-slate-200 shadow-sm hover:border-indigo-300 hover:shadow-md cursor-pointer"} group`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3 md:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 md:gap-4 flex-1",children:[(()=>{const{icon:ce,bg:ae}=vl(b.unit);return e.jsxs("div",{className:`w-10 h-10 md:w-12 md:h-12 rounded-xl flex items-center justify-center shrink-0 shadow-sm transform group-hover:rotate-3 transition-transform ${ae} text-white relative`,children:[e.jsx(ce,{size:18}),te.has(b.name.toLowerCase())&&e.jsx("div",{className:"absolute -top-1 -right-1 w-4 h-4 bg-emerald-500 rounded-full flex items-center justify-center border-2 border-white",children:e.jsx(at,{size:10,className:"text-white"})})]})})(),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-1",children:[e.jsxs("span",{className:`px-2 py-0.5 rounded-[6px] text-[9px] md:text-[10px] font-black uppercase tracking-wider ${d==="Easy"?"bg-green-100 text-green-700":d==="Medium"?"bg-orange-100 text-orange-700":"bg-red-100 text-red-700"}`,children:["AI ","•"," ",d]}),te.has(b.name.toLowerCase())&&e.jsxs("span",{className:"px-2 py-0.5 rounded-[6px] text-[9px] md:text-[10px] font-black uppercase tracking-wider bg-emerald-100 text-emerald-700",children:["Best: ",te.get(b.name.toLowerCase())?.bestScore,"%"]}),e.jsx("span",{className:"w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-emerald-500 animate-pulse"})]}),e.jsx("h3",{className:"font-bold text-[14px] md:text-[16px] leading-tight mb-1 md:mb-1.5 text-[#0a1628] transition-colors",children:b.name}),e.jsxs("p",{className:"text-[11px] md:text-[12px] text-slate-500 mb-1.5 line-clamp-1",children:[b.subject," — ",b.unit]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:gap-3 text-[11px] md:text-[12px] font-bold text-slate-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qe,{size:12})," 5 Qs"]}),e.jsx("span",{className:"hidden sm:inline",children:"•"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ht,{size:12})," 10 min"]}),e.jsx("span",{className:"hidden sm:inline",children:"•"}),e.jsxs("span",{className:"flex items-center gap-1 text-rose-500",children:[e.jsx(Ds,{size:12})," +",d==="Hard"?75:d==="Medium"?50:25," XP"]})]})]})]}),e.jsxs("div",{className:"shrink-0 flex flex-col items-center gap-1.5",children:[e.jsx("div",{className:`px-3 py-1.5 md:px-4 md:py-2 rounded-xl text-[11px] md:text-[12px] font-black uppercase tracking-wider shadow-sm transition-all ${f===b.id?"bg-indigo-100 text-indigo-600":te.has(b.name.toLowerCase())?"bg-orange-500 text-white group-hover:bg-orange-600 shadow-orange-200":"bg-indigo-500 text-white group-hover:bg-indigo-600 shadow-indigo-200"}`,children:f===b.id?"Loading...":te.has(b.name.toLowerCase())?"Retry":"Start"}),te.has(b.name.toLowerCase())&&e.jsxs("button",{onClick:ce=>{ce.stopPropagation();const ae=te.get(b.name.toLowerCase());R({topic:b.name,items:ae?.history||[]})},className:"flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-bold text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-colors",children:[e.jsx(Ea,{size:11})," History"]})]})]})},b.id))}),$.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-slate-500 relative z-10",children:[e.jsx(We,{size:48,className:"mb-3"}),e.jsx("p",{className:"font-medium",children:"No topics found"}),e.jsx("p",{className:"text-sm",children:"Try adjusting your filters or search query"})]})]}),e.jsx(Je,{children:N&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onClick:()=>R(null),children:e.jsxs(E.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.9,opacity:0},onClick:b=>b.stopPropagation(),className:"bg-white rounded-2xl p-6 max-w-md w-full shadow-2xl max-h-[80vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-black text-slate-800",children:"Quiz History"}),e.jsx("button",{onClick:()=>R(null),className:"p-1.5 rounded-full hover:bg-slate-100",children:e.jsx(Ze,{size:18,className:"text-slate-400"})})]}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:N.topic}),N.items.length===0?e.jsx("p",{className:"text-center text-slate-400 py-8 text-sm",children:"No history found for this topic."}):e.jsx("div",{className:"space-y-3",children:N.items.map((b,Q)=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 rounded-xl border border-slate-100",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-slate-700",children:new Date(b.date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsxs("p",{className:"text-xs text-slate-400",children:[b.difficulty," difficulty"]})]}),e.jsxs("div",{className:`text-lg font-black ${b.score>=80?"text-emerald-600":b.score>=50?"text-amber-600":"text-rose-600"}`,children:[b.score,"%"]})]},Q))})]})})})]})},kl=` @keyframes head-sway { 0%, 100% { transform: rotate(-2deg) translateY(0); } 50% { transform: rotate(2deg) translateY(-2px); } @@ -191,4 +191,4 @@ import{j as e,r as a,b as Et,d as Fe,c as Gs}from"./vendor-react-B4AQeu28.js";im transform-origin: 50% 55%; animation: mouth-talk 3s ease-in-out infinite; } -`,Ms=({assessmentDismissed:t,initialAssessmentCompleted:s})=>{const l="absolute inset-0 w-full h-full object-contain",[n,i]=a.useState(!1);a.useEffect(()=>{t&&!s&&!sessionStorage.getItem("mathpulse_assessment_reminder_shown")?i(!0):i(!1)},[t,s]);const c=()=>{sessionStorage.setItem("mathpulse_assessment_reminder_shown","true"),i(!1),window.dispatchEvent(new CustomEvent("mathpulse:open-assessment"))};return e.jsxs(e.Fragment,{children:[e.jsx("style",{children:kl}),e.jsxs("div",{className:"relative w-full h-[250px] flex items-end justify-center drop-shadow-sm select-none pointer-events-none",children:[n&&e.jsxs(E.div,{initial:{opacity:0,scale:.8,x:10},animate:{opacity:1,scale:1,x:0},className:"absolute top-0 right-0 z-50 max-w-[180px] bg-white rounded-2xl shadow-lg border border-[#dde3eb] p-3 cursor-pointer pointer-events-auto",onClick:c,children:[e.jsx("p",{className:"text-[11px] font-bold text-[#0a1628] leading-snug",children:"Psst! Complete your assessment for a personalized path!"}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-1",children:[e.jsx("div",{className:"w-1.5 h-1.5 bg-purple-500 rounded-full animate-pulse"}),e.jsx("span",{className:"text-[10px] text-[#5a6578] font-medium",children:"Tap to start"})]}),e.jsx("div",{className:"absolute -bottom-2 left-4 w-3 h-3 bg-white border-r border-b border-[#dde3eb] rotate-45"})]}),e.jsx("img",{src:"/mascot/modules_avatar_body.png",alt:"Desk setup",className:`${l} z-10`}),e.jsxs("div",{className:`${l} z-20 animate-head-sway`,children:[e.jsx("img",{src:"/mascot/modules_left_horn.png",alt:"Left Horn",className:`${l} z-0 animate-horn-left`}),e.jsx("img",{src:"/mascot/modules_right_horn.png",alt:"Right Horn",className:`${l} z-0 animate-horn-right`}),e.jsx("img",{src:"/mascot/modules_head.png",alt:"Mascot Head",className:`${l} z-[1]`}),e.jsx("img",{src:"/mascot/modules_eyes.png",alt:"Eyes",className:`${l} z-[2] animate-blink`}),e.jsx("img",{src:"/mascot/modules_mouth.png",alt:"Mouth",className:`${l} z-[3] animate-mouth`})]})]})]})},As={common:"bg-slate-100 text-slate-500",rare:"bg-blue-50 text-blue-500",epic:"bg-amber-50 text-amber-500"},Es=["bg-[#1FA7E1]/80 text-white","bg-[#9956DE]/80 text-white","bg-[#FFB356]/90 text-white","bg-[#7274ED]/80 text-white","bg-[#1FA7E1]/80 text-white","bg-[#9956DE]/80 text-white","bg-gradient-to-r from-[#FFB356] to-[#FF8C00] text-white"],Cl=({isOpen:t,onClose:s,onClaim:l,weekRewards:n,todayReward:i,canClaim:c,isClaiming:r,claimedDays:x,currentDayIndex:d,timeUntilReset:h})=>{const[S,m]=a.useState(!1);if(!t)return null;const z=()=>{if(!c||S)return;m(!0),i?.rarity==="epic"?fs({particleCount:150,spread:80,origin:{y:.6},colors:["#FFD700","#FFA500","#FF8C00","#FF6B6B","#4ade80"]}):fs({particleCount:100,spread:70,origin:{y:.6},colors:["#FFD700","#FFA500","#FF8C00"]}),setTimeout(()=>{m(!1),l()},1200)},p=R=>R+1,u=R=>R===d,k=R=>x.includes(R),f=R=>R>d,C=n.slice(0,6),N=n[6];return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-8",children:[e.jsx(Je,{children:t&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 bg-slate-900/60 backdrop-blur-sm",onClick:s})}),e.jsxs(E.div,{initial:{scale:.9,opacity:0,y:20},animate:{scale:1,opacity:1,y:0},exit:{scale:.9,opacity:0,y:20},className:"relative w-full max-w-[420px] bg-[#f7f9fc] rounded-3xl border border-[#dde3eb] shadow-2xl flex flex-col items-center p-5 overflow-visible",children:[e.jsxs("div",{className:"absolute -top-6 w-[85%] h-12 bg-gradient-to-r from-[#9956DE] via-[#7274ED] to-[#1FA7E1] rounded-xl shadow-lg flex items-center justify-center z-20",children:[e.jsx("div",{className:"absolute -left-2.5 -z-10 w-5 h-8 bg-[#633299] rounded-l-full rotate-12 top-1.5"}),e.jsx("div",{className:"absolute -right-2.5 -z-10 w-5 h-8 bg-[#10709b] rounded-r-full -rotate-12 top-1.5"}),e.jsx("h2",{className:"text-white font-black text-lg tracking-wide uppercase drop-shadow-sm font-display",children:"Daily Rewards"})]}),e.jsx("button",{onClick:s,className:"absolute -right-3 -top-3 w-8 h-8 bg-white hover:bg-slate-100 border border-slate-200 text-slate-500 hover:text-slate-800 rounded-full flex items-center justify-center z-30 shadow-md transition-transform hover:scale-105 active:scale-95",children:e.jsx(Ze,{size:16,strokeWidth:3})}),e.jsxs("div",{className:"mt-6 mb-2 text-center w-full",children:[e.jsx("h3",{className:"text-xl font-bold text-slate-800 font-display mt-2",children:"Welcome Back!"}),e.jsx("p",{className:"text-slate-500 font-medium text-xs mt-0.5",children:"Claim your daily reward for today."})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 w-full mb-5 relative z-10",children:[C.map((R,T)=>{const F=p(T),X=k(T),Z=u(T),Y=f(T);return e.jsxs("div",{className:`relative rounded-xl flex flex-col overflow-hidden border-[1.5px] transition-all ${Z&&!X?"border-amber-400 shadow-[0_0_15px_rgba(251,191,36,0.25)] scale-105 z-10 bg-amber-50":X?"border-[#dde3eb] bg-slate-200/50":"border-[#dde3eb] bg-white"}`,children:[e.jsxs("div",{className:`py-0.5 text-center font-black text-[10px] uppercase tracking-wider ${Z&&!X?"bg-amber-400 text-amber-900":Es[T]}`,children:["Day ",F]}),e.jsx("div",{className:"absolute top-5 right-1 z-10",children:e.jsx("span",{className:`text-[8px] font-bold uppercase px-1 rounded ${As[R.rarity]}`,children:R.rarity})}),e.jsxs("div",{className:"flex-1 p-2 flex flex-col items-center justify-center relative min-h-[75px]",children:[X&&e.jsxs(E.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",bounce:.5},className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-emerald-200/50"})}),e.jsxs("div",{className:"relative w-14 h-14 rounded-full border-[3px] border-emerald-500 bg-emerald-100 flex items-center justify-center transform -rotate-12 shadow-lg",children:[e.jsx(_t,{className:"w-8 h-8 text-emerald-600"}),e.jsx("div",{className:"absolute -bottom-2.5 left-1/2 -translate-x-1/2 bg-emerald-500 rounded-md px-2 py-0.5 border-2 border-emerald-300 shadow-md",children:e.jsx("span",{className:"text-[9px] font-black text-white uppercase tracking-wider leading-none whitespace-nowrap",children:"Claimed"})})]})]}),Y&&e.jsx("div",{className:"absolute top-1 right-1 bg-slate-200 rounded-full p-0.5 z-10",children:e.jsx(rs,{size:8,className:"text-slate-400"})}),e.jsxs("div",{className:`flex flex-col items-center transition-all w-full ${X?"opacity-30 grayscale":""}`,children:[e.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center border-2 mb-1",style:{backgroundColor:R.color+"20",borderColor:R.color+"40"},children:e.jsx("span",{className:"text-lg",children:R.icon})}),e.jsx("div",{className:`font-black text-xs leading-none mt-0.5 text-center ${Z?"text-amber-600":X?"text-slate-500":"text-slate-600"}`,children:R.label})]})]})]},R.id)}),N&&e.jsxs("div",{className:`col-span-3 relative rounded-xl flex flex-col overflow-hidden border-[1.5px] transition-all mt-1 ${u(6)&&!k(6)?"border-amber-400 shadow-[0_0_20px_rgba(251,191,36,0.3)] scale-[1.02] z-10 bg-amber-50":k(6)?"border-[#dde3eb] bg-slate-200/50":"border-[#dde3eb] bg-white"}`,children:[e.jsx("div",{className:`py-1 text-center font-black text-[10px] uppercase tracking-widest ${u(6)&&!k(6)?"bg-amber-400 text-amber-900":Es[6]}`,children:"Day 7 • Epic Reward"}),e.jsx("div",{className:"absolute top-6 right-2 z-10",children:e.jsx("span",{className:`text-[8px] font-bold uppercase px-1.5 py-0.5 rounded ${As[N.rarity]}`,children:N.rarity})}),e.jsxs("div",{className:"flex items-center justify-center gap-5 p-3 relative",children:[k(6)&&e.jsxs(E.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",bounce:.5},className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 rounded-full bg-rose-200/50"})}),e.jsxs("div",{className:"relative w-20 h-20 rounded-full border-[4px] border-rose-500 bg-rose-100 flex items-center justify-center transform rotate-12 shadow-lg",children:[e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"Claimed",className:"w-14 h-14 object-contain drop-shadow-md"}),e.jsx("div",{className:"absolute -bottom-3 left-1/2 -translate-x-1/2 bg-rose-500 rounded-md px-2.5 py-1 border-2 border-rose-300 shadow-md",children:e.jsx("span",{className:"text-[10px] font-black text-white uppercase tracking-wider leading-none whitespace-nowrap",children:"Claimed"})})]})]}),e.jsxs("div",{className:`flex items-center justify-center gap-5 w-full transition-all ${k(6)?"opacity-30 grayscale":""}`,children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center border-2 shadow-sm mb-0.5",style:{backgroundColor:N.color+"20",borderColor:N.color+"40"},children:e.jsx("span",{className:"text-2xl",children:N.icon})}),e.jsx("span",{className:`font-black text-sm ${u(6)?"text-amber-600":"text-slate-600"}`,children:N.label})]}),N.rarity==="epic"&&e.jsxs("div",{className:"relative mt-1",children:[e.jsx("div",{className:"w-14 h-14 bg-purple-50 rounded-xl flex items-center justify-center border-2 border-purple-200 shadow-sm",children:e.jsx(La,{className:"w-8 h-8 text-purple-500 drop-shadow-md"})}),e.jsx("div",{className:"absolute -right-5 -bottom-4 w-14 h-14 bg-white rounded-xl p-1 border-2 border-amber-300 shadow-lg transform rotate-[-5deg]",children:e.jsx("img",{src:"/avatar/crown_thumbnail.png",alt:"Crown",className:"w-full h-full object-contain drop-shadow-md"})})]})]})]})]})]}),e.jsxs("div",{className:"mb-3 flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(jr,{size:14}),e.jsx("span",{className:"font-mono font-medium",children:h}),e.jsx("span",{children:"until next reset"})]}),e.jsx(E.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:z,disabled:!c||r||S,className:`w-[85%] py-3 rounded-full font-black text-base tracking-wide uppercase shadow-lg transition-all mt-2 ${!c||r||S?"bg-slate-200 text-slate-400 cursor-not-allowed border border-slate-300":"bg-gradient-to-r from-[#FFB356] to-[#FF8C00] text-white hover:from-[#FFA500] hover:to-[#FF7F00] border-b-4 border-[#e67e00]"}`,children:r||S?"Claiming...":c?"Claim!":"Claimed"})]})]})};function Sl(t){const[s,l]=a.useState({difficulty:"normal",loading:!0});return a.useEffect(()=>{if(!t){l({difficulty:"normal",loading:!1});return}const n=mt(Ue,"users",t);return as(n,c=>{if(!c.exists()){l({difficulty:"normal",loading:!1});return}const x=c.data()?.moduleDifficulty||"normal";l({difficulty:["normal","easier","remedial"].includes(x)?x:"normal",loading:!1})},c=>{console.error("[useModuleDifficulty] snapshot error:",c),l({difficulty:"normal",loading:!1})})},[t]),s}function zl(t,s){return s==="normal"?t:s==="easier"?t.filter(l=>{const n=l.tags||[],i=l.difficulty||"";return n.some(c=>["foundation","basic","introductory"].includes(c.toLowerCase()))||["foundation","basic","introductory"].includes(i.toLowerCase())||!n.includes("advanced")&&!i.toLowerCase().includes("advanced")}):s==="remedial"?t.filter(l=>{const n=l.tags||[],i=l.difficulty||"";return n.some(c=>["remedial","review","catch-up"].includes(c.toLowerCase()))||["remedial","review","catch-up"].includes(i.toLowerCase())}):t}const _l=new Set([7,14,30,60,100]),Ct={lastClaimedDate:"",lastClaimedWeekSeed:0,claimedDays:[],currentStreak:0,longestStreak:0,totalClaimed:0,hintTokens:0,streakShields:0,activeMultiplier:null};function Ml(t){if(t<=0)return"00:00:00";const s=Math.floor(t/1e3),l=Math.floor(s/3600),n=Math.floor(s%3600/60),i=s%60;return`${String(l).padStart(2,"0")}:${String(n).padStart(2,"0")}:${String(i).padStart(2,"0")}`}function Al(){const t=ns();return t.setDate(t.getDate()-1),ls(t)}function Ws(t){return t?new Date(t.expiresAt).getTime()>Date.now():!1}function Us(t){return mt(Ue,"users",t,"dailyRewards",t)}function El(t){return mt(Ue,"users",t)}async function Ts(t){try{const s=Us(t),l=await Yt(s);if(!l.exists())return{...Ct};const n=l.data(),i=is();return n.lastClaimedWeekSeed&&n.lastClaimedWeekSeed!==i?{...n,claimedDays:[],lastClaimedWeekSeed:i}:{...Ct,...n,activeMultiplier:n.activeMultiplier&&Ws(n.activeMultiplier)?n.activeMultiplier:null}}catch(s){return console.error("[dailyRewardService] Error getting state:",s),{...Ct}}}function Tl(t){const s=ls();return t.lastClaimedDate!==s}async function Pl(t){const s=ls(),l=is(),n=os(),c=cs()[n];if(!c)throw new Error(`No reward found for day index ${n}`);try{const r=await Ys(Ue,async d=>{const h=Us(t),S=El(t),m=await d.get(h),z=await d.get(S);let p;if(m.exists()?p={...Ct,...m.data()}:(p={...Ct,lastClaimedWeekSeed:l},d.set(h,p)),p.lastClaimedWeekSeed!==l&&(p.claimedDays=[],p.lastClaimedWeekSeed=l),p.lastClaimedDate===s)return{code:"ALREADY_CLAIMED",state:p};let u=p.currentStreak,k=!1;if(!p.lastClaimedDate||p.currentStreak===0)u=1;else{const T=Al();p.lastClaimedDate===T?u=p.currentStreak+1:p.streakShields>0?(p.streakShields-=1,u=p.currentStreak+1,k=!0):u=1}const f=Math.max(p.longestStreak,u);let C=0,N=1;switch(c.type){case"xp":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||0;N=Ws(p.activeMultiplier)?p.activeMultiplier?.multiplier??1:1,C=Math.floor(T*N);break}case"hint_token":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||0;p.hintTokens+=T;break}case"streak_shield":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||0;p.streakShields+=T;break}case"xp_multiplier":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||60,F=c.id.includes("2")?2:1.5,X=new Date;X.setMinutes(X.getMinutes()+T),p.activeMultiplier={multiplier:F,expiresAt:X.toISOString()};break}case"badge_unlock":break}const R=[...p.claimedDays,n];return p.lastClaimedDate=s,p.currentStreak=u,p.longestStreak=f,p.totalClaimed+=1,d.set(h,p,{merge:!0}),z.exists()&&d.update(S,{hintTokens:p.hintTokens,streakShields:p.streakShields,activeMultiplier:p.activeMultiplier,lastClaimedDate:p.lastClaimedDate,updatedAt:Ps()}),{code:"SUCCESS",state:p,newClaimedDays:R,newStreak:u,newLongestStreak:f,xpAwarded:C,multiplierApplied:N,streakPreserved:k}});if(r.code==="ALREADY_CLAIMED")return{success:!1,reward:c,dayIndex:n,streakAfter:r.state.currentStreak,longestStreakAfter:r.state.longestStreak,hintTokensAfter:r.state.hintTokens,streakShieldsAfter:r.state.streakShields,streakPreserved:!1,xpAwarded:0,multiplierApplied:1,isMilestone:!1,error:"Already claimed today"};if(r.xpAwarded>0)try{await na(t,r.xpAwarded,"daily_reward",`Daily Reward Day ${n+1}! +${r.xpAwarded} XP`)}catch(d){console.error("[dailyRewardService] Error awarding XP:",d)}if(c.type==="badge_unlock"&&typeof c.value=="string")try{await Is(t,c.value)}catch(d){console.error("[dailyRewardService] Error unlocking avatar item:",d)}const x=_l.has(r.newStreak);return{success:!0,reward:c,dayIndex:n,streakAfter:r.newStreak,longestStreakAfter:r.newLongestStreak,hintTokensAfter:r.state.hintTokens,streakShieldsAfter:r.state.streakShields,streakPreserved:r.streakPreserved,xpAwarded:r.xpAwarded,multiplierApplied:r.multiplierApplied,isMilestone:x}}catch(r){throw console.error("[dailyRewardService] Error claiming daily reward:",r),r}}function Ll(t){const[s,l]=a.useState(null),[n,i]=a.useState(!1),[c,r]=a.useState(!1),[x,d]=a.useState(null),[h,S]=a.useState(null),[m,z]=a.useState("00:00:00"),p=a.useRef(null),u=a.useMemo(()=>cs(),[]),k=a.useMemo(()=>_r(),[]),f=a.useCallback(async()=>{if(!t){l(null);return}try{S(null);const F=await Ts(t);l(F)}catch(F){const X=F instanceof Error?F.message:"Failed to load rewards";S(X),console.error("[useDailyReward] refresh error:",F)}},[t]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const F=()=>{const Z=Cr().getTime()-Date.now();z(Ml(Z))};return F(),p.current=setInterval(F,1e3),()=>{p.current&&(clearInterval(p.current),p.current=null)}},[]);const C=a.useMemo(()=>!s||n?!1:Tl(s),[s,n]),N=a.useMemo(()=>!s?.activeMultiplier||new Date(s.activeMultiplier.expiresAt).getTime()<=Date.now()?null:s.activeMultiplier,[s?.activeMultiplier]),R=a.useCallback(async()=>{if(!(!t||!C)){i(!0),S(null);try{const F=await Pl(t);if(d(F),F.success){r(!0);const X=await Ts(t);l(X)}else S(F.error||"Claim failed")}catch(F){const X=F instanceof Error?F.message:"Claim failed";S(X),console.error("[useDailyReward] claim error:",F)}finally{i(!1)}}},[t,C]),T=a.useCallback(()=>{r(!1)},[]);return{weekRewards:u,todayReward:k,canClaim:C,isClaiming:n,claimedDays:s?.claimedDays??[],currentStreak:s?.currentStreak??0,longestStreak:s?.longestStreak??0,totalClaimed:s?.totalClaimed??0,hintTokens:s?.hintTokens??0,streakShields:s?.streakShields??0,activeMultiplier:N,timeUntilReset:m,showModal:c,lastClaimResult:x,error:h,claim:R,dismissModal:T,refresh:f}}const Rl=["all","Q1","Q2","Q3","Q4"],An=({onEarnXP:t,atRiskSubjects:s=[],priorityTopics:l=[],initialModuleId:n=null,isInQuizMode:i=!1,setIsInQuizMode:c,hasCompletedDiagnostic:r=!1})=>{const{userProfile:x,currentUser:d}=Ht(),[h,S]=a.useState(()=>{const o=sessionStorage.getItem("mathpulse_modules_tab");return o==="practice"||o==="recommended"||o==="teacher_uploaded"?(sessionStorage.removeItem("mathpulse_modules_tab"),o):"modules"}),m=x,z=m?.grade,p=ia(z);Ra(p);const[u,k]=a.useState(""),[f,C]=a.useState("all"),[N,R]=a.useState("all"),[T,F]=a.useState("all"),[X,Z]=a.useState(!1),[Y,te]=a.useState(null),[$,pe]=a.useState(null),[he,ze]=a.useState(null);a.useEffect(()=>{if(x?.uid)return Zt(x.uid,ze)},[x?.uid]);const Ce=a.useMemo(()=>{const o=m?.learnerCurriculumAssignments?.subjects??m?.assignedSubjects??m?.curriculumAssignedSubjects??[];return Array.isArray(o)?o:[]},[m]),{difficulty:b}=Sl(d?.uid||null),H=a.useMemo(()=>{const o=oa(p,Ce);return zl(o,b)},[p,Ce,b]),ce=n&&H.find(o=>o.id===n)||null,[ae,le]=a.useState(ce),[ge,Ne]=a.useState(null),B=Fe.useRef(null),[Ee,_e]=a.useState(null),[ye,fe]=a.useState(!1),[Me,Ae]=a.useState(null),[g,q]=a.useState(!1),[M,O]=a.useState([]),[I,J]=a.useState(!1);a.useEffect(()=>{if(h!=="teacher_uploaded"||!Ue)return;J(!0);const o=as(Ks(Js(Ue,"modules"),Zs("moduleType","==","teacher_uploaded")),P=>{const y=P.docs.map(L=>({...L.data(),moduleId:L.id}));O(y),J(!1)},P=>{console.error("Error fetching teacher modules:",P),J(!1)});return()=>o()},[h]);const[be,ke]=a.useState(!1),{weekRewards:D,todayReward:ne,canClaim:me,isClaiming:Ge,claimedDays:ft,timeUntilReset:bt,claim:De,lastClaimResult:Xe}=Ll(x?.uid??null);a.useEffect(()=>{if(!x?.uid)return;let o=!1;const P=async K=>{o||(me||K)&&ke(!0)},y=K=>{K.detail?.tab==="Modules"&&P(!0)},L=setTimeout(()=>P(),500);return window.addEventListener("mathpulse:navigate",y),()=>{o=!0,clearTimeout(L),window.removeEventListener("mathpulse:navigate",y)}},[x?.uid,me]);const et=async()=>{if(x?.uid)try{await De(),Xe?.success&&(pa({userId:x.uid,type:"daily_checkin",title:"Daily Reward Claimed!",message:`You earned ${Xe.reward.label} and kept your streak alive!`,metadata:{rewardId:Xe.reward.id,streakDay:Xe.dayIndex+1}}).catch(console.error),Xe.reward.rarity==="epic"&&Is(x.uid,"acc_crown").then(()=>st.success("👑 Epic reward unlocked!")).catch(console.error)),setTimeout(()=>ke(!1),1e3)}catch(o){const P=o instanceof Error?o.message:"";console.error("Failed to claim daily reward:",o),P.includes("Already claimed")?st.info("You already claimed your reward today!"):st.error("Failed to claim daily reward. Please try again.")}};a.useEffect(()=>{if(n){const o=H.find(P=>P.id===n);o&&le(o)}},[n,H]),a.useEffect(()=>{x?.uid&&(q(!0),ca(x.uid).then(o=>{Ae(o)}).catch(o=>{console.error("Failed to load competency profile:",o)}).finally(()=>{q(!1)}))},[x?.uid]);const j=a.useMemo(()=>{const o=l.length>0?l:s.map(y=>da(y)).filter(y=>y!==null),P=new Set;return o.filter(y=>P.has(y)?!1:(P.add(y),!0))},[l,s]),{data:Te=[]}=Xs({queryKey:ma.modules(p,j),enabled:!0,staleTime:600*1e3,gcTime:1800*1e3,queryFn:async()=>{const o=H;if(j.length===0)return o;const P=new Map(j.map((y,L)=>[ha[y],L]));return[...o].sort((y,L)=>{const K=P.get(y.id)??Number.POSITIVE_INFINITY,de=P.get(L.id)??Number.POSITIVE_INFINITY;return K-de})}}),lt=a.useMemo(()=>{const o=new Set;return Te.forEach(P=>o.add(P.competency_group)),Array.from(o)},[Te]),Le=a.useMemo(()=>{const o=u.trim().toLowerCase(),P=Te.filter(y=>{const L=!o||y.title.toLowerCase().includes(o),K=!o||y.description.toLowerCase().includes(o),de=!o||y.lessons.some(w=>w.title.toLowerCase().includes(o)),ie=!o||y.quizzes.some(w=>w.title.toLowerCase().includes(o)),xe=o?y.competencies.some(w=>w.outcome.toLowerCase().includes(o)||w.code.toLowerCase().includes(o)):!0,je=f==="all"||y.subjectId===f,He=N==="all"||y.quarter===N,we=T==="all"||y.competency_group===T;return(L||K||de||ie||xe)&&je&&He&&we});if(Me?.competencies){const y=new Set(Object.entries(Me.competencies).filter(([,K])=>K.score<50).map(([K])=>K)),L=new Set(Object.entries(Me.competencies).filter(([,K])=>K.score>=80).map(([K])=>K));return P.sort((K,de)=>{const ie=K.competencies.map(W=>W.code),xe=de.competencies.map(W=>W.code),je=ie.some(W=>y.has(W))?1:0,He=xe.some(W=>y.has(W))?1:0,we=ie.some(W=>L.has(W))?1:0,w=xe.some(W=>L.has(W))?1:0,v=je*2+we;return He*2+w-v})}return P},[Te,u,f,N,T,Me]),Be=a.useMemo(()=>he?Le.map(o=>{const y=Object.values(he.subjects||{}).find(ie=>ie.modulesProgress?.[o.id])?.modulesProgress?.[o.id];if(!y)return o;const L=o.lessons.length+o.quizzes.length,K=(y.lessonsCompleted?.length||0)+(y.quizzesCompleted?.length||0),de=L>0?Math.round(K/L*100):0;return{...o,progress:de}}):Le,[Le,he]),gt=a.useMemo(()=>{const o=N==="all"?"All Quarters":N,P=f==="all"?"All Subjects":xs[f]?.label??"Subject";return`${p} · ${P} · ${o}`},[p,f,N]),nt=a.useMemo(()=>{const o=new Set(Te.map(P=>P.subjectId));return Array.from(o)},[Te]),Ve=()=>{C("all"),R("all"),F("all"),k("")};a.useEffect(()=>{h!=="recommended"||j.length===0||(fe(!0),xa({weakTopics:j.map(o=>us[o]),subject:f!=="all"?f:"General Mathematics",userId:x?.uid}).then(o=>{_e(o.curriculumContext),fe(!1)}).catch(()=>fe(!1)))},[h,j]);const it=(o,P)=>{t&&t(P,`Quiz Completed! +${P} XP`)},ot=async o=>{if(d?.uid)try{await Da(d.uid,o),st.success("You'll be notified when this module becomes available.")}catch{}};return a.useEffect(()=>{c&&c(!!ge)},[ge,c]),ge?e.jsx(Bs,{quiz:ge,onClose:()=>{B.current=null,Ne(null)},onComplete:it,onQuizEnd:B.current??void 0,studentId:x?.uid}):ae?e.jsx(wl,{module:ae,onBack:()=>le(null),onEarnXP:t,isInQuizMode:i,setIsInQuizMode:c}):$?e.jsxs("div",{className:"h-full overflow-y-auto px-4 sm:px-6 xl:px-10 pb-8 scrollbar-hide scroll-smooth relative",children:[e.jsxs("button",{onClick:()=>pe(null),className:"mb-4 inline-flex items-center gap-2 text-sm font-bold text-slate-600 hover:text-slate-900 transition-colors",children:[e.jsx(Ye,{className:"rotate-180",size:16}),"Back to Modules"]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-[#F08386]/30 p-6 md:p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F08386]/12 border border-[#F08386]/30 text-[#F08386] text-xs font-bold",children:"Teacher Upload"}),$.quarter&&e.jsx("span",{className:"px-2 py-1 rounded-md bg-slate-100 text-slate-600 text-xs",children:$.quarter})]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-display font-black text-slate-900 mb-2",children:$.title}),e.jsxs("p",{className:"text-sm text-slate-600 mb-6",children:[$.subject," · ",$.gradeLevel]}),$.summary&&e.jsx("p",{className:"text-slate-700 text-base leading-relaxed mb-6",children:$.summary}),$.learningObjectives?.length>0&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900 mb-2",children:"Learning Objectives"}),e.jsx("ul",{className:"list-disc list-inside space-y-1 text-slate-700",children:$.learningObjectives.map((o,P)=>e.jsx("li",{children:o},P))})]}),$.sections?.length>0&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900 mb-3",children:"Sections"}),e.jsx("div",{className:"space-y-3",children:$.sections.map((o,P)=>{const y=o.stepType||(o.content.includes("video lesson")?"video_lesson":o.content.includes("practice")?"practice":o.content.includes("assessment")?"assessment":o.content.includes("chat")?"chat_session":o.content.includes("review")?"review":void 0),L=!!y,K=y==="video_lesson"?ka:y==="practice"?Dt:y==="assessment"?_t:y==="chat_session"?Ca:y==="review"?Rt:null;return e.jsx("button",{type:"button",disabled:!L,onClick:()=>{if(L)if(y==="video_lesson"&&o.youtubeQuery)window.open(`https://www.youtube.com/results?search_query=${encodeURIComponent(o.youtubeQuery)}`,"_blank");else if(y==="video_lesson"){const de=o.topic||o.title.replace(/^Step \d+:\s*/,"");window.open(`https://www.youtube.com/results?search_query=${encodeURIComponent(de+" math lesson")}`,"_blank")}else y==="practice"||y==="assessment"?st.info(`Starting ${y==="assessment"?"assessment":"practice"}: ${o.topic||o.title}`):st.info(`Opening: ${o.title}`)},className:`w-full text-left border rounded-xl p-4 transition-all ${L?"border-slate-200 hover:border-indigo-300 hover:shadow-md hover:-translate-y-0.5 cursor-pointer group":"border-slate-200"} ${o.isCompleted?"bg-emerald-50/50 border-emerald-200":""}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-1 flex items-center gap-2",children:[K&&e.jsx(K,{size:14,className:"text-indigo-500 shrink-0"}),o.title,o.isCompleted&&e.jsx(_t,{size:14,className:"text-emerald-500 shrink-0"})]}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:o.content})]}),L&&e.jsx(Ye,{size:16,className:"text-slate-400 group-hover:text-indigo-500 shrink-0 transition-colors"})]})},P)})})]}),$.practice?.length>0&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900 mb-3",children:"Practice Questions"}),e.jsx("div",{className:"space-y-3",children:$.practice.map((o,P)=>e.jsxs("div",{className:"border border-slate-200 rounded-xl p-4",children:[e.jsx("p",{className:"text-sm font-bold text-slate-800 mb-2",children:o.question}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:o.options.map((y,L)=>e.jsxs("div",{className:"text-xs text-slate-600 bg-slate-50 rounded-lg px-3 py-2",children:[y.label,". ",y.text]},L))}),e.jsxs("p",{className:"text-xs text-emerald-700 font-semibold",children:["Answer: ",o.answer]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:o.explanation})]},P))})]})]})]}):e.jsxs("div",{className:"h-full overflow-y-auto px-4 sm:px-6 xl:px-10 pb-8 scrollbar-hide scroll-smooth relative",onScroll:o=>Z(o.currentTarget.scrollTop>100),children:[e.jsx(Cl,{isOpen:be,onClose:()=>ke(!1),onClaim:et,weekRewards:D,todayReward:ne,canClaim:me,isClaiming:Ge,claimedDays:ft,currentDayIndex:os(),timeUntilReset:bt}),e.jsxs("div",{className:"flex flex-col lg:flex-row justify-between items-start lg:items-center py-4 md:py-6 gap-4 md:gap-6",children:[e.jsxs("div",{className:"flex-1 max-w-3xl",children:[e.jsx("h1",{className:"text-[28px] md:text-[44px] font-display font-black text-[#202124] tracking-tight leading-[1.1] mb-3 md:mb-4",children:"Curriculum Modules"}),e.jsx("p",{className:"text-[#3c4043] text-[13px] md:text-[17px] leading-relaxed md:leading-[1.7] md:pr-10",children:"MathPulse AI loads modules directly from DepEd Strengthened SHS curriculum guides with AI-powered RAG lesson generation. Currently available: General Mathematics, Business Mathematics, and Statistics & Probability. Pre-Calculus and Basic Calculus modules are coming soon once teaching module PDFs are sourced."}),e.jsx("div",{className:"mt-4 flex items-center gap-3",children:e.jsx("div",{className:"inline-flex items-center rounded-full border border-sky-200 bg-sky-50 px-4 py-2 text-sm font-bold text-sky-900",children:gt})})]}),e.jsx("div",{className:"hidden lg:flex flex-shrink-0 items-center justify-end w-[350px]",children:e.jsx(Ms,{assessmentDismissed:x?.assessmentDismissed,initialAssessmentCompleted:x?.initialAssessmentCompleted})})]}),e.jsxs("div",{className:`sticky top-0 z-30 -mx-4 px-4 sm:-mx-6 sm:px-6 xl:-mx-10 xl:px-10 pt-3 pb-3 space-y-3 transition-colors duration-300 ${X?"bg-[#f8faff] border-b border-[#dde3eb] shadow-sm":"bg-transparent"}`,children:[e.jsxs("div",{className:"flex flex-col lg:flex-row items-center gap-3 w-full",children:[e.jsxs("div",{className:"relative flex-1 w-full",children:[e.jsx("div",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-[#5f6368]",children:e.jsx(Ia,{size:16,strokeWidth:2.5})}),e.jsx("input",{id:"modules-search",name:"modules-search","aria-label":"Search modules",type:"text",value:u,onChange:o=>k(o.target.value),placeholder:"Search modules, lessons, or assessments...",className:"w-full pl-10 pr-10 py-2 rounded-xl border border-[#dadce0] bg-white text-[#202124] text-[13px] font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all shadow-sm"}),!1]}),e.jsxs("div",{className:"flex flex-row overflow-x-auto no-scrollbar items-center gap-2 w-full lg:w-auto shrink-0 -mx-4 px-4 sm:mx-0 sm:px-0 pb-1 sm:pb-0",children:[e.jsxs("select",{value:f,onChange:o=>C(o.target.value),className:"shrink-0 rounded-xl border border-slate-200 bg-white pl-3 pr-8 py-2 text-xs font-semibold text-slate-700 focus:border-sky-400 focus:outline-none shadow-sm","aria-label":"Subject",children:[e.jsx("option",{value:"all",children:"All Subjects"}),nt.map(o=>e.jsx("option",{value:o,children:xs[o].label},o))]}),e.jsx("select",{value:N,onChange:o=>R(o.target.value),className:"shrink-0 rounded-xl border border-slate-200 bg-white pl-3 pr-8 py-2 text-xs font-semibold text-slate-700 focus:border-sky-400 focus:outline-none shadow-sm","aria-label":"Quarter",children:Rl.map(o=>e.jsx("option",{value:o,children:o==="all"?"All Quarters":o},o))}),e.jsxs("select",{value:T,onChange:o=>F(o.target.value),className:"shrink-0 rounded-xl border border-slate-200 bg-white pl-3 pr-8 py-2 text-xs font-semibold text-slate-700 focus:border-sky-400 focus:outline-none shadow-sm","aria-label":"Competency Group",children:[e.jsx("option",{value:"all",children:"All Competencies"}),lt.map(o=>e.jsx("option",{value:o,children:o},o))]}),e.jsxs("button",{type:"button",onClick:Ve,className:"inline-flex shrink-0 items-center justify-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-bold text-slate-700 transition-colors hover:bg-slate-50 shadow-sm",children:[e.jsx(Fa,{size:14}),"Reset"]})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-3 mt-2",children:[e.jsx("div",{className:"flex items-center bg-slate-100/80 p-1 rounded-full border border-slate-200/60 shadow-inner gap-1 overflow-x-auto no-scrollbar w-full md:w-auto",children:[{id:"modules",label:"Modules",icon:qe,color:"text-[#1FA7E1]"},{id:"recommended",label:"Recommended",icon:Lt,color:"text-[#75D06A]"},{id:"practice",label:"Practice",icon:We,color:"text-[#FFB356]"},{id:"teacher_uploaded",label:"Teacher Uploaded",icon:ua,color:"text-[#F08386]"}].map(o=>{const P=h===o.id;return e.jsxs("button",{onClick:()=>S(o.id),className:`relative flex items-center gap-1.5 px-4 py-1.5 rounded-full text-[13px] font-bold transition-all duration-300 flex-shrink-0 ${P?"shadow-sm":"text-slate-500 hover:text-slate-700 hover:bg-slate-200/50"}`,children:[P&&e.jsx(E.div,{layoutId:"modulesTabBackground",className:"absolute inset-0 bg-white rounded-full shadow-[0_2px_15px_-3px_rgba(0,0,0,0.1)] border border-slate-100",transition:{type:"spring",bounce:.2,duration:.6}}),e.jsxs("span",{className:`relative z-10 flex items-center gap-1.5 ${P?o.color:""}`,children:[e.jsx(o.icon,{size:15,strokeWidth:P?2.5:2}),o.label]})]},o.id)})}),e.jsxs("div",{className:"flex items-center gap-2 ml-1",children:[h==="modules"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-indigo-50 border border-indigo-100 flex items-center justify-center text-indigo-500",children:e.jsx(Sa,{size:15,strokeWidth:2.5})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"DepEd Strengthened SHS Modules"})]}),h==="recommended"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#75D06A]/10 flex items-center justify-center",children:e.jsx($a,{size:15,className:"text-[#75D06A]"})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"Suggested Next"})]}),h==="practice"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#FFB356]/10 flex items-center justify-center",children:e.jsx(We,{size:15,className:"text-[#FFB356]"})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"Practice Center"})]}),h==="teacher_uploaded"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#F08386]/15 border border-[#F08386]/30 flex items-center justify-center text-[#F08386]",children:e.jsx(bs,{size:15,strokeWidth:2.5})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"Teacher Uploaded Modules"})]})]})]})]}),e.jsx("div",{className:"flex lg:hidden items-center justify-center w-full mt-2 mb-2",children:e.jsx(Ms,{assessmentDismissed:x?.assessmentDismissed,initialAssessmentCompleted:x?.initialAssessmentCompleted})}),e.jsxs("div",{className:"pt-4",children:[j.length>0&&e.jsxs("div",{className:"mb-4 rounded-2xl border border-amber-300 bg-amber-50 px-5 py-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"inline-flex items-center gap-2 text-sm font-black text-amber-900",children:[e.jsx(Ls,{size:15}),"Assessment Focus Areas"]}),e.jsx("p",{className:"mt-1 text-sm text-amber-900/80",children:"Modules are currently prioritized by your latest diagnostic needs."})]}),e.jsxs("button",{type:"button",onClick:()=>S("recommended"),className:"inline-flex items-center gap-1.5 rounded-xl bg-amber-600 px-3 py-2 text-xs font-bold text-white transition-colors hover:bg-amber-700",children:["View Recommended",e.jsx(Ye,{size:14})]})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:j.map((o,P)=>e.jsxs("span",{className:"rounded-full bg-white px-3 py-1 text-xs font-semibold text-amber-900 shadow-sm",children:[P+1,". ",us[o]]},o))})]}),e.jsx(Je,{mode:"wait",children:e.jsx(E.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3},className:"pb-8 mt-4",children:h==="practice"?e.jsx(Nl,{userId:x?.uid??"",onStartQuiz:o=>{B.current=async(P,y)=>{if(!x?.uid)return;const L=P.title?.replace(/^Practice Quiz:\s*/i,"").replace(/\s*\(AI\)\s*$/i,"")||"",K=Math.round(y.filter(de=>de.correct).length/Math.max(y.length,1)*100);if(L){const de=`mathpulse_practice_completed_${x.uid}`;try{const ie=localStorage.getItem(de),xe=ie?JSON.parse(ie):[],je=new Map(xe),He=L.toLowerCase(),we=je.get(He)||{bestScore:0,attempts:0,history:[]};we.bestScore=Math.max(we.bestScore,K),we.attempts+=1,we.history.unshift({date:new Date().toISOString(),score:K,difficulty:P.difficulty||"Medium"}),je.set(He,we),localStorage.setItem(de,JSON.stringify(Array.from(je.entries())))}catch{}}if(P.generatedQuizId)try{const de=new Map((P.loadedQuestions||[]).map(je=>[je.id,je])),ie=y.map(je=>{const we=de.get(je.questionId)?.options?.findIndex(w=>w.trim().toLowerCase()===je.answer.trim().toLowerCase())??0;return{question_id:je.questionId,selected_index:we}}),xe=await bl({session_id:P.generatedQuizId,userId:x.uid,answers:ie});st.success(`Score: ${xe.score_percent}% | Correct: ${xe.correct_count}/${xe.total} | +${xe.xp_earned} XP`)}catch(de){console.error(de),st.success(`Score: ${K}%`)}},Ne(o)},searchQuery:u,atRiskTopics:j}):h==="teacher_uploaded"?I?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-6",children:[1,2,3].map(o=>e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 p-6 animate-pulse",children:[e.jsx("div",{className:"h-4 bg-slate-200 rounded w-3/4 mb-4"}),e.jsx("div",{className:"h-3 bg-slate-100 rounded w-1/2 mb-3"}),e.jsx("div",{className:"h-3 bg-slate-100 rounded w-5/6"})]},o))}):M.length===0?e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-[#F08386]/10 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(bs,{size:32,className:"text-[#F08386]"})}),e.jsx("h3",{className:"text-lg font-bold text-slate-800 mb-2",children:"No Teacher-Uploaded Modules Yet"}),e.jsx("p",{className:"text-slate-500 text-sm",children:"Your teachers haven't uploaded any custom modules yet."})]}):e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-3 md:gap-6 mt-6",children:M.map(o=>e.jsxs("div",{className:"bg-white rounded-2xl border border-[#F08386]/30 p-6 hover:border-[#F08386]/60 hover:shadow-md transition-all cursor-pointer",onClick:()=>pe(o),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F08386]/12 border border-[#F08386]/30 text-[#F08386] text-xs font-bold",children:"Teacher Upload"}),o.quarter&&e.jsx("span",{className:"px-2 py-1 rounded-md bg-slate-100 text-slate-600 text-xs",children:o.quarter})]}),e.jsx("h3",{className:"text-lg font-bold text-slate-900 mb-2 line-clamp-2",children:o.title}),e.jsxs("p",{className:"text-sm text-slate-600 mb-3",children:[o.subject," · ",o.gradeLevel]}),o.summary&&e.jsx("p",{className:"text-xs text-slate-500 line-clamp-3",children:o.summary})]},o.moduleId))}):h==="modules"?e.jsx(Dl,{modules:Be,onSelectModule:le,onPreviewSources:te,isAtRisk:j.length>0&&r,weakTopics:m?.assessmentResults?.weakTopics||[],onNotifyMe:ot}):e.jsx(Il,{modules:Be,fullPool:Te,onSelectModule:le,onPreviewSources:te,isAtRisk:j.length>0&&r,learningPathContext:Ee,learningPathLoading:ye,weakTopics:m?.assessmentResults?.weakTopics||[],onNotifyMe:ot})},h)})]}),e.jsx(Je,{children:Y&&e.jsxs(E.aside,{initial:{opacity:0,x:24},animate:{opacity:1,x:0},exit:{opacity:0,x:24},transition:{duration:.25},className:"fixed inset-y-0 right-0 z-[80] w-full max-w-xl border-l border-slate-200 bg-white p-6 shadow-2xl",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-black uppercase tracking-wide text-sky-700",children:"Curriculum Preview"}),e.jsx("h3",{className:"mt-1 text-xl font-black text-slate-900",children:Y.title}),e.jsxs("p",{className:"mt-1 text-sm text-slate-600",children:[Y.active_grade_level," · ",Y.subject," · ",Y.quarter]})]}),e.jsx("button",{type:"button",onClick:()=>te(null),className:"rounded-lg border border-slate-200 p-2 text-slate-500 hover:bg-slate-50",children:e.jsx(Ze,{size:16})})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto pr-1",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-slate-50 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Competency Group"}),e.jsx("p",{className:"mt-1 text-sm font-semibold text-slate-800",children:Y.competency_group})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Performance Standard"}),e.jsx("p",{className:"mt-1 text-sm text-slate-700",children:Y.performance_standard})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Competencies"}),e.jsx("div",{className:"mt-2 space-y-2",children:Y.competencies.map(o=>e.jsxs("div",{className:"rounded-xl border border-slate-100 bg-slate-50 p-3",children:[e.jsx("p",{className:"text-xs font-black text-slate-600",children:o.code}),e.jsx("p",{className:"mt-1 text-sm text-slate-700",children:o.outcome})]},o.code))})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Sources & Attribution"}),e.jsx("div",{className:"mt-3 space-y-2",children:Y.module_sources?.map(o=>e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",className:"flex items-center justify-between rounded-xl border border-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50",children:[e.jsx("span",{children:o.title}),e.jsx(za,{size:14,className:"text-slate-400"})]},o.id))}),e.jsxs("div",{className:"mt-4 rounded-xl bg-slate-50 border border-slate-100 p-3",children:[e.jsx("p",{className:"text-[11px] font-semibold text-slate-600 leading-relaxed",children:"Curriculum content adapted from the DepEd Strengthened Senior High School (SHS) Teaching Modules. Original materials are the intellectual property of the Department of Education — Schools Division Office of Navotas City. All rights reserved by the original authors and publishers."}),e.jsx("p",{className:"text-[10px] text-slate-500 mt-2 leading-relaxed",children:"Used under the Fair Use Doctrine (Republic Act No. 8293, Intellectual Property Code of the Philippines, Section 185) for non-commercial educational purposes. No copyright infringement is intended. This platform does not claim ownership of the source curriculum materials."})]})]})]})]})})]})},Dl=({modules:t,onSelectModule:s,onPreviewSources:l,isAtRisk:n=!1,weakTopics:i=[],onNotifyMe:c})=>e.jsx("div",{className:"pr-2 space-y-8",children:e.jsx("div",{children:t.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-[#dde3eb] p-8 text-center",children:[e.jsx("p",{className:"text-slate-700 font-semibold",children:"No matching modules found."}),e.jsx("p",{className:"mt-2 text-sm text-slate-500",children:"If modules are not yet available for your selected view, this area will unlock after assessment sync and content rollout."})]}):e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3 md:gap-6",children:t.map((r,x)=>{const d=i.some(h=>r.content_domain&&r.content_domain.toLowerCase().includes(h.toLowerCase())||r.title&&r.title.toLowerCase().includes(h.toLowerCase())||r.competency_group&&r.competency_group.toLowerCase().includes(h.toLowerCase())||r.subject&&r.subject.toLowerCase().includes(h.toLowerCase()));return e.jsx(Jt,{module:r,index:x,onClick:()=>s(r),onPreviewSources:()=>l(r),isAtRisk:n,isRecommended:d,onNotifyMe:c},r.id)})})})}),Il=({modules:t,fullPool:s,onSelectModule:l,onPreviewSources:n,isAtRisk:i=!1,learningPathContext:c=null,learningPathLoading:r=!1,weakTopics:x=[],onNotifyMe:d})=>{const h=t.filter(m=>m.progress>0&&m.progress<100),S=(t.length>0?t:s).filter(m=>m.progress===0).slice(0,6);return e.jsxs("div",{className:"pr-2 space-y-10",children:[r&&e.jsxs("div",{className:"mb-6 rounded-2xl border border-sky-200 bg-sky-50 px-5 py-4 flex items-center gap-3",children:[e.jsx("div",{className:"w-5 h-5 rounded-full border-2 border-sky-400 border-t-transparent animate-spin flex-shrink-0"}),e.jsx("p",{className:"text-sm font-semibold text-sky-800",children:"Building your personalized learning path from DepEd curriculum..."})]}),c&&!r&&e.jsxs("div",{className:"mb-6 rounded-2xl border border-indigo-200 bg-gradient-to-br from-indigo-50 to-purple-50 px-5 py-4 shadow-sm",children:[e.jsx("p",{className:"text-xs font-black uppercase tracking-wide text-indigo-700 mb-2",children:"📚 Your Personalized Learning Path"}),e.jsx("pre",{className:"whitespace-pre-wrap text-sm text-indigo-900 font-medium leading-relaxed font-sans",children:c})]}),h.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"w-10 h-10 rounded-[14px] bg-[#FF8B8B]/10 flex items-center justify-center text-[20px] shadow-inner",children:"🔥"}),e.jsx("h2",{className:"font-display font-black text-[24px] text-slate-800 tracking-tight",children:"Continue This Module"})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3 md:gap-6",children:h.slice(0,4).map((m,z)=>{const p=x.some(u=>m.content_domain&&m.content_domain.toLowerCase().includes(u.toLowerCase())||m.title&&m.title.toLowerCase().includes(u.toLowerCase())||m.competency_group&&m.competency_group.toLowerCase().includes(u.toLowerCase())||m.subject&&m.subject.toLowerCase().includes(u.toLowerCase()));return e.jsx(Jt,{module:m,index:z,onClick:()=>l(m),onPreviewSources:()=>n(m),isAtRisk:i,badgeLabel:"In Progress",isRecommended:p,onNotifyMe:d},m.id)})})]}),e.jsx("div",{children:S.length===0?e.jsx("div",{className:"bg-white rounded-2xl border border-[#dde3eb] p-8 text-center text-slate-500 font-medium",children:"You are all caught up. Practice more quizzes to unlock additional recommendations."}):e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3 md:gap-6",children:S.map((m,z)=>{const p=x.some(u=>m.content_domain&&m.content_domain.toLowerCase().includes(u.toLowerCase())||m.title&&m.title.toLowerCase().includes(u.toLowerCase())||m.competency_group&&m.competency_group.toLowerCase().includes(u.toLowerCase())||m.subject&&m.subject.toLowerCase().includes(u.toLowerCase()));return e.jsx(Jt,{module:m,index:z,onClick:()=>l(m),onPreviewSources:()=>n(m),isAtRisk:i,badgeLabel:"Start",isRecommended:p,onNotifyMe:d},m.id)})})})]})};export{An as default}; +`,Ms=({assessmentDismissed:t,initialAssessmentCompleted:s})=>{const l="absolute inset-0 w-full h-full object-contain",[n,i]=a.useState(!1);a.useEffect(()=>{t&&!s&&!sessionStorage.getItem("mathpulse_assessment_reminder_shown")?i(!0):i(!1)},[t,s]);const c=()=>{sessionStorage.setItem("mathpulse_assessment_reminder_shown","true"),i(!1),window.dispatchEvent(new CustomEvent("mathpulse:open-assessment"))};return e.jsxs(e.Fragment,{children:[e.jsx("style",{children:kl}),e.jsxs("div",{className:"relative w-full h-[250px] flex items-end justify-center drop-shadow-sm select-none pointer-events-none",children:[n&&e.jsxs(E.div,{initial:{opacity:0,scale:.8,x:10},animate:{opacity:1,scale:1,x:0},className:"absolute top-0 right-0 z-50 max-w-[180px] bg-white rounded-2xl shadow-lg border border-[#dde3eb] p-3 cursor-pointer pointer-events-auto",onClick:c,children:[e.jsx("p",{className:"text-[11px] font-bold text-[#0a1628] leading-snug",children:"Psst! Complete your assessment for a personalized path!"}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-1",children:[e.jsx("div",{className:"w-1.5 h-1.5 bg-purple-500 rounded-full animate-pulse"}),e.jsx("span",{className:"text-[10px] text-[#5a6578] font-medium",children:"Tap to start"})]}),e.jsx("div",{className:"absolute -bottom-2 left-4 w-3 h-3 bg-white border-r border-b border-[#dde3eb] rotate-45"})]}),e.jsx("img",{src:"/mascot/modules_avatar_body.png",alt:"Desk setup",className:`${l} z-10`}),e.jsxs("div",{className:`${l} z-20 animate-head-sway`,children:[e.jsx("img",{src:"/mascot/modules_left_horn.png",alt:"Left Horn",className:`${l} z-0 animate-horn-left`}),e.jsx("img",{src:"/mascot/modules_right_horn.png",alt:"Right Horn",className:`${l} z-0 animate-horn-right`}),e.jsx("img",{src:"/mascot/modules_head.png",alt:"Mascot Head",className:`${l} z-[1]`}),e.jsx("img",{src:"/mascot/modules_eyes.png",alt:"Eyes",className:`${l} z-[2] animate-blink`}),e.jsx("img",{src:"/mascot/modules_mouth.png",alt:"Mouth",className:`${l} z-[3] animate-mouth`})]})]})]})},As={common:"bg-slate-100 text-slate-500",rare:"bg-blue-50 text-blue-500",epic:"bg-amber-50 text-amber-500"},Es=["bg-[#1FA7E1]/80 text-white","bg-[#9956DE]/80 text-white","bg-[#FFB356]/90 text-white","bg-[#7274ED]/80 text-white","bg-[#1FA7E1]/80 text-white","bg-[#9956DE]/80 text-white","bg-gradient-to-r from-[#FFB356] to-[#FF8C00] text-white"],Cl=({isOpen:t,onClose:s,onClaim:l,weekRewards:n,todayReward:i,canClaim:c,isClaiming:r,claimedDays:x,currentDayIndex:d,timeUntilReset:h})=>{const[S,m]=a.useState(!1);if(!t)return null;const z=()=>{if(!c||S)return;m(!0),i?.rarity==="epic"?fs({particleCount:150,spread:80,origin:{y:.6},colors:["#FFD700","#FFA500","#FF8C00","#FF6B6B","#4ade80"]}):fs({particleCount:100,spread:70,origin:{y:.6},colors:["#FFD700","#FFA500","#FF8C00"]}),setTimeout(()=>{m(!1),l()},1200)},p=R=>R+1,u=R=>R===d,k=R=>x.includes(R),f=R=>R>d,C=n.slice(0,6),N=n[6];return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-8",children:[e.jsx(Je,{children:t&&e.jsx(E.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 bg-slate-900/60 backdrop-blur-sm",onClick:s})}),e.jsxs(E.div,{initial:{scale:.9,opacity:0,y:20},animate:{scale:1,opacity:1,y:0},exit:{scale:.9,opacity:0,y:20},className:"relative w-full max-w-[420px] bg-[#f7f9fc] rounded-3xl border border-[#dde3eb] shadow-2xl flex flex-col items-center p-5 overflow-visible",children:[e.jsxs("div",{className:"absolute -top-6 w-[85%] h-12 bg-gradient-to-r from-[#9956DE] via-[#7274ED] to-[#1FA7E1] rounded-xl shadow-lg flex items-center justify-center z-20",children:[e.jsx("div",{className:"absolute -left-2.5 -z-10 w-5 h-8 bg-[#633299] rounded-l-full rotate-12 top-1.5"}),e.jsx("div",{className:"absolute -right-2.5 -z-10 w-5 h-8 bg-[#10709b] rounded-r-full -rotate-12 top-1.5"}),e.jsx("h2",{className:"text-white font-black text-lg tracking-wide uppercase drop-shadow-sm font-display",children:"Daily Rewards"})]}),e.jsx("button",{onClick:s,className:"absolute -right-3 -top-3 w-8 h-8 bg-white hover:bg-slate-100 border border-slate-200 text-slate-500 hover:text-slate-800 rounded-full flex items-center justify-center z-30 shadow-md transition-transform hover:scale-105 active:scale-95",children:e.jsx(Ze,{size:16,strokeWidth:3})}),e.jsxs("div",{className:"mt-6 mb-2 text-center w-full",children:[e.jsx("h3",{className:"text-xl font-bold text-slate-800 font-display mt-2",children:"Welcome Back!"}),e.jsx("p",{className:"text-slate-500 font-medium text-xs mt-0.5",children:"Claim your daily reward for today."})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 w-full mb-5 relative z-10",children:[C.map((R,T)=>{const F=p(T),X=k(T),Z=u(T),Y=f(T);return e.jsxs("div",{className:`relative rounded-xl flex flex-col overflow-hidden border-[1.5px] transition-all ${Z&&!X?"border-amber-400 shadow-[0_0_15px_rgba(251,191,36,0.25)] scale-105 z-10 bg-amber-50":X?"border-[#dde3eb] bg-slate-200/50":"border-[#dde3eb] bg-white"}`,children:[e.jsxs("div",{className:`py-0.5 text-center font-black text-[10px] uppercase tracking-wider ${Z&&!X?"bg-amber-400 text-amber-900":Es[T]}`,children:["Day ",F]}),e.jsx("div",{className:"absolute top-5 right-1 z-10",children:e.jsx("span",{className:`text-[8px] font-bold uppercase px-1 rounded ${As[R.rarity]}`,children:R.rarity})}),e.jsxs("div",{className:"flex-1 p-2 flex flex-col items-center justify-center relative min-h-[75px]",children:[X&&e.jsxs(E.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",bounce:.5},className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-emerald-200/50"})}),e.jsxs("div",{className:"relative w-14 h-14 rounded-full border-[3px] border-emerald-500 bg-emerald-100 flex items-center justify-center transform -rotate-12 shadow-lg",children:[e.jsx(_t,{className:"w-8 h-8 text-emerald-600"}),e.jsx("div",{className:"absolute -bottom-2.5 left-1/2 -translate-x-1/2 bg-emerald-500 rounded-md px-2 py-0.5 border-2 border-emerald-300 shadow-md",children:e.jsx("span",{className:"text-[9px] font-black text-white uppercase tracking-wider leading-none whitespace-nowrap",children:"Claimed"})})]})]}),Y&&e.jsx("div",{className:"absolute top-1 right-1 bg-slate-200 rounded-full p-0.5 z-10",children:e.jsx(rs,{size:8,className:"text-slate-400"})}),e.jsxs("div",{className:`flex flex-col items-center transition-all w-full ${X?"opacity-30 grayscale":""}`,children:[e.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center border-2 mb-1",style:{backgroundColor:R.color+"20",borderColor:R.color+"40"},children:e.jsx("span",{className:"text-lg",children:R.icon})}),e.jsx("div",{className:`font-black text-xs leading-none mt-0.5 text-center ${Z?"text-amber-600":X?"text-slate-500":"text-slate-600"}`,children:R.label})]})]})]},R.id)}),N&&e.jsxs("div",{className:`col-span-3 relative rounded-xl flex flex-col overflow-hidden border-[1.5px] transition-all mt-1 ${u(6)&&!k(6)?"border-amber-400 shadow-[0_0_20px_rgba(251,191,36,0.3)] scale-[1.02] z-10 bg-amber-50":k(6)?"border-[#dde3eb] bg-slate-200/50":"border-[#dde3eb] bg-white"}`,children:[e.jsx("div",{className:`py-1 text-center font-black text-[10px] uppercase tracking-widest ${u(6)&&!k(6)?"bg-amber-400 text-amber-900":Es[6]}`,children:"Day 7 • Epic Reward"}),e.jsx("div",{className:"absolute top-6 right-2 z-10",children:e.jsx("span",{className:`text-[8px] font-bold uppercase px-1.5 py-0.5 rounded ${As[N.rarity]}`,children:N.rarity})}),e.jsxs("div",{className:"flex items-center justify-center gap-5 p-3 relative",children:[k(6)&&e.jsxs(E.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",bounce:.5},className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 rounded-full bg-rose-200/50"})}),e.jsxs("div",{className:"relative w-20 h-20 rounded-full border-[4px] border-rose-500 bg-rose-100 flex items-center justify-center transform rotate-12 shadow-lg",children:[e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"Claimed",className:"w-14 h-14 object-contain drop-shadow-md"}),e.jsx("div",{className:"absolute -bottom-3 left-1/2 -translate-x-1/2 bg-rose-500 rounded-md px-2.5 py-1 border-2 border-rose-300 shadow-md",children:e.jsx("span",{className:"text-[10px] font-black text-white uppercase tracking-wider leading-none whitespace-nowrap",children:"Claimed"})})]})]}),e.jsxs("div",{className:`flex items-center justify-center gap-5 w-full transition-all ${k(6)?"opacity-30 grayscale":""}`,children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center border-2 shadow-sm mb-0.5",style:{backgroundColor:N.color+"20",borderColor:N.color+"40"},children:e.jsx("span",{className:"text-2xl",children:N.icon})}),e.jsx("span",{className:`font-black text-sm ${u(6)?"text-amber-600":"text-slate-600"}`,children:N.label})]}),N.rarity==="epic"&&e.jsxs("div",{className:"relative mt-1",children:[e.jsx("div",{className:"w-14 h-14 bg-purple-50 rounded-xl flex items-center justify-center border-2 border-purple-200 shadow-sm",children:e.jsx(La,{className:"w-8 h-8 text-purple-500 drop-shadow-md"})}),e.jsx("div",{className:"absolute -right-5 -bottom-4 w-14 h-14 bg-white rounded-xl p-1 border-2 border-amber-300 shadow-lg transform rotate-[-5deg]",children:e.jsx("img",{src:"/avatar/crown_thumbnail.png",alt:"Crown",className:"w-full h-full object-contain drop-shadow-md"})})]})]})]})]})]}),e.jsxs("div",{className:"mb-3 flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(jr,{size:14}),e.jsx("span",{className:"font-mono font-medium",children:h}),e.jsx("span",{children:"until next reset"})]}),e.jsx(E.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:z,disabled:!c||r||S,className:`w-[85%] py-3 rounded-full font-black text-base tracking-wide uppercase shadow-lg transition-all mt-2 ${!c||r||S?"bg-slate-200 text-slate-400 cursor-not-allowed border border-slate-300":"bg-gradient-to-r from-[#FFB356] to-[#FF8C00] text-white hover:from-[#FFA500] hover:to-[#FF7F00] border-b-4 border-[#e67e00]"}`,children:r||S?"Claiming...":c?"Claim!":"Claimed"})]})]})};function Sl(t){const[s,l]=a.useState({difficulty:"normal",loading:!0});return a.useEffect(()=>{if(!t){l({difficulty:"normal",loading:!1});return}const n=mt(Ue,"users",t);return as(n,c=>{if(!c.exists()){l({difficulty:"normal",loading:!1});return}const x=c.data()?.moduleDifficulty||"normal";l({difficulty:["normal","easier","remedial"].includes(x)?x:"normal",loading:!1})},c=>{console.error("[useModuleDifficulty] snapshot error:",c),l({difficulty:"normal",loading:!1})})},[t]),s}function zl(t,s){return s==="normal"?t:s==="easier"?t.filter(l=>{const n=l.tags||[],i=l.difficulty||"";return n.some(c=>["foundation","basic","introductory"].includes(c.toLowerCase()))||["foundation","basic","introductory"].includes(i.toLowerCase())||!n.includes("advanced")&&!i.toLowerCase().includes("advanced")}):s==="remedial"?t.filter(l=>{const n=l.tags||[],i=l.difficulty||"";return n.some(c=>["remedial","review","catch-up"].includes(c.toLowerCase()))||["remedial","review","catch-up"].includes(i.toLowerCase())}):t}const _l=new Set([7,14,30,60,100]),Ct={lastClaimedDate:"",lastClaimedWeekSeed:0,claimedDays:[],currentStreak:0,longestStreak:0,totalClaimed:0,hintTokens:0,streakShields:0,activeMultiplier:null};function Ml(t){if(t<=0)return"00:00:00";const s=Math.floor(t/1e3),l=Math.floor(s/3600),n=Math.floor(s%3600/60),i=s%60;return`${String(l).padStart(2,"0")}:${String(n).padStart(2,"0")}:${String(i).padStart(2,"0")}`}function Al(){const t=ns();return t.setDate(t.getDate()-1),ls(t)}function Ws(t){return t?new Date(t.expiresAt).getTime()>Date.now():!1}function Us(t){return mt(Ue,"users",t,"dailyRewards",t)}function El(t){return mt(Ue,"users",t)}async function Ts(t){try{const s=Us(t),l=await Yt(s);if(!l.exists())return{...Ct};const n=l.data(),i=is();return n.lastClaimedWeekSeed&&n.lastClaimedWeekSeed!==i?{...n,claimedDays:[],lastClaimedWeekSeed:i}:{...Ct,...n,activeMultiplier:n.activeMultiplier&&Ws(n.activeMultiplier)?n.activeMultiplier:null}}catch(s){return console.error("[dailyRewardService] Error getting state:",s),{...Ct}}}function Tl(t){const s=ls();return t.lastClaimedDate!==s}async function Pl(t){const s=ls(),l=is(),n=os(),c=cs()[n];if(!c)throw new Error(`No reward found for day index ${n}`);try{const r=await Ys(Ue,async d=>{const h=Us(t),S=El(t),m=await d.get(h),z=await d.get(S);let p;if(m.exists()?p={...Ct,...m.data()}:(p={...Ct,lastClaimedWeekSeed:l},d.set(h,p)),p.lastClaimedWeekSeed!==l&&(p.claimedDays=[],p.lastClaimedWeekSeed=l),p.lastClaimedDate===s)return{code:"ALREADY_CLAIMED",state:p};let u=p.currentStreak,k=!1;if(!p.lastClaimedDate||p.currentStreak===0)u=1;else{const T=Al();p.lastClaimedDate===T?u=p.currentStreak+1:p.streakShields>0?(p.streakShields-=1,u=p.currentStreak+1,k=!0):u=1}const f=Math.max(p.longestStreak,u);let C=0,N=1;switch(c.type){case"xp":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||0;N=Ws(p.activeMultiplier)?p.activeMultiplier?.multiplier??1:1,C=Math.floor(T*N);break}case"hint_token":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||0;p.hintTokens+=T;break}case"streak_shield":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||0;p.streakShields+=T;break}case"xp_multiplier":{const T=typeof c.value=="number"?c.value:parseInt(c.value,10)||60,F=c.id.includes("2")?2:1.5,X=new Date;X.setMinutes(X.getMinutes()+T),p.activeMultiplier={multiplier:F,expiresAt:X.toISOString()};break}case"badge_unlock":break}const R=[...p.claimedDays,n];return p.lastClaimedDate=s,p.currentStreak=u,p.longestStreak=f,p.totalClaimed+=1,d.set(h,p,{merge:!0}),z.exists()&&d.update(S,{hintTokens:p.hintTokens,streakShields:p.streakShields,activeMultiplier:p.activeMultiplier,lastClaimedDate:p.lastClaimedDate,updatedAt:Ps()}),{code:"SUCCESS",state:p,newClaimedDays:R,newStreak:u,newLongestStreak:f,xpAwarded:C,multiplierApplied:N,streakPreserved:k}});if(r.code==="ALREADY_CLAIMED")return{success:!1,reward:c,dayIndex:n,streakAfter:r.state.currentStreak,longestStreakAfter:r.state.longestStreak,hintTokensAfter:r.state.hintTokens,streakShieldsAfter:r.state.streakShields,streakPreserved:!1,xpAwarded:0,multiplierApplied:1,isMilestone:!1,error:"Already claimed today"};if(r.xpAwarded>0)try{await na(t,r.xpAwarded,"daily_reward",`Daily Reward Day ${n+1}! +${r.xpAwarded} XP`)}catch(d){console.error("[dailyRewardService] Error awarding XP:",d)}if(c.type==="badge_unlock"&&typeof c.value=="string")try{await Is(t,c.value)}catch(d){console.error("[dailyRewardService] Error unlocking avatar item:",d)}const x=_l.has(r.newStreak);return{success:!0,reward:c,dayIndex:n,streakAfter:r.newStreak,longestStreakAfter:r.newLongestStreak,hintTokensAfter:r.state.hintTokens,streakShieldsAfter:r.state.streakShields,streakPreserved:r.streakPreserved,xpAwarded:r.xpAwarded,multiplierApplied:r.multiplierApplied,isMilestone:x}}catch(r){throw console.error("[dailyRewardService] Error claiming daily reward:",r),r}}function Ll(t){const[s,l]=a.useState(null),[n,i]=a.useState(!1),[c,r]=a.useState(!1),[x,d]=a.useState(null),[h,S]=a.useState(null),[m,z]=a.useState("00:00:00"),p=a.useRef(null),u=a.useMemo(()=>cs(),[]),k=a.useMemo(()=>_r(),[]),f=a.useCallback(async()=>{if(!t){l(null);return}try{S(null);const F=await Ts(t);l(F)}catch(F){const X=F instanceof Error?F.message:"Failed to load rewards";S(X),console.error("[useDailyReward] refresh error:",F)}},[t]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const F=()=>{const Z=Cr().getTime()-Date.now();z(Ml(Z))};return F(),p.current=setInterval(F,1e3),()=>{p.current&&(clearInterval(p.current),p.current=null)}},[]);const C=a.useMemo(()=>!s||n?!1:Tl(s),[s,n]),N=a.useMemo(()=>!s?.activeMultiplier||new Date(s.activeMultiplier.expiresAt).getTime()<=Date.now()?null:s.activeMultiplier,[s?.activeMultiplier]),R=a.useCallback(async()=>{if(!(!t||!C)){i(!0),S(null);try{const F=await Pl(t);if(d(F),F.success){r(!0);const X=await Ts(t);l(X)}else S(F.error||"Claim failed")}catch(F){const X=F instanceof Error?F.message:"Claim failed";S(X),console.error("[useDailyReward] claim error:",F)}finally{i(!1)}}},[t,C]),T=a.useCallback(()=>{r(!1)},[]);return{weekRewards:u,todayReward:k,canClaim:C,isClaiming:n,claimedDays:s?.claimedDays??[],currentStreak:s?.currentStreak??0,longestStreak:s?.longestStreak??0,totalClaimed:s?.totalClaimed??0,hintTokens:s?.hintTokens??0,streakShields:s?.streakShields??0,activeMultiplier:N,timeUntilReset:m,showModal:c,lastClaimResult:x,error:h,claim:R,dismissModal:T,refresh:f}}const Rl=["all","Q1","Q2","Q3","Q4"],An=({onEarnXP:t,atRiskSubjects:s=[],priorityTopics:l=[],initialModuleId:n=null,isInQuizMode:i=!1,setIsInQuizMode:c,hasCompletedDiagnostic:r=!1})=>{const{userProfile:x,currentUser:d}=Qt(),[h,S]=a.useState(()=>{const o=sessionStorage.getItem("mathpulse_modules_tab");return o==="practice"||o==="recommended"||o==="teacher_uploaded"?(sessionStorage.removeItem("mathpulse_modules_tab"),o):"modules"}),m=x,z=m?.grade,p=ia(z);Ra(p);const[u,k]=a.useState(""),[f,C]=a.useState("all"),[N,R]=a.useState("all"),[T,F]=a.useState("all"),[X,Z]=a.useState(!1),[Y,te]=a.useState(null),[$,pe]=a.useState(null),[he,ze]=a.useState(null);a.useEffect(()=>{if(x?.uid)return Zt(x.uid,ze)},[x?.uid]);const Ce=a.useMemo(()=>{const o=m?.learnerCurriculumAssignments?.subjects??m?.assignedSubjects??m?.curriculumAssignedSubjects??[];return Array.isArray(o)?o:[]},[m]),{difficulty:b}=Sl(d?.uid||null),Q=a.useMemo(()=>{const o=oa(p,Ce);return zl(o,b)},[p,Ce,b]),ce=n&&Q.find(o=>o.id===n)||null,[ae,le]=a.useState(ce),[ge,Ne]=a.useState(null),B=Fe.useRef(null),[Ee,_e]=a.useState(null),[ye,fe]=a.useState(!1),[Me,Ae]=a.useState(null),[g,q]=a.useState(!1),[M,O]=a.useState([]),[I,J]=a.useState(!1);a.useEffect(()=>{if(h!=="teacher_uploaded"||!Ue)return;J(!0);const o=as(Ks(Js(Ue,"modules"),Zs("moduleType","==","teacher_uploaded")),P=>{const y=P.docs.map(L=>({...L.data(),moduleId:L.id}));O(y),J(!1)},P=>{console.error("Error fetching teacher modules:",P),J(!1)});return()=>o()},[h]);const[be,ke]=a.useState(!1),{weekRewards:D,todayReward:ne,canClaim:me,isClaiming:Ge,claimedDays:ft,timeUntilReset:bt,claim:De,lastClaimResult:Xe}=Ll(x?.uid??null);a.useEffect(()=>{if(!x?.uid)return;let o=!1;const P=async K=>{o||(me||K)&&ke(!0)},y=K=>{K.detail?.tab==="Modules"&&P(!0)},L=setTimeout(()=>P(),500);return window.addEventListener("mathpulse:navigate",y),()=>{o=!0,clearTimeout(L),window.removeEventListener("mathpulse:navigate",y)}},[x?.uid,me]);const et=async()=>{if(x?.uid)try{await De(),Xe?.success&&(pa({userId:x.uid,type:"daily_checkin",title:"Daily Reward Claimed!",message:`You earned ${Xe.reward.label} and kept your streak alive!`,metadata:{rewardId:Xe.reward.id,streakDay:Xe.dayIndex+1}}).catch(console.error),Xe.reward.rarity==="epic"&&Is(x.uid,"acc_crown").then(()=>st.success("👑 Epic reward unlocked!")).catch(console.error)),setTimeout(()=>ke(!1),1e3)}catch(o){const P=o instanceof Error?o.message:"";console.error("Failed to claim daily reward:",o),P.includes("Already claimed")?st.info("You already claimed your reward today!"):st.error("Failed to claim daily reward. Please try again.")}};a.useEffect(()=>{if(n){const o=Q.find(P=>P.id===n);o&&le(o)}},[n,Q]),a.useEffect(()=>{x?.uid&&(q(!0),ca(x.uid).then(o=>{Ae(o)}).catch(o=>{console.error("Failed to load competency profile:",o)}).finally(()=>{q(!1)}))},[x?.uid]);const j=a.useMemo(()=>{const o=l.length>0?l:s.map(y=>da(y)).filter(y=>y!==null),P=new Set;return o.filter(y=>P.has(y)?!1:(P.add(y),!0))},[l,s]),{data:Te=[]}=Xs({queryKey:ma.modules(p,j),enabled:!0,staleTime:600*1e3,gcTime:1800*1e3,queryFn:async()=>{const o=Q;if(j.length===0)return o;const P=new Map(j.map((y,L)=>[ha[y],L]));return[...o].sort((y,L)=>{const K=P.get(y.id)??Number.POSITIVE_INFINITY,de=P.get(L.id)??Number.POSITIVE_INFINITY;return K-de})}}),lt=a.useMemo(()=>{const o=new Set;return Te.forEach(P=>o.add(P.competency_group)),Array.from(o)},[Te]),Le=a.useMemo(()=>{const o=u.trim().toLowerCase(),P=Te.filter(y=>{const L=!o||y.title.toLowerCase().includes(o),K=!o||y.description.toLowerCase().includes(o),de=!o||y.lessons.some(w=>w.title.toLowerCase().includes(o)),ie=!o||y.quizzes.some(w=>w.title.toLowerCase().includes(o)),xe=o?y.competencies.some(w=>w.outcome.toLowerCase().includes(o)||w.code.toLowerCase().includes(o)):!0,je=f==="all"||y.subjectId===f,Qe=N==="all"||y.quarter===N,we=T==="all"||y.competency_group===T;return(L||K||de||ie||xe)&&je&&Qe&&we});if(Me?.competencies){const y=new Set(Object.entries(Me.competencies).filter(([,K])=>K.score<50).map(([K])=>K)),L=new Set(Object.entries(Me.competencies).filter(([,K])=>K.score>=80).map(([K])=>K));return P.sort((K,de)=>{const ie=K.competencies.map(W=>W.code),xe=de.competencies.map(W=>W.code),je=ie.some(W=>y.has(W))?1:0,Qe=xe.some(W=>y.has(W))?1:0,we=ie.some(W=>L.has(W))?1:0,w=xe.some(W=>L.has(W))?1:0,v=je*2+we;return Qe*2+w-v})}return P},[Te,u,f,N,T,Me]),Be=a.useMemo(()=>he?Le.map(o=>{const y=Object.values(he.subjects||{}).find(ie=>ie.modulesProgress?.[o.id])?.modulesProgress?.[o.id];if(!y)return o;const L=o.lessons.length+o.quizzes.length,K=(y.lessonsCompleted?.length||0)+(y.quizzesCompleted?.length||0),de=L>0?Math.round(K/L*100):0;return{...o,progress:de}}):Le,[Le,he]),gt=a.useMemo(()=>{const o=N==="all"?"All Quarters":N,P=f==="all"?"All Subjects":xs[f]?.label??"Subject";return`${p} · ${P} · ${o}`},[p,f,N]),nt=a.useMemo(()=>{const o=new Set(Te.map(P=>P.subjectId));return Array.from(o)},[Te]),Ve=()=>{C("all"),R("all"),F("all"),k("")};a.useEffect(()=>{h!=="recommended"||j.length===0||(fe(!0),xa({weakTopics:j.map(o=>us[o]),subject:f!=="all"?f:"General Mathematics",userId:x?.uid}).then(o=>{_e(o.curriculumContext),fe(!1)}).catch(()=>fe(!1)))},[h,j]);const it=(o,P)=>{t&&t(P,`Quiz Completed! +${P} XP`)},ot=async o=>{if(d?.uid)try{await Da(d.uid,o),st.success("You'll be notified when this module becomes available.")}catch{}};return a.useEffect(()=>{c&&c(!!ge)},[ge,c]),ge?e.jsx(Bs,{quiz:ge,onClose:()=>{B.current=null,Ne(null)},onComplete:it,onQuizEnd:B.current??void 0,studentId:x?.uid}):ae?e.jsx(wl,{module:ae,onBack:()=>le(null),onEarnXP:t,isInQuizMode:i,setIsInQuizMode:c}):$?e.jsxs("div",{className:"h-full overflow-y-auto px-4 sm:px-6 xl:px-10 pb-8 scrollbar-hide scroll-smooth relative",children:[e.jsxs("button",{onClick:()=>pe(null),className:"mb-4 inline-flex items-center gap-2 text-sm font-bold text-slate-600 hover:text-slate-900 transition-colors",children:[e.jsx(Ye,{className:"rotate-180",size:16}),"Back to Modules"]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-[#F08386]/30 p-6 md:p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F08386]/12 border border-[#F08386]/30 text-[#F08386] text-xs font-bold",children:"Teacher Upload"}),$.quarter&&e.jsx("span",{className:"px-2 py-1 rounded-md bg-slate-100 text-slate-600 text-xs",children:$.quarter})]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-display font-black text-slate-900 mb-2",children:$.title}),e.jsxs("p",{className:"text-sm text-slate-600 mb-6",children:[$.subject," · ",$.gradeLevel]}),$.summary&&e.jsx("p",{className:"text-slate-700 text-base leading-relaxed mb-6",children:$.summary}),$.learningObjectives?.length>0&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900 mb-2",children:"Learning Objectives"}),e.jsx("ul",{className:"list-disc list-inside space-y-1 text-slate-700",children:$.learningObjectives.map((o,P)=>e.jsx("li",{children:o},P))})]}),$.sections?.length>0&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900 mb-3",children:"Sections"}),e.jsx("div",{className:"space-y-3",children:$.sections.map((o,P)=>{const y=o.stepType||(o.content.includes("video lesson")?"video_lesson":o.content.includes("practice")?"practice":o.content.includes("assessment")?"assessment":o.content.includes("chat")?"chat_session":o.content.includes("review")?"review":void 0),L=!!y,K=y==="video_lesson"?ka:y==="practice"?Dt:y==="assessment"?_t:y==="chat_session"?Ca:y==="review"?Rt:null;return e.jsx("button",{type:"button",disabled:!L,onClick:()=>{if(L)if(y==="video_lesson"&&o.youtubeQuery)window.open(`https://www.youtube.com/results?search_query=${encodeURIComponent(o.youtubeQuery)}`,"_blank");else if(y==="video_lesson"){const de=o.topic||o.title.replace(/^Step \d+:\s*/,"");window.open(`https://www.youtube.com/results?search_query=${encodeURIComponent(de+" math lesson")}`,"_blank")}else y==="practice"||y==="assessment"?st.info(`Starting ${y==="assessment"?"assessment":"practice"}: ${o.topic||o.title}`):st.info(`Opening: ${o.title}`)},className:`w-full text-left border rounded-xl p-4 transition-all ${L?"border-slate-200 hover:border-indigo-300 hover:shadow-md hover:-translate-y-0.5 cursor-pointer group":"border-slate-200"} ${o.isCompleted?"bg-emerald-50/50 border-emerald-200":""}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-1 flex items-center gap-2",children:[K&&e.jsx(K,{size:14,className:"text-indigo-500 shrink-0"}),o.title,o.isCompleted&&e.jsx(_t,{size:14,className:"text-emerald-500 shrink-0"})]}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:o.content})]}),L&&e.jsx(Ye,{size:16,className:"text-slate-400 group-hover:text-indigo-500 shrink-0 transition-colors"})]})},P)})})]}),$.practice?.length>0&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900 mb-3",children:"Practice Questions"}),e.jsx("div",{className:"space-y-3",children:$.practice.map((o,P)=>e.jsxs("div",{className:"border border-slate-200 rounded-xl p-4",children:[e.jsx("p",{className:"text-sm font-bold text-slate-800 mb-2",children:o.question}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:o.options.map((y,L)=>e.jsxs("div",{className:"text-xs text-slate-600 bg-slate-50 rounded-lg px-3 py-2",children:[y.label,". ",y.text]},L))}),e.jsxs("p",{className:"text-xs text-emerald-700 font-semibold",children:["Answer: ",o.answer]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:o.explanation})]},P))})]})]})]}):e.jsxs("div",{className:"h-full overflow-y-auto px-4 sm:px-6 xl:px-10 pb-8 scrollbar-hide scroll-smooth relative",onScroll:o=>Z(o.currentTarget.scrollTop>100),children:[e.jsx(Cl,{isOpen:be,onClose:()=>ke(!1),onClaim:et,weekRewards:D,todayReward:ne,canClaim:me,isClaiming:Ge,claimedDays:ft,currentDayIndex:os(),timeUntilReset:bt}),e.jsxs("div",{className:"flex flex-col lg:flex-row justify-between items-start lg:items-center py-4 md:py-6 gap-4 md:gap-6",children:[e.jsxs("div",{className:"flex-1 max-w-3xl",children:[e.jsx("h1",{className:"text-[28px] md:text-[44px] font-display font-black text-[#202124] tracking-tight leading-[1.1] mb-3 md:mb-4",children:"Curriculum Modules"}),e.jsx("p",{className:"text-[#3c4043] text-[13px] md:text-[17px] leading-relaxed md:leading-[1.7] md:pr-10",children:"MathPulse AI loads modules directly from DepEd Strengthened SHS curriculum guides with AI-powered RAG lesson generation. Currently available: General Mathematics, Business Mathematics, and Statistics & Probability. Pre-Calculus and Basic Calculus modules are coming soon once teaching module PDFs are sourced."}),e.jsx("div",{className:"mt-4 flex items-center gap-3",children:e.jsx("div",{className:"inline-flex items-center rounded-full border border-sky-200 bg-sky-50 px-4 py-2 text-sm font-bold text-sky-900",children:gt})})]}),e.jsx("div",{className:"hidden lg:flex flex-shrink-0 items-center justify-end w-[350px]",children:e.jsx(Ms,{assessmentDismissed:x?.assessmentDismissed,initialAssessmentCompleted:x?.initialAssessmentCompleted})})]}),e.jsxs("div",{className:`sticky top-0 z-30 -mx-4 px-4 sm:-mx-6 sm:px-6 xl:-mx-10 xl:px-10 pt-3 pb-3 space-y-3 transition-colors duration-300 ${X?"bg-[#f8faff] border-b border-[#dde3eb] shadow-sm":"bg-transparent"}`,children:[e.jsxs("div",{className:"flex flex-col lg:flex-row items-center gap-3 w-full",children:[e.jsxs("div",{className:"relative flex-1 w-full",children:[e.jsx("div",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-[#5f6368]",children:e.jsx(Ia,{size:16,strokeWidth:2.5})}),e.jsx("input",{id:"modules-search",name:"modules-search","aria-label":"Search modules",type:"text",value:u,onChange:o=>k(o.target.value),placeholder:"Search modules, lessons, or assessments...",className:"w-full pl-10 pr-10 py-2 rounded-xl border border-[#dadce0] bg-white text-[#202124] text-[13px] font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all shadow-sm"}),!1]}),e.jsxs("div",{className:"flex flex-row overflow-x-auto no-scrollbar items-center gap-2 w-full lg:w-auto shrink-0 -mx-4 px-4 sm:mx-0 sm:px-0 pb-1 sm:pb-0",children:[e.jsxs("select",{value:f,onChange:o=>C(o.target.value),className:"shrink-0 rounded-xl border border-slate-200 bg-white pl-3 pr-8 py-2 text-xs font-semibold text-slate-700 focus:border-sky-400 focus:outline-none shadow-sm","aria-label":"Subject",children:[e.jsx("option",{value:"all",children:"All Subjects"}),nt.map(o=>e.jsx("option",{value:o,children:xs[o].label},o))]}),e.jsx("select",{value:N,onChange:o=>R(o.target.value),className:"shrink-0 rounded-xl border border-slate-200 bg-white pl-3 pr-8 py-2 text-xs font-semibold text-slate-700 focus:border-sky-400 focus:outline-none shadow-sm","aria-label":"Quarter",children:Rl.map(o=>e.jsx("option",{value:o,children:o==="all"?"All Quarters":o},o))}),e.jsxs("select",{value:T,onChange:o=>F(o.target.value),className:"shrink-0 rounded-xl border border-slate-200 bg-white pl-3 pr-8 py-2 text-xs font-semibold text-slate-700 focus:border-sky-400 focus:outline-none shadow-sm","aria-label":"Competency Group",children:[e.jsx("option",{value:"all",children:"All Competencies"}),lt.map(o=>e.jsx("option",{value:o,children:o},o))]}),e.jsxs("button",{type:"button",onClick:Ve,className:"inline-flex shrink-0 items-center justify-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-bold text-slate-700 transition-colors hover:bg-slate-50 shadow-sm",children:[e.jsx(Fa,{size:14}),"Reset"]})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-3 mt-2",children:[e.jsx("div",{className:"flex items-center bg-slate-100/80 p-1 rounded-full border border-slate-200/60 shadow-inner gap-1 overflow-x-auto no-scrollbar w-full md:w-auto",children:[{id:"modules",label:"Modules",icon:qe,color:"text-[#1FA7E1]"},{id:"recommended",label:"Recommended",icon:Lt,color:"text-[#75D06A]"},{id:"practice",label:"Practice",icon:We,color:"text-[#FFB356]"},{id:"teacher_uploaded",label:"Teacher Uploaded",icon:ua,color:"text-[#F08386]"}].map(o=>{const P=h===o.id;return e.jsxs("button",{onClick:()=>S(o.id),className:`relative flex items-center gap-1.5 px-4 py-1.5 rounded-full text-[13px] font-bold transition-all duration-300 flex-shrink-0 ${P?"shadow-sm":"text-slate-500 hover:text-slate-700 hover:bg-slate-200/50"}`,children:[P&&e.jsx(E.div,{layoutId:"modulesTabBackground",className:"absolute inset-0 bg-white rounded-full shadow-[0_2px_15px_-3px_rgba(0,0,0,0.1)] border border-slate-100",transition:{type:"spring",bounce:.2,duration:.6}}),e.jsxs("span",{className:`relative z-10 flex items-center gap-1.5 ${P?o.color:""}`,children:[e.jsx(o.icon,{size:15,strokeWidth:P?2.5:2}),o.label]})]},o.id)})}),e.jsxs("div",{className:"flex items-center gap-2 ml-1",children:[h==="modules"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-indigo-50 border border-indigo-100 flex items-center justify-center text-indigo-500",children:e.jsx(Sa,{size:15,strokeWidth:2.5})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"DepEd Strengthened SHS Modules"})]}),h==="recommended"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#75D06A]/10 flex items-center justify-center",children:e.jsx($a,{size:15,className:"text-[#75D06A]"})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"Suggested Next"})]}),h==="practice"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#FFB356]/10 flex items-center justify-center",children:e.jsx(We,{size:15,className:"text-[#FFB356]"})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"Practice Center"})]}),h==="teacher_uploaded"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#F08386]/15 border border-[#F08386]/30 flex items-center justify-center text-[#F08386]",children:e.jsx(bs,{size:15,strokeWidth:2.5})}),e.jsx("span",{className:"font-display font-black text-[15px] text-slate-700 tracking-tight whitespace-nowrap",children:"Teacher Uploaded Modules"})]})]})]})]}),e.jsx("div",{className:"flex lg:hidden items-center justify-center w-full mt-2 mb-2",children:e.jsx(Ms,{assessmentDismissed:x?.assessmentDismissed,initialAssessmentCompleted:x?.initialAssessmentCompleted})}),e.jsxs("div",{className:"pt-4",children:[j.length>0&&e.jsxs("div",{className:"mb-4 rounded-2xl border border-amber-300 bg-amber-50 px-5 py-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"inline-flex items-center gap-2 text-sm font-black text-amber-900",children:[e.jsx(Ls,{size:15}),"Assessment Focus Areas"]}),e.jsx("p",{className:"mt-1 text-sm text-amber-900/80",children:"Modules are currently prioritized by your latest diagnostic needs."})]}),e.jsxs("button",{type:"button",onClick:()=>S("recommended"),className:"inline-flex items-center gap-1.5 rounded-xl bg-amber-600 px-3 py-2 text-xs font-bold text-white transition-colors hover:bg-amber-700",children:["View Recommended",e.jsx(Ye,{size:14})]})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:j.map((o,P)=>e.jsxs("span",{className:"rounded-full bg-white px-3 py-1 text-xs font-semibold text-amber-900 shadow-sm",children:[P+1,". ",us[o]]},o))})]}),e.jsx(Je,{mode:"wait",children:e.jsx(E.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3},className:"pb-8 mt-4",children:h==="practice"?e.jsx(Nl,{userId:x?.uid??"",onStartQuiz:o=>{B.current=async(P,y)=>{if(!x?.uid)return;const L=P.title?.replace(/^Practice Quiz:\s*/i,"").replace(/\s*\(AI\)\s*$/i,"")||"",K=Math.round(y.filter(de=>de.correct).length/Math.max(y.length,1)*100);if(L){const de=`mathpulse_practice_completed_${x.uid}`;try{const ie=localStorage.getItem(de),xe=ie?JSON.parse(ie):[],je=new Map(xe),Qe=L.toLowerCase(),we=je.get(Qe)||{bestScore:0,attempts:0,history:[]};we.bestScore=Math.max(we.bestScore,K),we.attempts+=1,we.history.unshift({date:new Date().toISOString(),score:K,difficulty:P.difficulty||"Medium"}),je.set(Qe,we),localStorage.setItem(de,JSON.stringify(Array.from(je.entries())))}catch{}}if(P.generatedQuizId)try{const de=new Map((P.loadedQuestions||[]).map(je=>[je.id,je])),ie=y.map(je=>{const we=de.get(je.questionId)?.options?.findIndex(w=>w.trim().toLowerCase()===je.answer.trim().toLowerCase())??0;return{question_id:je.questionId,selected_index:we}}),xe=await bl({session_id:P.generatedQuizId,userId:x.uid,answers:ie});st.success(`Score: ${xe.score_percent}% | Correct: ${xe.correct_count}/${xe.total} | +${xe.xp_earned} XP`)}catch(de){console.error(de),st.success(`Score: ${K}%`)}},Ne(o)},searchQuery:u,atRiskTopics:j}):h==="teacher_uploaded"?I?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-6",children:[1,2,3].map(o=>e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 p-6 animate-pulse",children:[e.jsx("div",{className:"h-4 bg-slate-200 rounded w-3/4 mb-4"}),e.jsx("div",{className:"h-3 bg-slate-100 rounded w-1/2 mb-3"}),e.jsx("div",{className:"h-3 bg-slate-100 rounded w-5/6"})]},o))}):M.length===0?e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-[#F08386]/10 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(bs,{size:32,className:"text-[#F08386]"})}),e.jsx("h3",{className:"text-lg font-bold text-slate-800 mb-2",children:"No Teacher-Uploaded Modules Yet"}),e.jsx("p",{className:"text-slate-500 text-sm",children:"Your teachers haven't uploaded any custom modules yet."})]}):e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-3 md:gap-6 mt-6",children:M.map(o=>e.jsxs("div",{className:"bg-white rounded-2xl border border-[#F08386]/30 p-6 hover:border-[#F08386]/60 hover:shadow-md transition-all cursor-pointer",onClick:()=>pe(o),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F08386]/12 border border-[#F08386]/30 text-[#F08386] text-xs font-bold",children:"Teacher Upload"}),o.quarter&&e.jsx("span",{className:"px-2 py-1 rounded-md bg-slate-100 text-slate-600 text-xs",children:o.quarter})]}),e.jsx("h3",{className:"text-lg font-bold text-slate-900 mb-2 line-clamp-2",children:o.title}),e.jsxs("p",{className:"text-sm text-slate-600 mb-3",children:[o.subject," · ",o.gradeLevel]}),o.summary&&e.jsx("p",{className:"text-xs text-slate-500 line-clamp-3",children:o.summary})]},o.moduleId))}):h==="modules"?e.jsx(Dl,{modules:Be,onSelectModule:le,onPreviewSources:te,isAtRisk:j.length>0&&r,weakTopics:m?.assessmentResults?.weakTopics||[],onNotifyMe:ot}):e.jsx(Il,{modules:Be,fullPool:Te,onSelectModule:le,onPreviewSources:te,isAtRisk:j.length>0&&r,learningPathContext:Ee,learningPathLoading:ye,weakTopics:m?.assessmentResults?.weakTopics||[],onNotifyMe:ot})},h)})]}),e.jsx(Je,{children:Y&&e.jsxs(E.aside,{initial:{opacity:0,x:24},animate:{opacity:1,x:0},exit:{opacity:0,x:24},transition:{duration:.25},className:"fixed inset-y-0 right-0 z-[80] w-full max-w-xl border-l border-slate-200 bg-white p-6 shadow-2xl",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-black uppercase tracking-wide text-sky-700",children:"Curriculum Preview"}),e.jsx("h3",{className:"mt-1 text-xl font-black text-slate-900",children:Y.title}),e.jsxs("p",{className:"mt-1 text-sm text-slate-600",children:[Y.active_grade_level," · ",Y.subject," · ",Y.quarter]})]}),e.jsx("button",{type:"button",onClick:()=>te(null),className:"rounded-lg border border-slate-200 p-2 text-slate-500 hover:bg-slate-50",children:e.jsx(Ze,{size:16})})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto pr-1",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-slate-50 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Competency Group"}),e.jsx("p",{className:"mt-1 text-sm font-semibold text-slate-800",children:Y.competency_group})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Performance Standard"}),e.jsx("p",{className:"mt-1 text-sm text-slate-700",children:Y.performance_standard})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Competencies"}),e.jsx("div",{className:"mt-2 space-y-2",children:Y.competencies.map(o=>e.jsxs("div",{className:"rounded-xl border border-slate-100 bg-slate-50 p-3",children:[e.jsx("p",{className:"text-xs font-black text-slate-600",children:o.code}),e.jsx("p",{className:"mt-1 text-sm text-slate-700",children:o.outcome})]},o.code))})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Sources & Attribution"}),e.jsx("div",{className:"mt-3 space-y-2",children:Y.module_sources?.map(o=>e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",className:"flex items-center justify-between rounded-xl border border-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50",children:[e.jsx("span",{children:o.title}),e.jsx(za,{size:14,className:"text-slate-400"})]},o.id))}),e.jsxs("div",{className:"mt-4 rounded-xl bg-slate-50 border border-slate-100 p-3",children:[e.jsx("p",{className:"text-[11px] font-semibold text-slate-600 leading-relaxed",children:"The learning materials and reference documents utilized within A Web-based AI-Driven Supplemental System in Learning Mathematics for Grade 11 General Mathematics are sourced from publicly accessible repositories of the Department of Education (DepEd), specifically the Schools Division Office (SDO) of Navotas."}),e.jsx("p",{className:"text-[10px] text-slate-500 mt-2 leading-relaxed",children:"These materials are used strictly for non-commercial, academic research, and system testing purposes under the Fair Use Doctrine of the Intellectual Property Code of the Philippines (Republic Act No. 8293)."}),e.jsx("p",{className:"text-[10px] text-slate-500 mt-2 leading-relaxed",children:"This platform is an independent academic capstone project. It is not officially affiliated with or endorsed by DepEd. Upon full implementation, the system's knowledge base will be updated to utilize the localized modules explicitly authorized by the partner institution."})]})]})]})]})})]})},Dl=({modules:t,onSelectModule:s,onPreviewSources:l,isAtRisk:n=!1,weakTopics:i=[],onNotifyMe:c})=>e.jsx("div",{className:"pr-2 space-y-8",children:e.jsx("div",{children:t.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-[#dde3eb] p-8 text-center",children:[e.jsx("p",{className:"text-slate-700 font-semibold",children:"No matching modules found."}),e.jsx("p",{className:"mt-2 text-sm text-slate-500",children:"If modules are not yet available for your selected view, this area will unlock after assessment sync and content rollout."})]}):e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3 md:gap-6",children:t.map((r,x)=>{const d=i.some(h=>r.content_domain&&r.content_domain.toLowerCase().includes(h.toLowerCase())||r.title&&r.title.toLowerCase().includes(h.toLowerCase())||r.competency_group&&r.competency_group.toLowerCase().includes(h.toLowerCase())||r.subject&&r.subject.toLowerCase().includes(h.toLowerCase()));return e.jsx(Jt,{module:r,index:x,onClick:()=>s(r),onPreviewSources:()=>l(r),isAtRisk:n,isRecommended:d,onNotifyMe:c},r.id)})})})}),Il=({modules:t,fullPool:s,onSelectModule:l,onPreviewSources:n,isAtRisk:i=!1,learningPathContext:c=null,learningPathLoading:r=!1,weakTopics:x=[],onNotifyMe:d})=>{const h=t.filter(m=>m.progress>0&&m.progress<100),S=(t.length>0?t:s).filter(m=>m.progress===0).slice(0,6);return e.jsxs("div",{className:"pr-2 space-y-10",children:[r&&e.jsxs("div",{className:"mb-6 rounded-2xl border border-sky-200 bg-sky-50 px-5 py-4 flex items-center gap-3",children:[e.jsx("div",{className:"w-5 h-5 rounded-full border-2 border-sky-400 border-t-transparent animate-spin flex-shrink-0"}),e.jsx("p",{className:"text-sm font-semibold text-sky-800",children:"Building your personalized learning path from DepEd curriculum..."})]}),c&&!r&&e.jsxs("div",{className:"mb-6 rounded-2xl border border-indigo-200 bg-gradient-to-br from-indigo-50 to-purple-50 px-5 py-4 shadow-sm",children:[e.jsx("p",{className:"text-xs font-black uppercase tracking-wide text-indigo-700 mb-2",children:"📚 Your Personalized Learning Path"}),e.jsx("pre",{className:"whitespace-pre-wrap text-sm text-indigo-900 font-medium leading-relaxed font-sans",children:c})]}),h.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"w-10 h-10 rounded-[14px] bg-[#FF8B8B]/10 flex items-center justify-center text-[20px] shadow-inner",children:"🔥"}),e.jsx("h2",{className:"font-display font-black text-[24px] text-slate-800 tracking-tight",children:"Continue This Module"})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3 md:gap-6",children:h.slice(0,4).map((m,z)=>{const p=x.some(u=>m.content_domain&&m.content_domain.toLowerCase().includes(u.toLowerCase())||m.title&&m.title.toLowerCase().includes(u.toLowerCase())||m.competency_group&&m.competency_group.toLowerCase().includes(u.toLowerCase())||m.subject&&m.subject.toLowerCase().includes(u.toLowerCase()));return e.jsx(Jt,{module:m,index:z,onClick:()=>l(m),onPreviewSources:()=>n(m),isAtRisk:i,badgeLabel:"In Progress",isRecommended:p,onNotifyMe:d},m.id)})})]}),e.jsx("div",{children:S.length===0?e.jsx("div",{className:"bg-white rounded-2xl border border-[#dde3eb] p-8 text-center text-slate-500 font-medium",children:"You are all caught up. Practice more quizzes to unlock additional recommendations."}):e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3 md:gap-6",children:S.map((m,z)=>{const p=x.some(u=>m.content_domain&&m.content_domain.toLowerCase().includes(u.toLowerCase())||m.title&&m.title.toLowerCase().includes(u.toLowerCase())||m.competency_group&&m.competency_group.toLowerCase().includes(u.toLowerCase())||m.subject&&m.subject.toLowerCase().includes(u.toLowerCase()));return e.jsx(Jt,{module:m,index:z,onClick:()=>l(m),onPreviewSources:()=>n(m),isAtRisk:i,badgeLabel:"Start",isRecommended:p,onNotifyMe:d},m.id)})})})]})};export{An as default}; diff --git a/assets/NotificationDropdown-txVZGqve.js b/assets/NotificationDropdown-DW0msTLi.js similarity index 94% rename from assets/NotificationDropdown-txVZGqve.js rename to assets/NotificationDropdown-DW0msTLi.js index f7551f7490b7773cca4f6af5056f2df667b41de8..73e75e2dba47d4f4c4ad2210b560ae0e5366eabd 100644 --- a/assets/NotificationDropdown-txVZGqve.js +++ b/assets/NotificationDropdown-DW0msTLi.js @@ -1,4 +1,4 @@ -import{e as n,E as b,u as N,h as w,m as j,a as g,U as k}from"./index-BvEKrMkD.js";import{r as _,j as e}from"./vendor-react-B4AQeu28.js";import"./vendor-firebase-firestore-CNv3xXal.js";import{C as y,f as v}from"./formatDistanceToNow-5Jvf3U0l.js";import{B as o}from"./bell-C57aSZcx.js";import{C}from"./circle-check-E415RSic.js";import{C as A}from"./circle-alert-fPu7cawt.js";import{S as z}from"./sparkles-av0wSNZT.js";/** +import{e as n,E as b,u as N,h as w,m as j,a as g,U as k}from"./index-BdLfAeGL.js";import{r as _,j as e}from"./vendor-react-B4AQeu28.js";import"./vendor-firebase-firestore-CNv3xXal.js";import{C as y,f as v}from"./formatDistanceToNow-DQ9IJwBi.js";import{B as o}from"./bell-C5_RRTsA.js";import{C}from"./circle-check-CuVe-qlS.js";import{C as A}from"./circle-alert-ByVTnT3r.js";import{S as z}from"./sparkles-DnAkO9TX.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ProfileModal-82NOIe2Y.js b/assets/ProfileModal-DG84pnuP.js similarity index 96% rename from assets/ProfileModal-82NOIe2Y.js rename to assets/ProfileModal-DG84pnuP.js index 833a8c3c3fff9135cc28dfc37bc27b32be54d57b..0c91b80e210627aa74c800eea1a4d73588a8354f 100644 --- a/assets/ProfileModal-82NOIe2Y.js +++ b/assets/ProfileModal-DG84pnuP.js @@ -1,4 +1,4 @@ -import{r,j as e}from"./vendor-react-B4AQeu28.js";import{e as R,h as U,m as k,U as u,A as x,b as w,H as _,a1 as D,aL as T,aV as B,j as V}from"./index-BvEKrMkD.js";import{B as b}from"./button-Bfg1pO9T.js";import{I as d}from"./input-B3TmduBc.js";import{S as $,a as q,c as G,d as p}from"./select-CU8TeDXy.js";import{P as X,M as z,V as C}from"./ProfilePictureUploader-Cd4j_44T.js";import{X as Y}from"./x-BYtx1i07.js";import{M as H}from"./mail-DahQBvd1.js";import{C as L}from"./circle-help-DeWZHKak.js";import{S as K}from"./save-DAHVTL2X.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-CDr90bpM.js";import"./check-BmWAQELM.js";import"./minus-DRsrXXF5.js";import"./plus-IoQaIojF.js";import"./upload-COEzjD21.js";/** +import{r,j as e}from"./vendor-react-B4AQeu28.js";import{e as R,h as U,m as k,U as u,A as x,b as w,H as _,a1 as D,aL as T,aV as B,j as V}from"./index-BdLfAeGL.js";import{B as b}from"./button-BbJLXpfi.js";import{I as d}from"./input-CHfZS1wQ.js";import{S as $,a as q,c as G,d as p}from"./select-C3tB_0M-.js";import{P as X,M as z,V as C}from"./ProfilePictureUploader-SMuKdVoO.js";import{X as Y}from"./x-BLhsirCD.js";import{M as H}from"./mail-9RdsJqkx.js";import{C as L}from"./circle-help-CZDuv1Gp.js";import{S as K}from"./save-CUEUjfb0.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-uSn_SWll.js";import"./check-DbVe23hB.js";import"./minus-rsVFzcwU.js";import"./plus-Z9YkmuN1.js";import"./upload-CbDKucU9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ProfilePictureUploader-Cd4j_44T.js b/assets/ProfilePictureUploader-SMuKdVoO.js similarity index 98% rename from assets/ProfilePictureUploader-Cd4j_44T.js rename to assets/ProfilePictureUploader-SMuKdVoO.js index af5a81e5bc21e95497930f816d0bff72458d154d..8a9b1307fb87654cfe1a4a24a3e74ad2e4e8a402 100644 --- a/assets/ProfilePictureUploader-Cd4j_44T.js +++ b/assets/ProfilePictureUploader-SMuKdVoO.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{e as V,o as B,k as K,J as ge,_ as $,b4 as we,u as xe,W as ye,X as be,Y as Ce,h as Pe,m as J,j as Q}from"./index-BvEKrMkD.js";import{g as Re,r as x,j as p}from"./vendor-react-B4AQeu28.js";import{_ as Ee,o as b,p as Se,q as _e,r as ze,s as De}from"./vendor-radix-C5nwdvGr.js";import{B as ee}from"./button-Bfg1pO9T.js";import{updateProfile as Me}from"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-core-D7GXCeNu.js";import{r as Ae,u as Te,a as Ne}from"./vendor-firebase-storage-Bi7H_66d.js";import{X as je}from"./x-BYtx1i07.js";import{M as Ue}from"./minus-DRsrXXF5.js";import{P as Fe}from"./plus-IoQaIojF.js";import{U as Ie}from"./upload-COEzjD21.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{e as V,o as B,k as K,J as ge,_ as $,b4 as we,u as xe,W as ye,X as be,Y as Ce,h as Pe,m as J,j as Q}from"./index-BdLfAeGL.js";import{g as Re,r as x,j as p}from"./vendor-react-B4AQeu28.js";import{_ as Ee,o as b,p as Se,q as _e,r as ze,s as De}from"./vendor-radix-C5nwdvGr.js";import{B as ee}from"./button-BbJLXpfi.js";import{updateProfile as Me}from"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-core-D7GXCeNu.js";import{r as Ae,u as Te,a as Ne}from"./vendor-firebase-storage-Bi7H_66d.js";import{X as je}from"./x-BLhsirCD.js";import{M as Ue}from"./minus-rsVFzcwU.js";import{P as Fe}from"./plus-Z9YkmuN1.js";import{U as Ie}from"./upload-CbDKucU9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -107,4 +107,4 @@ import{e as V,o as B,k as K,J as ge,_ as $,b4 as we,u as xe,W as ye,X as be,Y as border-left: 0; border-right: 0; } -`,nt=1,at=3,st=1,ct=(function(a){Ee(o,a);function o(){var e=a!==null&&a.apply(this,arguments)||this;return e.cropperRef=x.createRef(),e.imageRef=x.createRef(),e.videoRef=x.createRef(),e.containerPosition={x:0,y:0},e.containerRef=null,e.styleRef=null,e.containerRect=null,e.mediaSize={width:0,height:0,naturalWidth:0,naturalHeight:0},e.dragStartPosition={x:0,y:0},e.dragStartCrop={x:0,y:0},e.gestureZoomStart=0,e.gestureRotationStart=0,e.isTouching=!1,e.lastPinchDistance=0,e.lastPinchRotation=0,e.rafDragTimeout=null,e.rafPinchTimeout=null,e.wheelTimer=null,e.currentDoc=typeof document<"u"?document:null,e.currentWindow=typeof window<"u"?window:null,e.resizeObserver=null,e.previousCropSize=null,e.isInitialized=!1,e.state={cropSize:null,hasWheelJustStarted:!1,mediaObjectFit:void 0},e.initResizeObserver=function(){if(!(typeof window.ResizeObserver>"u"||!e.containerRef)){var t=!0;e.resizeObserver=new window.ResizeObserver(function(r){if(t){t=!1;return}e.computeSizes()}),e.resizeObserver.observe(e.containerRef)}},e.preventZoomSafari=function(t){return t.preventDefault()},e.cleanEvents=function(){e.currentDoc&&(e.currentDoc.removeEventListener("mousemove",e.onMouseMove),e.currentDoc.removeEventListener("mouseup",e.onDragStopped),e.currentDoc.removeEventListener("touchmove",e.onTouchMove),e.currentDoc.removeEventListener("touchend",e.onDragStopped),e.currentDoc.removeEventListener("gesturechange",e.onGestureChange),e.currentDoc.removeEventListener("gestureend",e.onGestureEnd),e.currentDoc.removeEventListener("scroll",e.onScroll))},e.clearScrollEvent=function(){e.containerRef&&e.containerRef.removeEventListener("wheel",e.onWheel),e.wheelTimer&&clearTimeout(e.wheelTimer)},e.onMediaLoad=function(){var t=e.computeSizes();t&&(e.previousCropSize=t,e.emitCropData(),e.setInitialCrop(t),e.isInitialized=!0),e.props.onMediaLoaded&&e.props.onMediaLoaded(e.mediaSize)},e.setInitialCrop=function(t){if(e.props.initialCroppedAreaPercentages){var r=et(e.props.initialCroppedAreaPercentages,e.mediaSize,e.props.rotation,t,e.props.minZoom,e.props.maxZoom),i=r.crop,n=r.zoom;e.props.onCropChange(i),e.props.onZoomChange&&e.props.onZoomChange(n)}else if(e.props.initialCroppedAreaPixels){var s=rt(e.props.initialCroppedAreaPixels,e.mediaSize,e.props.rotation,t,e.props.minZoom,e.props.maxZoom),i=s.crop,n=s.zoom;e.props.onCropChange(i),e.props.onZoomChange&&e.props.onZoomChange(n)}},e.computeSizes=function(){var t,r,i,n,s,c,l=e.imageRef.current||e.videoRef.current;if(l&&e.containerRef){e.containerRect=e.containerRef.getBoundingClientRect(),e.saveContainerPosition();var u=e.containerRect.width/e.containerRect.height,h=((t=e.imageRef.current)===null||t===void 0?void 0:t.naturalWidth)||((r=e.videoRef.current)===null||r===void 0?void 0:r.videoWidth)||0,d=((i=e.imageRef.current)===null||i===void 0?void 0:i.naturalHeight)||((n=e.videoRef.current)===null||n===void 0?void 0:n.videoHeight)||0,m=l.offsetWidthw?{width:e.containerRect.height*w,height:e.containerRect.height}:{width:e.containerRect.width,height:e.containerRect.width/w};break;case"horizontal-cover":v={width:e.containerRect.width,height:e.containerRect.width/w};break;case"vertical-cover":v={width:e.containerRect.height*w,height:e.containerRect.height};break}else v={width:l.offsetWidth,height:l.offsetHeight};e.mediaSize=b(b({},v),{naturalWidth:h,naturalHeight:d}),e.props.setMediaSize&&e.props.setMediaSize(e.mediaSize);var f=e.props.cropSize?e.props.cropSize:Xe(e.mediaSize.width,e.mediaSize.height,e.containerRect.width,e.containerRect.height,e.props.aspect,e.props.rotation);return(((s=e.state.cropSize)===null||s===void 0?void 0:s.height)!==f.height||((c=e.state.cropSize)===null||c===void 0?void 0:c.width)!==f.width)&&e.props.onCropSizeChange&&e.props.onCropSizeChange(f),e.setState({cropSize:f},e.recomputeCropPosition),e.props.setCropSize&&e.props.setCropSize(f),f}},e.saveContainerPosition=function(){if(e.containerRef){var t=e.containerRef.getBoundingClientRect();e.containerPosition={x:t.left,y:t.top}}},e.onMouseDown=function(t){e.currentDoc&&(t.preventDefault(),e.currentDoc.addEventListener("mousemove",e.onMouseMove),e.currentDoc.addEventListener("mouseup",e.onDragStopped),e.saveContainerPosition(),e.onDragStart(o.getMousePoint(t)))},e.onMouseMove=function(t){return e.onDrag(o.getMousePoint(t))},e.onScroll=function(t){e.currentDoc&&(t.preventDefault(),e.saveContainerPosition())},e.onTouchStart=function(t){e.currentDoc&&(e.isTouching=!0,!(e.props.onTouchRequest&&!e.props.onTouchRequest(t))&&(e.currentDoc.addEventListener("touchmove",e.onTouchMove,{passive:!1}),e.currentDoc.addEventListener("touchend",e.onDragStopped),e.saveContainerPosition(),t.touches.length===2?e.onPinchStart(t):t.touches.length===1&&e.onDragStart(o.getTouchPoint(t.touches[0]))))},e.onTouchMove=function(t){t.preventDefault(),t.touches.length===2?e.onPinchMove(t):t.touches.length===1&&e.onDrag(o.getTouchPoint(t.touches[0]))},e.onGestureStart=function(t){e.currentDoc&&(t.preventDefault(),e.currentDoc.addEventListener("gesturechange",e.onGestureChange),e.currentDoc.addEventListener("gestureend",e.onGestureEnd),e.gestureZoomStart=e.props.zoom,e.gestureRotationStart=e.props.rotation)},e.onGestureChange=function(t){if(t.preventDefault(),!e.isTouching){var r=o.getMousePoint(t),i=e.gestureZoomStart-1+t.scale;if(e.setNewZoom(i,r,{shouldUpdatePosition:!0}),e.props.onRotationChange){var n=e.gestureRotationStart+t.rotation;e.props.onRotationChange(n)}}},e.onGestureEnd=function(t){e.cleanEvents()},e.onDragStart=function(t){var r,i,n=t.x,s=t.y;e.dragStartPosition={x:n,y:s},e.dragStartCrop=b({},e.props.crop),(i=(r=e.props).onInteractionStart)===null||i===void 0||i.call(r)},e.onDrag=function(t){var r=t.x,i=t.y;e.currentWindow&&(e.rafDragTimeout&&e.currentWindow.cancelAnimationFrame(e.rafDragTimeout),e.rafDragTimeout=e.currentWindow.requestAnimationFrame(function(){if(e.state.cropSize&&!(r===void 0||i===void 0)){var n=r-e.dragStartPosition.x,s=i-e.dragStartPosition.y,c={x:e.dragStartCrop.x+n,y:e.dragStartCrop.y+s},l=e.props.restrictPosition?N(c,e.mediaSize,e.state.cropSize,e.props.zoom,e.props.rotation):c;e.props.onCropChange(l)}}))},e.onDragStopped=function(){var t,r;e.isTouching=!1,e.cleanEvents(),e.emitCropData(),(r=(t=e.props).onInteractionEnd)===null||r===void 0||r.call(t)},e.onWheel=function(t){if(e.currentWindow&&!(e.props.onWheelRequest&&!e.props.onWheelRequest(t))){t.preventDefault();var r=o.getMousePoint(t),i=Ye(t).pixelY,n=e.props.zoom-i*e.props.zoomSpeed/200;e.setNewZoom(n,r,{shouldUpdatePosition:!0}),e.state.hasWheelJustStarted||e.setState({hasWheelJustStarted:!0},function(){var s,c;return(c=(s=e.props).onInteractionStart)===null||c===void 0?void 0:c.call(s)}),e.wheelTimer&&clearTimeout(e.wheelTimer),e.wheelTimer=e.currentWindow.setTimeout(function(){return e.setState({hasWheelJustStarted:!1},function(){var s,c;return(c=(s=e.props).onInteractionEnd)===null||c===void 0?void 0:c.call(s)})},250)}},e.getPointOnContainer=function(t,r){var i=t.x,n=t.y;if(!e.containerRect)throw new Error("The Cropper is not mounted");return{x:e.containerRect.width/2-(i-r.x),y:e.containerRect.height/2-(n-r.y)}},e.getPointOnMedia=function(t){var r=t.x,i=t.y,n=e.props,s=n.crop,c=n.zoom;return{x:(r+s.x)/c,y:(i+s.y)/c}},e.setNewZoom=function(t,r,i){var n=i===void 0?{}:i,s=n.shouldUpdatePosition,c=s===void 0?!0:s;if(!(!e.state.cropSize||!e.props.onZoomChange)){var l=O(t,e.props.minZoom,e.props.maxZoom);if(c){var u=e.getPointOnContainer(r,e.containerPosition),h=e.getPointOnMedia(u),d={x:h.x*l-u.x,y:h.y*l-u.y},m=e.props.restrictPosition?N(d,e.mediaSize,e.state.cropSize,l,e.props.rotation):d;e.props.onCropChange(m)}e.props.onZoomChange(l)}},e.getCropData=function(){if(!e.state.cropSize)return null;var t=e.props.restrictPosition?N(e.props.crop,e.mediaSize,e.state.cropSize,e.props.zoom,e.props.rotation):e.props.crop;return Ke(t,e.mediaSize,e.state.cropSize,e.getAspect(),e.props.zoom,e.props.rotation,e.props.restrictPosition)},e.emitCropData=function(){var t=e.getCropData();if(t){var r=t.croppedAreaPercentages,i=t.croppedAreaPixels;e.props.onCropComplete&&e.props.onCropComplete(r,i),e.props.onCropAreaChange&&e.props.onCropAreaChange(r,i)}},e.emitCropAreaChange=function(){var t=e.getCropData();if(t){var r=t.croppedAreaPercentages,i=t.croppedAreaPixels;e.props.onCropAreaChange&&e.props.onCropAreaChange(r,i)}},e.recomputeCropPosition=function(){var t,r;if(e.state.cropSize){var i=e.props.crop;if(e.isInitialized&&(!((t=e.previousCropSize)===null||t===void 0)&&t.width)&&(!((r=e.previousCropSize)===null||r===void 0)&&r.height)){var n=Math.abs(e.previousCropSize.width-e.state.cropSize.width)>1e-6||Math.abs(e.previousCropSize.height-e.state.cropSize.height)>1e-6;if(n){var s=e.state.cropSize.width/e.previousCropSize.width,c=e.state.cropSize.height/e.previousCropSize.height;i={x:e.props.crop.x*s,y:e.props.crop.y*c}}}var l=e.props.restrictPosition?N(i,e.mediaSize,e.state.cropSize,e.props.zoom,e.props.rotation):i;e.previousCropSize=e.state.cropSize,e.props.onCropChange(l),e.emitCropData()}},e.onKeyDown=function(t){var r,i,n=e.props,s=n.crop,c=n.onCropChange,l=n.keyboardStep,u=n.zoom,h=n.rotation,d=l;if(e.state.cropSize){t.shiftKey&&(d*=.2);var m=b({},s);switch(t.key){case"ArrowUp":m.y-=d,t.preventDefault();break;case"ArrowDown":m.y+=d,t.preventDefault();break;case"ArrowLeft":m.x-=d,t.preventDefault();break;case"ArrowRight":m.x+=d,t.preventDefault();break;default:return}e.props.restrictPosition&&(m=N(m,e.mediaSize,e.state.cropSize,u,h)),t.repeat||(i=(r=e.props).onInteractionStart)===null||i===void 0||i.call(r),c(m)}},e.onKeyUp=function(t){var r,i;switch(t.key){case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":t.preventDefault();break;default:return}e.emitCropData(),(i=(r=e.props).onInteractionEnd)===null||i===void 0||i.call(r)},e}return o.prototype.componentDidMount=function(){!this.currentDoc||!this.currentWindow||(this.containerRef&&(this.containerRef.ownerDocument&&(this.currentDoc=this.containerRef.ownerDocument),this.currentDoc.defaultView&&(this.currentWindow=this.currentDoc.defaultView),this.initResizeObserver(),typeof window.ResizeObserver>"u"&&this.currentWindow.addEventListener("resize",this.computeSizes),this.props.zoomWithScroll&&this.containerRef.addEventListener("wheel",this.onWheel,{passive:!1}),this.containerRef.addEventListener("gesturestart",this.onGestureStart)),this.currentDoc.addEventListener("scroll",this.onScroll),this.props.disableAutomaticStylesInjection||(this.styleRef=this.currentDoc.createElement("style"),this.styleRef.setAttribute("type","text/css"),this.props.nonce&&this.styleRef.setAttribute("nonce",this.props.nonce),this.styleRef.innerHTML=it,this.currentDoc.head.appendChild(this.styleRef)),this.imageRef.current&&this.imageRef.current.complete&&this.onMediaLoad(),this.props.setImageRef&&this.props.setImageRef(this.imageRef),this.props.setVideoRef&&this.props.setVideoRef(this.videoRef),this.props.setCropperRef&&this.props.setCropperRef(this.cropperRef))},o.prototype.componentWillUnmount=function(){var e,t;!this.currentDoc||!this.currentWindow||(typeof window.ResizeObserver>"u"&&this.currentWindow.removeEventListener("resize",this.computeSizes),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),this.containerRef&&this.containerRef.removeEventListener("gesturestart",this.preventZoomSafari),this.styleRef&&((t=this.styleRef.parentNode)===null||t===void 0||t.removeChild(this.styleRef)),this.cleanEvents(),this.props.zoomWithScroll&&this.clearScrollEvent())},o.prototype.componentDidUpdate=function(e){var t,r,i,n,s,c,l,u,h;e.rotation!==this.props.rotation?(this.computeSizes(),this.recomputeCropPosition()):e.aspect!==this.props.aspect?this.computeSizes():e.objectFit!==this.props.objectFit?this.computeSizes():e.zoom!==this.props.zoom?this.recomputeCropPosition():((t=e.cropSize)===null||t===void 0?void 0:t.height)!==((r=this.props.cropSize)===null||r===void 0?void 0:r.height)||((i=e.cropSize)===null||i===void 0?void 0:i.width)!==((n=this.props.cropSize)===null||n===void 0?void 0:n.width)?this.computeSizes():(((s=e.crop)===null||s===void 0?void 0:s.x)!==((c=this.props.crop)===null||c===void 0?void 0:c.x)||((l=e.crop)===null||l===void 0?void 0:l.y)!==((u=this.props.crop)===null||u===void 0?void 0:u.y))&&this.emitCropAreaChange(),e.zoomWithScroll!==this.props.zoomWithScroll&&this.containerRef&&(this.props.zoomWithScroll?this.containerRef.addEventListener("wheel",this.onWheel,{passive:!1}):this.clearScrollEvent()),e.video!==this.props.video&&((h=this.videoRef.current)===null||h===void 0||h.load());var d=this.getObjectFit();d!==this.state.mediaObjectFit&&this.setState({mediaObjectFit:d},this.computeSizes)},o.prototype.getAspect=function(){var e=this.props,t=e.cropSize,r=e.aspect;return t?t.width/t.height:r},o.prototype.getObjectFit=function(){var e,t,r,i;if(this.props.objectFit==="cover"){var n=this.imageRef.current||this.videoRef.current;if(n&&this.containerRef){this.containerRect=this.containerRef.getBoundingClientRect();var s=this.containerRect.width/this.containerRect.height,c=((e=this.imageRef.current)===null||e===void 0?void 0:e.naturalWidth)||((t=this.videoRef.current)===null||t===void 0?void 0:t.videoWidth)||0,l=((r=this.imageRef.current)===null||r===void 0?void 0:r.naturalHeight)||((i=this.videoRef.current)===null||i===void 0?void 0:i.videoHeight)||0,u=c/l;return uArray.isArray(e)?e:Array.isArray(o)?o:[t,r],[e,o,t,r]);return p.jsxs(Se,{"data-slot":"slider",defaultValue:o,value:e,min:t,max:r,className:B("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",a),...i,children:[p.jsx(_e,{"data-slot":"slider-track",className:B("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-4 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:p.jsx(ze,{"data-slot":"slider-range",className:B("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:n.length},(s,c)=>p.jsx(De,{"data-slot":"slider-thumb",className:"border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"},c))]})}const de=["image/png","image/jpeg","image/webp"],he=2*1024*1024,fe=256,ut=a=>{const o=a.normalize("NFKD").toLowerCase(),e=o.lastIndexOf("."),t=e>0?o.slice(0,e):o,r=e>0?o.slice(e).replace(/[^.a-z0-9]/g,""):"";return`${t.replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"profile-picture"}${r}`},pt=(a,o,e=Date.now())=>`profile-pictures/${a}/${e}-${ut(o)}`,me=a=>de.includes(a.type)?a.size>he?"Profile pictures must be 2MB or smaller.":a.name.trim()?null:"Please choose a valid image file.":"Only PNG, JPEG, and WebP images are allowed.",dt=a=>new Promise((o,e)=>{const t=URL.createObjectURL(a),r=new Image,i=setTimeout(()=>{URL.revokeObjectURL(t),e(new Error("Image loading timed out. Please try a different file."))},15e3);r.onload=()=>{clearTimeout(i),URL.revokeObjectURL(t),o(r)},r.onerror=()=>{clearTimeout(i),URL.revokeObjectURL(t),e(new Error("Unable to read the selected image. Please try another file."))},r.crossOrigin="anonymous",r.src=t}),ue=(a,o,e)=>new Promise((t,r)=>{a.toBlob(i=>{if(!i){r(new Error("Failed to prepare the image for upload."));return}t(i)},o,e)}),ht=async(a,o=fe)=>{const e=await dt(a),t=document.createElement("canvas");t.width=o,t.height=o;const r=t.getContext("2d");if(!r)throw new Error("Your browser cannot process image uploads right now.");const i=e.naturalWidth||e.width,n=e.naturalHeight||e.height,s=Math.min(i,n),c=Math.max(0,(i-s)/2),l=Math.max(0,(n-s)/2);r.clearRect(0,0,o,o),r.drawImage(e,c,l,s,s,0,0,o,o);try{return await ue(t,"image/webp",.9)}catch{return await ue(t,"image/jpeg",.9)}},j=(a,o,e)=>{let t;const r=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`${e} timed out after ${Math.round(o/1e3)}s`)),o)});return Promise.race([a,r]).finally(()=>clearTimeout(t))},ft=async(a,o,e)=>{const t=we.options.projectId;if(!t)throw new Error("Firebase project ID is not configured.");const r=await a.getIdToken(),i=`https://firestore.googleapis.com/v1/projects/${t}/databases/(default)/documents/users/${o}?updateMask.fieldPaths=photo&updateMask.fieldPaths=updatedAt`,n=await fetch(i,{method:"PATCH",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({fields:{photo:{stringValue:e},updatedAt:{timestampValue:new Date().toISOString()}}})});if(!n.ok){const s=await n.text().catch(()=>"");throw new Error(`Firestore REST update failed (${n.status}): ${s}`)}},mt=async({file:a,uid:o,currentUser:e=K.currentUser,syncFirestore:t=!0})=>{const r=me(a);if(r)throw new Error(r);const i=e??K.currentUser;if(!i)throw new Error("You need to be signed in to change your profile picture.");const n=o||i.uid;if(!n)throw new Error("Unable to determine which profile should be updated.");if(i.uid!==n)throw new Error("The signed-in user does not match the profile being edited.");const s=await j(ht(a,fe),2e4,"Image processing"),c=pt(n,a.name),l=Ae(ge,c),u=await j(Te(l,s,{contentType:s.type||"image/webp",cacheControl:"public, max-age=31536000, immutable"}),3e4,"Storage upload"),h=await j(Ne(u.ref),1e4,"Download URL retrieval");try{await j(Me(i,{photoURL:h}),1e4,"Auth profile update")}catch(d){console.warn("[PROFILE UPLOAD] Auth profile update failed (non-fatal):",d)}if(t){try{await j(ft(i,n,h),1e4,"Firestore profile sync")}catch(d){console.error("[PROFILE UPLOAD] Firestore REST sync failed:",d),console.warn("[PROFILE UPLOAD] Photo was uploaded but the database record may be stale. It will refresh on next login.")}try{const{doc:d,updateDoc:m}=await $(async()=>{const{doc:v,updateDoc:f}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{doc:v,updateDoc:f}},__vite__mapDeps([0,1])),{db:w}=await $(async()=>{const{db:v}=await import("./index-BvEKrMkD.js").then(f=>f.b7);return{db:v}},__vite__mapDeps([2,3,0,1,4,5,6,7,8,9,10,11]));await m(d(w,"leaderboard",n),{photo:h}).catch(()=>$(async()=>{const{setDoc:v}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{setDoc:v}},__vite__mapDeps([0,1])).then(({setDoc:v})=>v(d(w,"leaderboard",n),{photo:h},{merge:!0})))}catch{}}return h},vt=a=>`${(a/(1024*1024)).toFixed(1)} MB`,gt=a=>{const o=(a||"").trim();return o?o.split(/\s+/).slice(0,2).map(e=>e[0]?.toUpperCase()).join(""):"U"},wt=a=>new Promise((o,e)=>{const t=new Image;t.onload=()=>o(t),t.onerror=()=>e(new Error("Unable to load the image for cropping.")),t.src=a}),pe=(a,o,e)=>new Promise((t,r)=>{a.toBlob(i=>{if(!i){r(new Error("Failed to prepare the cropped image."));return}t(i)},o,e)}),xt=async(a,o,e)=>{const t=await wt(a),r=document.createElement("canvas"),i=640;r.width=i,r.height=i;const n=r.getContext("2d");if(!n)throw new Error("Your browser cannot process the selected image right now.");n.clearRect(0,0,i,i),n.drawImage(t,o.x,o.y,o.width,o.height,0,0,i,i);let s;try{s=await pe(r,"image/webp",.92)}catch{s=await pe(r,"image/jpeg",.92)}if(!s)throw new Error("Could not create an image from the cropped area.");const c=s.type==="image/webp"?"webp":"jpg",u=`${e.name.replace(/\.[^/.]+$/,"")||"profile-picture"}-cropped.${c}`;return new File([s],u,{type:s.type,lastModified:Date.now()})},Nt=({uid:a,photoURL:o,displayName:e,className:t="",onUploaded:r,syncFirestore:i=!0})=>{const{currentUser:n,refreshProfile:s}=xe(),[c,l]=x.useState(null),[u,h]=x.useState(null),[d,m]=x.useState({x:0,y:0}),[w,v]=x.useState(1),[f,R]=x.useState(null),[y,g]=x.useState(""),[E,_]=x.useState(!1),P=x.useRef(null);x.useEffect(()=>{if(!c){h(null);return}const C=URL.createObjectURL(c);return h(C),()=>URL.revokeObjectURL(C)},[c]);const k=u||o||"",W=x.useMemo(()=>`${de.map(S=>S.replace("image/","").toUpperCase()).join(", ")} up to ${vt(he)}. The image will be cropped to a circular avatar.`,[]),D=()=>{l(null),m({x:0,y:0}),v(1),R(null),g(""),P.current&&(P.current.value="")},z=C=>{const S=C.target.files?.[0]||null;if(!S)return;const M=me(S);if(M){g(M),l(null),C.target.value="";return}g(""),l(S),m({x:0,y:0}),v(1),R(null)},T=async()=>{if(!c){g("Choose an image before saving.");return}_(!0),g("");const C=6e4;let S;try{const M=(async()=>{const I=u&&f?await xt(u,f,c):c,Z=a||n?.uid;return mt({file:I,uid:Z,currentUser:n,syncFirestore:i})})(),F=new Promise((I,Z)=>{S=setTimeout(()=>Z(new Error("Upload timed out. Please check your connection and try again.")),C)}),ve=await Promise.race([M,F]);r?.(ve),s().catch(I=>console.warn("[ProfilePictureUploader] refreshProfile failed:",I)),Q.success("Profile picture updated."),D()}catch(M){const F=M instanceof Error?M.message:"Failed to update your profile picture.";g(F),Q.error(F)}finally{clearTimeout(S),_(!1)}},U=()=>{P.current?.click()};return p.jsxs(p.Fragment,{children:[p.jsxs("section",{className:`flex items-center gap-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm ${t}`,children:[p.jsxs("div",{className:"relative cursor-pointer group",onClick:U,role:"button",tabIndex:0,onKeyDown:C=>C.key==="Enter"&&U(),"aria-label":"Change profile picture",children:[p.jsxs(ye,{className:"size-16 sm:size-20 ring-4 ring-sky-50 shadow-sm transition-transform duration-200 group-hover:scale-105",children:[p.jsx(be,{src:k,alt:`${e||"User"} profile picture`}),p.jsx(Ce,{className:"bg-gradient-to-br from-sky-600 to-cyan-500 text-lg font-semibold text-white",children:gt(e)})]}),p.jsx("span",{className:"absolute -right-1 -top-1 inline-flex items-center justify-center rounded-full bg-slate-900 p-1.5 text-white shadow-md transition-colors group-hover:bg-slate-700",children:p.jsx(Oe,{size:14})})]}),p.jsxs("div",{className:"space-y-1 flex-1",children:[p.jsx("p",{className:"text-sm font-semibold text-slate-900",children:"Profile picture"}),p.jsx("p",{className:"text-xs text-slate-500",children:"Click your avatar to upload a new photo."}),y&&p.jsx("p",{className:"text-xs font-medium text-rose-600 mt-1",children:y})]}),p.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:z,className:"sr-only","aria-label":"Choose profile picture"})]}),p.jsx(Pe,{children:u&&p.jsxs(p.Fragment,{children:[p.jsx(J.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-[60]",onClick:D}),p.jsx(J.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",duration:.5,bounce:.3},className:"fixed inset-0 z-[60] flex items-center justify-center p-4 sm:p-6",onClick:C=>C.stopPropagation(),children:p.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-lg overflow-hidden flex flex-col",children:[p.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-slate-100",children:[p.jsx("h3",{className:"text-lg font-bold text-slate-900",children:"Update profile picture"}),p.jsx("button",{onClick:D,className:"p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors","aria-label":"Close modal",children:p.jsx(je,{size:20})})]}),p.jsxs("div",{className:"p-4 sm:p-6 bg-slate-50 flex flex-col items-center",children:[p.jsx("div",{className:"relative h-[350px] sm:h-[450px] w-[350px] sm:w-[450px] mx-auto overflow-hidden rounded-xl bg-slate-100 ring-1 ring-inset ring-slate-200 shadow-inner",children:p.jsx(ct,{image:u,crop:d,zoom:w,aspect:1,cropShape:"round",showGrid:!1,objectFit:"cover",restrictPosition:!0,onCropChange:m,onZoomChange:v,onCropComplete:(C,S)=>R(S),style:{containerStyle:{backgroundColor:"#f8fafc"}}})}),p.jsxs("div",{className:"mt-6 w-full max-w-xs flex items-center gap-4",children:[p.jsx(Ue,{size:18,className:"text-slate-500"}),p.jsx(lt,{value:[w],min:1,max:3,step:.05,onValueChange:C=>v(C[0]||1),"aria-label":"Profile picture zoom",className:"flex-1 cursor-pointer"}),p.jsx(Fe,{size:18,className:"text-slate-500"})]}),p.jsx("p",{className:"mt-4 text-xs text-slate-500 text-center",children:W})]}),p.jsxs("div",{className:"p-4 border-t border-slate-100 flex items-center justify-end gap-3 bg-white",children:[p.jsx(ee,{type:"button",variant:"ghost",onClick:D,disabled:E,className:"font-medium text-slate-600 hover:text-slate-900 hover:bg-slate-100 px-5",children:"Cancel"}),p.jsx(ee,{type:"button",onClick:T,disabled:E||!c,className:"bg-sky-600 hover:bg-sky-700 text-white min-w-[120px] gap-2 shadow-sm",children:E?p.jsxs(p.Fragment,{children:[p.jsx(Ie,{size:16,className:"animate-pulse"}),"Saving..."]}):"Save picture"})]})]})})]})})]})};export{At as M,Nt as P,Tt as V}; +`,nt=1,at=3,st=1,ct=(function(a){Ee(o,a);function o(){var e=a!==null&&a.apply(this,arguments)||this;return e.cropperRef=x.createRef(),e.imageRef=x.createRef(),e.videoRef=x.createRef(),e.containerPosition={x:0,y:0},e.containerRef=null,e.styleRef=null,e.containerRect=null,e.mediaSize={width:0,height:0,naturalWidth:0,naturalHeight:0},e.dragStartPosition={x:0,y:0},e.dragStartCrop={x:0,y:0},e.gestureZoomStart=0,e.gestureRotationStart=0,e.isTouching=!1,e.lastPinchDistance=0,e.lastPinchRotation=0,e.rafDragTimeout=null,e.rafPinchTimeout=null,e.wheelTimer=null,e.currentDoc=typeof document<"u"?document:null,e.currentWindow=typeof window<"u"?window:null,e.resizeObserver=null,e.previousCropSize=null,e.isInitialized=!1,e.state={cropSize:null,hasWheelJustStarted:!1,mediaObjectFit:void 0},e.initResizeObserver=function(){if(!(typeof window.ResizeObserver>"u"||!e.containerRef)){var t=!0;e.resizeObserver=new window.ResizeObserver(function(r){if(t){t=!1;return}e.computeSizes()}),e.resizeObserver.observe(e.containerRef)}},e.preventZoomSafari=function(t){return t.preventDefault()},e.cleanEvents=function(){e.currentDoc&&(e.currentDoc.removeEventListener("mousemove",e.onMouseMove),e.currentDoc.removeEventListener("mouseup",e.onDragStopped),e.currentDoc.removeEventListener("touchmove",e.onTouchMove),e.currentDoc.removeEventListener("touchend",e.onDragStopped),e.currentDoc.removeEventListener("gesturechange",e.onGestureChange),e.currentDoc.removeEventListener("gestureend",e.onGestureEnd),e.currentDoc.removeEventListener("scroll",e.onScroll))},e.clearScrollEvent=function(){e.containerRef&&e.containerRef.removeEventListener("wheel",e.onWheel),e.wheelTimer&&clearTimeout(e.wheelTimer)},e.onMediaLoad=function(){var t=e.computeSizes();t&&(e.previousCropSize=t,e.emitCropData(),e.setInitialCrop(t),e.isInitialized=!0),e.props.onMediaLoaded&&e.props.onMediaLoaded(e.mediaSize)},e.setInitialCrop=function(t){if(e.props.initialCroppedAreaPercentages){var r=et(e.props.initialCroppedAreaPercentages,e.mediaSize,e.props.rotation,t,e.props.minZoom,e.props.maxZoom),i=r.crop,n=r.zoom;e.props.onCropChange(i),e.props.onZoomChange&&e.props.onZoomChange(n)}else if(e.props.initialCroppedAreaPixels){var s=rt(e.props.initialCroppedAreaPixels,e.mediaSize,e.props.rotation,t,e.props.minZoom,e.props.maxZoom),i=s.crop,n=s.zoom;e.props.onCropChange(i),e.props.onZoomChange&&e.props.onZoomChange(n)}},e.computeSizes=function(){var t,r,i,n,s,c,l=e.imageRef.current||e.videoRef.current;if(l&&e.containerRef){e.containerRect=e.containerRef.getBoundingClientRect(),e.saveContainerPosition();var u=e.containerRect.width/e.containerRect.height,h=((t=e.imageRef.current)===null||t===void 0?void 0:t.naturalWidth)||((r=e.videoRef.current)===null||r===void 0?void 0:r.videoWidth)||0,d=((i=e.imageRef.current)===null||i===void 0?void 0:i.naturalHeight)||((n=e.videoRef.current)===null||n===void 0?void 0:n.videoHeight)||0,m=l.offsetWidthw?{width:e.containerRect.height*w,height:e.containerRect.height}:{width:e.containerRect.width,height:e.containerRect.width/w};break;case"horizontal-cover":v={width:e.containerRect.width,height:e.containerRect.width/w};break;case"vertical-cover":v={width:e.containerRect.height*w,height:e.containerRect.height};break}else v={width:l.offsetWidth,height:l.offsetHeight};e.mediaSize=b(b({},v),{naturalWidth:h,naturalHeight:d}),e.props.setMediaSize&&e.props.setMediaSize(e.mediaSize);var f=e.props.cropSize?e.props.cropSize:Xe(e.mediaSize.width,e.mediaSize.height,e.containerRect.width,e.containerRect.height,e.props.aspect,e.props.rotation);return(((s=e.state.cropSize)===null||s===void 0?void 0:s.height)!==f.height||((c=e.state.cropSize)===null||c===void 0?void 0:c.width)!==f.width)&&e.props.onCropSizeChange&&e.props.onCropSizeChange(f),e.setState({cropSize:f},e.recomputeCropPosition),e.props.setCropSize&&e.props.setCropSize(f),f}},e.saveContainerPosition=function(){if(e.containerRef){var t=e.containerRef.getBoundingClientRect();e.containerPosition={x:t.left,y:t.top}}},e.onMouseDown=function(t){e.currentDoc&&(t.preventDefault(),e.currentDoc.addEventListener("mousemove",e.onMouseMove),e.currentDoc.addEventListener("mouseup",e.onDragStopped),e.saveContainerPosition(),e.onDragStart(o.getMousePoint(t)))},e.onMouseMove=function(t){return e.onDrag(o.getMousePoint(t))},e.onScroll=function(t){e.currentDoc&&(t.preventDefault(),e.saveContainerPosition())},e.onTouchStart=function(t){e.currentDoc&&(e.isTouching=!0,!(e.props.onTouchRequest&&!e.props.onTouchRequest(t))&&(e.currentDoc.addEventListener("touchmove",e.onTouchMove,{passive:!1}),e.currentDoc.addEventListener("touchend",e.onDragStopped),e.saveContainerPosition(),t.touches.length===2?e.onPinchStart(t):t.touches.length===1&&e.onDragStart(o.getTouchPoint(t.touches[0]))))},e.onTouchMove=function(t){t.preventDefault(),t.touches.length===2?e.onPinchMove(t):t.touches.length===1&&e.onDrag(o.getTouchPoint(t.touches[0]))},e.onGestureStart=function(t){e.currentDoc&&(t.preventDefault(),e.currentDoc.addEventListener("gesturechange",e.onGestureChange),e.currentDoc.addEventListener("gestureend",e.onGestureEnd),e.gestureZoomStart=e.props.zoom,e.gestureRotationStart=e.props.rotation)},e.onGestureChange=function(t){if(t.preventDefault(),!e.isTouching){var r=o.getMousePoint(t),i=e.gestureZoomStart-1+t.scale;if(e.setNewZoom(i,r,{shouldUpdatePosition:!0}),e.props.onRotationChange){var n=e.gestureRotationStart+t.rotation;e.props.onRotationChange(n)}}},e.onGestureEnd=function(t){e.cleanEvents()},e.onDragStart=function(t){var r,i,n=t.x,s=t.y;e.dragStartPosition={x:n,y:s},e.dragStartCrop=b({},e.props.crop),(i=(r=e.props).onInteractionStart)===null||i===void 0||i.call(r)},e.onDrag=function(t){var r=t.x,i=t.y;e.currentWindow&&(e.rafDragTimeout&&e.currentWindow.cancelAnimationFrame(e.rafDragTimeout),e.rafDragTimeout=e.currentWindow.requestAnimationFrame(function(){if(e.state.cropSize&&!(r===void 0||i===void 0)){var n=r-e.dragStartPosition.x,s=i-e.dragStartPosition.y,c={x:e.dragStartCrop.x+n,y:e.dragStartCrop.y+s},l=e.props.restrictPosition?N(c,e.mediaSize,e.state.cropSize,e.props.zoom,e.props.rotation):c;e.props.onCropChange(l)}}))},e.onDragStopped=function(){var t,r;e.isTouching=!1,e.cleanEvents(),e.emitCropData(),(r=(t=e.props).onInteractionEnd)===null||r===void 0||r.call(t)},e.onWheel=function(t){if(e.currentWindow&&!(e.props.onWheelRequest&&!e.props.onWheelRequest(t))){t.preventDefault();var r=o.getMousePoint(t),i=Ye(t).pixelY,n=e.props.zoom-i*e.props.zoomSpeed/200;e.setNewZoom(n,r,{shouldUpdatePosition:!0}),e.state.hasWheelJustStarted||e.setState({hasWheelJustStarted:!0},function(){var s,c;return(c=(s=e.props).onInteractionStart)===null||c===void 0?void 0:c.call(s)}),e.wheelTimer&&clearTimeout(e.wheelTimer),e.wheelTimer=e.currentWindow.setTimeout(function(){return e.setState({hasWheelJustStarted:!1},function(){var s,c;return(c=(s=e.props).onInteractionEnd)===null||c===void 0?void 0:c.call(s)})},250)}},e.getPointOnContainer=function(t,r){var i=t.x,n=t.y;if(!e.containerRect)throw new Error("The Cropper is not mounted");return{x:e.containerRect.width/2-(i-r.x),y:e.containerRect.height/2-(n-r.y)}},e.getPointOnMedia=function(t){var r=t.x,i=t.y,n=e.props,s=n.crop,c=n.zoom;return{x:(r+s.x)/c,y:(i+s.y)/c}},e.setNewZoom=function(t,r,i){var n=i===void 0?{}:i,s=n.shouldUpdatePosition,c=s===void 0?!0:s;if(!(!e.state.cropSize||!e.props.onZoomChange)){var l=O(t,e.props.minZoom,e.props.maxZoom);if(c){var u=e.getPointOnContainer(r,e.containerPosition),h=e.getPointOnMedia(u),d={x:h.x*l-u.x,y:h.y*l-u.y},m=e.props.restrictPosition?N(d,e.mediaSize,e.state.cropSize,l,e.props.rotation):d;e.props.onCropChange(m)}e.props.onZoomChange(l)}},e.getCropData=function(){if(!e.state.cropSize)return null;var t=e.props.restrictPosition?N(e.props.crop,e.mediaSize,e.state.cropSize,e.props.zoom,e.props.rotation):e.props.crop;return Ke(t,e.mediaSize,e.state.cropSize,e.getAspect(),e.props.zoom,e.props.rotation,e.props.restrictPosition)},e.emitCropData=function(){var t=e.getCropData();if(t){var r=t.croppedAreaPercentages,i=t.croppedAreaPixels;e.props.onCropComplete&&e.props.onCropComplete(r,i),e.props.onCropAreaChange&&e.props.onCropAreaChange(r,i)}},e.emitCropAreaChange=function(){var t=e.getCropData();if(t){var r=t.croppedAreaPercentages,i=t.croppedAreaPixels;e.props.onCropAreaChange&&e.props.onCropAreaChange(r,i)}},e.recomputeCropPosition=function(){var t,r;if(e.state.cropSize){var i=e.props.crop;if(e.isInitialized&&(!((t=e.previousCropSize)===null||t===void 0)&&t.width)&&(!((r=e.previousCropSize)===null||r===void 0)&&r.height)){var n=Math.abs(e.previousCropSize.width-e.state.cropSize.width)>1e-6||Math.abs(e.previousCropSize.height-e.state.cropSize.height)>1e-6;if(n){var s=e.state.cropSize.width/e.previousCropSize.width,c=e.state.cropSize.height/e.previousCropSize.height;i={x:e.props.crop.x*s,y:e.props.crop.y*c}}}var l=e.props.restrictPosition?N(i,e.mediaSize,e.state.cropSize,e.props.zoom,e.props.rotation):i;e.previousCropSize=e.state.cropSize,e.props.onCropChange(l),e.emitCropData()}},e.onKeyDown=function(t){var r,i,n=e.props,s=n.crop,c=n.onCropChange,l=n.keyboardStep,u=n.zoom,h=n.rotation,d=l;if(e.state.cropSize){t.shiftKey&&(d*=.2);var m=b({},s);switch(t.key){case"ArrowUp":m.y-=d,t.preventDefault();break;case"ArrowDown":m.y+=d,t.preventDefault();break;case"ArrowLeft":m.x-=d,t.preventDefault();break;case"ArrowRight":m.x+=d,t.preventDefault();break;default:return}e.props.restrictPosition&&(m=N(m,e.mediaSize,e.state.cropSize,u,h)),t.repeat||(i=(r=e.props).onInteractionStart)===null||i===void 0||i.call(r),c(m)}},e.onKeyUp=function(t){var r,i;switch(t.key){case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":t.preventDefault();break;default:return}e.emitCropData(),(i=(r=e.props).onInteractionEnd)===null||i===void 0||i.call(r)},e}return o.prototype.componentDidMount=function(){!this.currentDoc||!this.currentWindow||(this.containerRef&&(this.containerRef.ownerDocument&&(this.currentDoc=this.containerRef.ownerDocument),this.currentDoc.defaultView&&(this.currentWindow=this.currentDoc.defaultView),this.initResizeObserver(),typeof window.ResizeObserver>"u"&&this.currentWindow.addEventListener("resize",this.computeSizes),this.props.zoomWithScroll&&this.containerRef.addEventListener("wheel",this.onWheel,{passive:!1}),this.containerRef.addEventListener("gesturestart",this.onGestureStart)),this.currentDoc.addEventListener("scroll",this.onScroll),this.props.disableAutomaticStylesInjection||(this.styleRef=this.currentDoc.createElement("style"),this.styleRef.setAttribute("type","text/css"),this.props.nonce&&this.styleRef.setAttribute("nonce",this.props.nonce),this.styleRef.innerHTML=it,this.currentDoc.head.appendChild(this.styleRef)),this.imageRef.current&&this.imageRef.current.complete&&this.onMediaLoad(),this.props.setImageRef&&this.props.setImageRef(this.imageRef),this.props.setVideoRef&&this.props.setVideoRef(this.videoRef),this.props.setCropperRef&&this.props.setCropperRef(this.cropperRef))},o.prototype.componentWillUnmount=function(){var e,t;!this.currentDoc||!this.currentWindow||(typeof window.ResizeObserver>"u"&&this.currentWindow.removeEventListener("resize",this.computeSizes),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),this.containerRef&&this.containerRef.removeEventListener("gesturestart",this.preventZoomSafari),this.styleRef&&((t=this.styleRef.parentNode)===null||t===void 0||t.removeChild(this.styleRef)),this.cleanEvents(),this.props.zoomWithScroll&&this.clearScrollEvent())},o.prototype.componentDidUpdate=function(e){var t,r,i,n,s,c,l,u,h;e.rotation!==this.props.rotation?(this.computeSizes(),this.recomputeCropPosition()):e.aspect!==this.props.aspect?this.computeSizes():e.objectFit!==this.props.objectFit?this.computeSizes():e.zoom!==this.props.zoom?this.recomputeCropPosition():((t=e.cropSize)===null||t===void 0?void 0:t.height)!==((r=this.props.cropSize)===null||r===void 0?void 0:r.height)||((i=e.cropSize)===null||i===void 0?void 0:i.width)!==((n=this.props.cropSize)===null||n===void 0?void 0:n.width)?this.computeSizes():(((s=e.crop)===null||s===void 0?void 0:s.x)!==((c=this.props.crop)===null||c===void 0?void 0:c.x)||((l=e.crop)===null||l===void 0?void 0:l.y)!==((u=this.props.crop)===null||u===void 0?void 0:u.y))&&this.emitCropAreaChange(),e.zoomWithScroll!==this.props.zoomWithScroll&&this.containerRef&&(this.props.zoomWithScroll?this.containerRef.addEventListener("wheel",this.onWheel,{passive:!1}):this.clearScrollEvent()),e.video!==this.props.video&&((h=this.videoRef.current)===null||h===void 0||h.load());var d=this.getObjectFit();d!==this.state.mediaObjectFit&&this.setState({mediaObjectFit:d},this.computeSizes)},o.prototype.getAspect=function(){var e=this.props,t=e.cropSize,r=e.aspect;return t?t.width/t.height:r},o.prototype.getObjectFit=function(){var e,t,r,i;if(this.props.objectFit==="cover"){var n=this.imageRef.current||this.videoRef.current;if(n&&this.containerRef){this.containerRect=this.containerRef.getBoundingClientRect();var s=this.containerRect.width/this.containerRect.height,c=((e=this.imageRef.current)===null||e===void 0?void 0:e.naturalWidth)||((t=this.videoRef.current)===null||t===void 0?void 0:t.videoWidth)||0,l=((r=this.imageRef.current)===null||r===void 0?void 0:r.naturalHeight)||((i=this.videoRef.current)===null||i===void 0?void 0:i.videoHeight)||0,u=c/l;return uArray.isArray(e)?e:Array.isArray(o)?o:[t,r],[e,o,t,r]);return p.jsxs(Se,{"data-slot":"slider",defaultValue:o,value:e,min:t,max:r,className:B("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",a),...i,children:[p.jsx(_e,{"data-slot":"slider-track",className:B("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-4 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:p.jsx(ze,{"data-slot":"slider-range",className:B("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:n.length},(s,c)=>p.jsx(De,{"data-slot":"slider-thumb",className:"border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"},c))]})}const de=["image/png","image/jpeg","image/webp"],he=2*1024*1024,fe=256,ut=a=>{const o=a.normalize("NFKD").toLowerCase(),e=o.lastIndexOf("."),t=e>0?o.slice(0,e):o,r=e>0?o.slice(e).replace(/[^.a-z0-9]/g,""):"";return`${t.replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"profile-picture"}${r}`},pt=(a,o,e=Date.now())=>`profile-pictures/${a}/${e}-${ut(o)}`,me=a=>de.includes(a.type)?a.size>he?"Profile pictures must be 2MB or smaller.":a.name.trim()?null:"Please choose a valid image file.":"Only PNG, JPEG, and WebP images are allowed.",dt=a=>new Promise((o,e)=>{const t=URL.createObjectURL(a),r=new Image,i=setTimeout(()=>{URL.revokeObjectURL(t),e(new Error("Image loading timed out. Please try a different file."))},15e3);r.onload=()=>{clearTimeout(i),URL.revokeObjectURL(t),o(r)},r.onerror=()=>{clearTimeout(i),URL.revokeObjectURL(t),e(new Error("Unable to read the selected image. Please try another file."))},r.crossOrigin="anonymous",r.src=t}),ue=(a,o,e)=>new Promise((t,r)=>{a.toBlob(i=>{if(!i){r(new Error("Failed to prepare the image for upload."));return}t(i)},o,e)}),ht=async(a,o=fe)=>{const e=await dt(a),t=document.createElement("canvas");t.width=o,t.height=o;const r=t.getContext("2d");if(!r)throw new Error("Your browser cannot process image uploads right now.");const i=e.naturalWidth||e.width,n=e.naturalHeight||e.height,s=Math.min(i,n),c=Math.max(0,(i-s)/2),l=Math.max(0,(n-s)/2);r.clearRect(0,0,o,o),r.drawImage(e,c,l,s,s,0,0,o,o);try{return await ue(t,"image/webp",.9)}catch{return await ue(t,"image/jpeg",.9)}},j=(a,o,e)=>{let t;const r=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`${e} timed out after ${Math.round(o/1e3)}s`)),o)});return Promise.race([a,r]).finally(()=>clearTimeout(t))},ft=async(a,o,e)=>{const t=we.options.projectId;if(!t)throw new Error("Firebase project ID is not configured.");const r=await a.getIdToken(),i=`https://firestore.googleapis.com/v1/projects/${t}/databases/(default)/documents/users/${o}?updateMask.fieldPaths=photo&updateMask.fieldPaths=updatedAt`,n=await fetch(i,{method:"PATCH",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({fields:{photo:{stringValue:e},updatedAt:{timestampValue:new Date().toISOString()}}})});if(!n.ok){const s=await n.text().catch(()=>"");throw new Error(`Firestore REST update failed (${n.status}): ${s}`)}},mt=async({file:a,uid:o,currentUser:e=K.currentUser,syncFirestore:t=!0})=>{const r=me(a);if(r)throw new Error(r);const i=e??K.currentUser;if(!i)throw new Error("You need to be signed in to change your profile picture.");const n=o||i.uid;if(!n)throw new Error("Unable to determine which profile should be updated.");if(i.uid!==n)throw new Error("The signed-in user does not match the profile being edited.");const s=await j(ht(a,fe),2e4,"Image processing"),c=pt(n,a.name),l=Ae(ge,c),u=await j(Te(l,s,{contentType:s.type||"image/webp",cacheControl:"public, max-age=31536000, immutable"}),3e4,"Storage upload"),h=await j(Ne(u.ref),1e4,"Download URL retrieval");try{await j(Me(i,{photoURL:h}),1e4,"Auth profile update")}catch(d){console.warn("[PROFILE UPLOAD] Auth profile update failed (non-fatal):",d)}if(t){try{await j(ft(i,n,h),1e4,"Firestore profile sync")}catch(d){console.error("[PROFILE UPLOAD] Firestore REST sync failed:",d),console.warn("[PROFILE UPLOAD] Photo was uploaded but the database record may be stale. It will refresh on next login.")}try{const{doc:d,updateDoc:m}=await $(async()=>{const{doc:v,updateDoc:f}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{doc:v,updateDoc:f}},__vite__mapDeps([0,1])),{db:w}=await $(async()=>{const{db:v}=await import("./index-BdLfAeGL.js").then(f=>f.b7);return{db:v}},__vite__mapDeps([2,3,0,1,4,5,6,7,8,9,10,11]));await m(d(w,"leaderboard",n),{photo:h}).catch(()=>$(async()=>{const{setDoc:v}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{setDoc:v}},__vite__mapDeps([0,1])).then(({setDoc:v})=>v(d(w,"leaderboard",n),{photo:h},{merge:!0})))}catch{}}return h},vt=a=>`${(a/(1024*1024)).toFixed(1)} MB`,gt=a=>{const o=(a||"").trim();return o?o.split(/\s+/).slice(0,2).map(e=>e[0]?.toUpperCase()).join(""):"U"},wt=a=>new Promise((o,e)=>{const t=new Image;t.onload=()=>o(t),t.onerror=()=>e(new Error("Unable to load the image for cropping.")),t.src=a}),pe=(a,o,e)=>new Promise((t,r)=>{a.toBlob(i=>{if(!i){r(new Error("Failed to prepare the cropped image."));return}t(i)},o,e)}),xt=async(a,o,e)=>{const t=await wt(a),r=document.createElement("canvas"),i=640;r.width=i,r.height=i;const n=r.getContext("2d");if(!n)throw new Error("Your browser cannot process the selected image right now.");n.clearRect(0,0,i,i),n.drawImage(t,o.x,o.y,o.width,o.height,0,0,i,i);let s;try{s=await pe(r,"image/webp",.92)}catch{s=await pe(r,"image/jpeg",.92)}if(!s)throw new Error("Could not create an image from the cropped area.");const c=s.type==="image/webp"?"webp":"jpg",u=`${e.name.replace(/\.[^/.]+$/,"")||"profile-picture"}-cropped.${c}`;return new File([s],u,{type:s.type,lastModified:Date.now()})},Nt=({uid:a,photoURL:o,displayName:e,className:t="",onUploaded:r,syncFirestore:i=!0})=>{const{currentUser:n,refreshProfile:s}=xe(),[c,l]=x.useState(null),[u,h]=x.useState(null),[d,m]=x.useState({x:0,y:0}),[w,v]=x.useState(1),[f,R]=x.useState(null),[y,g]=x.useState(""),[E,_]=x.useState(!1),P=x.useRef(null);x.useEffect(()=>{if(!c){h(null);return}const C=URL.createObjectURL(c);return h(C),()=>URL.revokeObjectURL(C)},[c]);const k=u||o||"",W=x.useMemo(()=>`${de.map(S=>S.replace("image/","").toUpperCase()).join(", ")} up to ${vt(he)}. The image will be cropped to a circular avatar.`,[]),D=()=>{l(null),m({x:0,y:0}),v(1),R(null),g(""),P.current&&(P.current.value="")},z=C=>{const S=C.target.files?.[0]||null;if(!S)return;const M=me(S);if(M){g(M),l(null),C.target.value="";return}g(""),l(S),m({x:0,y:0}),v(1),R(null)},T=async()=>{if(!c){g("Choose an image before saving.");return}_(!0),g("");const C=6e4;let S;try{const M=(async()=>{const I=u&&f?await xt(u,f,c):c,Z=a||n?.uid;return mt({file:I,uid:Z,currentUser:n,syncFirestore:i})})(),F=new Promise((I,Z)=>{S=setTimeout(()=>Z(new Error("Upload timed out. Please check your connection and try again.")),C)}),ve=await Promise.race([M,F]);r?.(ve),s().catch(I=>console.warn("[ProfilePictureUploader] refreshProfile failed:",I)),Q.success("Profile picture updated."),D()}catch(M){const F=M instanceof Error?M.message:"Failed to update your profile picture.";g(F),Q.error(F)}finally{clearTimeout(S),_(!1)}},U=()=>{P.current?.click()};return p.jsxs(p.Fragment,{children:[p.jsxs("section",{className:`flex items-center gap-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm ${t}`,children:[p.jsxs("div",{className:"relative cursor-pointer group",onClick:U,role:"button",tabIndex:0,onKeyDown:C=>C.key==="Enter"&&U(),"aria-label":"Change profile picture",children:[p.jsxs(ye,{className:"size-16 sm:size-20 ring-4 ring-sky-50 shadow-sm transition-transform duration-200 group-hover:scale-105",children:[p.jsx(be,{src:k,alt:`${e||"User"} profile picture`}),p.jsx(Ce,{className:"bg-gradient-to-br from-sky-600 to-cyan-500 text-lg font-semibold text-white",children:gt(e)})]}),p.jsx("span",{className:"absolute -right-1 -top-1 inline-flex items-center justify-center rounded-full bg-slate-900 p-1.5 text-white shadow-md transition-colors group-hover:bg-slate-700",children:p.jsx(Oe,{size:14})})]}),p.jsxs("div",{className:"space-y-1 flex-1",children:[p.jsx("p",{className:"text-sm font-semibold text-slate-900",children:"Profile picture"}),p.jsx("p",{className:"text-xs text-slate-500",children:"Click your avatar to upload a new photo."}),y&&p.jsx("p",{className:"text-xs font-medium text-rose-600 mt-1",children:y})]}),p.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:z,className:"sr-only","aria-label":"Choose profile picture"})]}),p.jsx(Pe,{children:u&&p.jsxs(p.Fragment,{children:[p.jsx(J.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-[60]",onClick:D}),p.jsx(J.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",duration:.5,bounce:.3},className:"fixed inset-0 z-[60] flex items-center justify-center p-4 sm:p-6",onClick:C=>C.stopPropagation(),children:p.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-lg overflow-hidden flex flex-col",children:[p.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-slate-100",children:[p.jsx("h3",{className:"text-lg font-bold text-slate-900",children:"Update profile picture"}),p.jsx("button",{onClick:D,className:"p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors","aria-label":"Close modal",children:p.jsx(je,{size:20})})]}),p.jsxs("div",{className:"p-4 sm:p-6 bg-slate-50 flex flex-col items-center",children:[p.jsx("div",{className:"relative h-[350px] sm:h-[450px] w-[350px] sm:w-[450px] mx-auto overflow-hidden rounded-xl bg-slate-100 ring-1 ring-inset ring-slate-200 shadow-inner",children:p.jsx(ct,{image:u,crop:d,zoom:w,aspect:1,cropShape:"round",showGrid:!1,objectFit:"cover",restrictPosition:!0,onCropChange:m,onZoomChange:v,onCropComplete:(C,S)=>R(S),style:{containerStyle:{backgroundColor:"#f8fafc"}}})}),p.jsxs("div",{className:"mt-6 w-full max-w-xs flex items-center gap-4",children:[p.jsx(Ue,{size:18,className:"text-slate-500"}),p.jsx(lt,{value:[w],min:1,max:3,step:.05,onValueChange:C=>v(C[0]||1),"aria-label":"Profile picture zoom",className:"flex-1 cursor-pointer"}),p.jsx(Fe,{size:18,className:"text-slate-500"})]}),p.jsx("p",{className:"mt-4 text-xs text-slate-500 text-center",children:W})]}),p.jsxs("div",{className:"p-4 border-t border-slate-100 flex items-center justify-end gap-3 bg-white",children:[p.jsx(ee,{type:"button",variant:"ghost",onClick:D,disabled:E,className:"font-medium text-slate-600 hover:text-slate-900 hover:bg-slate-100 px-5",children:"Cancel"}),p.jsx(ee,{type:"button",onClick:T,disabled:E||!c,className:"bg-sky-600 hover:bg-sky-700 text-white min-w-[120px] gap-2 shadow-sm",children:E?p.jsxs(p.Fragment,{children:[p.jsx(Ie,{size:16,className:"animate-pulse"}),"Saving..."]}):"Save picture"})]})]})})]})})]})};export{At as M,Nt as P,Tt as V}; diff --git a/assets/QuizBattlePage-H3hCehZd.js b/assets/QuizBattlePage-BgqU8ht-.js similarity index 99% rename from assets/QuizBattlePage-H3hCehZd.js rename to assets/QuizBattlePage-BgqU8ht-.js index df4623fb226f4dc7c0adcb68de5ca265d60308a6..c171d0c797f1f950a5d0772b40ff828f00de8b1a 100644 --- a/assets/QuizBattlePage-H3hCehZd.js +++ b/assets/QuizBattlePage-BgqU8ht-.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-BVFD1ZML.js","assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{e as xa,o as u,m as y,g as et,aM as De,k as st,aN as q,_ as pa,$ as Ha,r as zt,M as Va,aO as Ua,N as Te,h as Ze,U as ke,q as Ke,u as Wa,F as gt,a2 as wt,a7 as vt,a6 as ea}from"./index-BvEKrMkD.js";import{r as i,j as e,d as Et}from"./vendor-react-B4AQeu28.js";import{q as jt}from"./quiz_battle_avatar-BXHPSput.js";import{g as Ya,s as ta}from"./subjects-ChEJ6J55.js";import{doc as Xa,getDoc as Ga,where as aa,orderBy as ha,limit as Ct,getDocs as It,query as Bt,collection as Mt}from"./vendor-firebase-firestore-CNv3xXal.js";import{a4 as L,a5 as ba,a6 as fa,a7 as _e,a8 as Za}from"./vendor-firebase-core-D7GXCeNu.js";import{B as z}from"./button-Bfg1pO9T.js";import{e as Ka,f as Ja}from"./vendor-radix-C5nwdvGr.js";import{S as Me,a as Fe,b as Ee,c as Re,d as de}from"./select-CU8TeDXy.js";import{I as es}from"./input-B3TmduBc.js";import{S as ts}from"./switch-kakgyvwt.js";import{S as xe,C as sa}from"./skeleton-CU_hcmX-.js";import{V as ga,a as wa,M as as,b as ss}from"./volume-x-C2kyFHU5.js";import{C as yt}from"./CompositeAvatar-DoKZfi7O.js";import{S as Je}from"./sparkles-av0wSNZT.js";import{C as Nt}from"./check-BmWAQELM.js";import{H as rs}from"./history-uiZLfMqH.js";import{C as Ue}from"./chevron-right-CbKJd0ln.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-DKW3TTRX.js";import"./chevron-up-CDr90bpM.js";import"./avatarData-ChByUhv2.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-h2NDr2Mk.js","assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{e as xa,o as u,m as y,g as et,aM as De,k as st,aN as q,_ as pa,$ as Ha,r as zt,M as Va,aO as Ua,N as Te,h as Ze,U as ke,q as Ke,u as Wa,F as gt,a2 as wt,a7 as vt,a6 as ea}from"./index-BdLfAeGL.js";import{r as i,j as e,d as Et}from"./vendor-react-B4AQeu28.js";import{q as jt}from"./quiz_battle_avatar-BXHPSput.js";import{g as Ya,s as ta}from"./subjects-Dw9HR29l.js";import{doc as Xa,getDoc as Ga,where as aa,orderBy as ha,limit as Ct,getDocs as It,query as Bt,collection as Mt}from"./vendor-firebase-firestore-CNv3xXal.js";import{a4 as L,a5 as ba,a6 as fa,a7 as _e,a8 as Za}from"./vendor-firebase-core-D7GXCeNu.js";import{B as z}from"./button-BbJLXpfi.js";import{e as Ka,f as Ja}from"./vendor-radix-C5nwdvGr.js";import{S as Me,a as Fe,b as Ee,c as Re,d as de}from"./select-C3tB_0M-.js";import{I as es}from"./input-CHfZS1wQ.js";import{S as ts}from"./switch-BZ2ceCBk.js";import{S as xe,C as sa}from"./skeleton-SSuNGBG3.js";import{V as ga,a as wa,M as as,b as ss}from"./volume-x-BfFSlkII.js";import{C as yt}from"./CompositeAvatar-DoKZfi7O.js";import{S as Je}from"./sparkles-DnAkO9TX.js";import{C as Nt}from"./check-DbVe23hB.js";import{H as rs}from"./history-VIZhCw1O.js";import{C as Ue}from"./chevron-right-BRRve0zL.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-Dl7iJ2BC.js";import"./chevron-up-uSn_SWll.js";import"./avatarData-ChByUhv2.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -9,7 +9,7 @@ import{e as xa,o as u,m as y,g as et,aM as De,k as st,aN as q,_ as pa,$ as Ha,r * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const os=[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]],ls=xa("pause",os),We=({width:a,x:s,delay:n,duration:c})=>{const d=["#9956DE","#7274ED","#1FA7E1","#6ED1CF","#75D06A","#FFB356","#FF8B8B","#FB96BB"],l=d[Math.floor(Math.random()*d.length)],w=Math.floor(Math.random()*10)+1;return e.jsx(y.div,{style:{"--x":`${s}`,"--width":`${a}`,"--aspect-ratio":`${w}`,"--background":`linear-gradient(${l}cc, transparent)`},className:"absolute left-[var(--x)] top-0 [aspect-ratio:1/var(--aspect-ratio)] [background:var(--background)] [width:var(--width)]",initial:{y:"100cqmax",x:"-50%"},animate:{y:"-100%",x:"-50%"},transition:{duration:c,delay:n,repeat:Number.POSITIVE_INFINITY,ease:"linear"}})},na=({children:a,perspective:s=100,className:n,bgVideo:c,beamsPerSide:d=6,beamSize:l=4,beamDelayMax:w=1.5,beamDelayMin:A=0,beamDuration:f=4,gridColor:N="rgba(100, 116, 139, 0.08)",...b})=>{const j=i.useCallback(()=>{const S=[],Y=Math.floor(100/l)/d;for(let O=0;Oj(),[j]),m=i.useMemo(()=>j(),[j]),v=i.useMemo(()=>j(),[j]),W=i.useMemo(()=>j(),[j]);return e.jsxs("div",{className:u("relative w-full h-full",n),...b,children:[c?e.jsx("video",{autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"pointer-events-none absolute inset-0 w-full h-full object-cover -z-10",src:c}):e.jsxs("div",{style:{"--perspective":`${s}px`,"--grid-color":N,"--beam-size":`${l}%`},className:"pointer-events-none absolute inset-0 overflow-hidden [clip-path:inset(0)] [container-type:size] [perspective:var(--perspective)] [transform-style:preserve-3d] -z-10 bg-[#42389d]",children:[e.jsx("div",{className:"absolute [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [transform-origin:50%_0%] [transform:rotateX(-90deg)] [width:100cqi]",children:h.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`top-${R}`))}),e.jsx("div",{className:"absolute top-full [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [transform-origin:50%_0%] [transform:rotateX(-90deg)] [width:100cqi]",children:v.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`bottom-${R}`))}),e.jsx("div",{className:"absolute left-0 top-0 [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [transform-origin:0%_0%] [transform:rotate(90deg)_rotateX(-90deg)] [width:100cqh]",children:W.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`left-${R}`))}),e.jsx("div",{className:"absolute right-0 top-0 [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [width:100cqh] [transform-origin:100%_0%] [transform:rotate(-90deg)_rotateX(-90deg)]",children:m.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`right-${R}`))})]}),e.jsx("div",{className:"relative z-10 w-full h-full",children:a})]})},is=15e3,ds="mathpulse.quizBattle.local",oa="".toLowerCase()==="true",rt=typeof window<"u",tt=()=>rt&&!1,Rt=()=>{const a=st.currentUser?.uid;return a||"local-student"},va=a=>`${ds}.${a}`,Pe=a=>{const s={stats:Se(a),history:[],queueStatus:"idle"};if(!rt)return s;try{const n=window.localStorage.getItem(va(a));if(!n)return s;const c=JSON.parse(n),d=Array.isArray(c.history)?c.history.map(w=>Ft(w.matchId||"local-match",w)):[];return{stats:c.stats?{...Se(a),...c.stats,userId:a,updatedAt:at(c.stats.updatedAt)}:Se(a),history:d,queueStatus:c.queueStatus==="queued"||c.queueStatus==="matched"?c.queueStatus:"idle"}}catch(n){return console.error("Error reading local Quiz Battle fallback store:",n),s}},ja=(a,s)=>{if(rt)try{window.localStorage.setItem(va(a),JSON.stringify(s))}catch(n){console.error("Error writing local Quiz Battle fallback store:",n)}},ya=a=>{const s=a||{},n=typeof s.code=="string"?s.code:"";return n?n.startsWith("functions/")?n.replace("functions/",""):n:""},ne=a=>{if(!tt())return!1;const s=ya(a);if(["internal","not-found","unavailable","deadline-exceeded"].includes(s))return!0;const n=a||{},c=(typeof n.message=="string"?n.message:a instanceof Error?a.message:"").toLowerCase();return c?c.includes("cors policy")||c.includes("no access-control-allow-origin")||c.includes("failed to fetch")||c.includes("network error")||c.includes("err_failed"):!1},Ye=(a,s)=>Math.floor(Math.random()*(s-a+1))+a,cs=(a,s)=>{const n=Math.max(3,a),c=s==="easy"?0:s==="medium"?1:s==="hard"?2:1,d=Ye(Math.max(0,n-3-c),n),l=Ye(Math.max(0,n-4+c),n),w=Math.min(n,Math.max(0,d)),A=Math.min(n,Math.max(0,l)),f=Math.max(0,Math.min(100,w/n*100+Ye(-8,6))),N=Ye(1800,6200);return{scoreFor:w,scoreAgainst:A,accuracy:f,averageResponseMs:N}},us=a=>{const s=Rt(),n=Pe(s),c=`local-bot-${Date.now()}-${Math.random().toString(16).slice(2,8)}`,d=cs(a.rounds,a.botDifficulty),l=d.scoreFor>d.scoreAgainst?"win":d.scoreFor0?m/h*100:0,averageAccuracy:h>0?(n.stats.averageAccuracy*n.stats.matchesPlayed+d.accuracy)/h:d.accuracy,averageResponseMs:h>0?Math.round((n.stats.averageResponseMs*n.stats.matchesPlayed+d.averageResponseMs)/h):d.averageResponseMs,currentStreak:S,bestStreak:R,favoriteTopicId:a.topicId,leaderboardScore:n.stats.leaderboardScore+j.xpEarned,updatedAt:w};ja(s,{stats:Y,history:[j,...n.history].slice(0,50),queueStatus:"idle"});try{pa(async()=>{const{emitPipelineEvent:O,getStudentContext:M}=await import("./pipelineService-BVFD1ZML.js");return{emitPipelineEvent:O,getStudentContext:M}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])).then(({emitPipelineEvent:O,getStudentContext:M})=>{const D=M();D&&O({student_id:s,event_type:"battle",event_data:{battle_id:c,topic:a.topicId,score:d.accuracy,won:l==="win",total_questions:a.rounds,correct_answers:d.scoreFor},occurred_at:new Date().toISOString(),class_id:D.classId,teacher_id:D.teacherId})}).catch(()=>{})}catch{}return{success:!0,matchId:c,status:"ready",botDifficulty:a.botDifficulty}},Na=a=>{const s=Rt(),n=Pe(s);ja(s,{...n,queueStatus:a})},ms=()=>Math.random().toString(36).slice(2,8).toUpperCase(),Tt=a=>{const s=Rt();return{roomId:`local-room-${Date.now()}`,roomCode:a||ms(),ownerStudentId:s,participantIds:[s],participantCount:1,status:"waiting",subjectId:"gen-math",topicId:"functions",difficulty:"medium",rounds:5,timePerQuestionSec:30,isOwner:!0}},ka=()=>rt&&!!st.currentUser?.uid&&!!De,_a=(a,s,n)=>`quizBattlePresence/${a}/${s}/${n}`,xs=async(a,s)=>{if(!ka()||!s.trim()||!De)return;const n=st.currentUser?.uid;if(!n)return;const c=ba(De,_a(a,s,n));try{await fa(c,{studentId:n,scope:a,resourceId:s,online:!0,heartbeatAt:_e(),updatedAt:_e()}),await Za(c).update({online:!1,updatedAt:_e(),disconnectedAt:_e()})}catch(d){console.warn("Realtime presence connect failed:",d)}},ps=async(a,s)=>{if(!ka()||!s.trim()||!De)return;const n=st.currentUser?.uid;if(!n)return;const c=ba(De,_a(a,s,n));try{await fa(c,{studentId:n,scope:a,resourceId:s,online:!1,updatedAt:_e(),disconnectedAt:_e()})}catch(d){console.warn("Realtime presence disconnect failed:",d)}},V=(a,s)=>{const n=`Unable to continue while ${a}. Please try again.`;if(s instanceof Error&&s.message.startsWith("Timed out while"))return s.message;const c=s||{},d=ya(s),l=typeof c.message=="string"?c.message.trim():"";return d==="unauthenticated"?"Your session has expired. Sign in again before starting a battle.":d==="permission-denied"?"Only student accounts can access Quiz Battle matchmaking.":d==="invalid-argument"?l||"Battle setup is invalid. Review the selected options and try again.":d==="already-exists"?l||"This room is already full. Try another room code.":d==="failed-precondition"?l||"Battle state changed. Please refresh and continue.":d==="unavailable"||d==="internal"||d==="not-found"||d==="deadline-exceeded"?/question generation temporarily unavailable/i.test(l)?l:"Quiz Battle service is temporarily unavailable. Please retry in a moment.":n},$=async(a,s,n=is)=>{let c;try{return await Promise.race([s,new Promise((d,l)=>{c=setTimeout(()=>{l(new Error(`Timed out while ${a}. Please try again.`))},n)})])}finally{c&&clearTimeout(c)}},at=a=>{if(!a)return new Date;if(a instanceof Date)return a;if(typeof a=="string"){const s=Date.parse(a);return Number.isNaN(s)?new Date:new Date(s)}if(typeof a=="number")return new Date(a);if(typeof a=="object"){const s=a;if(typeof s.toDate=="function")return s.toDate();if(typeof s.seconds=="number")return new Date(s.seconds*1e3)}return new Date},hs=()=>({mode:"online",subjectId:"gen-math",topicId:"",difficulty:"medium",rounds:5,timePerQuestionSec:30,queueType:"public_matchmaking",botDifficulty:"medium",adaptiveBot:!1}),bs=a=>{const s=[];return a.subjectId.trim()||s.push({field:"subjectId",message:"Choose a category before starting."}),a.topicId.trim()||s.push({field:"topicId",message:"Choose a strand or topic before starting."}),(a.rounds<3||a.rounds>20)&&s.push({field:"rounds",message:"Questions must be between 3 and 20."}),(a.timePerQuestionSec<10||a.timePerQuestionSec>180)&&s.push({field:"timePerQuestionSec",message:"Timer must be between 10s and 180s."}),a.mode==="bot"&&a.queueType!=="public_matchmaking"&&s.push({field:"queueType",message:"Bot battles use instant start and do not support private room mode."}),s},Se=a=>({userId:a,matchesPlayed:0,wins:0,losses:0,draws:0,winRate:0,averageAccuracy:0,averageResponseMs:0,bestStreak:0,currentStreak:0,favoriteTopicId:void 0,leaderboardScore:0,updatedAt:new Date}),fs=async a=>{try{const s=Xa(et,"studentBattleStats",a),n=await Ga(s),c=tt()?Pe(a).stats:null;if(!n.exists())return c&&c.matchesPlayed>0?c:Se(a);const d=n.data(),l={...Se(a),...d,userId:a,updatedAt:at(d.updatedAt)};return c&&c.matchesPlayed>l.matchesPlayed?c:l}catch(s){if(console.error("Error loading battle stats:",s),tt()){const n=Pe(a).stats;if(n.matchesPlayed>0)return n}return Se(a)}},Ft=(a,s)=>({matchId:s.matchId||a,mode:s.mode||"online",status:s.status||"completed",subjectId:s.subjectId||"gen-math",topicId:s.topicId||"unknown-topic",difficulty:s.difficulty||"medium",rounds:s.rounds||0,timePerQuestionSec:s.timePerQuestionSec||0,scoreFor:s.scoreFor||0,scoreAgainst:s.scoreAgainst||0,outcome:s.outcome||"draw",accuracy:s.accuracy||0,averageResponseMs:s.averageResponseMs||0,bestStreak:s.bestStreak||0,xpEarned:s.xpEarned||0,opponentName:s.opponentName||"Unknown opponent",opponentType:s.opponentType||"student",createdAt:at(s.createdAt),endedAt:at(s.endedAt)}),gs=async(a,s={})=>{const n=s.limitCount||25,c=tt()?Pe(a).history:[],d=w=>w.filter(f=>!(s.mode&&s.mode!=="all"&&f.mode!==s.mode||s.subjectId&&f.subjectId!==s.subjectId||s.startDate&&f.endedAts.endDate)).sort((f,N)=>N.endedAt.getTime()-f.endedAt.getTime()).slice(0,n),l=w=>{if(c.length===0)return d(w);const A=new Map;return[...c,...w].forEach(f=>{A.set(f.matchId,f)}),d(Array.from(A.values()))};try{const w=[aa("studentId","==",a),ha("endedAt","desc"),Ct(n)],f=(await It(Bt(Mt(et,"quizBattleHistory"),...w))).docs.map(N=>Ft(N.id,N.data()));return l(f)}catch(w){try{const f=(await It(Bt(Mt(et,"quizBattleHistory"),aa("studentId","==",a),Ct(n)))).docs.map(N=>Ft(N.id,N.data())).sort((N,b)=>b.endedAt.getTime()-N.endedAt.getTime());return l(f)}catch(A){return console.error("Error loading battle history:",w,A),d(c)}}},ws=async a=>{const s=L(q,"quizBattleJoinQueue");try{return(await $("joining Quiz Battle matchmaking queue",s({setup:a}))).data}catch(n){if(ne(n))return Na("queued"),{success:!0,status:"queued",queueEntryId:`local-queue-${Date.now()}`};throw new Error(V("joining Quiz Battle matchmaking queue",n))}},la=async()=>{const a=L(q,"quizBattleLeaveQueue");try{return(await $("leaving Quiz Battle matchmaking queue",a({}))).data}catch(s){if(ne(s))return Na("idle"),{success:!0,status:"idle"};throw new Error(V("leaving Quiz Battle matchmaking queue",s))}},vs=async a=>{const s=L(q,"quizBattleCreatePrivateRoom");try{return(await $("creating Quiz Battle private room",s({setup:a}))).data}catch(n){if(ne(n))return{success:!0,room:Tt()};throw new Error(V("creating Quiz Battle private room",n))}},js=async a=>{const s=L(q,"quizBattleJoinPrivateRoom");try{return(await $("joining Quiz Battle private room",s({roomCode:a}),2e4)).data}catch(n){if(ne(n))return{success:!0,room:Tt(a.trim().toUpperCase()||void 0)};throw new Error(V("joining Quiz Battle private room",n))}},ys=async a=>{const s=L(q,"quizBattleGetPrivateRoomState");try{return(await $("loading Quiz Battle private room state",s(a),2e4)).data}catch(n){if(ne(n))return{success:!0,room:Tt(a.roomCode?.trim().toUpperCase()||void 0)};throw new Error(V("loading Quiz Battle private room state",n))}},Ns=async(a={})=>{const s=L(q,"quizBattleLeavePrivateRoom");try{return(await $("leaving Quiz Battle private room",s(a),2e4)).data}catch(n){if(ne(n))return{success:!0,status:"idle"};throw new Error(V("leaving Quiz Battle private room",n))}},ia=async()=>{const a=L(q,"quizBattleResumeSession");try{return(await $("resuming Quiz Battle session",a({}),2e4)).data}catch(s){if(ne(s))return{success:!0,sessionType:"idle"};throw new Error(V("resuming Quiz Battle session",s))}},ks=async(a,s)=>{if(!s.trim())return;const n=L(q,"quizBattleHeartbeat");await xs(a,s);try{await $("sending Quiz Battle heartbeat",n({scope:a,resourceId:s}),12e3)}catch(c){if(!ne(c))throw new Error(V("sending Quiz Battle heartbeat",c))}},_s=async a=>{const s=L(q,"quizBattleCreateBotMatch");try{return(await $("starting Quiz Battle bot match",s({setup:a}))).data}catch(n){if(ne(n))return us(a);throw new Error(V("starting Quiz Battle bot match",n))}},Ss=async a=>{const s=L(q,"quizBattleGetGenerationAudit");return(await $("verifying Quiz Battle generation metadata",s({matchId:a}),2e4)).data},re=async a=>{const s=L(q,"quizBattleStartMatch");try{const c=(await $("starting Quiz Battle match",s({matchId:a}),2e4)).data.match;if(c.mode==="online")try{const d=await Ss(a);if(oa&&!d.isAiSource)throw new Error(`Quiz Battle generation audit failed: expected AI source, got "${d.questionSetSource||"unknown"}".`)}catch(d){if(d instanceof Error&&d.message.startsWith("Quiz Battle generation audit failed"))throw d;if(console.warn("Quiz Battle generation audit unavailable:",d),oa)throw new Error("Unable to verify Quiz Battle generation metadata. Please retry in a moment.")}return c}catch(n){throw new Error(V("starting Quiz Battle match",n))}},kt=async a=>{const s=L(q,"quizBattleGetMatchState");try{return(await $("loading Quiz Battle match state",s({matchId:a}),2e4)).data.match}catch(n){throw new Error(V("loading Quiz Battle match state",n))}},As=async a=>{const s=L(q,"quizBattleSubmitAnswer");try{return(await $("submitting Quiz Battle answer",s({...a,idempotencyKey:a.idempotencyKey||`client-${Date.now()}-${Math.random().toString(16).slice(2,8)}`}),2e4)).data}catch(n){throw new Error(V("submitting Quiz Battle answer",n))}},zs=async a=>{const s=L(q,"quizBattleRequestRematch");try{return(await $("creating Quiz Battle rematch",s({matchId:a}),2e4)).data}catch(n){throw new Error(V("creating Quiz Battle rematch",n))}},Cs=async(a=20)=>{try{const s=Bt(Mt(et,"studentBattleLeaderboard"),ha("leaderboardScore","desc"),Ct(a));return(await It(s)).docs.map((c,d)=>{const l=c.data();return{userId:l.userId||c.id,displayName:l.displayName||"Student",photo:l.photo,rank:l.rank||d+1,leaderboardScore:l.leaderboardScore||0,winRate:l.winRate||0,bestStreak:l.bestStreak||0}})}catch(s){return console.error("Error loading Quiz Battle leaderboard:",s),[]}};function pe({className:a,...s}){return e.jsx("div",{"data-slot":"card",className:u("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",a),...s})}function he({className:a,...s}){return e.jsx("div",{"data-slot":"card-header",className:u("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",a),...s})}function be({className:a,...s}){return e.jsx("h4",{"data-slot":"card-title",className:u("leading-none",a),...s})}function ye({className:a,...s}){return e.jsx("p",{"data-slot":"card-description",className:u("text-muted-foreground",a),...s})}function Xe({className:a,...s}){return e.jsx("div",{"data-slot":"card-content",className:u("px-6 [&:last-child]:pb-6",a),...s})}function Is({className:a,...s}){return e.jsx(Ka,{"data-slot":"tabs",className:u("flex flex-col gap-2",a),...s})}function Ne({className:a,...s}){return e.jsx(Ja,{"data-slot":"tabs-content",className:u("flex-1 outline-none",a),...s})}const Sa=Et.memo(({playerRoundStreak:a,playerVisualMultiplier:s,liveXpEarned:n,activeMatch:c,subjects:d,battleSoundEnabled:l,onToggleSound:w,isFullscreen:A,onToggleFullscreen:f,isDesignPauseAvailable:N,onTogglePause:b})=>e.jsxs("header",{className:"flex items-center justify-between shrink-0 h-14 sm:h-16 relative gap-2 sm:gap-4",children:[e.jsx("div",{className:"flex items-center min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 md:gap-4 px-2.5 sm:px-4 py-1.5 sm:py-2 md:px-5 md:py-2.5 rounded-full bg-white/5 border border-white/10 backdrop-blur-md min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 text-amber-400 font-bold text-xs sm:text-sm shrink-0",children:[e.jsx(Ha,{className:"w-3 h-3 sm:w-4 sm:h-4"})," ",a]}),e.jsx("div",{className:"w-px h-3 sm:h-4 bg-white/10 shrink-0"}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 text-violet-300 font-bold text-xs sm:text-sm shrink-0",children:[e.jsx(zt,{className:"w-3 h-3 sm:w-4 sm:h-4"})," ",s.toFixed(2),"x"]}),e.jsx("div",{className:"w-px h-3 sm:h-4 bg-white/10 shrink-0"}),e.jsxs(y.div,{animate:n>0?{scale:[1,1.25,1]}:{},transition:{duration:.35},className:"flex flex-col items-center text-emerald-400 bg-emerald-500/10 px-2 sm:px-3 py-0.5 rounded-full border border-emerald-500/20 font-bold shadow-[0_0_10px_rgba(16,185,129,0.15)] shrink-0",children:[e.jsxs("span",{className:"text-xs sm:text-sm leading-none tabular-nums",children:[n," pts"]}),e.jsx("span",{className:"hidden sm:block text-[8px] leading-none text-emerald-500/70 uppercase tracking-widest font-black whitespace-nowrap",children:"Battle Score"})]},n)]})}),e.jsxs("div",{className:"absolute left-1/2 -translate-x-1/2 hidden md:flex items-center gap-3 bg-black/20 px-5 py-2 rounded-full border border-white/5 min-w-0 max-w-[48%]",children:[e.jsx("div",{className:"w-3.5 h-3.5 rounded-sm bg-orange-400 shadow-[0_0_10px_rgba(251,146,60,0.5)] shrink-0"}),e.jsx("div",{className:"flex flex-col items-start justify-center -space-y-0.5 min-w-0",children:(()=>{if(!c?.topicId)return e.jsx("span",{className:"font-bold text-white/90 tracking-wide text-sm leading-none truncate",children:"Practice Match"});for(const j of d){const h=j.modules?.find(m=>m.id===c.topicId);if(h)return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[9px] font-black text-white/40 uppercase tracking-widest leading-none",children:j.title}),e.jsx("span",{className:"font-bold text-white/90 tracking-wide text-sm leading-none pt-1 truncate",children:h.title})]})}return e.jsx("span",{className:"font-bold text-white/90 tracking-wide text-sm leading-none truncate",children:c.topicId.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" ")})})()})]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-3",children:[e.jsx(z,{variant:"outline",size:"icon",className:"h-9 w-9 sm:h-12 sm:w-12 rounded-full border-white/20 bg-black/20 hover:bg-white/10 text-white",onClick:w,children:l?e.jsx(ga,{className:"h-4 w-4 sm:h-5 sm:w-5"}):e.jsx(wa,{className:"h-4 w-4 sm:h-5 sm:w-5"})}),e.jsx(z,{variant:"outline",size:"icon",className:"hidden sm:flex h-12 w-12 rounded-full border-white/20 bg-black/20 hover:bg-white/10 text-white",onClick:f,children:A?e.jsx(as,{className:"h-5 w-5"}):e.jsx(ss,{className:"h-5 w-5"})}),e.jsx(z,{variant:"outline",size:"icon",className:u("h-9 w-9 sm:h-12 sm:w-12 rounded-full border-white/20 text-white",N?"bg-black/20 hover:bg-white/10":"bg-black/10 opacity-50 cursor-not-allowed"),onClick:b,disabled:!N,children:e.jsx(Va,{className:"h-4 w-4 sm:h-5 sm:w-5"})})]})]}));Sa.displayName="BattleHeader";const Aa=Et.memo(({studentProfile:a,activeMatch:s,scorePulseTarget:n,quizBattleAvatar:c,opponentId:d})=>{const[l,w]=i.useState(null);return i.useEffect(()=>{if(!d)return;let A=!1;return Ua(d).then(f=>{!A&&f?.avatarLayers&&w(f.avatarLayers)}).catch(()=>{}),()=>{A=!0}},[d]),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 w-full xl:max-w-[1400px] mx-auto px-2 sm:px-4 md:px-8 shrink-0 h-28 sm:h-32 md:h-48 flex justify-between items-end pb-0 pointer-events-none z-30",children:[e.jsxs("div",{className:"flex items-end gap-1.5 sm:gap-3 md:gap-6 relative pointer-events-auto",children:[e.jsx("div",{className:"relative w-16 h-16 sm:w-28 sm:h-28 md:w-40 md:h-40 rounded-t-[40px] flex items-end",children:e.jsx(yt,{layers:a?.avatarLayers||{},className:"w-full h-full object-contain origin-bottom scale-[1.15]"})}),e.jsxs("div",{className:"bg-black/40 backdrop-blur-xl border border-white/20 rounded-xl sm:rounded-2xl px-2 sm:px-4 py-2 sm:py-3 md:px-5 shadow-[0_8px_30px_rgba(0,0,0,0.5)] flex items-center gap-1.5 sm:gap-3 md:gap-4 mb-2 sm:mb-4 max-w-[130px] sm:max-w-[220px] md:max-w-[280px]",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-white font-black text-xs sm:text-base md:text-lg truncate tracking-wide",children:a?.name||"Player"}),e.jsxs("span",{className:"text-[9px] sm:text-xs md:text-sm text-white/50 font-bold uppercase tracking-wider",children:["Level ",a?.level||1]})]}),e.jsx("div",{className:"h-6 sm:h-10 w-px bg-white/20"}),e.jsxs("div",{className:"flex flex-col items-center justify-center shrink-0 w-6 sm:w-10 md:w-12",children:[e.jsx(y.span,{animate:n==="player"?{scale:[1,1.4,1],color:["#fff","#34d399","#fff"]}:{},transition:{duration:.5},className:"text-lg sm:text-2xl md:text-3xl font-black text-white leading-none",children:s.scoreFor}),e.jsx("span",{className:"text-[7px] sm:text-[9px] md:text-[10px] text-emerald-400 font-bold uppercase tracking-widest mt-0.5 sm:mt-1 leading-none",children:"Score"})]})]})]}),e.jsxs("div",{className:"flex items-end gap-1.5 sm:gap-3 md:gap-6 relative flex-row-reverse pointer-events-auto",children:[e.jsx("div",{className:"relative w-16 h-16 sm:w-28 sm:h-28 md:w-40 md:h-40 rounded-t-[40px] flex items-end justify-center",children:s.mode==="bot"?e.jsx(Te,{className:"h-8 w-8 sm:h-16 sm:w-16 md:h-20 md:w-20 text-rose-400 mb-3 sm:mb-6 drop-shadow-xl",strokeWidth:1.5}):l?e.jsx(yt,{layers:l,className:"w-full h-full object-contain origin-bottom scale-[1.15]"}):e.jsx(yt,{layers:{},className:"w-full h-full object-contain origin-bottom scale-[1.15]"})}),e.jsxs("div",{className:"bg-black/40 backdrop-blur-xl border border-white/20 rounded-xl sm:rounded-2xl px-2 sm:px-4 py-2 sm:py-3 md:px-5 shadow-[0_8px_30px_rgba(0,0,0,0.5)] flex items-center gap-1.5 sm:gap-3 md:gap-4 mb-2 sm:mb-4 flex-row-reverse text-right max-w-[130px] sm:max-w-[220px] md:max-w-[280px]",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-white font-black text-xs sm:text-base md:text-lg truncate tracking-wide",children:s.opponentName||"Anonymous"}),e.jsx("span",{className:"text-[9px] sm:text-xs md:text-sm text-rose-400 font-bold uppercase tracking-wider",children:s.mode==="bot"?"System Bot":"Challenger"})]}),e.jsx("div",{className:"h-6 sm:h-10 w-px bg-white/20"}),e.jsxs("div",{className:"flex flex-col items-center justify-center shrink-0 w-6 sm:w-10 md:w-12",children:[e.jsx(y.span,{animate:n==="opponent"?{scale:[1,1.4,1],color:["#fff","#fb7185","#fff"]}:{},transition:{duration:.5},className:"text-lg sm:text-2xl md:text-3xl font-black text-white leading-none",children:s.scoreAgainst}),e.jsx("span",{className:"text-[7px] sm:text-[9px] md:text-[10px] text-rose-400 font-bold uppercase tracking-widest mt-0.5 sm:mt-1 leading-none",children:"Score"})]})]})]})]})});Aa.displayName="BattleFooter";const za=Et.memo(({activeMatch:a,roundSecondsLeft:s,lastRoundResult:n,selectedOptionIndex:c,roundLocked:d,answerSubmitting:l,designPauseActive:w,onOptionSelect:A,floatingMomentum:f,lastRoundMomentumDelta:N,studentProfile:b,quizBattleAvatar:j})=>e.jsxs("div",{className:"flex-1 flex flex-col justify-center items-center gap-4 md:gap-6 w-full min-h-0 overflow-y-auto pt-4 pb-28 z-20 no-scrollbar",children:[e.jsxs("div",{className:u("relative bg-[#1e2536] border shadow-[0_20px_60px_rgba(0,0,0,0.4)] rounded-[1.5rem] p-5 md:p-6 w-full max-w-4xl text-center flex flex-col items-center",s<=3?"border-rose-400/50":"border-white/10"),children:[e.jsxs("div",{className:"absolute -top-3.5 bg-[#2f3547] border border-white/10 text-white/80 px-4 py-1 rounded-full text-xs font-black shadow-lg uppercase tracking-wider",children:[a.currentRound," / ",a.totalRounds]}),e.jsx(Ze,{children:f&&f.tone==="positive"&&e.jsx(y.div,{initial:{opacity:0,y:14,scale:.92},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-10,scale:.9},className:u("absolute -top-12 rounded-full border px-3 py-1 text-[10px] font-black uppercase tracking-[0.15em] backdrop-blur-lg",f.tone==="positive"?"border-emerald-300/70 bg-emerald-500/20 text-emerald-100":f.tone==="negative"?"border-rose-300/70 bg-rose-500/20 text-rose-100":"border-slate-300/50 bg-slate-500/20 text-slate-100"),children:f.label},f.id)}),e.jsx("p",{className:"text-base sm:text-lg md:text-xl text-white font-extrabold leading-tight tracking-tight mt-1 min-h-[40px] flex items-center justify-center",children:a.currentQuestion?.prompt}),typeof window<"u"&&window.location.search.includes("debug=true")&&a.currentQuestion?.varianceApplied&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2 justify-center",children:a.currentQuestion.varianceApplied.map(h=>e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-[10px] font-medium bg-blue-500/20 text-blue-200 border border-blue-400/30",children:h.replace(/_/g," ")},h))})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 md:gap-4 w-full max-w-4xl px-4",children:a.currentQuestion?.choices.map((h,m)=>{const v=c===m,W=l||d,S=!!n&&n.roundNumber===a.currentRound,R=S&&n.correctOptionIndex===m;let Y=-1;if(S)if(a.mode==="bot")if(n.botCorrect)Y=n.correctOptionIndex;else{const D=[0,1,2,3].filter(C=>C!==n.correctOptionIndex);Y=D[n.roundNumber%D.length]}else Y=typeof n.botSelectedIndex=="number"?n.botSelectedIndex:-1;const O=Y===m;let M="bg-[#1e2433] hover:bg-[#283042] border-[#2f384e] text-white shadow-[0_6px_0_rgba(15,20,30,0.5)]";return S?R?M="bg-emerald-500 text-emerald-950 border-emerald-400 shadow-[0_6px_0_rgba(5,150,105,1)]":v?M="bg-rose-500 text-white border-rose-400 shadow-[0_6px_0_rgba(225,29,72,1)]":M="bg-[#1e2433] opacity-40 border-[#2f384e] shadow-[0_6px_0_rgba(15,20,30,0.5)] text-white":v&&(M="bg-indigo-500 text-white border-indigo-400 shadow-[0_6px_0_rgba(79,70,229,1)]"),e.jsxs(y.button,{whileTap:{y:8,scale:.98},whileHover:!S&&!W?{scale:1.02}:{},disabled:W||d||w,onClick:()=>A(m),className:u("relative h-16 md:h-20 rounded-2xl md:rounded-3xl font-black text-base md:text-lg pl-6 pr-20 border-[2px] border-b-[4px] flex items-center justify-start text-left transition-all disabled:cursor-not-allowed",M,v&&!S?"ring-[4px] ring-white/20 ring-offset-[4px] ring-offset-[#0B0F19]":"",s<=3&&!W&&!S?"shadow-[0_0_0_2px_rgba(251,113,133,0.45),0_6px_0_rgba(127,29,29,1)]":""),children:[e.jsx("span",{className:"mr-3 md:mr-4 text-xs md:text-sm opacity-60 bg-black/20 px-3 py-1 rounded-full",children:String.fromCharCode(65+m)}),e.jsx("span",{className:"line-clamp-2",children:h}),e.jsxs("div",{className:"absolute right-3 md:right-4 flex items-center gap-1.5 md:gap-2",children:[O&&e.jsx(y.div,{initial:{opacity:0,scale:.5},animate:{opacity:1,scale:1},className:"w-8 h-8 md:w-10 md:h-10 rounded-full border-[3px] border-[#0B0F19] overflow-hidden bg-rose-500 shadow-lg flex items-center justify-center z-10",children:a.mode==="bot"?e.jsx(Te,{className:"w-4 h-4 md:w-5 md:h-5 text-white"}):e.jsx(ke,{className:"w-4 h-4 md:w-5 md:h-5 text-white"})}),v&&e.jsx(y.div,{initial:{opacity:0,scale:.5},animate:{opacity:1,scale:1},className:"w-8 h-8 md:w-10 md:h-10 rounded-full border-[3px] border-[#0B0F19] overflow-hidden bg-indigo-200 shadow-lg z-20",children:e.jsx("img",{src:b?.photo||j,alt:"You",className:"w-full h-full object-cover"})})]})]},m)})}),e.jsx(Ze,{children:d&&!n&&a.mode==="online"&&e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"mt-4 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/70 font-semibold bg-black/30 px-6 py-2 rounded-full border border-white/10",children:[e.jsx(Ke,{className:"w-4 h-4 animate-spin text-amber-400"}),"Waiting for opponent..."]}),e.jsx("p",{className:"text-white/30 text-[11px] mt-1",children:"Choices locked until round resolves"})]})}),e.jsx(Ze,{children:n?.studentCorrect&&e.jsx(y.div,{initial:{opacity:0,scale:.8,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:1.1,filter:"blur(10px)"},transition:{type:"spring",damping:20,stiffness:300},className:"fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[100] pointer-events-none flex flex-col items-center justify-center",children:e.jsxs("div",{className:"bg-[#1e2433]/95 backdrop-blur-xl border border-white/10 rounded-[2rem] p-6 md:p-8 shadow-[0_30px_80px_rgba(0,0,0,0.6)] flex flex-col items-center min-w-[280px] md:min-w-[320px]",children:[e.jsx("img",{src:j,alt:"Mascot",className:"w-24 h-24 md:w-32 md:h-32 mb-4 drop-shadow-xl"}),e.jsx("h2",{className:u("text-3xl md:text-4xl font-black mb-4 uppercase tracking-widest",n.studentCorrect?"text-emerald-400":"text-rose-400"),children:n.studentCorrect?"Correct!":"Incorrect"}),n.studentCorrect?e.jsxs("div",{className:"flex items-center gap-3 w-full justify-center",children:[e.jsx("div",{className:"flex items-center gap-2 bg-emerald-500/20 text-emerald-400 px-4 py-2 rounded-2xl font-bold border border-emerald-500/30",children:e.jsx("span",{children:"+ 10 XP"})}),N!==null&&N>0&&e.jsx("div",{className:"flex items-center gap-2 bg-amber-500/20 text-amber-400 px-4 py-2 rounded-2xl font-bold border border-amber-500/30",children:e.jsxs("span",{children:["+ ",N," ",e.jsx(Je,{className:"w-4 h-4 inline"})]})})]}):e.jsxs("div",{className:"bg-rose-500/20 border border-rose-500/30 text-rose-400 font-bold px-5 py-2 rounded-xl text-center",children:["Correct: ",String.fromCharCode(65+n.correctOptionIndex)]})]})})})]}));za.displayName="BattleActiveContent";const _t={width:1280,height:720},St=` + */const os=[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]],ls=xa("pause",os),We=({width:a,x:s,delay:n,duration:c})=>{const d=["#9956DE","#7274ED","#1FA7E1","#6ED1CF","#75D06A","#FFB356","#FF8B8B","#FB96BB"],l=d[Math.floor(Math.random()*d.length)],w=Math.floor(Math.random()*10)+1;return e.jsx(y.div,{style:{"--x":`${s}`,"--width":`${a}`,"--aspect-ratio":`${w}`,"--background":`linear-gradient(${l}cc, transparent)`},className:"absolute left-[var(--x)] top-0 [aspect-ratio:1/var(--aspect-ratio)] [background:var(--background)] [width:var(--width)]",initial:{y:"100cqmax",x:"-50%"},animate:{y:"-100%",x:"-50%"},transition:{duration:c,delay:n,repeat:Number.POSITIVE_INFINITY,ease:"linear"}})},na=({children:a,perspective:s=100,className:n,bgVideo:c,beamsPerSide:d=6,beamSize:l=4,beamDelayMax:w=1.5,beamDelayMin:A=0,beamDuration:f=4,gridColor:N="rgba(100, 116, 139, 0.08)",...b})=>{const j=i.useCallback(()=>{const S=[],Y=Math.floor(100/l)/d;for(let O=0;Oj(),[j]),m=i.useMemo(()=>j(),[j]),v=i.useMemo(()=>j(),[j]),W=i.useMemo(()=>j(),[j]);return e.jsxs("div",{className:u("relative w-full h-full",n),...b,children:[c?e.jsx("video",{autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"pointer-events-none absolute inset-0 w-full h-full object-cover -z-10",src:c}):e.jsxs("div",{style:{"--perspective":`${s}px`,"--grid-color":N,"--beam-size":`${l}%`},className:"pointer-events-none absolute inset-0 overflow-hidden [clip-path:inset(0)] [container-type:size] [perspective:var(--perspective)] [transform-style:preserve-3d] -z-10 bg-[#42389d]",children:[e.jsx("div",{className:"absolute [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [transform-origin:50%_0%] [transform:rotateX(-90deg)] [width:100cqi]",children:h.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`top-${R}`))}),e.jsx("div",{className:"absolute top-full [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [transform-origin:50%_0%] [transform:rotateX(-90deg)] [width:100cqi]",children:v.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`bottom-${R}`))}),e.jsx("div",{className:"absolute left-0 top-0 [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [transform-origin:0%_0%] [transform:rotate(90deg)_rotateX(-90deg)] [width:100cqh]",children:W.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`left-${R}`))}),e.jsx("div",{className:"absolute right-0 top-0 [transform-style:preserve-3d] [background-size:var(--beam-size)_var(--beam-size)] [background:linear-gradient(var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_-0.5px_/var(--beam-size)_var(--beam-size),linear-gradient(90deg,_var(--grid-color)_0_1px,_transparent_1px_var(--beam-size))_50%_50%_/var(--beam-size)_var(--beam-size)] [container-type:inline-size] [height:100cqmax] [width:100cqh] [transform-origin:100%_0%] [transform:rotate(-90deg)_rotateX(-90deg)]",children:m.map((S,R)=>e.jsx(We,{width:`${l}%`,x:`${S.x*l}%`,delay:S.delay,duration:f},`right-${R}`))})]}),e.jsx("div",{className:"relative z-10 w-full h-full",children:a})]})},is=15e3,ds="mathpulse.quizBattle.local",oa="".toLowerCase()==="true",rt=typeof window<"u",tt=()=>rt&&!1,Rt=()=>{const a=st.currentUser?.uid;return a||"local-student"},va=a=>`${ds}.${a}`,Pe=a=>{const s={stats:Se(a),history:[],queueStatus:"idle"};if(!rt)return s;try{const n=window.localStorage.getItem(va(a));if(!n)return s;const c=JSON.parse(n),d=Array.isArray(c.history)?c.history.map(w=>Ft(w.matchId||"local-match",w)):[];return{stats:c.stats?{...Se(a),...c.stats,userId:a,updatedAt:at(c.stats.updatedAt)}:Se(a),history:d,queueStatus:c.queueStatus==="queued"||c.queueStatus==="matched"?c.queueStatus:"idle"}}catch(n){return console.error("Error reading local Quiz Battle fallback store:",n),s}},ja=(a,s)=>{if(rt)try{window.localStorage.setItem(va(a),JSON.stringify(s))}catch(n){console.error("Error writing local Quiz Battle fallback store:",n)}},ya=a=>{const s=a||{},n=typeof s.code=="string"?s.code:"";return n?n.startsWith("functions/")?n.replace("functions/",""):n:""},ne=a=>{if(!tt())return!1;const s=ya(a);if(["internal","not-found","unavailable","deadline-exceeded"].includes(s))return!0;const n=a||{},c=(typeof n.message=="string"?n.message:a instanceof Error?a.message:"").toLowerCase();return c?c.includes("cors policy")||c.includes("no access-control-allow-origin")||c.includes("failed to fetch")||c.includes("network error")||c.includes("err_failed"):!1},Ye=(a,s)=>Math.floor(Math.random()*(s-a+1))+a,cs=(a,s)=>{const n=Math.max(3,a),c=s==="easy"?0:s==="medium"?1:s==="hard"?2:1,d=Ye(Math.max(0,n-3-c),n),l=Ye(Math.max(0,n-4+c),n),w=Math.min(n,Math.max(0,d)),A=Math.min(n,Math.max(0,l)),f=Math.max(0,Math.min(100,w/n*100+Ye(-8,6))),N=Ye(1800,6200);return{scoreFor:w,scoreAgainst:A,accuracy:f,averageResponseMs:N}},us=a=>{const s=Rt(),n=Pe(s),c=`local-bot-${Date.now()}-${Math.random().toString(16).slice(2,8)}`,d=cs(a.rounds,a.botDifficulty),l=d.scoreFor>d.scoreAgainst?"win":d.scoreFor0?m/h*100:0,averageAccuracy:h>0?(n.stats.averageAccuracy*n.stats.matchesPlayed+d.accuracy)/h:d.accuracy,averageResponseMs:h>0?Math.round((n.stats.averageResponseMs*n.stats.matchesPlayed+d.averageResponseMs)/h):d.averageResponseMs,currentStreak:S,bestStreak:R,favoriteTopicId:a.topicId,leaderboardScore:n.stats.leaderboardScore+j.xpEarned,updatedAt:w};ja(s,{stats:Y,history:[j,...n.history].slice(0,50),queueStatus:"idle"});try{pa(async()=>{const{emitPipelineEvent:O,getStudentContext:M}=await import("./pipelineService-h2NDr2Mk.js");return{emitPipelineEvent:O,getStudentContext:M}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])).then(({emitPipelineEvent:O,getStudentContext:M})=>{const D=M();D&&O({student_id:s,event_type:"battle",event_data:{battle_id:c,topic:a.topicId,score:d.accuracy,won:l==="win",total_questions:a.rounds,correct_answers:d.scoreFor},occurred_at:new Date().toISOString(),class_id:D.classId,teacher_id:D.teacherId})}).catch(()=>{})}catch{}return{success:!0,matchId:c,status:"ready",botDifficulty:a.botDifficulty}},Na=a=>{const s=Rt(),n=Pe(s);ja(s,{...n,queueStatus:a})},ms=()=>Math.random().toString(36).slice(2,8).toUpperCase(),Tt=a=>{const s=Rt();return{roomId:`local-room-${Date.now()}`,roomCode:a||ms(),ownerStudentId:s,participantIds:[s],participantCount:1,status:"waiting",subjectId:"gen-math",topicId:"functions",difficulty:"medium",rounds:5,timePerQuestionSec:30,isOwner:!0}},ka=()=>rt&&!!st.currentUser?.uid&&!!De,_a=(a,s,n)=>`quizBattlePresence/${a}/${s}/${n}`,xs=async(a,s)=>{if(!ka()||!s.trim()||!De)return;const n=st.currentUser?.uid;if(!n)return;const c=ba(De,_a(a,s,n));try{await fa(c,{studentId:n,scope:a,resourceId:s,online:!0,heartbeatAt:_e(),updatedAt:_e()}),await Za(c).update({online:!1,updatedAt:_e(),disconnectedAt:_e()})}catch(d){console.warn("Realtime presence connect failed:",d)}},ps=async(a,s)=>{if(!ka()||!s.trim()||!De)return;const n=st.currentUser?.uid;if(!n)return;const c=ba(De,_a(a,s,n));try{await fa(c,{studentId:n,scope:a,resourceId:s,online:!1,updatedAt:_e(),disconnectedAt:_e()})}catch(d){console.warn("Realtime presence disconnect failed:",d)}},V=(a,s)=>{const n=`Unable to continue while ${a}. Please try again.`;if(s instanceof Error&&s.message.startsWith("Timed out while"))return s.message;const c=s||{},d=ya(s),l=typeof c.message=="string"?c.message.trim():"";return d==="unauthenticated"?"Your session has expired. Sign in again before starting a battle.":d==="permission-denied"?"Only student accounts can access Quiz Battle matchmaking.":d==="invalid-argument"?l||"Battle setup is invalid. Review the selected options and try again.":d==="already-exists"?l||"This room is already full. Try another room code.":d==="failed-precondition"?l||"Battle state changed. Please refresh and continue.":d==="unavailable"||d==="internal"||d==="not-found"||d==="deadline-exceeded"?/question generation temporarily unavailable/i.test(l)?l:"Quiz Battle service is temporarily unavailable. Please retry in a moment.":n},$=async(a,s,n=is)=>{let c;try{return await Promise.race([s,new Promise((d,l)=>{c=setTimeout(()=>{l(new Error(`Timed out while ${a}. Please try again.`))},n)})])}finally{c&&clearTimeout(c)}},at=a=>{if(!a)return new Date;if(a instanceof Date)return a;if(typeof a=="string"){const s=Date.parse(a);return Number.isNaN(s)?new Date:new Date(s)}if(typeof a=="number")return new Date(a);if(typeof a=="object"){const s=a;if(typeof s.toDate=="function")return s.toDate();if(typeof s.seconds=="number")return new Date(s.seconds*1e3)}return new Date},hs=()=>({mode:"online",subjectId:"gen-math",topicId:"",difficulty:"medium",rounds:5,timePerQuestionSec:30,queueType:"public_matchmaking",botDifficulty:"medium",adaptiveBot:!1}),bs=a=>{const s=[];return a.subjectId.trim()||s.push({field:"subjectId",message:"Choose a category before starting."}),a.topicId.trim()||s.push({field:"topicId",message:"Choose a strand or topic before starting."}),(a.rounds<3||a.rounds>20)&&s.push({field:"rounds",message:"Questions must be between 3 and 20."}),(a.timePerQuestionSec<10||a.timePerQuestionSec>180)&&s.push({field:"timePerQuestionSec",message:"Timer must be between 10s and 180s."}),a.mode==="bot"&&a.queueType!=="public_matchmaking"&&s.push({field:"queueType",message:"Bot battles use instant start and do not support private room mode."}),s},Se=a=>({userId:a,matchesPlayed:0,wins:0,losses:0,draws:0,winRate:0,averageAccuracy:0,averageResponseMs:0,bestStreak:0,currentStreak:0,favoriteTopicId:void 0,leaderboardScore:0,updatedAt:new Date}),fs=async a=>{try{const s=Xa(et,"studentBattleStats",a),n=await Ga(s),c=tt()?Pe(a).stats:null;if(!n.exists())return c&&c.matchesPlayed>0?c:Se(a);const d=n.data(),l={...Se(a),...d,userId:a,updatedAt:at(d.updatedAt)};return c&&c.matchesPlayed>l.matchesPlayed?c:l}catch(s){if(console.error("Error loading battle stats:",s),tt()){const n=Pe(a).stats;if(n.matchesPlayed>0)return n}return Se(a)}},Ft=(a,s)=>({matchId:s.matchId||a,mode:s.mode||"online",status:s.status||"completed",subjectId:s.subjectId||"gen-math",topicId:s.topicId||"unknown-topic",difficulty:s.difficulty||"medium",rounds:s.rounds||0,timePerQuestionSec:s.timePerQuestionSec||0,scoreFor:s.scoreFor||0,scoreAgainst:s.scoreAgainst||0,outcome:s.outcome||"draw",accuracy:s.accuracy||0,averageResponseMs:s.averageResponseMs||0,bestStreak:s.bestStreak||0,xpEarned:s.xpEarned||0,opponentName:s.opponentName||"Unknown opponent",opponentType:s.opponentType||"student",createdAt:at(s.createdAt),endedAt:at(s.endedAt)}),gs=async(a,s={})=>{const n=s.limitCount||25,c=tt()?Pe(a).history:[],d=w=>w.filter(f=>!(s.mode&&s.mode!=="all"&&f.mode!==s.mode||s.subjectId&&f.subjectId!==s.subjectId||s.startDate&&f.endedAts.endDate)).sort((f,N)=>N.endedAt.getTime()-f.endedAt.getTime()).slice(0,n),l=w=>{if(c.length===0)return d(w);const A=new Map;return[...c,...w].forEach(f=>{A.set(f.matchId,f)}),d(Array.from(A.values()))};try{const w=[aa("studentId","==",a),ha("endedAt","desc"),Ct(n)],f=(await It(Bt(Mt(et,"quizBattleHistory"),...w))).docs.map(N=>Ft(N.id,N.data()));return l(f)}catch(w){try{const f=(await It(Bt(Mt(et,"quizBattleHistory"),aa("studentId","==",a),Ct(n)))).docs.map(N=>Ft(N.id,N.data())).sort((N,b)=>b.endedAt.getTime()-N.endedAt.getTime());return l(f)}catch(A){return console.error("Error loading battle history:",w,A),d(c)}}},ws=async a=>{const s=L(q,"quizBattleJoinQueue");try{return(await $("joining Quiz Battle matchmaking queue",s({setup:a}))).data}catch(n){if(ne(n))return Na("queued"),{success:!0,status:"queued",queueEntryId:`local-queue-${Date.now()}`};throw new Error(V("joining Quiz Battle matchmaking queue",n))}},la=async()=>{const a=L(q,"quizBattleLeaveQueue");try{return(await $("leaving Quiz Battle matchmaking queue",a({}))).data}catch(s){if(ne(s))return Na("idle"),{success:!0,status:"idle"};throw new Error(V("leaving Quiz Battle matchmaking queue",s))}},vs=async a=>{const s=L(q,"quizBattleCreatePrivateRoom");try{return(await $("creating Quiz Battle private room",s({setup:a}))).data}catch(n){if(ne(n))return{success:!0,room:Tt()};throw new Error(V("creating Quiz Battle private room",n))}},js=async a=>{const s=L(q,"quizBattleJoinPrivateRoom");try{return(await $("joining Quiz Battle private room",s({roomCode:a}),2e4)).data}catch(n){if(ne(n))return{success:!0,room:Tt(a.trim().toUpperCase()||void 0)};throw new Error(V("joining Quiz Battle private room",n))}},ys=async a=>{const s=L(q,"quizBattleGetPrivateRoomState");try{return(await $("loading Quiz Battle private room state",s(a),2e4)).data}catch(n){if(ne(n))return{success:!0,room:Tt(a.roomCode?.trim().toUpperCase()||void 0)};throw new Error(V("loading Quiz Battle private room state",n))}},Ns=async(a={})=>{const s=L(q,"quizBattleLeavePrivateRoom");try{return(await $("leaving Quiz Battle private room",s(a),2e4)).data}catch(n){if(ne(n))return{success:!0,status:"idle"};throw new Error(V("leaving Quiz Battle private room",n))}},ia=async()=>{const a=L(q,"quizBattleResumeSession");try{return(await $("resuming Quiz Battle session",a({}),2e4)).data}catch(s){if(ne(s))return{success:!0,sessionType:"idle"};throw new Error(V("resuming Quiz Battle session",s))}},ks=async(a,s)=>{if(!s.trim())return;const n=L(q,"quizBattleHeartbeat");await xs(a,s);try{await $("sending Quiz Battle heartbeat",n({scope:a,resourceId:s}),12e3)}catch(c){if(!ne(c))throw new Error(V("sending Quiz Battle heartbeat",c))}},_s=async a=>{const s=L(q,"quizBattleCreateBotMatch");try{return(await $("starting Quiz Battle bot match",s({setup:a}))).data}catch(n){if(ne(n))return us(a);throw new Error(V("starting Quiz Battle bot match",n))}},Ss=async a=>{const s=L(q,"quizBattleGetGenerationAudit");return(await $("verifying Quiz Battle generation metadata",s({matchId:a}),2e4)).data},re=async a=>{const s=L(q,"quizBattleStartMatch");try{const c=(await $("starting Quiz Battle match",s({matchId:a}),2e4)).data.match;if(c.mode==="online")try{const d=await Ss(a);if(oa&&!d.isAiSource)throw new Error(`Quiz Battle generation audit failed: expected AI source, got "${d.questionSetSource||"unknown"}".`)}catch(d){if(d instanceof Error&&d.message.startsWith("Quiz Battle generation audit failed"))throw d;if(console.warn("Quiz Battle generation audit unavailable:",d),oa)throw new Error("Unable to verify Quiz Battle generation metadata. Please retry in a moment.")}return c}catch(n){throw new Error(V("starting Quiz Battle match",n))}},kt=async a=>{const s=L(q,"quizBattleGetMatchState");try{return(await $("loading Quiz Battle match state",s({matchId:a}),2e4)).data.match}catch(n){throw new Error(V("loading Quiz Battle match state",n))}},As=async a=>{const s=L(q,"quizBattleSubmitAnswer");try{return(await $("submitting Quiz Battle answer",s({...a,idempotencyKey:a.idempotencyKey||`client-${Date.now()}-${Math.random().toString(16).slice(2,8)}`}),2e4)).data}catch(n){throw new Error(V("submitting Quiz Battle answer",n))}},zs=async a=>{const s=L(q,"quizBattleRequestRematch");try{return(await $("creating Quiz Battle rematch",s({matchId:a}),2e4)).data}catch(n){throw new Error(V("creating Quiz Battle rematch",n))}},Cs=async(a=20)=>{try{const s=Bt(Mt(et,"studentBattleLeaderboard"),ha("leaderboardScore","desc"),Ct(a));return(await It(s)).docs.map((c,d)=>{const l=c.data();return{userId:l.userId||c.id,displayName:l.displayName||"Student",photo:l.photo,rank:l.rank||d+1,leaderboardScore:l.leaderboardScore||0,winRate:l.winRate||0,bestStreak:l.bestStreak||0}})}catch(s){return console.error("Error loading Quiz Battle leaderboard:",s),[]}};function pe({className:a,...s}){return e.jsx("div",{"data-slot":"card",className:u("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",a),...s})}function he({className:a,...s}){return e.jsx("div",{"data-slot":"card-header",className:u("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",a),...s})}function be({className:a,...s}){return e.jsx("h4",{"data-slot":"card-title",className:u("leading-none",a),...s})}function ye({className:a,...s}){return e.jsx("p",{"data-slot":"card-description",className:u("text-muted-foreground",a),...s})}function Xe({className:a,...s}){return e.jsx("div",{"data-slot":"card-content",className:u("px-6 [&:last-child]:pb-6",a),...s})}function Is({className:a,...s}){return e.jsx(Ka,{"data-slot":"tabs",className:u("flex flex-col gap-2",a),...s})}function Ne({className:a,...s}){return e.jsx(Ja,{"data-slot":"tabs-content",className:u("flex-1 outline-none",a),...s})}const Sa=Et.memo(({playerRoundStreak:a,playerVisualMultiplier:s,liveXpEarned:n,activeMatch:c,subjects:d,battleSoundEnabled:l,onToggleSound:w,isFullscreen:A,onToggleFullscreen:f,isDesignPauseAvailable:N,onTogglePause:b})=>e.jsxs("header",{className:"flex items-center justify-between shrink-0 h-14 sm:h-16 relative gap-2 sm:gap-4",children:[e.jsx("div",{className:"flex items-center min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 md:gap-4 px-2.5 sm:px-4 py-1.5 sm:py-2 md:px-5 md:py-2.5 rounded-full bg-white/5 border border-white/10 backdrop-blur-md min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 text-amber-400 font-bold text-xs sm:text-sm shrink-0",children:[e.jsx(Ha,{className:"w-3 h-3 sm:w-4 sm:h-4"})," ",a]}),e.jsx("div",{className:"w-px h-3 sm:h-4 bg-white/10 shrink-0"}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 text-violet-300 font-bold text-xs sm:text-sm shrink-0",children:[e.jsx(zt,{className:"w-3 h-3 sm:w-4 sm:h-4"})," ",s.toFixed(2),"x"]}),e.jsx("div",{className:"w-px h-3 sm:h-4 bg-white/10 shrink-0"}),e.jsxs(y.div,{animate:n>0?{scale:[1,1.25,1]}:{},transition:{duration:.35},className:"flex flex-col items-center text-emerald-400 bg-emerald-500/10 px-2 sm:px-3 py-0.5 rounded-full border border-emerald-500/20 font-bold shadow-[0_0_10px_rgba(16,185,129,0.15)] shrink-0",children:[e.jsxs("span",{className:"text-xs sm:text-sm leading-none tabular-nums",children:[n," pts"]}),e.jsx("span",{className:"hidden sm:block text-[8px] leading-none text-emerald-500/70 uppercase tracking-widest font-black whitespace-nowrap",children:"Battle Score"})]},n)]})}),e.jsxs("div",{className:"absolute left-1/2 -translate-x-1/2 hidden md:flex items-center gap-3 bg-black/20 px-5 py-2 rounded-full border border-white/5 min-w-0 max-w-[48%]",children:[e.jsx("div",{className:"w-3.5 h-3.5 rounded-sm bg-orange-400 shadow-[0_0_10px_rgba(251,146,60,0.5)] shrink-0"}),e.jsx("div",{className:"flex flex-col items-start justify-center -space-y-0.5 min-w-0",children:(()=>{if(!c?.topicId)return e.jsx("span",{className:"font-bold text-white/90 tracking-wide text-sm leading-none truncate",children:"Practice Match"});for(const j of d){const h=j.modules?.find(m=>m.id===c.topicId);if(h)return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[9px] font-black text-white/40 uppercase tracking-widest leading-none",children:j.title}),e.jsx("span",{className:"font-bold text-white/90 tracking-wide text-sm leading-none pt-1 truncate",children:h.title})]})}return e.jsx("span",{className:"font-bold text-white/90 tracking-wide text-sm leading-none truncate",children:c.topicId.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" ")})})()})]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-3",children:[e.jsx(z,{variant:"outline",size:"icon",className:"h-9 w-9 sm:h-12 sm:w-12 rounded-full border-white/20 bg-black/20 hover:bg-white/10 text-white",onClick:w,children:l?e.jsx(ga,{className:"h-4 w-4 sm:h-5 sm:w-5"}):e.jsx(wa,{className:"h-4 w-4 sm:h-5 sm:w-5"})}),e.jsx(z,{variant:"outline",size:"icon",className:"hidden sm:flex h-12 w-12 rounded-full border-white/20 bg-black/20 hover:bg-white/10 text-white",onClick:f,children:A?e.jsx(as,{className:"h-5 w-5"}):e.jsx(ss,{className:"h-5 w-5"})}),e.jsx(z,{variant:"outline",size:"icon",className:u("h-9 w-9 sm:h-12 sm:w-12 rounded-full border-white/20 text-white",N?"bg-black/20 hover:bg-white/10":"bg-black/10 opacity-50 cursor-not-allowed"),onClick:b,disabled:!N,children:e.jsx(Va,{className:"h-4 w-4 sm:h-5 sm:w-5"})})]})]}));Sa.displayName="BattleHeader";const Aa=Et.memo(({studentProfile:a,activeMatch:s,scorePulseTarget:n,quizBattleAvatar:c,opponentId:d})=>{const[l,w]=i.useState(null);return i.useEffect(()=>{if(!d)return;let A=!1;return Ua(d).then(f=>{!A&&f?.avatarLayers&&w(f.avatarLayers)}).catch(()=>{}),()=>{A=!0}},[d]),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 w-full xl:max-w-[1400px] mx-auto px-2 sm:px-4 md:px-8 shrink-0 h-28 sm:h-32 md:h-48 flex justify-between items-end pb-0 pointer-events-none z-30",children:[e.jsxs("div",{className:"flex items-end gap-1.5 sm:gap-3 md:gap-6 relative pointer-events-auto",children:[e.jsx("div",{className:"relative w-16 h-16 sm:w-28 sm:h-28 md:w-40 md:h-40 rounded-t-[40px] flex items-end",children:e.jsx(yt,{layers:a?.avatarLayers||{},className:"w-full h-full object-contain origin-bottom scale-[1.15]"})}),e.jsxs("div",{className:"bg-black/40 backdrop-blur-xl border border-white/20 rounded-xl sm:rounded-2xl px-2 sm:px-4 py-2 sm:py-3 md:px-5 shadow-[0_8px_30px_rgba(0,0,0,0.5)] flex items-center gap-1.5 sm:gap-3 md:gap-4 mb-2 sm:mb-4 max-w-[130px] sm:max-w-[220px] md:max-w-[280px]",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-white font-black text-xs sm:text-base md:text-lg truncate tracking-wide",children:a?.name||"Player"}),e.jsxs("span",{className:"text-[9px] sm:text-xs md:text-sm text-white/50 font-bold uppercase tracking-wider",children:["Level ",a?.level||1]})]}),e.jsx("div",{className:"h-6 sm:h-10 w-px bg-white/20"}),e.jsxs("div",{className:"flex flex-col items-center justify-center shrink-0 w-6 sm:w-10 md:w-12",children:[e.jsx(y.span,{animate:n==="player"?{scale:[1,1.4,1],color:["#fff","#34d399","#fff"]}:{},transition:{duration:.5},className:"text-lg sm:text-2xl md:text-3xl font-black text-white leading-none",children:s.scoreFor}),e.jsx("span",{className:"text-[7px] sm:text-[9px] md:text-[10px] text-emerald-400 font-bold uppercase tracking-widest mt-0.5 sm:mt-1 leading-none",children:"Score"})]})]})]}),e.jsxs("div",{className:"flex items-end gap-1.5 sm:gap-3 md:gap-6 relative flex-row-reverse pointer-events-auto",children:[e.jsx("div",{className:"relative w-16 h-16 sm:w-28 sm:h-28 md:w-40 md:h-40 rounded-t-[40px] flex items-end justify-center",children:s.mode==="bot"?e.jsx(Te,{className:"h-8 w-8 sm:h-16 sm:w-16 md:h-20 md:w-20 text-rose-400 mb-3 sm:mb-6 drop-shadow-xl",strokeWidth:1.5}):l?e.jsx(yt,{layers:l,className:"w-full h-full object-contain origin-bottom scale-[1.15]"}):e.jsx(yt,{layers:{},className:"w-full h-full object-contain origin-bottom scale-[1.15]"})}),e.jsxs("div",{className:"bg-black/40 backdrop-blur-xl border border-white/20 rounded-xl sm:rounded-2xl px-2 sm:px-4 py-2 sm:py-3 md:px-5 shadow-[0_8px_30px_rgba(0,0,0,0.5)] flex items-center gap-1.5 sm:gap-3 md:gap-4 mb-2 sm:mb-4 flex-row-reverse text-right max-w-[130px] sm:max-w-[220px] md:max-w-[280px]",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-white font-black text-xs sm:text-base md:text-lg truncate tracking-wide",children:s.opponentName||"Anonymous"}),e.jsx("span",{className:"text-[9px] sm:text-xs md:text-sm text-rose-400 font-bold uppercase tracking-wider",children:s.mode==="bot"?"System Bot":"Challenger"})]}),e.jsx("div",{className:"h-6 sm:h-10 w-px bg-white/20"}),e.jsxs("div",{className:"flex flex-col items-center justify-center shrink-0 w-6 sm:w-10 md:w-12",children:[e.jsx(y.span,{animate:n==="opponent"?{scale:[1,1.4,1],color:["#fff","#fb7185","#fff"]}:{},transition:{duration:.5},className:"text-lg sm:text-2xl md:text-3xl font-black text-white leading-none",children:s.scoreAgainst}),e.jsx("span",{className:"text-[7px] sm:text-[9px] md:text-[10px] text-rose-400 font-bold uppercase tracking-widest mt-0.5 sm:mt-1 leading-none",children:"Score"})]})]})]})]})});Aa.displayName="BattleFooter";const za=Et.memo(({activeMatch:a,roundSecondsLeft:s,lastRoundResult:n,selectedOptionIndex:c,roundLocked:d,answerSubmitting:l,designPauseActive:w,onOptionSelect:A,floatingMomentum:f,lastRoundMomentumDelta:N,studentProfile:b,quizBattleAvatar:j})=>e.jsxs("div",{className:"flex-1 flex flex-col justify-center items-center gap-4 md:gap-6 w-full min-h-0 overflow-y-auto pt-4 pb-28 z-20 no-scrollbar",children:[e.jsxs("div",{className:u("relative bg-[#1e2536] border shadow-[0_20px_60px_rgba(0,0,0,0.4)] rounded-[1.5rem] p-5 md:p-6 w-full max-w-4xl text-center flex flex-col items-center",s<=3?"border-rose-400/50":"border-white/10"),children:[e.jsxs("div",{className:"absolute -top-3.5 bg-[#2f3547] border border-white/10 text-white/80 px-4 py-1 rounded-full text-xs font-black shadow-lg uppercase tracking-wider",children:[a.currentRound," / ",a.totalRounds]}),e.jsx(Ze,{children:f&&f.tone==="positive"&&e.jsx(y.div,{initial:{opacity:0,y:14,scale:.92},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-10,scale:.9},className:u("absolute -top-12 rounded-full border px-3 py-1 text-[10px] font-black uppercase tracking-[0.15em] backdrop-blur-lg",f.tone==="positive"?"border-emerald-300/70 bg-emerald-500/20 text-emerald-100":f.tone==="negative"?"border-rose-300/70 bg-rose-500/20 text-rose-100":"border-slate-300/50 bg-slate-500/20 text-slate-100"),children:f.label},f.id)}),e.jsx("p",{className:"text-base sm:text-lg md:text-xl text-white font-extrabold leading-tight tracking-tight mt-1 min-h-[40px] flex items-center justify-center",children:a.currentQuestion?.prompt}),typeof window<"u"&&window.location.search.includes("debug=true")&&a.currentQuestion?.varianceApplied&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2 justify-center",children:a.currentQuestion.varianceApplied.map(h=>e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-[10px] font-medium bg-blue-500/20 text-blue-200 border border-blue-400/30",children:h.replace(/_/g," ")},h))})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 md:gap-4 w-full max-w-4xl px-4",children:a.currentQuestion?.choices.map((h,m)=>{const v=c===m,W=l||d,S=!!n&&n.roundNumber===a.currentRound,R=S&&n.correctOptionIndex===m;let Y=-1;if(S)if(a.mode==="bot")if(n.botCorrect)Y=n.correctOptionIndex;else{const D=[0,1,2,3].filter(C=>C!==n.correctOptionIndex);Y=D[n.roundNumber%D.length]}else Y=typeof n.botSelectedIndex=="number"?n.botSelectedIndex:-1;const O=Y===m;let M="bg-[#1e2433] hover:bg-[#283042] border-[#2f384e] text-white shadow-[0_6px_0_rgba(15,20,30,0.5)]";return S?R?M="bg-emerald-500 text-emerald-950 border-emerald-400 shadow-[0_6px_0_rgba(5,150,105,1)]":v?M="bg-rose-500 text-white border-rose-400 shadow-[0_6px_0_rgba(225,29,72,1)]":M="bg-[#1e2433] opacity-40 border-[#2f384e] shadow-[0_6px_0_rgba(15,20,30,0.5)] text-white":v&&(M="bg-indigo-500 text-white border-indigo-400 shadow-[0_6px_0_rgba(79,70,229,1)]"),e.jsxs(y.button,{whileTap:{y:8,scale:.98},whileHover:!S&&!W?{scale:1.02}:{},disabled:W||d||w,onClick:()=>A(m),className:u("relative h-16 md:h-20 rounded-2xl md:rounded-3xl font-black text-base md:text-lg pl-6 pr-20 border-[2px] border-b-[4px] flex items-center justify-start text-left transition-all disabled:cursor-not-allowed",M,v&&!S?"ring-[4px] ring-white/20 ring-offset-[4px] ring-offset-[#0B0F19]":"",s<=3&&!W&&!S?"shadow-[0_0_0_2px_rgba(251,113,133,0.45),0_6px_0_rgba(127,29,29,1)]":""),children:[e.jsx("span",{className:"mr-3 md:mr-4 text-xs md:text-sm opacity-60 bg-black/20 px-3 py-1 rounded-full",children:String.fromCharCode(65+m)}),e.jsx("span",{className:"line-clamp-2",children:h}),e.jsxs("div",{className:"absolute right-3 md:right-4 flex items-center gap-1.5 md:gap-2",children:[O&&e.jsx(y.div,{initial:{opacity:0,scale:.5},animate:{opacity:1,scale:1},className:"w-8 h-8 md:w-10 md:h-10 rounded-full border-[3px] border-[#0B0F19] overflow-hidden bg-rose-500 shadow-lg flex items-center justify-center z-10",children:a.mode==="bot"?e.jsx(Te,{className:"w-4 h-4 md:w-5 md:h-5 text-white"}):e.jsx(ke,{className:"w-4 h-4 md:w-5 md:h-5 text-white"})}),v&&e.jsx(y.div,{initial:{opacity:0,scale:.5},animate:{opacity:1,scale:1},className:"w-8 h-8 md:w-10 md:h-10 rounded-full border-[3px] border-[#0B0F19] overflow-hidden bg-indigo-200 shadow-lg z-20",children:e.jsx("img",{src:b?.photo||j,alt:"You",className:"w-full h-full object-cover"})})]})]},m)})}),e.jsx(Ze,{children:d&&!n&&a.mode==="online"&&e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"mt-4 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/70 font-semibold bg-black/30 px-6 py-2 rounded-full border border-white/10",children:[e.jsx(Ke,{className:"w-4 h-4 animate-spin text-amber-400"}),"Waiting for opponent..."]}),e.jsx("p",{className:"text-white/30 text-[11px] mt-1",children:"Choices locked until round resolves"})]})}),e.jsx(Ze,{children:n?.studentCorrect&&e.jsx(y.div,{initial:{opacity:0,scale:.8,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:1.1,filter:"blur(10px)"},transition:{type:"spring",damping:20,stiffness:300},className:"fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[100] pointer-events-none flex flex-col items-center justify-center",children:e.jsxs("div",{className:"bg-[#1e2433]/95 backdrop-blur-xl border border-white/10 rounded-[2rem] p-6 md:p-8 shadow-[0_30px_80px_rgba(0,0,0,0.6)] flex flex-col items-center min-w-[280px] md:min-w-[320px]",children:[e.jsx("img",{src:j,alt:"Mascot",className:"w-24 h-24 md:w-32 md:h-32 mb-4 drop-shadow-xl"}),e.jsx("h2",{className:u("text-3xl md:text-4xl font-black mb-4 uppercase tracking-widest",n.studentCorrect?"text-emerald-400":"text-rose-400"),children:n.studentCorrect?"Correct!":"Incorrect"}),n.studentCorrect?e.jsxs("div",{className:"flex items-center gap-3 w-full justify-center",children:[e.jsx("div",{className:"flex items-center gap-2 bg-emerald-500/20 text-emerald-400 px-4 py-2 rounded-2xl font-bold border border-emerald-500/30",children:e.jsx("span",{children:"+ 10 XP"})}),N!==null&&N>0&&e.jsx("div",{className:"flex items-center gap-2 bg-amber-500/20 text-amber-400 px-4 py-2 rounded-2xl font-bold border border-amber-500/30",children:e.jsxs("span",{children:["+ ",N," ",e.jsx(Je,{className:"w-4 h-4 inline"})]})})]}):e.jsxs("div",{className:"bg-rose-500/20 border border-rose-500/30 text-rose-400 font-bold px-5 py-2 rounded-xl text-center",children:["Correct: ",String.fromCharCode(65+n.correctOptionIndex)]})]})})})]}));za.displayName="BattleActiveContent";const _t={width:1280,height:720},St=` @keyframes mascot-float { 0%, 100% { transform: translateY(0) rotate(-3deg); } 50% { transform: translateY(-24px) rotate(3deg); } diff --git a/assets/RewardsModal-BqWMkrYX.js b/assets/RewardsModal-Duh63-te.js similarity index 99% rename from assets/RewardsModal-BqWMkrYX.js rename to assets/RewardsModal-Duh63-te.js index 0ff95c1d6d0644c8afd3e5824148cb0c03c924c0..0df7f61dfa0ba0deb8240d11a7b8b9df178bd8d6 100644 --- a/assets/RewardsModal-BqWMkrYX.js +++ b/assets/RewardsModal-Duh63-te.js @@ -1 +1 @@ -import{r as i,j as e}from"./vendor-react-B4AQeu28.js";import{getDoc as F,doc as S}from"./vendor-firebase-firestore-CNv3xXal.js";import{aR as g,A as u,aS as U,aT as P,U as $,H as B,i as R,D as I,a1 as T,T as j,aU as q,a6 as N,R as H,V as L,a2 as M,$ as v,a7 as w,B as G,Z as X,r as V,F as Z,G as K,b as Q,aK as W,g as J}from"./index-BvEKrMkD.js";import{X as O}from"./x-BYtx1i07.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const Y={BookOpen:Q,GraduationCap:K,Trophy:Z,Target:V,Zap:X,Brain:G,Star:w,Flame:v,Swords:M,Shield:L,RefreshCw:H,Crown:N,Sun:q,TrendingUp:j,Globe:T,User:I,UserPlus:R,Calendar:B,Users:$,Compass:P,Heart:U,Award:u},me=({isOpen:o,onClose:c,userLevel:n,currentXP:x,xpToNextLevel:m,totalXP:p,userId:d})=>{const[y,b]=i.useState(!0),[k,_]=i.useState(new Set),[E,C]=i.useState({});i.useEffect(()=>{if(!o||!d)return;(async()=>{b(!0);try{const t=await W(d);_(new Set(t.map(a=>a.id)));const l=await F(S(J,"progress",d));l.exists()&&C(l.data())}catch(t){console.error("Error loading achievements:",t)}finally{b(!1)}})()},[o,d]);const D=s=>{const{condition:t,threshold:l}=s,a=E;let r=0,f=l??1;switch(t){case"lesson_complete":r=a.totalLessonsCompleted||0;break;case"quiz_complete":r=a.totalQuizzesCompleted||0;break;case"battle_win":case"battle_undefeated":r=a.battleWins||0;break;case"mastery_10":case"social_streak_30":case"social_daily_return":r=a.consecutiveDaysActive||0;break;case"mastery_xp":r=p;break;case"explore_friend_added":case"social_friend":case"explore_social":r=a.friendsAdded||0;break;case"perfect_score":{r=(a.quizAttempts||[]).filter(z=>z.score===100).length;break}default:return}return{progress:Math.min(r,f),total:f}},h=g.map(s=>{const t=Y[s.icon.name]??u,l=k.has(s.id),a=D(s);return{id:s.id,icon:t,title:s.title,description:s.description,progress:a?.progress,total:a?.total,unlocked:l,color:l?s.iconColor:"text-slate-500",bgColor:l?s.iconColor.replace("text-","bg-").replace("-500","/10").replace("-400","/10").replace("-600","/10"):"bg-slate-100"}}),A=h.filter(s=>s.unlocked).length;return o?e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-2 sm:p-8",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:c}),e.jsxs("div",{className:"relative bg-[#f7f9fc] rounded-2xl shadow-2xl border border-[#dde3eb] w-full max-w-2xl max-h-[90vh] sm:max-h-[85vh] flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-[#9956DE] via-[#7274ED] to-[#1FA7E1] p-4 md:p-6 text-white relative flex-shrink-0",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_14%_12%,rgba(251,150,187,0.35),transparent_42%),radial-gradient(circle_at_80%_80%,rgba(117,208,106,0.25),transparent_38%)]"}),e.jsxs("div",{className:"flex items-center justify-between mb-4 relative z-10",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl md:text-2xl font-display font-bold",children:"Rewards & Achievements"}),e.jsxs("p",{className:"text-white/90 text-sm font-body",children:[A," / ",g.length," Achievements Unlocked"]})]}),e.jsx("button",{onClick:c,className:"text-white/90 hover:text-white hover:bg-white/20 p-2 rounded-xl transition-colors",children:e.jsx(O,{size:24})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 md:gap-3 relative z-10",children:[e.jsxs("div",{className:"bg-white/15 backdrop-blur-sm rounded-xl p-3 md:p-4 border border-white/25",children:[e.jsxs("div",{className:"flex items-center gap-1 md:gap-2 mb-1",children:[e.jsx(N,{size:16,className:"text-[#FFB356]"}),e.jsx("span",{className:"text-[10px] md:text-xs font-medium text-white/90 font-body",children:"Level"})]}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:n})]}),e.jsxs("div",{className:"bg-white/15 backdrop-blur-sm rounded-xl p-3 md:p-4 border border-white/25",children:[e.jsxs("div",{className:"flex items-center gap-1 md:gap-2 mb-1",children:[e.jsx(w,{size:16,className:"text-[#6ED1CF]"}),e.jsx("span",{className:"text-[10px] md:text-xs font-medium text-white/90 font-body",children:"Total XP"})]}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:p.toLocaleString()})]}),e.jsxs("div",{className:"bg-white/15 backdrop-blur-sm rounded-xl p-3 md:p-4 border border-white/25",children:[e.jsxs("div",{className:"flex items-center gap-1 md:gap-2 mb-1",children:[e.jsx(v,{size:16,className:"text-[#FF8B8B]"}),e.jsx("span",{className:"text-[10px] md:text-xs font-medium text-white/90 font-body",children:"Daily Rewards"})]}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:"Check-in"})]})]}),e.jsxs("div",{className:"mt-4 relative z-10",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("span",{className:"text-sm font-bold text-white font-body",children:["Level ",n]}),e.jsxs("span",{className:"text-sm font-bold text-white font-body",children:["Level ",n+1]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex justify-between items-center mb-1",children:e.jsxs("span",{className:"text-xs text-white/90",children:[x," / ",m," XP"]})}),e.jsx("div",{className:"h-3 bg-white/20 rounded-full overflow-hidden border border-white/20",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-[#6ED1CF] via-[#75D06A] to-[#FFB356] rounded-full transition-all duration-500 e-w",style:{"--w":`${x/m*100}%`}})})]})]})]}),e.jsx("div",{className:"p-4 md:p-6 overflow-y-auto flex-1",children:y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-[#9956DE] border-t-transparent rounded-full"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-display font-bold text-[#0a1628] mb-4",children:"Achievements"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:h.map(s=>{const t=s.icon;return e.jsx("div",{className:`${s.unlocked?"bg-white border-[#9956DE]/25":"bg-[#edf1f7] border-[#dde3eb]"} border-2 rounded-xl p-4 transition-all ${s.unlocked?"shadow-md":"opacity-60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-12 h-12 ${s.bgColor} rounded-xl flex items-center justify-center flex-shrink-0`,children:e.jsx(t,{size:24,className:s.color})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:`text-sm font-bold ${s.unlocked?"text-[#0a1628]":"text-slate-500"} font-body`,children:s.title}),s.unlocked&&e.jsx("span",{className:"px-2 py-0.5 bg-[#75D06A] text-white text-[9px] font-bold rounded-full",children:"Unlocked"})]}),e.jsx("p",{className:`text-xs ${s.unlocked?"text-[#5a6578]":"text-slate-500"} mb-2`,children:s.description}),s.progress!==void 0&&s.total!==void 0&&!s.unlocked&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-1",children:[e.jsx("span",{className:"text-[10px] text-slate-500",children:"Progress"}),e.jsxs("span",{className:"text-[10px] font-bold text-[#5a6578]",children:[s.progress," / ",s.total]})]}),e.jsx("div",{className:"h-1.5 bg-[#dde3eb] rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-[#7274ED] to-[#1FA7E1] rounded-full transition-all e-w",style:{"--w":`${s.progress/s.total*100}%`}})})]})]})]})},s.id)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-[#dde3eb]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 bg-gradient-to-br from-[#7274ED] to-[#1FA7E1] rounded-lg flex items-center justify-center",children:e.jsx(j,{size:16,className:"text-white"})}),e.jsx("h3",{className:"text-base font-display font-bold text-[#0a1628]",children:"How to Earn XP"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[{activity:"Complete a video lesson",xp:50},{activity:"Complete exercises",xp:100},{activity:"Perfect quiz score",xp:150},{activity:"Finish a quiz",xp:75},{activity:"Daily check-in",xp:"20-100"}].map((s,t)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-1.5 h-1.5 bg-[#1FA7E1] rounded-full"}),e.jsxs("span",{className:"text-xs text-[#5a6578] font-body",children:[s.activity,":"]}),e.jsxs("span",{className:"text-xs font-bold text-[#7274ED]",children:["+",s.xp," XP"]})]},t))})]})]})})]})]}):null};export{me as default}; +import{r as i,j as e}from"./vendor-react-B4AQeu28.js";import{getDoc as F,doc as S}from"./vendor-firebase-firestore-CNv3xXal.js";import{aR as g,A as u,aS as U,aT as P,U as $,H as B,i as R,D as I,a1 as T,T as j,aU as q,a6 as N,R as H,V as L,a2 as M,$ as v,a7 as w,B as G,Z as X,r as V,F as Z,G as K,b as Q,aK as W,g as J}from"./index-BdLfAeGL.js";import{X as O}from"./x-BLhsirCD.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const Y={BookOpen:Q,GraduationCap:K,Trophy:Z,Target:V,Zap:X,Brain:G,Star:w,Flame:v,Swords:M,Shield:L,RefreshCw:H,Crown:N,Sun:q,TrendingUp:j,Globe:T,User:I,UserPlus:R,Calendar:B,Users:$,Compass:P,Heart:U,Award:u},me=({isOpen:o,onClose:c,userLevel:n,currentXP:x,xpToNextLevel:m,totalXP:p,userId:d})=>{const[y,b]=i.useState(!0),[k,_]=i.useState(new Set),[E,C]=i.useState({});i.useEffect(()=>{if(!o||!d)return;(async()=>{b(!0);try{const t=await W(d);_(new Set(t.map(a=>a.id)));const l=await F(S(J,"progress",d));l.exists()&&C(l.data())}catch(t){console.error("Error loading achievements:",t)}finally{b(!1)}})()},[o,d]);const D=s=>{const{condition:t,threshold:l}=s,a=E;let r=0,f=l??1;switch(t){case"lesson_complete":r=a.totalLessonsCompleted||0;break;case"quiz_complete":r=a.totalQuizzesCompleted||0;break;case"battle_win":case"battle_undefeated":r=a.battleWins||0;break;case"mastery_10":case"social_streak_30":case"social_daily_return":r=a.consecutiveDaysActive||0;break;case"mastery_xp":r=p;break;case"explore_friend_added":case"social_friend":case"explore_social":r=a.friendsAdded||0;break;case"perfect_score":{r=(a.quizAttempts||[]).filter(z=>z.score===100).length;break}default:return}return{progress:Math.min(r,f),total:f}},h=g.map(s=>{const t=Y[s.icon.name]??u,l=k.has(s.id),a=D(s);return{id:s.id,icon:t,title:s.title,description:s.description,progress:a?.progress,total:a?.total,unlocked:l,color:l?s.iconColor:"text-slate-500",bgColor:l?s.iconColor.replace("text-","bg-").replace("-500","/10").replace("-400","/10").replace("-600","/10"):"bg-slate-100"}}),A=h.filter(s=>s.unlocked).length;return o?e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-2 sm:p-8",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:c}),e.jsxs("div",{className:"relative bg-[#f7f9fc] rounded-2xl shadow-2xl border border-[#dde3eb] w-full max-w-2xl max-h-[90vh] sm:max-h-[85vh] flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-[#9956DE] via-[#7274ED] to-[#1FA7E1] p-4 md:p-6 text-white relative flex-shrink-0",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_14%_12%,rgba(251,150,187,0.35),transparent_42%),radial-gradient(circle_at_80%_80%,rgba(117,208,106,0.25),transparent_38%)]"}),e.jsxs("div",{className:"flex items-center justify-between mb-4 relative z-10",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl md:text-2xl font-display font-bold",children:"Rewards & Achievements"}),e.jsxs("p",{className:"text-white/90 text-sm font-body",children:[A," / ",g.length," Achievements Unlocked"]})]}),e.jsx("button",{onClick:c,className:"text-white/90 hover:text-white hover:bg-white/20 p-2 rounded-xl transition-colors",children:e.jsx(O,{size:24})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 md:gap-3 relative z-10",children:[e.jsxs("div",{className:"bg-white/15 backdrop-blur-sm rounded-xl p-3 md:p-4 border border-white/25",children:[e.jsxs("div",{className:"flex items-center gap-1 md:gap-2 mb-1",children:[e.jsx(N,{size:16,className:"text-[#FFB356]"}),e.jsx("span",{className:"text-[10px] md:text-xs font-medium text-white/90 font-body",children:"Level"})]}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:n})]}),e.jsxs("div",{className:"bg-white/15 backdrop-blur-sm rounded-xl p-3 md:p-4 border border-white/25",children:[e.jsxs("div",{className:"flex items-center gap-1 md:gap-2 mb-1",children:[e.jsx(w,{size:16,className:"text-[#6ED1CF]"}),e.jsx("span",{className:"text-[10px] md:text-xs font-medium text-white/90 font-body",children:"Total XP"})]}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:p.toLocaleString()})]}),e.jsxs("div",{className:"bg-white/15 backdrop-blur-sm rounded-xl p-3 md:p-4 border border-white/25",children:[e.jsxs("div",{className:"flex items-center gap-1 md:gap-2 mb-1",children:[e.jsx(v,{size:16,className:"text-[#FF8B8B]"}),e.jsx("span",{className:"text-[10px] md:text-xs font-medium text-white/90 font-body",children:"Daily Rewards"})]}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:"Check-in"})]})]}),e.jsxs("div",{className:"mt-4 relative z-10",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("span",{className:"text-sm font-bold text-white font-body",children:["Level ",n]}),e.jsxs("span",{className:"text-sm font-bold text-white font-body",children:["Level ",n+1]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex justify-between items-center mb-1",children:e.jsxs("span",{className:"text-xs text-white/90",children:[x," / ",m," XP"]})}),e.jsx("div",{className:"h-3 bg-white/20 rounded-full overflow-hidden border border-white/20",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-[#6ED1CF] via-[#75D06A] to-[#FFB356] rounded-full transition-all duration-500 e-w",style:{"--w":`${x/m*100}%`}})})]})]})]}),e.jsx("div",{className:"p-4 md:p-6 overflow-y-auto flex-1",children:y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-[#9956DE] border-t-transparent rounded-full"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-display font-bold text-[#0a1628] mb-4",children:"Achievements"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:h.map(s=>{const t=s.icon;return e.jsx("div",{className:`${s.unlocked?"bg-white border-[#9956DE]/25":"bg-[#edf1f7] border-[#dde3eb]"} border-2 rounded-xl p-4 transition-all ${s.unlocked?"shadow-md":"opacity-60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-12 h-12 ${s.bgColor} rounded-xl flex items-center justify-center flex-shrink-0`,children:e.jsx(t,{size:24,className:s.color})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:`text-sm font-bold ${s.unlocked?"text-[#0a1628]":"text-slate-500"} font-body`,children:s.title}),s.unlocked&&e.jsx("span",{className:"px-2 py-0.5 bg-[#75D06A] text-white text-[9px] font-bold rounded-full",children:"Unlocked"})]}),e.jsx("p",{className:`text-xs ${s.unlocked?"text-[#5a6578]":"text-slate-500"} mb-2`,children:s.description}),s.progress!==void 0&&s.total!==void 0&&!s.unlocked&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-1",children:[e.jsx("span",{className:"text-[10px] text-slate-500",children:"Progress"}),e.jsxs("span",{className:"text-[10px] font-bold text-[#5a6578]",children:[s.progress," / ",s.total]})]}),e.jsx("div",{className:"h-1.5 bg-[#dde3eb] rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-[#7274ED] to-[#1FA7E1] rounded-full transition-all e-w",style:{"--w":`${s.progress/s.total*100}%`}})})]})]})]})},s.id)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-[#dde3eb]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 bg-gradient-to-br from-[#7274ED] to-[#1FA7E1] rounded-lg flex items-center justify-center",children:e.jsx(j,{size:16,className:"text-white"})}),e.jsx("h3",{className:"text-base font-display font-bold text-[#0a1628]",children:"How to Earn XP"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[{activity:"Complete a video lesson",xp:50},{activity:"Complete exercises",xp:100},{activity:"Perfect quiz score",xp:150},{activity:"Finish a quiz",xp:75},{activity:"Daily check-in",xp:"20-100"}].map((s,t)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-1.5 h-1.5 bg-[#1FA7E1] rounded-full"}),e.jsxs("span",{className:"text-xs text-[#5a6578] font-body",children:[s.activity,":"]}),e.jsxs("span",{className:"text-xs font-bold text-[#7274ED]",children:["+",s.xp," XP"]})]},t))})]})]})})]})]}):null};export{me as default}; diff --git a/assets/RightSidebar-CjDA-c42.js b/assets/RightSidebar-DRNR3ylv.js similarity index 98% rename from assets/RightSidebar-CjDA-c42.js rename to assets/RightSidebar-DRNR3ylv.js index bb64fc6c1deee68b3e3329c8a8c136ce8b153571..2b97202e441ea7488187e03be07107def8388832 100644 --- a/assets/RightSidebar-CjDA-c42.js +++ b/assets/RightSidebar-DRNR3ylv.js @@ -1 +1 @@ -import{r as o,j as e}from"./vendor-react-B4AQeu28.js";import{q as S}from"./quiz_battle_avatar-BXHPSput.js";import{h as q,m as c,Z as _,a2 as B,a5 as P,F as W,a6 as v,a7 as X,q as Y,D as k}from"./index-BvEKrMkD.js";import{C as M}from"./circle-check-big-mtMsU82c.js";import{T as O,a as Z,b as H}from"./tooltip-DDXcKYaB.js";import{C as T}from"./chevron-right-CbKJd0ln.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const E=[{id:1,title:"Quiz Battle",subtitle:"Challenge players worldwide!",bgColor:"bg-[#9956de]",orbColor:"bg-[#6D28D9]",icon:e.jsx(B,{size:24,className:"text-white"}),buttonText:"Join Battle",actionType:"quiz-battle",avatarText:"Waiting for you to join..."},{id:2,title:"Topic Explorer",subtitle:"Dive into a new math topic today",bgColor:"bg-[#FF8B8B]",orbColor:"bg-[#E06A6A]",icon:e.jsx(_,{size:24,className:"text-white"}),buttonText:"Explore",actionType:"explore",avatarText:"Knowledge is power!"},{id:3,title:"Speed Runner",subtitle:"Finish a quiz in under 5 mins",bgColor:"bg-[#75D06A]",orbColor:"bg-[#58B34D]",icon:e.jsx(M,{size:24,className:"text-white"}),buttonText:null,actionType:null,avatarText:"Ready for action!"}],J=({onNavigateToQuizBattle:s,userPhoto:a})=>{const[x,m]=o.useState(0);o.useEffect(()=>{const r=setInterval(()=>{m(l=>(l+1)%E.length)},5e3);return()=>clearInterval(r)},[]);const t=E[x];return e.jsx("div",{className:"bg-white rounded-[24px] p-4 shadow-sm border border-slate-100 flex flex-col gap-6 mt-4 relative overflow-hidden",children:e.jsx("div",{className:"relative h-[185px] rounded-[-20px] rounded-2xl overflow-hidden cursor-pointer group",children:e.jsx(q,{mode:"wait",children:e.jsxs(c.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.3},className:`absolute inset-0 ${t.bgColor} p-4 sm:p-5 flex flex-col justify-between overflow-hidden`,children:[e.jsxs("div",{className:"absolute top-4 right-4 flex gap-1 items-center z-20",children:[e.jsx("div",{className:"w-3 h-1.5 rounded-full bg-white/60"}),e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-white/40"}),e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-white/40"})]}),t.actionType==="quiz-battle"&&e.jsx("div",{className:"absolute -right-4 -bottom-6 w-32 h-32 opacity-25 mix-blend-overlay pointer-events-none z-0 transform group-hover:scale-105 transition-transform duration-700",children:e.jsx("img",{src:S,alt:"",className:"w-full h-full object-contain"})}),e.jsx("div",{className:`absolute -right-4 -top-8 w-36 h-36 rounded-full ${t.orbColor} opacity-90 blur-2xl group-hover:scale-110 transition-transform duration-700 pointer-events-none`}),e.jsx("div",{className:"absolute right-4 top-1/2 -translate-y-1/2 w-[48px] h-[48px] rounded-2xl rotate-12 bg-white/20 backdrop-blur-md shadow-sm border border-white/20 group-hover:rotate-[25deg] group-hover:scale-110 transition-transform duration-700 flex items-center justify-center z-10",children:t.icon}),e.jsxs("div",{className:"relative z-10 w-full pr-[60px]",children:[e.jsx("h3",{className:"font-display font-bold text-[20px] leading-tight text-white mb-0.5",children:t.title}),e.jsx("p",{className:"text-[12px] font-medium text-white/90 leading-snug",children:t.subtitle}),t.buttonText&&e.jsx("button",{onClick:r=>{r.stopPropagation(),t.actionType==="quiz-battle"&&s&&s()},className:"mt-2.5 bg-white text-[#0a1628] px-2 py-1 rounded-lg font-bold text-xs shadow-sm hover:scale-105 transition-transform uppercase tracking-wider whitespace-nowrap w-fit",children:t.buttonText})]}),e.jsxs("div",{className:"flex items-center gap-2.5 relative z-10 mt-auto pt-2",children:[a?e.jsxs("div",{className:"relative group/avatar shrink-0",children:[e.jsx("div",{className:"absolute inset-0 bg-white/40 blur-md rounded-full animate-pulse"}),e.jsx("img",{src:a,alt:"You",className:"w-8 h-8 rounded-full border-[2px] border-white object-cover relative z-10 shadow-md group-hover/avatar:scale-110 transition-transform"}),t.actionType==="quiz-battle"&&e.jsx("div",{className:"absolute -bottom-1 -right-1 w-[16px] h-[16px] bg-[#75D06A] border-2 border-[#7C3AED] rounded-full z-20 flex items-center justify-center",children:e.jsx(_,{size:8,className:"text-white",fill:"currentColor"})})]}):null,e.jsx("span",{className:"text-[12px] font-bold text-white tracking-wide leading-tight flex-1 pr-[60px]",children:t.avatarText})]})]},t.id)})})})},K=s=>{if(s>=1e3){const a=s/1e3;return a>=10?`${Math.round(a)}k`:`${a.toFixed(1)}k`}return`${s}`},G=({entry:s,rank:a,isYou:x,userPhoto:m,rankColor:t})=>{const r=x?s?.photo||m:s?.photo,l=x?"You":s?.name||"---",h=s?.xp||0;return e.jsxs(e.Fragment,{children:[e.jsxs(c.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.3+a*.1},className:"relative mb-2",children:[a===1&&e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 z-20",children:e.jsx(v,{size:22,className:"text-amber-400 drop-shadow-md mb-1",fill:"#fbbf24",strokeWidth:1.5})}),e.jsx("div",{className:`w-10 h-10 rounded-full border-[3px] ${a===1?"w-[52px] h-[52px]":""} ${t.border} z-10 relative overflow-hidden ${t.shadow} bg-white`,children:r?e.jsx("img",{src:r,alt:l,className:"w-full h-full object-cover",onError:f=>{f.target.style.display="none"}}):e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-slate-200 to-slate-300 flex items-center justify-center",children:e.jsx(k,{size:a===1?22:16,className:"text-slate-400"})})}),e.jsx("div",{className:`absolute -bottom-2 left-1/2 -translate-x-1/2 ${t.badge} text-white text-[10px] font-bold px-2 py-0.5 rounded-full z-20 shadow-sm`,children:a})]}),e.jsxs("div",{className:"mt-2 text-center",children:[e.jsx("span",{className:`block ${a===1?"text-[13px] font-black":"text-[12px] font-bold"} text-[#0a1628] truncate max-w-[80px]`,children:l}),e.jsxs("span",{className:`block ${a===1?"text-[11px]":"text-[10px]"} ${t.badge.replace("bg-","text-").replace("-500","-600").replace("-400","-600").replace("amber","amber")} font-bold`,children:[K(h)," XP"]})]})]})},ce=({currentUserId:s,onOpenRewards:a,onOpenLeaderboard:x,onNavigateToModules:m,onNavigateToQuizBattle:t,userLevel:r,userPhoto:l,currentXP:h,xpToNextLevel:f})=>{const N=h/f*100,[$,D]=o.useState([]),[F,u]=o.useState(!0),[y,g]=o.useState(null),p=o.useRef(null),n=o.useRef(null);o.useEffect(()=>{if(!s){u(!1);return}u(!0),g(null);const d=P(b=>{D(b),u(!1),g(null),n.current&&(clearTimeout(n.current),n.current=null)},s,!1,"all",3);return p.current=d,n.current=setTimeout(()=>{u(!1),g("Leaderboard data unavailable")},15e3),()=>{n.current&&(clearTimeout(n.current),n.current=null),p.current&&(p.current(),p.current=null)}},[s]);const i=$.slice(0,3);i.some(d=>d.userId===s);const z=[{bg:"from-amber-100 to-amber-50",border:"border-amber-400",badge:"bg-amber-500",shadow:"shadow-md"},{bg:"from-slate-200 to-slate-100",border:"border-sky-400",badge:"bg-sky-500",shadow:"shadow-sm"},{bg:"from-orange-50 to-slate-50",border:"border-orange-400",badge:"bg-orange-500",shadow:"shadow-sm"}],A=["74px","54px","38px"],L=["w-[78px]","w-[70px]","w-[70px]"],w=(d,b,C,R,j)=>e.jsxs("div",{className:"flex flex-col items-center relative z-10",children:[e.jsx(G,{entry:d,rank:C,isYou:R==="You",userPhoto:l,rankColor:z[j]}),e.jsxs(c.div,{initial:{height:0},animate:{height:A[b]},transition:{delay:.2+b*.1,duration:.5,ease:"easeOut"},className:`${L[b]} bg-gradient-to-b ${z[j].bg} rounded-t-xl rounded-b-md border-t-2 border-white/20 flex items-center justify-center relative shadow-[inset_0_-4px_6px_rgba(0,0,0,0.05),0_4px_6px_rgba(0,0,0,0.05)]`,children:[e.jsx("span",{className:`${j===0?"text-amber-400 text-3xl":"text-slate-400 text-2xl"} font-black opacity-40 translate-y-1`,children:C}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-1.5 bg-white/70 rounded-t-xl"})]})]});return e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs(c.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.1,duration:.4,ease:[.22,1,.36,1]},onClick:a,className:"rounded-2xl border border-[#9956DE]/25 cursor-pointer transition-all group relative overflow-hidden bg-gradient-to-br from-[#9956DE] via-[#7274ED] to-[#1FA7E1] hover:shadow-[0_16px_40px_rgba(114,116,237,0.28)] hover:-translate-y-0.5",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_18%_8%,rgba(251,150,187,0.32),transparent_42%),radial-gradient(circle_at_85%_84%,rgba(117,208,106,0.24),transparent_40%)]"}),e.jsxs("div",{className:"relative z-10 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"shrink-0 w-8 h-8 bg-white/20 rounded-xl flex items-center justify-center border border-white/35 backdrop-blur-sm",children:e.jsx(W,{size:14,className:"text-white"})}),e.jsxs("h3",{className:"font-display font-bold text-[13px] leading-tight text-white tracking-wide",children:["Rewards & ",e.jsx("br",{className:"hidden 2xl:block"})," Achievements"]})]}),e.jsx(T,{size:14,className:"shrink-0 text-white/80 group-hover:text-white group-hover:translate-x-0.5 transition-all"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-1 mb-3 bg-white/10 p-1.5 rounded-xl border border-white/20 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-body px-1 text-white",children:[e.jsx(v,{size:12,className:"text-[#FFB356]"}),e.jsxs("span",{className:"font-bold",children:["Lv ",r]})]}),e.jsx("div",{className:"w-px h-3 bg-white/35"}),e.jsxs(O,{children:[e.jsx(Z,{asChild:!0,children:e.jsxs("button",{onClick:d=>{d.stopPropagation(),m?.()},className:"flex items-center gap-1.5 text-xs font-body px-1 text-white cursor-pointer transition-colors active:scale-95",children:[e.jsx(X,{size:12,className:"text-[#6ED1CF]"}),e.jsxs("span",{className:"font-bold whitespace-nowrap",children:[h," XP"]})]})}),e.jsx(H,{side:"top",className:"bg-slate-900 text-white border border-slate-700",children:"Review more lessons to earn more XP!"})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-1.5",children:[e.jsxs("span",{className:"text-[11px] font-body text-white/90",children:["Next: Level ",r+1]}),e.jsxs("span",{className:"text-[11px] font-body font-semibold text-white",children:[Math.round(N),"%"]})]}),e.jsx("div",{className:"h-2 bg-white/25 rounded-full overflow-hidden border border-white/20",children:e.jsx(c.div,{initial:{width:0},animate:{width:`${N}%`},transition:{duration:1,ease:"easeOut"},className:"h-full bg-gradient-to-r from-[#6ED1CF] via-[#75D06A] to-[#FFB356] rounded-full"})})]})]})]}),e.jsx(c.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.2,duration:.4,ease:[.22,1,.36,1]},children:e.jsx(J,{onNavigateToQuizBattle:t,userPhoto:l})}),e.jsxs(c.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.3,duration:.4,ease:[.22,1,.36,1]},onClick:x,className:"bg-white rounded-xl border border-slate-200/80 hover:shadow-md hover:border-amber-200/60 transition-all group overflow-hidden cursor-pointer",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 bg-amber-50 rounded-lg flex items-center justify-center border border-amber-200/60 transition-colors group-hover:bg-amber-100/50",children:e.jsx(v,{size:14,className:"text-amber-500"})}),e.jsx("h3",{className:"font-display font-bold text-sm text-[#0a1628]",children:"Leaderboards"})]}),e.jsx(T,{size:14,className:"text-slate-400 group-hover:translate-x-0.5 group-hover:text-amber-500 transition-transform"})]}),e.jsx("div",{className:"pt-8 pb-3 px-2 bg-gradient-to-b from-slate-50/30 to-white flex items-end justify-center gap-1.5 min-h-[170px]",children:F?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8",children:[e.jsx(Y,{className:"w-5 h-5 animate-spin text-amber-400 mb-2"}),e.jsx("span",{className:"text-xs text-slate-400",children:"Loading rankings..."})]}):y||i.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8",children:[e.jsx(k,{className:"w-8 h-8 text-slate-300 mb-2"}),e.jsx("span",{className:"text-xs text-slate-400 text-center",children:y||"No rankings available yet"})]}):e.jsxs(e.Fragment,{children:[w(i[1],1,2,i[1]?.name||"---",1),w(i[0],0,1,i[0]?.name||"---",0),w(i[2],2,3,i[2]?.name||"---",2)]})})]})]})};export{ce as default}; +import{r as o,j as e}from"./vendor-react-B4AQeu28.js";import{q as S}from"./quiz_battle_avatar-BXHPSput.js";import{h as q,m as c,Z as _,a2 as B,a5 as P,F as W,a6 as v,a7 as X,q as Y,D as k}from"./index-BdLfAeGL.js";import{C as M}from"./circle-check-big-B54zXy3k.js";import{T as O,a as Z,b as H}from"./tooltip-Blvwukwg.js";import{C as T}from"./chevron-right-BRRve0zL.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const E=[{id:1,title:"Quiz Battle",subtitle:"Challenge players worldwide!",bgColor:"bg-[#9956de]",orbColor:"bg-[#6D28D9]",icon:e.jsx(B,{size:24,className:"text-white"}),buttonText:"Join Battle",actionType:"quiz-battle",avatarText:"Waiting for you to join..."},{id:2,title:"Topic Explorer",subtitle:"Dive into a new math topic today",bgColor:"bg-[#FF8B8B]",orbColor:"bg-[#E06A6A]",icon:e.jsx(_,{size:24,className:"text-white"}),buttonText:"Explore",actionType:"explore",avatarText:"Knowledge is power!"},{id:3,title:"Speed Runner",subtitle:"Finish a quiz in under 5 mins",bgColor:"bg-[#75D06A]",orbColor:"bg-[#58B34D]",icon:e.jsx(M,{size:24,className:"text-white"}),buttonText:null,actionType:null,avatarText:"Ready for action!"}],J=({onNavigateToQuizBattle:s,userPhoto:a})=>{const[x,m]=o.useState(0);o.useEffect(()=>{const r=setInterval(()=>{m(l=>(l+1)%E.length)},5e3);return()=>clearInterval(r)},[]);const t=E[x];return e.jsx("div",{className:"bg-white rounded-[24px] p-4 shadow-sm border border-slate-100 flex flex-col gap-6 mt-4 relative overflow-hidden",children:e.jsx("div",{className:"relative h-[185px] rounded-[-20px] rounded-2xl overflow-hidden cursor-pointer group",children:e.jsx(q,{mode:"wait",children:e.jsxs(c.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.3},className:`absolute inset-0 ${t.bgColor} p-4 sm:p-5 flex flex-col justify-between overflow-hidden`,children:[e.jsxs("div",{className:"absolute top-4 right-4 flex gap-1 items-center z-20",children:[e.jsx("div",{className:"w-3 h-1.5 rounded-full bg-white/60"}),e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-white/40"}),e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-white/40"})]}),t.actionType==="quiz-battle"&&e.jsx("div",{className:"absolute -right-4 -bottom-6 w-32 h-32 opacity-25 mix-blend-overlay pointer-events-none z-0 transform group-hover:scale-105 transition-transform duration-700",children:e.jsx("img",{src:S,alt:"",className:"w-full h-full object-contain"})}),e.jsx("div",{className:`absolute -right-4 -top-8 w-36 h-36 rounded-full ${t.orbColor} opacity-90 blur-2xl group-hover:scale-110 transition-transform duration-700 pointer-events-none`}),e.jsx("div",{className:"absolute right-4 top-1/2 -translate-y-1/2 w-[48px] h-[48px] rounded-2xl rotate-12 bg-white/20 backdrop-blur-md shadow-sm border border-white/20 group-hover:rotate-[25deg] group-hover:scale-110 transition-transform duration-700 flex items-center justify-center z-10",children:t.icon}),e.jsxs("div",{className:"relative z-10 w-full pr-[60px]",children:[e.jsx("h3",{className:"font-display font-bold text-[20px] leading-tight text-white mb-0.5",children:t.title}),e.jsx("p",{className:"text-[12px] font-medium text-white/90 leading-snug",children:t.subtitle}),t.buttonText&&e.jsx("button",{onClick:r=>{r.stopPropagation(),t.actionType==="quiz-battle"&&s&&s()},className:"mt-2.5 bg-white text-[#0a1628] px-2 py-1 rounded-lg font-bold text-xs shadow-sm hover:scale-105 transition-transform uppercase tracking-wider whitespace-nowrap w-fit",children:t.buttonText})]}),e.jsxs("div",{className:"flex items-center gap-2.5 relative z-10 mt-auto pt-2",children:[a?e.jsxs("div",{className:"relative group/avatar shrink-0",children:[e.jsx("div",{className:"absolute inset-0 bg-white/40 blur-md rounded-full animate-pulse"}),e.jsx("img",{src:a,alt:"You",className:"w-8 h-8 rounded-full border-[2px] border-white object-cover relative z-10 shadow-md group-hover/avatar:scale-110 transition-transform"}),t.actionType==="quiz-battle"&&e.jsx("div",{className:"absolute -bottom-1 -right-1 w-[16px] h-[16px] bg-[#75D06A] border-2 border-[#7C3AED] rounded-full z-20 flex items-center justify-center",children:e.jsx(_,{size:8,className:"text-white",fill:"currentColor"})})]}):null,e.jsx("span",{className:"text-[12px] font-bold text-white tracking-wide leading-tight flex-1 pr-[60px]",children:t.avatarText})]})]},t.id)})})})},K=s=>{if(s>=1e3){const a=s/1e3;return a>=10?`${Math.round(a)}k`:`${a.toFixed(1)}k`}return`${s}`},G=({entry:s,rank:a,isYou:x,userPhoto:m,rankColor:t})=>{const r=x?s?.photo||m:s?.photo,l=x?"You":s?.name||"---",h=s?.xp||0;return e.jsxs(e.Fragment,{children:[e.jsxs(c.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.3+a*.1},className:"relative mb-2",children:[a===1&&e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 z-20",children:e.jsx(v,{size:22,className:"text-amber-400 drop-shadow-md mb-1",fill:"#fbbf24",strokeWidth:1.5})}),e.jsx("div",{className:`w-10 h-10 rounded-full border-[3px] ${a===1?"w-[52px] h-[52px]":""} ${t.border} z-10 relative overflow-hidden ${t.shadow} bg-white`,children:r?e.jsx("img",{src:r,alt:l,className:"w-full h-full object-cover",onError:f=>{f.target.style.display="none"}}):e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-slate-200 to-slate-300 flex items-center justify-center",children:e.jsx(k,{size:a===1?22:16,className:"text-slate-400"})})}),e.jsx("div",{className:`absolute -bottom-2 left-1/2 -translate-x-1/2 ${t.badge} text-white text-[10px] font-bold px-2 py-0.5 rounded-full z-20 shadow-sm`,children:a})]}),e.jsxs("div",{className:"mt-2 text-center",children:[e.jsx("span",{className:`block ${a===1?"text-[13px] font-black":"text-[12px] font-bold"} text-[#0a1628] truncate max-w-[80px]`,children:l}),e.jsxs("span",{className:`block ${a===1?"text-[11px]":"text-[10px]"} ${t.badge.replace("bg-","text-").replace("-500","-600").replace("-400","-600").replace("amber","amber")} font-bold`,children:[K(h)," XP"]})]})]})},ce=({currentUserId:s,onOpenRewards:a,onOpenLeaderboard:x,onNavigateToModules:m,onNavigateToQuizBattle:t,userLevel:r,userPhoto:l,currentXP:h,xpToNextLevel:f})=>{const N=h/f*100,[$,D]=o.useState([]),[F,u]=o.useState(!0),[y,g]=o.useState(null),p=o.useRef(null),n=o.useRef(null);o.useEffect(()=>{if(!s){u(!1);return}u(!0),g(null);const d=P(b=>{D(b),u(!1),g(null),n.current&&(clearTimeout(n.current),n.current=null)},s,!1,"all",3);return p.current=d,n.current=setTimeout(()=>{u(!1),g("Leaderboard data unavailable")},15e3),()=>{n.current&&(clearTimeout(n.current),n.current=null),p.current&&(p.current(),p.current=null)}},[s]);const i=$.slice(0,3);i.some(d=>d.userId===s);const z=[{bg:"from-amber-100 to-amber-50",border:"border-amber-400",badge:"bg-amber-500",shadow:"shadow-md"},{bg:"from-slate-200 to-slate-100",border:"border-sky-400",badge:"bg-sky-500",shadow:"shadow-sm"},{bg:"from-orange-50 to-slate-50",border:"border-orange-400",badge:"bg-orange-500",shadow:"shadow-sm"}],A=["74px","54px","38px"],L=["w-[78px]","w-[70px]","w-[70px]"],w=(d,b,C,R,j)=>e.jsxs("div",{className:"flex flex-col items-center relative z-10",children:[e.jsx(G,{entry:d,rank:C,isYou:R==="You",userPhoto:l,rankColor:z[j]}),e.jsxs(c.div,{initial:{height:0},animate:{height:A[b]},transition:{delay:.2+b*.1,duration:.5,ease:"easeOut"},className:`${L[b]} bg-gradient-to-b ${z[j].bg} rounded-t-xl rounded-b-md border-t-2 border-white/20 flex items-center justify-center relative shadow-[inset_0_-4px_6px_rgba(0,0,0,0.05),0_4px_6px_rgba(0,0,0,0.05)]`,children:[e.jsx("span",{className:`${j===0?"text-amber-400 text-3xl":"text-slate-400 text-2xl"} font-black opacity-40 translate-y-1`,children:C}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-1.5 bg-white/70 rounded-t-xl"})]})]});return e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs(c.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.1,duration:.4,ease:[.22,1,.36,1]},onClick:a,className:"rounded-2xl border border-[#9956DE]/25 cursor-pointer transition-all group relative overflow-hidden bg-gradient-to-br from-[#9956DE] via-[#7274ED] to-[#1FA7E1] hover:shadow-[0_16px_40px_rgba(114,116,237,0.28)] hover:-translate-y-0.5",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_18%_8%,rgba(251,150,187,0.32),transparent_42%),radial-gradient(circle_at_85%_84%,rgba(117,208,106,0.24),transparent_40%)]"}),e.jsxs("div",{className:"relative z-10 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"shrink-0 w-8 h-8 bg-white/20 rounded-xl flex items-center justify-center border border-white/35 backdrop-blur-sm",children:e.jsx(W,{size:14,className:"text-white"})}),e.jsxs("h3",{className:"font-display font-bold text-[13px] leading-tight text-white tracking-wide",children:["Rewards & ",e.jsx("br",{className:"hidden 2xl:block"})," Achievements"]})]}),e.jsx(T,{size:14,className:"shrink-0 text-white/80 group-hover:text-white group-hover:translate-x-0.5 transition-all"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-1 mb-3 bg-white/10 p-1.5 rounded-xl border border-white/20 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-body px-1 text-white",children:[e.jsx(v,{size:12,className:"text-[#FFB356]"}),e.jsxs("span",{className:"font-bold",children:["Lv ",r]})]}),e.jsx("div",{className:"w-px h-3 bg-white/35"}),e.jsxs(O,{children:[e.jsx(Z,{asChild:!0,children:e.jsxs("button",{onClick:d=>{d.stopPropagation(),m?.()},className:"flex items-center gap-1.5 text-xs font-body px-1 text-white cursor-pointer transition-colors active:scale-95",children:[e.jsx(X,{size:12,className:"text-[#6ED1CF]"}),e.jsxs("span",{className:"font-bold whitespace-nowrap",children:[h," XP"]})]})}),e.jsx(H,{side:"top",className:"bg-slate-900 text-white border border-slate-700",children:"Review more lessons to earn more XP!"})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-1.5",children:[e.jsxs("span",{className:"text-[11px] font-body text-white/90",children:["Next: Level ",r+1]}),e.jsxs("span",{className:"text-[11px] font-body font-semibold text-white",children:[Math.round(N),"%"]})]}),e.jsx("div",{className:"h-2 bg-white/25 rounded-full overflow-hidden border border-white/20",children:e.jsx(c.div,{initial:{width:0},animate:{width:`${N}%`},transition:{duration:1,ease:"easeOut"},className:"h-full bg-gradient-to-r from-[#6ED1CF] via-[#75D06A] to-[#FFB356] rounded-full"})})]})]})]}),e.jsx(c.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.2,duration:.4,ease:[.22,1,.36,1]},children:e.jsx(J,{onNavigateToQuizBattle:t,userPhoto:l})}),e.jsxs(c.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.3,duration:.4,ease:[.22,1,.36,1]},onClick:x,className:"bg-white rounded-xl border border-slate-200/80 hover:shadow-md hover:border-amber-200/60 transition-all group overflow-hidden cursor-pointer",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 bg-amber-50 rounded-lg flex items-center justify-center border border-amber-200/60 transition-colors group-hover:bg-amber-100/50",children:e.jsx(v,{size:14,className:"text-amber-500"})}),e.jsx("h3",{className:"font-display font-bold text-sm text-[#0a1628]",children:"Leaderboards"})]}),e.jsx(T,{size:14,className:"text-slate-400 group-hover:translate-x-0.5 group-hover:text-amber-500 transition-transform"})]}),e.jsx("div",{className:"pt-8 pb-3 px-2 bg-gradient-to-b from-slate-50/30 to-white flex items-end justify-center gap-1.5 min-h-[170px]",children:F?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8",children:[e.jsx(Y,{className:"w-5 h-5 animate-spin text-amber-400 mb-2"}),e.jsx("span",{className:"text-xs text-slate-400",children:"Loading rankings..."})]}):y||i.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8",children:[e.jsx(k,{className:"w-8 h-8 text-slate-300 mb-2"}),e.jsx("span",{className:"text-xs text-slate-400 text-center",children:y||"No rankings available yet"})]}):e.jsxs(e.Fragment,{children:[w(i[1],1,2,i[1]?.name||"---",1),w(i[0],0,1,i[0]?.name||"---",0),w(i[2],2,3,i[2]?.name||"---",2)]})})]})]})};export{ce as default}; diff --git a/assets/ScientificCalculator-B-rMzwD3.js b/assets/ScientificCalculator-DQTxoI7Z.js similarity index 99% rename from assets/ScientificCalculator-B-rMzwD3.js rename to assets/ScientificCalculator-DQTxoI7Z.js index f17fb5cdd503e02d0b1a7c60827affcceb76bbbc..b065783b51197ded428f078cb59797718495c9f6 100644 --- a/assets/ScientificCalculator-B-rMzwD3.js +++ b/assets/ScientificCalculator-DQTxoI7Z.js @@ -1,4 +1,4 @@ -import{r as c,j as e}from"./vendor-react-B4AQeu28.js";import{e as Z,n as de,h as U,m as ue}from"./index-BvEKrMkD.js";import{a as fe,C as pe}from"./chevron-up-CDr90bpM.js";import{X as be}from"./x-BYtx1i07.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";/** +import{r as c,j as e}from"./vendor-react-B4AQeu28.js";import{e as Z,n as de,h as U,m as ue}from"./index-BdLfAeGL.js";import{a as fe,C as pe}from"./chevron-up-uSn_SWll.js";import{X as be}from"./x-BLhsirCD.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/SettingsModal-BcXV1uwF.js b/assets/SettingsModal-YXgi6gjA.js similarity index 96% rename from assets/SettingsModal-BcXV1uwF.js rename to assets/SettingsModal-YXgi6gjA.js index 7f2465e0b09f4fabbbe9600c947802725ed482db..07f540bc7b3f62f23819a0f1d426d0708d141271 100644 --- a/assets/SettingsModal-BcXV1uwF.js +++ b/assets/SettingsModal-YXgi6gjA.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{e as U,u as Me,aW as Le,aX as De,aY as qe,aZ as Ie,a_ as Fe,a$ as Ve,D as Oe,V as He,a1 as Ge,b as Ue,h as $e,m as H,L as Be,F as Xe,a2 as Ye,$ as Qe,_ as G,j as d,b0 as We,aV as Je,b1 as Ke,b2 as Ze,b3 as es}from"./index-BvEKrMkD.js";import{r as a,j as e}from"./vendor-react-B4AQeu28.js";import{S as ss,a as ts,b as as,c as ns,d as te}from"./select-CU8TeDXy.js";import{B as p}from"./button-Bfg1pO9T.js";import{I as n}from"./input-B3TmduBc.js";import{S as x}from"./switch-kakgyvwt.js";import je from"./ConfirmModal-DE1CbRDa.js";import{P as is,M as rs,V as ls}from"./ProfilePictureUploader-Cd4j_44T.js";import{B as ge}from"./bell-C57aSZcx.js";import{D as ve}from"./download-BYKPAk50.js";import{X as Ne}from"./x-BYtx1i07.js";import{C as cs}from"./circle-help-DeWZHKak.js";import{G as os}from"./gift-CL3L8vH3.js";import{C as ds}from"./chart-column-DKW3TTRX.js";import{M as xs}from"./megaphone-DpNhcxX3.js";import{C as ms}from"./clock-0vnF72R6.js";import{T as hs}from"./trash-2-B056YIHV.js";import{E as us,a as bs}from"./eye-DbYh0OO3.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-CDr90bpM.js";import"./check-BmWAQELM.js";import"./log-out-BDL1J1Fs.js";import"./minus-DRsrXXF5.js";import"./plus-IoQaIojF.js";import"./upload-COEzjD21.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{e as U,u as Me,aW as Le,aX as De,aY as qe,aZ as Ie,a_ as Fe,a$ as Ve,D as Oe,V as He,a1 as Ge,b as Ue,h as $e,m as H,L as Be,F as Xe,a2 as Ye,$ as Qe,_ as G,j as d,b0 as We,aV as Je,b1 as Ke,b2 as Ze,b3 as es}from"./index-BdLfAeGL.js";import{r as a,j as e}from"./vendor-react-B4AQeu28.js";import{S as ss,a as ts,b as as,c as ns,d as te}from"./select-C3tB_0M-.js";import{B as p}from"./button-BbJLXpfi.js";import{I as n}from"./input-CHfZS1wQ.js";import{S as x}from"./switch-BZ2ceCBk.js";import je from"./ConfirmModal-DPzAgSP6.js";import{P as is,M as rs,V as ls}from"./ProfilePictureUploader-SMuKdVoO.js";import{B as ge}from"./bell-C5_RRTsA.js";import{D as ve}from"./download-CPe9YOUv.js";import{X as Ne}from"./x-BLhsirCD.js";import{C as cs}from"./circle-help-CZDuv1Gp.js";import{G as os}from"./gift-CHSGDZhC.js";import{C as ds}from"./chart-column-Dl7iJ2BC.js";import{M as xs}from"./megaphone-Cd4AJY3E.js";import{C as ms}from"./clock-CpBwkoND.js";import{T as hs}from"./trash-2-f-pq6QuO.js";import{E as us,a as bs}from"./eye-8D1uq8DN.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-uSn_SWll.js";import"./check-DbVe23hB.js";import"./log-out-CccGdaTy.js";import"./minus-rsVFzcwU.js";import"./plus-Z9YkmuN1.js";import"./upload-CbDKucU9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -19,4 +19,4 @@ import{e as U,u as Me,aW as Le,aX as De,aY as qe,aZ as Ie,a_ as Fe,a$ as Ve,D as * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Ns=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],ks=U("smartphone",Ns),ws=()=>{const{userProfile:m,userRole:y}=Me(),[r,z]=a.useState(Le),[R,_]=a.useState(De),[k,T]=a.useState(!1),[D,E]=a.useState(null);a.useEffect(()=>{if(!m?.uid)return;(async()=>{T(!0),E(null);try{if(y==="teacher"){const u=await Fe(m.uid);z(u)}if(y==="admin"){const u=await Ve();_(u)}}catch(u){E(u instanceof Error?u.message:"Failed to load settings")}finally{T(!1)}})()},[m?.uid,y]);const o=a.useCallback(async g=>{if(!m?.uid)return;const u=await qe(m.uid,g);z(u)},[m?.uid]),M=a.useCallback(async g=>{const u=await Ie(g);_(u)},[]);return{teacherPrefs:r,adminConfig:R,loading:k,error:D,saveTeacherPrefs:o,saveAdminConfig:M}},ae=()=>JSON.parse(JSON.stringify(We)),rt=({isOpen:m,onClose:y,profileData:r,onSave:z,settingsData:R,onSaveSettings:_,onApplySettingsPreview:k,onExportData:T,onClearCache:D,onResetData:E})=>{const o=r?.role||"student",{teacherPrefs:M,adminConfig:g,saveTeacherPrefs:u,saveAdminConfig:ke}=ws(),[b,ne]=a.useState("account"),[l,h]=a.useState({}),[i,ie]=a.useState(ae()),[w,C]=a.useState(M),[j,$]=a.useState(g),[B,re]=a.useState(!1),[q,le]=a.useState(!1),[X,ce]=a.useState(!1),[Y,oe]=a.useState(!1),[de,Cs]=a.useState(!1),[we,I]=a.useState(!1),[Ce,F]=a.useState(!1),[Se,P]=a.useState(!1),[L,xe]=a.useState(""),[f,Ae]=a.useState(null),[v,me]=a.useState(!1),[Q,he]=a.useState(!1),[W,ue]=a.useState(""),[V,be]=a.useState(""),J=a.useRef(!1),K=a.useRef(ae());a.useEffect(()=>{if(!m){J.current=!1;return}if(J.current)return;J.current=!0;const s=R?JSON.parse(JSON.stringify(R)):ae();K.current=s,h({uid:r?.uid,name:r?.name||"",email:r?.email||"",phone:r?.phone||"",photo:r?.photo||"",avatarLayers:r?.avatarLayers,role:r?.role,gender:r?.gender,lrn:r?.lrn||"",grade:r?.grade||"",section:r?.section||"",school:r?.school||"",department:r?.department||"",subject:r?.subject||"",yearsOfExperience:r?.yearsOfExperience||"",qualification:r?.qualification||"",position:r?.position||""}),ie(s),C(M),$(g)},[m,r,R,M,g]),a.useEffect(()=>{m&&k?.(i)},[m,i,k]),a.useEffect(()=>{if(!m)return;const s=t=>{t.key==="Escape"&&(k?.(K.current),y())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[m,y,k]);const Z=a.useMemo(()=>{const s=[{id:"account",label:"Account",icon:Oe},{id:"notifications",label:"Notifications",icon:ge},{id:"appearance",label:"Appearance",icon:js}];return o==="student"&&(s.push({id:"privacy",label:"Privacy & Security",icon:He}),s.push({id:"learning",label:"Learning",icon:Ge})),o==="teacher"&&s.push({id:"teaching",label:"Teaching",icon:Ue}),o==="admin"&&s.push({id:"system",label:"System",icon:vs}),s.push({id:"data",label:"Data & Storage",icon:ve}),s},[o]),c=s=>{ie(t=>s(t))},ee=s=>{Ae(s),xe(""),he(!1),s==="password"&&ue(""),s==="email"&&be(l.email||""),P(!0)},fe=async()=>{if(!L.trim()){d.error("Current password is required");return}me(!0);try{if(f==="password"){if(W.length<8){d.error("New password must be at least 8 characters");return}await Ke(L,W),d.success("Password updated")}else if(f==="email"){if(!V.includes("@")){d.error("Enter a valid email");return}await Ze(L,V),h(s=>({...s,email:V})),d.success("Email updated")}else if(f==="delete"){await es(L,l.uid||""),d.success("Account deleted"),y();return}P(!1)}catch(s){d.error(s instanceof Error?s.message:"Authentication failed")}finally{me(!1)}},Ee=async()=>{const s=Je({name:l.name,phone:l.phone});if(s){d.error(s);return}re(!0);try{z&&await z(l),_&&await _(i),o==="teacher"&&await u(w),o==="admin"&&await ke(j),y()}catch(t){d.error(t instanceof Error?t.message:"Failed to save settings")}finally{re(!1)}},se=()=>{P(!1),I(!1),F(!1),k?.(K.current),y()},Pe=async()=>{if(!(!T||X)){ce(!0);try{await T()}catch(s){d.error(s instanceof Error?s.message:"Failed to export data")}finally{ce(!1)}}},ze=async()=>{if(!(!D||Y)){oe(!0);try{await D()}catch(s){d.error(s instanceof Error?s.message:"Failed to clear cache")}finally{oe(!1)}}},Re=async()=>{if(!(!E||q)){I(!1),le(!0);try{await E(),d.success("Testing data reset completed")}catch(s){d.error(s instanceof Error?s.message:"Failed to reset testing data")}finally{le(!1)}}},_e=()=>{F(!1),ee("delete")};return m?e.jsx($e,{children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"fixed inset-0 z-[100] flex items-end sm:items-center justify-center sm:p-4",children:[e.jsx(H.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:se,className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(H.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.2},className:"relative bg-[#f7f9fc] rounded-t-2xl sm:rounded-2xl shadow-2xl border border-[#dde3eb] w-full sm:max-w-4xl h-[92vh] sm:max-h-[85vh] overflow-hidden flex flex-col sm:flex-row",children:[e.jsxs("div",{className:"hidden sm:flex w-64 flex-shrink-0 bg-slate-50 border-r border-slate-200 flex-col p-6 overflow-y-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-display font-bold text-[#0a1628]",children:"Settings"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Manage your preferences"})]}),e.jsx("nav",{className:"space-y-1",children:Z.map(s=>{const t=s.icon;return e.jsxs("button",{onClick:()=>ne(s.id),className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all ${b===s.id?"bg-sky-50 text-sky-700 shadow-sm":"text-slate-500 hover:bg-slate-100 hover:text-sky-700"}`,children:[e.jsx(t,{size:18}),e.jsx("span",{className:"text-sm font-medium",children:s.label})]},s.id)})})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[e.jsx("div",{className:"sm:hidden flex items-center border-b border-[#dde3eb] bg-slate-50 overflow-x-auto no-scrollbar px-2",children:Z.map(s=>{const t=s.icon;return e.jsxs("button",{onClick:()=>ne(s.id),className:`flex flex-col items-center gap-0.5 px-3 py-2.5 shrink-0 text-xs font-medium border-b-2 transition-colors ${b===s.id?"border-sky-600 text-sky-700":"border-transparent text-slate-500"}`,children:[e.jsx(t,{size:16}),e.jsx("span",{className:"whitespace-nowrap",children:s.label})]},s.id)})}),e.jsxs("div",{className:"flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[#dde3eb]",children:[e.jsx("h3",{className:"text-base sm:text-lg font-display font-bold text-[#0a1628]",children:Z.find(s=>s.id===b)?.label}),e.jsx("button",{onClick:se,className:"p-2 hover:bg-[#edf1f7] rounded-xl transition-colors",children:e.jsx(Ne,{size:20,className:"text-[#5a6578]"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 sm:p-6",children:[b==="account"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(is,{uid:l.uid,photoURL:l.photo,displayName:l.name,onUploaded:s=>h(t=>({...t,photo:s}))}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Full Name"}),e.jsx(n,{type:"text",value:l.name||"",onChange:s=>h(t=>({...t,name:s.target.value})),maxLength:100,autoComplete:"name",className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Email Address"}),e.jsxs("div",{className:"flex items-center gap-2 max-w-md",children:[e.jsx(n,{type:"email",value:l.email||"",disabled:!0,className:"flex-1 bg-slate-100"}),e.jsx(p,{variant:"outline",size:"sm",onClick:()=>ee("email"),children:"Change"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Phone Number"}),e.jsx(n,{type:"tel",value:l.phone||"",onChange:s=>h(t=>({...t,phone:s.target.value})),maxLength:20,inputMode:"tel",autoComplete:"tel",pattern:"^\\+?[0-9 ()\\-.]{7,20}$",placeholder:"+63 912 345 6789",className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Gender"}),e.jsxs(ss,{value:l.gender||"",onValueChange:s=>h(t=>({...t,gender:s})),children:[e.jsx(ts,{className:"max-w-md bg-white border-[#dde3eb] rounded-lg",children:e.jsx(as,{placeholder:"Select gender (optional)"})}),e.jsxs(ns,{children:[e.jsx(te,{value:"male",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"size-4 text-blue-500"}),e.jsx("span",{children:"Male"})]})}),e.jsx(te,{value:"female",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"size-4 text-pink-500"}),e.jsx("span",{children:"Female"})]})}),e.jsx(te,{value:"prefer_not_to_say",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"size-4 text-gray-500"}),e.jsx("span",{children:"Prefer not to say"})]})})]})]})]}),o==="student"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"LRN"}),e.jsx(n,{value:l.lrn||"",onChange:s=>h(t=>({...t,lrn:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Grade Level"}),e.jsx(n,{value:l.grade||"",onChange:s=>h(t=>({...t,grade:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Section"}),e.jsx(n,{value:l.section||"",onChange:s=>h(t=>({...t,section:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"School"}),e.jsx(n,{value:l.school||"",onChange:s=>h(t=>({...t,school:s.target.value})),className:"max-w-md"})]})]}),o==="teacher"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Department"}),e.jsx(n,{value:l.department||"",onChange:s=>h(t=>({...t,department:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Subject"}),e.jsx(n,{value:l.subject||"",onChange:s=>h(t=>({...t,subject:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Years of Experience"}),e.jsx(n,{value:l.yearsOfExperience||"",onChange:s=>h(t=>({...t,yearsOfExperience:s.target.value})),className:"max-w-md"})]})]}),o==="admin"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Position"}),e.jsx(n,{value:l.position||"",onChange:s=>h(t=>({...t,position:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Change Password"}),e.jsxs(p,{variant:"outline",className:"rounded-xl",onClick:()=>ee("password"),children:[e.jsx(Be,{size:16,className:"mr-2"}),"Update Password"]})]})]}),b==="notifications"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Push Notifications"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Get notified on your device"})]}),e.jsx(x,{checked:i.notifications.pushNotifications,onCheckedChange:s=>c(t=>({...t,notifications:{...t.notifications,pushNotifications:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Sound Effects"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Play sounds for notifications"})]}),e.jsx(x,{checked:i.notifications.soundEnabled,onCheckedChange:s=>c(t=>({...t,notifications:{...t.notifications,soundEnabled:s}}))})]}),o==="teacher"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Student Submissions"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Notify when students submit work"})]}),e.jsx(x,{checked:w.notifyOnSubmission,onCheckedChange:s=>C(t=>({...t,notifyOnSubmission:s}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Student Activity Alerts"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Notify on at-risk student activity"})]}),e.jsx(x,{checked:w.notifyOnStudentActivity,onCheckedChange:s=>C(t=>({...t,notifyOnStudentActivity:s}))})]})]}),e.jsxs("div",{className:"pt-4",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] mb-3 font-body",children:"Notification Types"}),e.jsx("div",{className:"space-y-3",children:[{key:"quizReminders",label:"Quiz Reminders"},{key:"newContent",label:"New Content"},{key:"achievements",label:"Achievements"},{key:"streakAlerts",label:"Streak Alerts"},{key:"weeklySummary",label:"Weekly Summary"}].map(s=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"checkbox",checked:i.notifications.notificationTypes[s.key],onChange:t=>c(N=>({...N,notifications:{...N.notifications,notificationTypes:{...N.notifications.notificationTypes,[s.key]:t.target.checked}}})),className:"w-4 h-4 rounded border-[#dde3eb] text-sky-600 focus:ring-sky-500"}),e.jsx("span",{className:"text-sm text-[#0a1628] font-body",children:s.label})]},s.key))})]}),e.jsxs("div",{className:"pt-4 border-t border-[#dde3eb]",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] mb-1 font-body",children:"Push Notification Categories"}),e.jsx("p",{className:"text-xs text-slate-500 mb-3",children:"Choose which kinds of pushes you want to receive on this device."}),e.jsxs("div",{className:"flex items-center justify-between py-2 mb-2 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Enable Push (master)"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"Turn off to silence ALL push categories."})]}),e.jsx(x,{checked:i.pushPreferences.pushEnabled,onCheckedChange:s=>c(t=>({...t,pushPreferences:{...t.pushPreferences,pushEnabled:s}}))})]}),e.jsx("div",{className:"space-y-2",children:[{key:"achievement",label:"Achievements unlocked",icon:Xe},{key:"quiz_battle",label:"Quiz battle invites & results",icon:Ye},{key:"daily_reward",label:"Daily reward reminders",icon:os},{key:"assignment",label:"New assignments / deadlines",icon:ps},{key:"streak_reminder",label:"Streak reminders",icon:Qe},{key:"leaderboard",label:"Leaderboard updates",icon:ds},{key:"system",label:"System announcements",icon:xs}].map(s=>{const t=s.key,N=s.icon;return e.jsxs("label",{className:"flex items-center justify-between py-1.5",children:[e.jsxs("span",{className:"text-sm text-[#0a1628] font-body flex items-center gap-2",children:[e.jsx(N,{className:"h-4 w-4 text-[#6c47ff]"}),s.label]}),e.jsx(x,{checked:!!i.pushPreferences[t],onCheckedChange:pe=>c(O=>({...O,pushPreferences:{...O.pushPreferences,[s.key]:pe}})),disabled:!i.pushPreferences.pushEnabled&&t!=="pushEnabled"})]},s.key)})}),e.jsx("div",{className:"mt-4",children:e.jsxs(p,{type:"button",variant:"outline",size:"sm",onClick:async()=>{try{const{requestPushPermissionAndRegister:s}=await G(async()=>{const{requestPushPermissionAndRegister:S}=await import("./index-BvEKrMkD.js").then(A=>A.b9);return{requestPushPermissionAndRegister:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),{auth:t}=await G(async()=>{const{auth:S}=await import("./index-BvEKrMkD.js").then(A=>A.b7);return{auth:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),N=t.currentUser?.uid;if(!N){d.error("You must be signed in to test push notifications.");return}if(!await s(N)){d.error("Push setup failed. Check that VITE_FIREBASE_VAPID_KEY is configured and notifications are allowed.");return}const{httpsCallable:O}=await G(async()=>{const{httpsCallable:S}=await import("./vendor-firebase-core-D7GXCeNu.js").then(A=>A.a9);return{httpsCallable:S}},[]),{cloudFunctions:Te}=await G(async()=>{const{cloudFunctions:S}=await import("./index-BvEKrMkD.js").then(A=>A.b7);return{cloudFunctions:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),ye=(await O(Te,"sendTestPush")({}))?.data?.sent??0;ye>0?d.success(`Sent test push to ${ye} device(s).`):d.message("No active devices found. Enable browser notifications first.")}catch(s){d.error(s instanceof Error?s.message:"Failed to send test push")}},children:[e.jsx(ge,{size:14,className:"mr-2"}),"Send test push"]})})]}),e.jsxs("div",{className:"pt-4 border-t border-[#dde3eb]",children:[e.jsxs("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:[e.jsx(ms,{size:16,className:"inline mr-2"}),"Quiet Hours"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(n,{type:"time",value:i.notifications.quietHours.start,onChange:s=>c(t=>({...t,notifications:{...t.notifications,quietHours:{...t.notifications.quietHours,start:s.target.value}}})),className:"w-32"}),e.jsx("span",{className:"text-[#5a6578]",children:"to"}),e.jsx(n,{type:"time",value:i.notifications.quietHours.end,onChange:s=>c(t=>({...t,notifications:{...t.notifications,quietHours:{...t.notifications.quietHours,end:s.target.value}}})),className:"w-32"})]})]})]}),b==="appearance"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Dark Mode"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Toggle dark theme"})]}),e.jsx(x,{checked:i.appearance.darkMode,onCheckedChange:s=>c(t=>({...t,appearance:{...t.appearance,darkMode:s}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-3 block font-body uppercase tracking-wider text-xs",children:"Font Size"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Small"}),e.jsx("input",{type:"range",min:"12",max:"20",value:i.appearance.fontSize,onChange:s=>c(t=>({...t,appearance:{...t.appearance,fontSize:Number(s.target.value)}})),className:"flex-1"}),e.jsx("span",{className:"text-xs text-slate-500",children:"Large"}),e.jsxs("span",{className:"text-xs font-mono text-slate-600 w-8",children:[i.appearance.fontSize,"px"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Compact View"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Show more content on screen"})]}),e.jsx(x,{checked:i.appearance.compactView,onCheckedChange:s=>c(t=>({...t,appearance:{...t.appearance,compactView:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Reduce Animations"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Minimize motion effects"})]}),e.jsx(x,{checked:i.appearance.reduceAnimations,onCheckedChange:s=>c(t=>({...t,appearance:{...t.appearance,reduceAnimations:s}}))})]})]}),b==="privacy"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Profile Visibility"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Who can see your profile"})]}),e.jsxs("select",{value:i.privacy.profileVisibility,onChange:s=>c(t=>({...t,privacy:{...t.privacy,profileVisibility:s.target.value}})),className:"px-3 py-2 border border-[#dde3eb] rounded-lg text-sm bg-white text-[#0a1628]",children:[e.jsx("option",{value:"everyone",children:"Everyone"}),e.jsx("option",{value:"students_and_staff",children:"Students and Staff"}),e.jsx("option",{value:"private",children:"Private"})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Show Activity Status"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Let others see when you're online"})]}),e.jsx(x,{checked:i.privacy.showActivityStatus,onCheckedChange:s=>c(t=>({...t,privacy:{...t.privacy,showActivityStatus:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Data Sharing"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Share anonymous usage data"})]}),e.jsx(x,{checked:i.privacy.dataSharing,onCheckedChange:s=>c(t=>({...t,privacy:{...t.privacy,dataSharing:s}}))})]})]}),b==="learning"&&o==="student"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Daily XP Goal"}),e.jsx(n,{type:"number",value:i.learning.dailyXpGoal,onChange:s=>c(t=>({...t,learning:{...t.learning,dailyXpGoal:Number(s.target.value||0)}})),className:"max-w-xs"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Preferred Study Time"}),e.jsxs("select",{value:i.learning.preferredStudyTime,onChange:s=>c(t=>({...t,learning:{...t.learning,preferredStudyTime:s.target.value}})),className:"px-3 py-2 border border-[#dde3eb] rounded-lg text-sm w-full max-w-xs bg-white text-[#0a1628]",children:[e.jsx("option",{value:"morning",children:"Morning (6AM - 12PM)"}),e.jsx("option",{value:"afternoon",children:"Afternoon (12PM - 6PM)"}),e.jsx("option",{value:"evening",children:"Evening (6PM - 12PM)"}),e.jsx("option",{value:"night",children:"Night (12AM - 6AM)"})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Auto-play Next Lesson"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Automatically start the next lesson"})]}),e.jsx(x,{checked:i.learning.autoPlayLessons,onCheckedChange:s=>c(t=>({...t,learning:{...t.learning,autoPlayLessons:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Show Hints During Quizzes"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Display helpful hints for questions"})]}),e.jsx(x,{checked:i.learning.showHints,onCheckedChange:s=>c(t=>({...t,learning:{...t.learning,showHints:s}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Quiz Difficulty Preference"}),e.jsxs("select",{value:i.learning.quizDifficultyPreference,onChange:s=>c(t=>({...t,learning:{...t.learning,quizDifficultyPreference:s.target.value}})),className:"px-3 py-2 border border-[#dde3eb] rounded-lg text-sm w-full max-w-xs bg-white text-[#0a1628]",children:[e.jsx("option",{value:"adaptive",children:"Adaptive (Recommended)"}),e.jsx("option",{value:"easy",children:"Easy"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"hard",children:"Hard"})]})]}),e.jsxs("div",{className:"pt-4 border-t border-[#dde3eb]",children:[e.jsxs("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:[e.jsx(ks,{size:16,className:"inline mr-2"}),"Study Reminders"]}),e.jsx(n,{type:"time",value:i.learning.studyReminderTime,onChange:s=>c(t=>({...t,learning:{...t.learning,studyReminderTime:s.target.value}})),className:"w-32"})]})]}),b==="teaching"&&o==="teacher"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Quiz Defaults"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Time Limit (min)"}),e.jsx(n,{type:"number",value:w.quizDefaults.timeLimitMinutes,onChange:s=>C(t=>({...t,quizDefaults:{...t.quizDefaults,timeLimitMinutes:Number(s.target.value)}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Passing Score (%)"}),e.jsx(n,{type:"number",value:w.quizDefaults.passingScore,onChange:s=>C(t=>({...t,quizDefaults:{...t.quizDefaults,passingScore:Number(s.target.value)}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Max Attempts"}),e.jsx(n,{type:"number",value:w.quizDefaults.maxAttempts,onChange:s=>C(t=>({...t,quizDefaults:{...t.quizDefaults,maxAttempts:Number(s.target.value)}}))})]})]}),e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body pt-4",children:"Class Preferences"}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Student Analytics Visibility"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Let students see their leaderboard rank"})]}),e.jsx(x,{checked:w.studentAnalyticsVisibility,onCheckedChange:s=>C(t=>({...t,studentAnalyticsVisibility:s}))})]})]}),b==="system"&&o==="admin"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Maintenance Mode"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Disable platform access for non-admins"})]}),e.jsx(x,{checked:j.maintenanceMode,onCheckedChange:s=>$(t=>({...t,maintenanceMode:s}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Default Grade Level"}),e.jsx(n,{value:j.defaultGradeLevel,disabled:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Default Curriculum"}),e.jsx(n,{value:j.defaultCurriculum,disabled:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Max Class Size"}),e.jsx(n,{type:"number",value:j.maxClassSize,disabled:!0})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Audit Log Visible"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Show audit logs in admin dashboard"})]}),e.jsx(x,{checked:j.auditLogVisible,onCheckedChange:s=>$(t=>({...t,auditLogVisible:s}))})]}),e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body pt-4",children:"AI Configuration"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Model Name"}),e.jsx(n,{value:j.aiConfig.modelName,disabled:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Temperature"}),e.jsx(n,{type:"number",value:j.aiConfig.temperature,disabled:!0})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"API Endpoint"}),e.jsx(n,{value:j.aiConfig.endpoint,disabled:!0})]})]})]}),b==="data"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 bg-sky-50 border border-sky-200 rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-sky-900 mb-1 font-body",children:"Download Your Data"}),e.jsx("p",{className:"text-xs text-sky-700 mb-3",children:"Export all your learning data and progress"}),e.jsxs(p,{variant:"outline",size:"sm",className:"rounded-xl",onClick:Pe,disabled:X,children:[e.jsx(ve,{size:16,className:"mr-2"}),X?"Exporting...":"Request Data Export"]})]}),e.jsxs("div",{className:"p-4 bg-white border border-[#dde3eb] rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] mb-1 font-body",children:"Clear Cache"}),e.jsx("p",{className:"text-xs text-[#5a6578] mb-3",children:"Free up space by clearing cached data"}),e.jsx(p,{variant:"outline",size:"sm",className:"rounded-xl",onClick:ze,disabled:Y,children:Y?"Clearing...":"Clear Cache"})]}),e.jsxs("div",{className:"p-4 bg-rose-50 border border-rose-200 rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-rose-900 mb-1",children:"Reset Progress"}),e.jsxs("p",{className:"text-xs text-rose-700 mb-3",children:[o==="student"&&"Reset quizzes, diagnostic state, XP, and learning progress for retesting.",o==="teacher"&&"Reset imported records, managed classrooms, and teacher-generated quiz artifacts.",o==="admin"&&"Reset admin testing artifacts like personal audit/content update records."]}),e.jsx(p,{variant:"outline",size:"sm",className:"rounded-xl text-rose-700 border-rose-300",disabled:!E||q,onClick:()=>I(!0),children:q?"Resetting...":"Reset Testing Data"})]}),e.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-red-900 mb-1",children:"Delete Account"}),e.jsx("p",{className:"text-xs text-red-700 mb-3",children:"Permanently delete your account and all data"}),e.jsxs(p,{variant:"outline",size:"sm",className:"rounded-xl text-red-700 border-red-300",onClick:()=>F(!0),disabled:de,children:[e.jsx(hs,{size:16,className:"mr-2"}),de?"Deleting...":"Delete Account"]})]})]})]}),e.jsxs("div",{className:"shrink-0 px-4 sm:px-6 py-3 sm:py-4 border-t border-[#dde3eb] bg-[#edf1f7] flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2 sm:gap-0",children:[e.jsx("p",{className:"text-xs text-slate-500 font-body text-center sm:text-left",children:"MathPulse AI v2.1.0"}),e.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[e.jsx(p,{variant:"outline",onClick:se,className:"rounded-lg border-[#dde3eb] flex-1 sm:flex-none",disabled:B,children:"Cancel"}),e.jsx(p,{onClick:Ee,className:"rounded-lg bg-sky-600 hover:bg-sky-700 text-white flex-1 sm:flex-none",disabled:B,children:B?"Saving...":"Save Changes"})]})]})]})]})]}),Se&&e.jsx(H.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[130] bg-black/50 backdrop-blur-sm flex items-center justify-center p-4",onClick:()=>{v||P(!1)},children:e.jsxs(H.div,{initial:{opacity:0,scale:.95,y:12},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:12},transition:{duration:.2},className:"w-full max-w-md rounded-2xl border border-[#dde3eb] bg-[#f7f9fc] shadow-2xl",onClick:s=>s.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[#dde3eb] px-6 py-4",children:[e.jsxs("h4",{className:"text-lg font-display font-bold text-[#0a1628]",children:[f==="password"&&"Change Password",f==="email"&&"Change Email",f==="delete"&&"Delete Account"]}),e.jsx("button",{onClick:()=>{v||P(!1)},className:"p-2 rounded-xl hover:bg-[#edf1f7] transition-colors","aria-label":"Close",children:e.jsx(Ne,{size:18,className:"text-[#5a6578]"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-4",children:[e.jsx("p",{className:"text-sm text-[#5a6578]",children:"Enter your current password to continue."}),e.jsxs("div",{className:"relative",children:[e.jsx(n,{type:Q?"text":"password",value:L,onChange:s=>xe(s.target.value),placeholder:"Current password",autoFocus:!0,className:"pr-10",disabled:v,onKeyDown:s=>{s.key==="Enter"&&fe()}}),e.jsx("button",{type:"button",onClick:()=>he(!Q),className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600",tabIndex:-1,children:Q?e.jsx(us,{size:16}):e.jsx(bs,{size:16})})]}),f==="password"&&e.jsx("div",{className:"relative",children:e.jsx(n,{type:"password",value:W,onChange:s=>ue(s.target.value),placeholder:"New password (min 8 chars)",disabled:v})}),f==="email"&&e.jsx(n,{type:"email",value:V,onChange:s=>be(s.target.value),placeholder:"New email address",disabled:v}),f==="delete"&&e.jsx("p",{className:"text-sm text-red-600 font-medium",children:"This action is permanent and cannot be undone."}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(p,{variant:"outline",onClick:()=>P(!1),disabled:v,children:"Cancel"}),e.jsx(p,{onClick:()=>void fe(),className:f==="delete"?"bg-red-600 hover:bg-red-700 text-white":"bg-sky-600 hover:bg-sky-700 text-white",disabled:v,children:v?"Processing...":f==="delete"?"Delete Forever":"Confirm"})]})]})]})}),e.jsx(je,{isOpen:we,onClose:()=>I(!1),onConfirm:Re,title:"Reset Testing Data?",message:`Reset ${o} testing data? This will clear quizzes, diagnostic assessments, assessment history, XP, and learning progress. This action cannot be undone.`,confirmText:q?"Resetting...":"Reset Data",cancelText:"Cancel",type:"warning",icon:"warning",zIndexClass:"z-[130]"}),e.jsx(je,{isOpen:Ce,onClose:()=>F(!1),onConfirm:_e,title:"Delete Account?",message:"You will need to re-authenticate to permanently delete your account. This cannot be undone.",confirmText:"Continue",cancelText:"Cancel",type:"danger",icon:"delete",zIndexClass:"z-[130]"})]})}):null};export{rt as default}; + */const Ns=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],ks=U("smartphone",Ns),ws=()=>{const{userProfile:m,userRole:y}=Me(),[r,z]=a.useState(Le),[R,_]=a.useState(De),[k,T]=a.useState(!1),[D,E]=a.useState(null);a.useEffect(()=>{if(!m?.uid)return;(async()=>{T(!0),E(null);try{if(y==="teacher"){const u=await Fe(m.uid);z(u)}if(y==="admin"){const u=await Ve();_(u)}}catch(u){E(u instanceof Error?u.message:"Failed to load settings")}finally{T(!1)}})()},[m?.uid,y]);const o=a.useCallback(async g=>{if(!m?.uid)return;const u=await qe(m.uid,g);z(u)},[m?.uid]),M=a.useCallback(async g=>{const u=await Ie(g);_(u)},[]);return{teacherPrefs:r,adminConfig:R,loading:k,error:D,saveTeacherPrefs:o,saveAdminConfig:M}},ae=()=>JSON.parse(JSON.stringify(We)),rt=({isOpen:m,onClose:y,profileData:r,onSave:z,settingsData:R,onSaveSettings:_,onApplySettingsPreview:k,onExportData:T,onClearCache:D,onResetData:E})=>{const o=r?.role||"student",{teacherPrefs:M,adminConfig:g,saveTeacherPrefs:u,saveAdminConfig:ke}=ws(),[b,ne]=a.useState("account"),[l,h]=a.useState({}),[i,ie]=a.useState(ae()),[w,C]=a.useState(M),[j,$]=a.useState(g),[B,re]=a.useState(!1),[q,le]=a.useState(!1),[X,ce]=a.useState(!1),[Y,oe]=a.useState(!1),[de,Cs]=a.useState(!1),[we,I]=a.useState(!1),[Ce,F]=a.useState(!1),[Se,P]=a.useState(!1),[L,xe]=a.useState(""),[f,Ae]=a.useState(null),[v,me]=a.useState(!1),[Q,he]=a.useState(!1),[W,ue]=a.useState(""),[V,be]=a.useState(""),J=a.useRef(!1),K=a.useRef(ae());a.useEffect(()=>{if(!m){J.current=!1;return}if(J.current)return;J.current=!0;const s=R?JSON.parse(JSON.stringify(R)):ae();K.current=s,h({uid:r?.uid,name:r?.name||"",email:r?.email||"",phone:r?.phone||"",photo:r?.photo||"",avatarLayers:r?.avatarLayers,role:r?.role,gender:r?.gender,lrn:r?.lrn||"",grade:r?.grade||"",section:r?.section||"",school:r?.school||"",department:r?.department||"",subject:r?.subject||"",yearsOfExperience:r?.yearsOfExperience||"",qualification:r?.qualification||"",position:r?.position||""}),ie(s),C(M),$(g)},[m,r,R,M,g]),a.useEffect(()=>{m&&k?.(i)},[m,i,k]),a.useEffect(()=>{if(!m)return;const s=t=>{t.key==="Escape"&&(k?.(K.current),y())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[m,y,k]);const Z=a.useMemo(()=>{const s=[{id:"account",label:"Account",icon:Oe},{id:"notifications",label:"Notifications",icon:ge},{id:"appearance",label:"Appearance",icon:js}];return o==="student"&&(s.push({id:"privacy",label:"Privacy & Security",icon:He}),s.push({id:"learning",label:"Learning",icon:Ge})),o==="teacher"&&s.push({id:"teaching",label:"Teaching",icon:Ue}),o==="admin"&&s.push({id:"system",label:"System",icon:vs}),s.push({id:"data",label:"Data & Storage",icon:ve}),s},[o]),c=s=>{ie(t=>s(t))},ee=s=>{Ae(s),xe(""),he(!1),s==="password"&&ue(""),s==="email"&&be(l.email||""),P(!0)},fe=async()=>{if(!L.trim()){d.error("Current password is required");return}me(!0);try{if(f==="password"){if(W.length<8){d.error("New password must be at least 8 characters");return}await Ke(L,W),d.success("Password updated")}else if(f==="email"){if(!V.includes("@")){d.error("Enter a valid email");return}await Ze(L,V),h(s=>({...s,email:V})),d.success("Email updated")}else if(f==="delete"){await es(L,l.uid||""),d.success("Account deleted"),y();return}P(!1)}catch(s){d.error(s instanceof Error?s.message:"Authentication failed")}finally{me(!1)}},Ee=async()=>{const s=Je({name:l.name,phone:l.phone});if(s){d.error(s);return}re(!0);try{z&&await z(l),_&&await _(i),o==="teacher"&&await u(w),o==="admin"&&await ke(j),y()}catch(t){d.error(t instanceof Error?t.message:"Failed to save settings")}finally{re(!1)}},se=()=>{P(!1),I(!1),F(!1),k?.(K.current),y()},Pe=async()=>{if(!(!T||X)){ce(!0);try{await T()}catch(s){d.error(s instanceof Error?s.message:"Failed to export data")}finally{ce(!1)}}},ze=async()=>{if(!(!D||Y)){oe(!0);try{await D()}catch(s){d.error(s instanceof Error?s.message:"Failed to clear cache")}finally{oe(!1)}}},Re=async()=>{if(!(!E||q)){I(!1),le(!0);try{await E(),d.success("Testing data reset completed")}catch(s){d.error(s instanceof Error?s.message:"Failed to reset testing data")}finally{le(!1)}}},_e=()=>{F(!1),ee("delete")};return m?e.jsx($e,{children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"fixed inset-0 z-[100] flex items-end sm:items-center justify-center sm:p-4",children:[e.jsx(H.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:se,className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(H.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.2},className:"relative bg-[#f7f9fc] rounded-t-2xl sm:rounded-2xl shadow-2xl border border-[#dde3eb] w-full sm:max-w-4xl h-[92vh] sm:max-h-[85vh] overflow-hidden flex flex-col sm:flex-row",children:[e.jsxs("div",{className:"hidden sm:flex w-64 flex-shrink-0 bg-slate-50 border-r border-slate-200 flex-col p-6 overflow-y-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-display font-bold text-[#0a1628]",children:"Settings"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-body",children:"Manage your preferences"})]}),e.jsx("nav",{className:"space-y-1",children:Z.map(s=>{const t=s.icon;return e.jsxs("button",{onClick:()=>ne(s.id),className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all ${b===s.id?"bg-sky-50 text-sky-700 shadow-sm":"text-slate-500 hover:bg-slate-100 hover:text-sky-700"}`,children:[e.jsx(t,{size:18}),e.jsx("span",{className:"text-sm font-medium",children:s.label})]},s.id)})})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[e.jsx("div",{className:"sm:hidden flex items-center border-b border-[#dde3eb] bg-slate-50 overflow-x-auto no-scrollbar px-2",children:Z.map(s=>{const t=s.icon;return e.jsxs("button",{onClick:()=>ne(s.id),className:`flex flex-col items-center gap-0.5 px-3 py-2.5 shrink-0 text-xs font-medium border-b-2 transition-colors ${b===s.id?"border-sky-600 text-sky-700":"border-transparent text-slate-500"}`,children:[e.jsx(t,{size:16}),e.jsx("span",{className:"whitespace-nowrap",children:s.label})]},s.id)})}),e.jsxs("div",{className:"flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[#dde3eb]",children:[e.jsx("h3",{className:"text-base sm:text-lg font-display font-bold text-[#0a1628]",children:Z.find(s=>s.id===b)?.label}),e.jsx("button",{onClick:se,className:"p-2 hover:bg-[#edf1f7] rounded-xl transition-colors",children:e.jsx(Ne,{size:20,className:"text-[#5a6578]"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 sm:p-6",children:[b==="account"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(is,{uid:l.uid,photoURL:l.photo,displayName:l.name,onUploaded:s=>h(t=>({...t,photo:s}))}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Full Name"}),e.jsx(n,{type:"text",value:l.name||"",onChange:s=>h(t=>({...t,name:s.target.value})),maxLength:100,autoComplete:"name",className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Email Address"}),e.jsxs("div",{className:"flex items-center gap-2 max-w-md",children:[e.jsx(n,{type:"email",value:l.email||"",disabled:!0,className:"flex-1 bg-slate-100"}),e.jsx(p,{variant:"outline",size:"sm",onClick:()=>ee("email"),children:"Change"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Phone Number"}),e.jsx(n,{type:"tel",value:l.phone||"",onChange:s=>h(t=>({...t,phone:s.target.value})),maxLength:20,inputMode:"tel",autoComplete:"tel",pattern:"^\\+?[0-9 ()\\-.]{7,20}$",placeholder:"+63 912 345 6789",className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Gender"}),e.jsxs(ss,{value:l.gender||"",onValueChange:s=>h(t=>({...t,gender:s})),children:[e.jsx(ts,{className:"max-w-md bg-white border-[#dde3eb] rounded-lg",children:e.jsx(as,{placeholder:"Select gender (optional)"})}),e.jsxs(ns,{children:[e.jsx(te,{value:"male",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"size-4 text-blue-500"}),e.jsx("span",{children:"Male"})]})}),e.jsx(te,{value:"female",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"size-4 text-pink-500"}),e.jsx("span",{children:"Female"})]})}),e.jsx(te,{value:"prefer_not_to_say",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"size-4 text-gray-500"}),e.jsx("span",{children:"Prefer not to say"})]})})]})]})]}),o==="student"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"LRN"}),e.jsx(n,{value:l.lrn||"",onChange:s=>h(t=>({...t,lrn:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Grade Level"}),e.jsx(n,{value:l.grade||"",onChange:s=>h(t=>({...t,grade:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Section"}),e.jsx(n,{value:l.section||"",onChange:s=>h(t=>({...t,section:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"School"}),e.jsx(n,{value:l.school||"",onChange:s=>h(t=>({...t,school:s.target.value})),className:"max-w-md"})]})]}),o==="teacher"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Department"}),e.jsx(n,{value:l.department||"",onChange:s=>h(t=>({...t,department:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Subject"}),e.jsx(n,{value:l.subject||"",onChange:s=>h(t=>({...t,subject:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Years of Experience"}),e.jsx(n,{value:l.yearsOfExperience||"",onChange:s=>h(t=>({...t,yearsOfExperience:s.target.value})),className:"max-w-md"})]})]}),o==="admin"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Position"}),e.jsx(n,{value:l.position||"",onChange:s=>h(t=>({...t,position:s.target.value})),className:"max-w-md"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Change Password"}),e.jsxs(p,{variant:"outline",className:"rounded-xl",onClick:()=>ee("password"),children:[e.jsx(Be,{size:16,className:"mr-2"}),"Update Password"]})]})]}),b==="notifications"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Push Notifications"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Get notified on your device"})]}),e.jsx(x,{checked:i.notifications.pushNotifications,onCheckedChange:s=>c(t=>({...t,notifications:{...t.notifications,pushNotifications:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Sound Effects"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Play sounds for notifications"})]}),e.jsx(x,{checked:i.notifications.soundEnabled,onCheckedChange:s=>c(t=>({...t,notifications:{...t.notifications,soundEnabled:s}}))})]}),o==="teacher"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Student Submissions"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Notify when students submit work"})]}),e.jsx(x,{checked:w.notifyOnSubmission,onCheckedChange:s=>C(t=>({...t,notifyOnSubmission:s}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Student Activity Alerts"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Notify on at-risk student activity"})]}),e.jsx(x,{checked:w.notifyOnStudentActivity,onCheckedChange:s=>C(t=>({...t,notifyOnStudentActivity:s}))})]})]}),e.jsxs("div",{className:"pt-4",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] mb-3 font-body",children:"Notification Types"}),e.jsx("div",{className:"space-y-3",children:[{key:"quizReminders",label:"Quiz Reminders"},{key:"newContent",label:"New Content"},{key:"achievements",label:"Achievements"},{key:"streakAlerts",label:"Streak Alerts"},{key:"weeklySummary",label:"Weekly Summary"}].map(s=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"checkbox",checked:i.notifications.notificationTypes[s.key],onChange:t=>c(N=>({...N,notifications:{...N.notifications,notificationTypes:{...N.notifications.notificationTypes,[s.key]:t.target.checked}}})),className:"w-4 h-4 rounded border-[#dde3eb] text-sky-600 focus:ring-sky-500"}),e.jsx("span",{className:"text-sm text-[#0a1628] font-body",children:s.label})]},s.key))})]}),e.jsxs("div",{className:"pt-4 border-t border-[#dde3eb]",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] mb-1 font-body",children:"Push Notification Categories"}),e.jsx("p",{className:"text-xs text-slate-500 mb-3",children:"Choose which kinds of pushes you want to receive on this device."}),e.jsxs("div",{className:"flex items-center justify-between py-2 mb-2 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Enable Push (master)"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"Turn off to silence ALL push categories."})]}),e.jsx(x,{checked:i.pushPreferences.pushEnabled,onCheckedChange:s=>c(t=>({...t,pushPreferences:{...t.pushPreferences,pushEnabled:s}}))})]}),e.jsx("div",{className:"space-y-2",children:[{key:"achievement",label:"Achievements unlocked",icon:Xe},{key:"quiz_battle",label:"Quiz battle invites & results",icon:Ye},{key:"daily_reward",label:"Daily reward reminders",icon:os},{key:"assignment",label:"New assignments / deadlines",icon:ps},{key:"streak_reminder",label:"Streak reminders",icon:Qe},{key:"leaderboard",label:"Leaderboard updates",icon:ds},{key:"system",label:"System announcements",icon:xs}].map(s=>{const t=s.key,N=s.icon;return e.jsxs("label",{className:"flex items-center justify-between py-1.5",children:[e.jsxs("span",{className:"text-sm text-[#0a1628] font-body flex items-center gap-2",children:[e.jsx(N,{className:"h-4 w-4 text-[#6c47ff]"}),s.label]}),e.jsx(x,{checked:!!i.pushPreferences[t],onCheckedChange:pe=>c(O=>({...O,pushPreferences:{...O.pushPreferences,[s.key]:pe}})),disabled:!i.pushPreferences.pushEnabled&&t!=="pushEnabled"})]},s.key)})}),e.jsx("div",{className:"mt-4",children:e.jsxs(p,{type:"button",variant:"outline",size:"sm",onClick:async()=>{try{const{requestPushPermissionAndRegister:s}=await G(async()=>{const{requestPushPermissionAndRegister:S}=await import("./index-BdLfAeGL.js").then(A=>A.b9);return{requestPushPermissionAndRegister:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),{auth:t}=await G(async()=>{const{auth:S}=await import("./index-BdLfAeGL.js").then(A=>A.b7);return{auth:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),N=t.currentUser?.uid;if(!N){d.error("You must be signed in to test push notifications.");return}if(!await s(N)){d.error("Push setup failed. Check that VITE_FIREBASE_VAPID_KEY is configured and notifications are allowed.");return}const{httpsCallable:O}=await G(async()=>{const{httpsCallable:S}=await import("./vendor-firebase-core-D7GXCeNu.js").then(A=>A.a9);return{httpsCallable:S}},[]),{cloudFunctions:Te}=await G(async()=>{const{cloudFunctions:S}=await import("./index-BdLfAeGL.js").then(A=>A.b7);return{cloudFunctions:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),ye=(await O(Te,"sendTestPush")({}))?.data?.sent??0;ye>0?d.success(`Sent test push to ${ye} device(s).`):d.message("No active devices found. Enable browser notifications first.")}catch(s){d.error(s instanceof Error?s.message:"Failed to send test push")}},children:[e.jsx(ge,{size:14,className:"mr-2"}),"Send test push"]})})]}),e.jsxs("div",{className:"pt-4 border-t border-[#dde3eb]",children:[e.jsxs("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:[e.jsx(ms,{size:16,className:"inline mr-2"}),"Quiet Hours"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(n,{type:"time",value:i.notifications.quietHours.start,onChange:s=>c(t=>({...t,notifications:{...t.notifications,quietHours:{...t.notifications.quietHours,start:s.target.value}}})),className:"w-32"}),e.jsx("span",{className:"text-[#5a6578]",children:"to"}),e.jsx(n,{type:"time",value:i.notifications.quietHours.end,onChange:s=>c(t=>({...t,notifications:{...t.notifications,quietHours:{...t.notifications.quietHours,end:s.target.value}}})),className:"w-32"})]})]})]}),b==="appearance"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Dark Mode"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Toggle dark theme"})]}),e.jsx(x,{checked:i.appearance.darkMode,onCheckedChange:s=>c(t=>({...t,appearance:{...t.appearance,darkMode:s}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-3 block font-body uppercase tracking-wider text-xs",children:"Font Size"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Small"}),e.jsx("input",{type:"range",min:"12",max:"20",value:i.appearance.fontSize,onChange:s=>c(t=>({...t,appearance:{...t.appearance,fontSize:Number(s.target.value)}})),className:"flex-1"}),e.jsx("span",{className:"text-xs text-slate-500",children:"Large"}),e.jsxs("span",{className:"text-xs font-mono text-slate-600 w-8",children:[i.appearance.fontSize,"px"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Compact View"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Show more content on screen"})]}),e.jsx(x,{checked:i.appearance.compactView,onCheckedChange:s=>c(t=>({...t,appearance:{...t.appearance,compactView:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Reduce Animations"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Minimize motion effects"})]}),e.jsx(x,{checked:i.appearance.reduceAnimations,onCheckedChange:s=>c(t=>({...t,appearance:{...t.appearance,reduceAnimations:s}}))})]})]}),b==="privacy"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Profile Visibility"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Who can see your profile"})]}),e.jsxs("select",{value:i.privacy.profileVisibility,onChange:s=>c(t=>({...t,privacy:{...t.privacy,profileVisibility:s.target.value}})),className:"px-3 py-2 border border-[#dde3eb] rounded-lg text-sm bg-white text-[#0a1628]",children:[e.jsx("option",{value:"everyone",children:"Everyone"}),e.jsx("option",{value:"students_and_staff",children:"Students and Staff"}),e.jsx("option",{value:"private",children:"Private"})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Show Activity Status"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Let others see when you're online"})]}),e.jsx(x,{checked:i.privacy.showActivityStatus,onCheckedChange:s=>c(t=>({...t,privacy:{...t.privacy,showActivityStatus:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Data Sharing"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Share anonymous usage data"})]}),e.jsx(x,{checked:i.privacy.dataSharing,onCheckedChange:s=>c(t=>({...t,privacy:{...t.privacy,dataSharing:s}}))})]})]}),b==="learning"&&o==="student"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Daily XP Goal"}),e.jsx(n,{type:"number",value:i.learning.dailyXpGoal,onChange:s=>c(t=>({...t,learning:{...t.learning,dailyXpGoal:Number(s.target.value||0)}})),className:"max-w-xs"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Preferred Study Time"}),e.jsxs("select",{value:i.learning.preferredStudyTime,onChange:s=>c(t=>({...t,learning:{...t.learning,preferredStudyTime:s.target.value}})),className:"px-3 py-2 border border-[#dde3eb] rounded-lg text-sm w-full max-w-xs bg-white text-[#0a1628]",children:[e.jsx("option",{value:"morning",children:"Morning (6AM - 12PM)"}),e.jsx("option",{value:"afternoon",children:"Afternoon (12PM - 6PM)"}),e.jsx("option",{value:"evening",children:"Evening (6PM - 12PM)"}),e.jsx("option",{value:"night",children:"Night (12AM - 6AM)"})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Auto-play Next Lesson"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Automatically start the next lesson"})]}),e.jsx(x,{checked:i.learning.autoPlayLessons,onCheckedChange:s=>c(t=>({...t,learning:{...t.learning,autoPlayLessons:s}}))})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Show Hints During Quizzes"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Display helpful hints for questions"})]}),e.jsx(x,{checked:i.learning.showHints,onCheckedChange:s=>c(t=>({...t,learning:{...t.learning,showHints:s}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:"Quiz Difficulty Preference"}),e.jsxs("select",{value:i.learning.quizDifficultyPreference,onChange:s=>c(t=>({...t,learning:{...t.learning,quizDifficultyPreference:s.target.value}})),className:"px-3 py-2 border border-[#dde3eb] rounded-lg text-sm w-full max-w-xs bg-white text-[#0a1628]",children:[e.jsx("option",{value:"adaptive",children:"Adaptive (Recommended)"}),e.jsx("option",{value:"easy",children:"Easy"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"hard",children:"Hard"})]})]}),e.jsxs("div",{className:"pt-4 border-t border-[#dde3eb]",children:[e.jsxs("label",{className:"text-sm font-bold text-[#5a6578] mb-2 block font-body uppercase tracking-wider text-xs",children:[e.jsx(ks,{size:16,className:"inline mr-2"}),"Study Reminders"]}),e.jsx(n,{type:"time",value:i.learning.studyReminderTime,onChange:s=>c(t=>({...t,learning:{...t.learning,studyReminderTime:s.target.value}})),className:"w-32"})]})]}),b==="teaching"&&o==="teacher"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Quiz Defaults"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Time Limit (min)"}),e.jsx(n,{type:"number",value:w.quizDefaults.timeLimitMinutes,onChange:s=>C(t=>({...t,quizDefaults:{...t.quizDefaults,timeLimitMinutes:Number(s.target.value)}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Passing Score (%)"}),e.jsx(n,{type:"number",value:w.quizDefaults.passingScore,onChange:s=>C(t=>({...t,quizDefaults:{...t.quizDefaults,passingScore:Number(s.target.value)}}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Max Attempts"}),e.jsx(n,{type:"number",value:w.quizDefaults.maxAttempts,onChange:s=>C(t=>({...t,quizDefaults:{...t.quizDefaults,maxAttempts:Number(s.target.value)}}))})]})]}),e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body pt-4",children:"Class Preferences"}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Student Analytics Visibility"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Let students see their leaderboard rank"})]}),e.jsx(x,{checked:w.studentAnalyticsVisibility,onCheckedChange:s=>C(t=>({...t,studentAnalyticsVisibility:s}))})]})]}),b==="system"&&o==="admin"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Maintenance Mode"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Disable platform access for non-admins"})]}),e.jsx(x,{checked:j.maintenanceMode,onCheckedChange:s=>$(t=>({...t,maintenanceMode:s}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Default Grade Level"}),e.jsx(n,{value:j.defaultGradeLevel,disabled:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Default Curriculum"}),e.jsx(n,{value:j.defaultCurriculum,disabled:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Max Class Size"}),e.jsx(n,{type:"number",value:j.maxClassSize,disabled:!0})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-[#dde3eb]",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body",children:"Audit Log Visible"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Show audit logs in admin dashboard"})]}),e.jsx(x,{checked:j.auditLogVisible,onCheckedChange:s=>$(t=>({...t,auditLogVisible:s}))})]}),e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] font-body pt-4",children:"AI Configuration"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Model Name"}),e.jsx(n,{value:j.aiConfig.modelName,disabled:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"Temperature"}),e.jsx(n,{type:"number",value:j.aiConfig.temperature,disabled:!0})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs text-[#5a6578] block mb-1",children:"API Endpoint"}),e.jsx(n,{value:j.aiConfig.endpoint,disabled:!0})]})]})]}),b==="data"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 bg-sky-50 border border-sky-200 rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-sky-900 mb-1 font-body",children:"Download Your Data"}),e.jsx("p",{className:"text-xs text-sky-700 mb-3",children:"Export all your learning data and progress"}),e.jsxs(p,{variant:"outline",size:"sm",className:"rounded-xl",onClick:Pe,disabled:X,children:[e.jsx(ve,{size:16,className:"mr-2"}),X?"Exporting...":"Request Data Export"]})]}),e.jsxs("div",{className:"p-4 bg-white border border-[#dde3eb] rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] mb-1 font-body",children:"Clear Cache"}),e.jsx("p",{className:"text-xs text-[#5a6578] mb-3",children:"Free up space by clearing cached data"}),e.jsx(p,{variant:"outline",size:"sm",className:"rounded-xl",onClick:ze,disabled:Y,children:Y?"Clearing...":"Clear Cache"})]}),e.jsxs("div",{className:"p-4 bg-rose-50 border border-rose-200 rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-rose-900 mb-1",children:"Reset Progress"}),e.jsxs("p",{className:"text-xs text-rose-700 mb-3",children:[o==="student"&&"Reset quizzes, diagnostic state, XP, and learning progress for retesting.",o==="teacher"&&"Reset imported records, managed classrooms, and teacher-generated quiz artifacts.",o==="admin"&&"Reset admin testing artifacts like personal audit/content update records."]}),e.jsx(p,{variant:"outline",size:"sm",className:"rounded-xl text-rose-700 border-rose-300",disabled:!E||q,onClick:()=>I(!0),children:q?"Resetting...":"Reset Testing Data"})]}),e.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-xl",children:[e.jsx("h4",{className:"text-sm font-bold text-red-900 mb-1",children:"Delete Account"}),e.jsx("p",{className:"text-xs text-red-700 mb-3",children:"Permanently delete your account and all data"}),e.jsxs(p,{variant:"outline",size:"sm",className:"rounded-xl text-red-700 border-red-300",onClick:()=>F(!0),disabled:de,children:[e.jsx(hs,{size:16,className:"mr-2"}),de?"Deleting...":"Delete Account"]})]})]})]}),e.jsxs("div",{className:"shrink-0 px-4 sm:px-6 py-3 sm:py-4 border-t border-[#dde3eb] bg-[#edf1f7] flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2 sm:gap-0",children:[e.jsx("p",{className:"text-xs text-slate-500 font-body text-center sm:text-left",children:"MathPulse AI v2.1.0"}),e.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[e.jsx(p,{variant:"outline",onClick:se,className:"rounded-lg border-[#dde3eb] flex-1 sm:flex-none",disabled:B,children:"Cancel"}),e.jsx(p,{onClick:Ee,className:"rounded-lg bg-sky-600 hover:bg-sky-700 text-white flex-1 sm:flex-none",disabled:B,children:B?"Saving...":"Save Changes"})]})]})]})]})]}),Se&&e.jsx(H.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[130] bg-black/50 backdrop-blur-sm flex items-center justify-center p-4",onClick:()=>{v||P(!1)},children:e.jsxs(H.div,{initial:{opacity:0,scale:.95,y:12},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:12},transition:{duration:.2},className:"w-full max-w-md rounded-2xl border border-[#dde3eb] bg-[#f7f9fc] shadow-2xl",onClick:s=>s.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[#dde3eb] px-6 py-4",children:[e.jsxs("h4",{className:"text-lg font-display font-bold text-[#0a1628]",children:[f==="password"&&"Change Password",f==="email"&&"Change Email",f==="delete"&&"Delete Account"]}),e.jsx("button",{onClick:()=>{v||P(!1)},className:"p-2 rounded-xl hover:bg-[#edf1f7] transition-colors","aria-label":"Close",children:e.jsx(Ne,{size:18,className:"text-[#5a6578]"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-4",children:[e.jsx("p",{className:"text-sm text-[#5a6578]",children:"Enter your current password to continue."}),e.jsxs("div",{className:"relative",children:[e.jsx(n,{type:Q?"text":"password",value:L,onChange:s=>xe(s.target.value),placeholder:"Current password",autoFocus:!0,className:"pr-10",disabled:v,onKeyDown:s=>{s.key==="Enter"&&fe()}}),e.jsx("button",{type:"button",onClick:()=>he(!Q),className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600",tabIndex:-1,children:Q?e.jsx(us,{size:16}):e.jsx(bs,{size:16})})]}),f==="password"&&e.jsx("div",{className:"relative",children:e.jsx(n,{type:"password",value:W,onChange:s=>ue(s.target.value),placeholder:"New password (min 8 chars)",disabled:v})}),f==="email"&&e.jsx(n,{type:"email",value:V,onChange:s=>be(s.target.value),placeholder:"New email address",disabled:v}),f==="delete"&&e.jsx("p",{className:"text-sm text-red-600 font-medium",children:"This action is permanent and cannot be undone."}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(p,{variant:"outline",onClick:()=>P(!1),disabled:v,children:"Cancel"}),e.jsx(p,{onClick:()=>void fe(),className:f==="delete"?"bg-red-600 hover:bg-red-700 text-white":"bg-sky-600 hover:bg-sky-700 text-white",disabled:v,children:v?"Processing...":f==="delete"?"Delete Forever":"Confirm"})]})]})]})}),e.jsx(je,{isOpen:we,onClose:()=>I(!1),onConfirm:Re,title:"Reset Testing Data?",message:`Reset ${o} testing data? This will clear quizzes, diagnostic assessments, assessment history, XP, and learning progress. This action cannot be undone.`,confirmText:q?"Resetting...":"Reset Data",cancelText:"Cancel",type:"warning",icon:"warning",zIndexClass:"z-[130]"}),e.jsx(je,{isOpen:Ce,onClose:()=>F(!1),onConfirm:_e,title:"Delete Account?",message:"You will need to re-authenticate to permanently delete your account. This cannot be undone.",confirmText:"Continue",cancelText:"Cancel",type:"danger",icon:"delete",zIndexClass:"z-[130]"})]})}):null};export{rt as default}; diff --git a/assets/Sidebar-CR8IPH6O.js b/assets/Sidebar-BohFsvbI.js similarity index 94% rename from assets/Sidebar-CR8IPH6O.js rename to assets/Sidebar-BohFsvbI.js index 9f4fd7810c633b4b67a016b94bdaf3e36919ee70..ff56adf0121b4ab36367d2cd6fb8abf75505f666 100644 --- a/assets/Sidebar-CR8IPH6O.js +++ b/assets/Sidebar-BohFsvbI.js @@ -1,4 +1,4 @@ -import{r as x,j as e}from"./vendor-react-B4AQeu28.js";import{S as $,a as B,L as u,D,M as G}from"./LogoutActionButton-Cu6gWsBL.js";import{e as z,m as c,o as P,U as M,G as N,b as m,V as q,a2 as F,F as U}from"./index-BvEKrMkD.js";import{T as S,a as L,b as C}from"./tooltip-DDXcKYaB.js";import{X as Q}from"./x-BYtx1i07.js";import{C as V}from"./chevron-right-CbKJd0ln.js";import{C as W}from"./chevron-left-DFU37_wB.js";import{C as A}from"./chart-column-DKW3TTRX.js";import{S as R}from"./shirt-DFiZ2C4J.js";/** +import{r as x,j as e}from"./vendor-react-B4AQeu28.js";import{S as $,a as B,L as u,D,M as G}from"./LogoutActionButton-Baak8j6y.js";import{e as z,m as c,o as P,U as M,G as N,b as m,V as q,a2 as F,F as U}from"./index-BdLfAeGL.js";import{T as S,a as L,b as C}from"./tooltip-Blvwukwg.js";import{X as Q}from"./x-BLhsirCD.js";import{C as V}from"./chevron-right-BRRve0zL.js";import{C as W}from"./chevron-left-CNwzgiLt.js";import{C as A}from"./chart-column-Dl7iJ2BC.js";import{S as R}from"./shirt-iZ6vtR5i.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/SupplementalBanner-CyLKxz9O.js b/assets/SupplementalBanner-BaLhyCv2.js similarity index 97% rename from assets/SupplementalBanner-CyLKxz9O.js rename to assets/SupplementalBanner-BaLhyCv2.js index 69300f4e39fe5309ba3a60599abd3a6760a31f3c..768b39eae3bfe45638dd72ce0ba28d5afda77afb 100644 --- a/assets/SupplementalBanner-CyLKxz9O.js +++ b/assets/SupplementalBanner-BaLhyCv2.js @@ -1 +1 @@ -import{j as e,r as y}from"./vendor-react-B4AQeu28.js";import{h as j,m as p,y as h,b as f,T as m,B as x}from"./index-BvEKrMkD.js";import{X as v}from"./x-BYtx1i07.js";import{S as w}from"./sparkles-av0wSNZT.js";import{C as g}from"./chevron-right-CbKJd0ln.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const b={"General Mathematics":[{label:"Functions Deep Dive",description:"Interactive review of function types and graphs",icon:e.jsx(m,{size:14})},{label:"Business Math Basics",description:"Simple & compound interest practice",icon:e.jsx(f,{size:14})}],"Statistics and Probability":[{label:"Distribution Visualizer",description:"Explore normal distribution curves",icon:e.jsx(m,{size:14})},{label:"Hypothesis Practice",description:"Step-by-step hypothesis testing",icon:e.jsx(x,{size:14})}],"Pre-Calculus":[{label:"Conic Sections Explorer",description:"Visual parabola, ellipse, hyperbola tool",icon:e.jsx(m,{size:14})},{label:"Trig Identity Practice",description:"Identity verification drill set",icon:e.jsx(x,{size:14})}],"Basic Calculus":[{label:"Limits Visualizer",description:"Graphical approach to limits",icon:e.jsx(m,{size:14})},{label:"Derivative Rules Drill",description:"Practice chain rule & implicit diff",icon:e.jsx(x,{size:14})}]};function u(i){const s=i.toLowerCase();return s==="functions"||s.includes("function")||s==="businessmath"||s.includes("business")||s==="logic"||s.includes("reason")||s.includes("general")||s.includes("gen-math")||s.includes("gen math")?"General Mathematics":s.includes("stat")||s.includes("prob")?"Statistics and Probability":s.includes("pre-calc")||s.includes("pre calc")||s.includes("precalc")?"Pre-Calculus":s.includes("basic")||s.includes("calc")?"Basic Calculus":null}function N(i){const s=i.trim().toLowerCase();return s==="functions"?"Functions and Graphs":s==="businessmath"?"Business and Financial Mathematics":s==="logic"?"Logic and Reasoning":i}const k=({atRiskSubjects:i=[],onAction:s,onDismiss:n})=>{const[l,a]=y.useState(!1);if(l||i.length===0)return null;const r=()=>{a(!0),n?.()};return e.jsx(j,{children:!l&&e.jsx(p.div,{initial:{opacity:0,y:-10,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-10,height:0},className:"overflow-hidden",children:e.jsxs("div",{className:"relative bg-gradient-to-r from-sky-600 via-sky-500 to-sky-600 rounded-2xl p-5 text-white shadow-lg shadow-sky-500/20",children:[e.jsx("button",{onClick:r,className:"absolute top-3 right-3 w-7 h-7 bg-white/20 hover:bg-white/30 rounded-full flex items-center justify-center transition-colors",children:e.jsx(v,{size:14})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(w,{size:24})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-lg mb-1",children:"Supplemental Materials Available"}),e.jsx("p",{className:"text-sky-100 text-sm mb-3",children:"Based on your diagnostic assessment, we've identified topics that could use extra practice. Strengthening these areas will improve your overall performance."}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:i.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-white/20 backdrop-blur-sm px-3 py-1 rounded-full text-xs font-semibold",children:[e.jsx(h,{size:12}),N(t)]},t))}),e.jsxs("button",{onClick:s,className:"inline-flex items-center gap-2 bg-white text-sky-600 font-bold text-sm px-4 py-2 rounded-xl hover:bg-sky-50 transition-colors",children:["Review Topics",e.jsx(g,{size:16})]})]})]})]})})})},z=({quizSubject:i,atRiskSubjects:s=[]})=>{const n=i?u(i):null;if(!s.some(r=>{const t=u(r);return t&&t===n})||!n)return null;const a=b[n]||[];return e.jsx(p.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},className:"mb-4 overflow-hidden",children:e.jsxs("div",{className:"bg-gradient-to-r from-rose-50 to-orange-50 border border-rose-200 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(h,{size:14,className:"text-rose-600"}),e.jsxs("span",{className:"text-xs font-bold text-rose-800",children:["Supplemental Focus Area — ",n]})]}),e.jsx("p",{className:"text-xs text-rose-700 mb-2",children:"This topic was flagged in your diagnostic. Take your time and review the explanations carefully."}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.slice(0,2).map((r,t)=>e.jsxs("span",{className:"inline-flex items-center gap-1 bg-rose-100 text-rose-700 px-2 py-0.5 rounded-md text-xs font-medium",children:[r.icon,r.label]},t))})]})})},C=({quizSubject:i,quizScore:s=0,atRiskSubjects:n=[],onAction:l})=>{const a=i?u(i):null,r=n.some(c=>{const d=u(c);return d&&d===a});if(s>=70&&!r)return null;const t=a?b[a]||[]:[],o=s<70;return e.jsx(p.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.5},className:"mt-4",children:e.jsx("div",{className:`rounded-2xl p-4 border-2 ${o?"bg-orange-50 border-orange-200":"bg-sky-50 border-sky-200"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${o?"bg-orange-500":"bg-sky-500"}`,children:e.jsx(f,{size:20,className:"text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-display font-bold text-[#0a1628] text-sm mb-1",children:o?"Review Recommended":"Supplemental Materials"}),e.jsx("p",{className:"text-xs text-[#5a6578] mb-2",children:o?`You scored ${s}% on this quiz. We recommend reviewing the following resources to strengthen your understanding.`:"This topic was identified as an area for growth. Check out these additional resources."}),t.length>0&&e.jsx("div",{className:"space-y-1.5 mb-3",children:t.map((c,d)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:`w-5 h-5 rounded flex items-center justify-center ${o?"bg-orange-100 text-orange-600":"bg-sky-100 text-sky-600"}`,children:c.icon}),e.jsx("span",{className:"font-medium text-[#0a1628]",children:c.label}),e.jsxs("span",{className:"text-slate-500",children:["— ",c.description]})]},d))}),l&&e.jsxs("button",{onClick:l,className:`inline-flex items-center gap-1.5 text-xs font-bold px-3 py-1.5 rounded-lg transition-colors ${o?"bg-orange-500 hover:bg-orange-600 text-white":"bg-sky-500 hover:bg-sky-600 text-white"}`,children:["Review Topics",e.jsx(g,{size:12})]})]})]})})})},I=i=>{switch(i.variant){case"compact":return e.jsx(z,{...i});case"results":return e.jsx(C,{...i});case"full":default:return e.jsx(k,{...i})}};export{I as default}; +import{j as e,r as y}from"./vendor-react-B4AQeu28.js";import{h as j,m as p,y as h,b as f,T as m,B as x}from"./index-BdLfAeGL.js";import{X as v}from"./x-BLhsirCD.js";import{S as w}from"./sparkles-DnAkO9TX.js";import{C as g}from"./chevron-right-BRRve0zL.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const b={"General Mathematics":[{label:"Functions Deep Dive",description:"Interactive review of function types and graphs",icon:e.jsx(m,{size:14})},{label:"Business Math Basics",description:"Simple & compound interest practice",icon:e.jsx(f,{size:14})}],"Statistics and Probability":[{label:"Distribution Visualizer",description:"Explore normal distribution curves",icon:e.jsx(m,{size:14})},{label:"Hypothesis Practice",description:"Step-by-step hypothesis testing",icon:e.jsx(x,{size:14})}],"Pre-Calculus":[{label:"Conic Sections Explorer",description:"Visual parabola, ellipse, hyperbola tool",icon:e.jsx(m,{size:14})},{label:"Trig Identity Practice",description:"Identity verification drill set",icon:e.jsx(x,{size:14})}],"Basic Calculus":[{label:"Limits Visualizer",description:"Graphical approach to limits",icon:e.jsx(m,{size:14})},{label:"Derivative Rules Drill",description:"Practice chain rule & implicit diff",icon:e.jsx(x,{size:14})}]};function u(i){const s=i.toLowerCase();return s==="functions"||s.includes("function")||s==="businessmath"||s.includes("business")||s==="logic"||s.includes("reason")||s.includes("general")||s.includes("gen-math")||s.includes("gen math")?"General Mathematics":s.includes("stat")||s.includes("prob")?"Statistics and Probability":s.includes("pre-calc")||s.includes("pre calc")||s.includes("precalc")?"Pre-Calculus":s.includes("basic")||s.includes("calc")?"Basic Calculus":null}function N(i){const s=i.trim().toLowerCase();return s==="functions"?"Functions and Graphs":s==="businessmath"?"Business and Financial Mathematics":s==="logic"?"Logic and Reasoning":i}const k=({atRiskSubjects:i=[],onAction:s,onDismiss:n})=>{const[l,a]=y.useState(!1);if(l||i.length===0)return null;const r=()=>{a(!0),n?.()};return e.jsx(j,{children:!l&&e.jsx(p.div,{initial:{opacity:0,y:-10,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-10,height:0},className:"overflow-hidden",children:e.jsxs("div",{className:"relative bg-gradient-to-r from-sky-600 via-sky-500 to-sky-600 rounded-2xl p-5 text-white shadow-lg shadow-sky-500/20",children:[e.jsx("button",{onClick:r,className:"absolute top-3 right-3 w-7 h-7 bg-white/20 hover:bg-white/30 rounded-full flex items-center justify-center transition-colors",children:e.jsx(v,{size:14})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(w,{size:24})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-lg mb-1",children:"Supplemental Materials Available"}),e.jsx("p",{className:"text-sky-100 text-sm mb-3",children:"Based on your diagnostic assessment, we've identified topics that could use extra practice. Strengthening these areas will improve your overall performance."}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:i.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-white/20 backdrop-blur-sm px-3 py-1 rounded-full text-xs font-semibold",children:[e.jsx(h,{size:12}),N(t)]},t))}),e.jsxs("button",{onClick:s,className:"inline-flex items-center gap-2 bg-white text-sky-600 font-bold text-sm px-4 py-2 rounded-xl hover:bg-sky-50 transition-colors",children:["Review Topics",e.jsx(g,{size:16})]})]})]})]})})})},z=({quizSubject:i,atRiskSubjects:s=[]})=>{const n=i?u(i):null;if(!s.some(r=>{const t=u(r);return t&&t===n})||!n)return null;const a=b[n]||[];return e.jsx(p.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},className:"mb-4 overflow-hidden",children:e.jsxs("div",{className:"bg-gradient-to-r from-rose-50 to-orange-50 border border-rose-200 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(h,{size:14,className:"text-rose-600"}),e.jsxs("span",{className:"text-xs font-bold text-rose-800",children:["Supplemental Focus Area — ",n]})]}),e.jsx("p",{className:"text-xs text-rose-700 mb-2",children:"This topic was flagged in your diagnostic. Take your time and review the explanations carefully."}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.slice(0,2).map((r,t)=>e.jsxs("span",{className:"inline-flex items-center gap-1 bg-rose-100 text-rose-700 px-2 py-0.5 rounded-md text-xs font-medium",children:[r.icon,r.label]},t))})]})})},C=({quizSubject:i,quizScore:s=0,atRiskSubjects:n=[],onAction:l})=>{const a=i?u(i):null,r=n.some(c=>{const d=u(c);return d&&d===a});if(s>=70&&!r)return null;const t=a?b[a]||[]:[],o=s<70;return e.jsx(p.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.5},className:"mt-4",children:e.jsx("div",{className:`rounded-2xl p-4 border-2 ${o?"bg-orange-50 border-orange-200":"bg-sky-50 border-sky-200"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${o?"bg-orange-500":"bg-sky-500"}`,children:e.jsx(f,{size:20,className:"text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-display font-bold text-[#0a1628] text-sm mb-1",children:o?"Review Recommended":"Supplemental Materials"}),e.jsx("p",{className:"text-xs text-[#5a6578] mb-2",children:o?`You scored ${s}% on this quiz. We recommend reviewing the following resources to strengthen your understanding.`:"This topic was identified as an area for growth. Check out these additional resources."}),t.length>0&&e.jsx("div",{className:"space-y-1.5 mb-3",children:t.map((c,d)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:`w-5 h-5 rounded flex items-center justify-center ${o?"bg-orange-100 text-orange-600":"bg-sky-100 text-sky-600"}`,children:c.icon}),e.jsx("span",{className:"font-medium text-[#0a1628]",children:c.label}),e.jsxs("span",{className:"text-slate-500",children:["— ",c.description]})]},d))}),l&&e.jsxs("button",{onClick:l,className:`inline-flex items-center gap-1.5 text-xs font-bold px-3 py-1.5 rounded-lg transition-colors ${o?"bg-orange-500 hover:bg-orange-600 text-white":"bg-sky-500 hover:bg-sky-600 text-white"}`,children:["Review Topics",e.jsx(g,{size:12})]})]})]})})})},I=i=>{switch(i.variant){case"compact":return e.jsx(z,{...i});case"results":return e.jsx(C,{...i});case"full":default:return e.jsx(k,{...i})}};export{I as default}; diff --git a/assets/SupplementalPillCarousel-D522wnTT.js b/assets/SupplementalPillCarousel-EeBQ4OFw.js similarity index 99% rename from assets/SupplementalPillCarousel-D522wnTT.js rename to assets/SupplementalPillCarousel-EeBQ4OFw.js index e90a709430aa7e5105d1e6d31fb63622a7b93829..bf03302b0067e984d0c885922c1cc9f7fca1ffb1 100644 --- a/assets/SupplementalPillCarousel-D522wnTT.js +++ b/assets/SupplementalPillCarousel-EeBQ4OFw.js @@ -1,4 +1,4 @@ -import{d as o,r as U,j as r}from"./vendor-react-B4AQeu28.js";import{o as se,h as Qe,m as Ie,y as Se,a as jt,L as Ze,I as et}from"./index-BvEKrMkD.js";import{f as Dt}from"./deepseekRagService-Bke9fSTt.js";import{T as Nt,D as Ot,d as It,b as At,c as _t,P as kt,O as Pt}from"./vendor-radix-C5nwdvGr.js";import{w as $t}from"./moduleWatchService-Boczzqau.js";import{C as Lt}from"./circle-alert-fPu7cawt.js";import{a as Bt,C as Ft}from"./chevron-up-CDr90bpM.js";import{B as Gt}from"./bell-C57aSZcx.js";import{C as tt}from"./clock-0vnF72R6.js";import{C as Ve}from"./chevron-right-CbKJd0ln.js";import{S as Ht}from"./sparkles-av0wSNZT.js";import{X as qt}from"./x-BYtx1i07.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const ke=[{topicId:"gm-q1-business-finance",label:"Business and Finance",subjectId:"gen-math",quarter:1,competencyCodes:["GM11-BF-1","GM11-BF-2","GM11-BF-3"]},{topicId:"gm-q1-patterns-sequences-series",label:"Patterns, Sequences, and Series",subjectId:"gen-math",quarter:1,competencyCodes:["GM11-PSS-1","GM11-PSS-2","GM11-PSS-3"]},{topicId:"gm-q1-financial-application-sequences-series",label:"Financial Application of Sequences and Series",subjectId:"gen-math",quarter:1,competencyCodes:["GM11-FASS-1","GM11-FASS-2"]},{topicId:"gm-q2-measurement-conversion",label:"Measurement and Conversion",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-MC-1","GM11-MC-2"]},{topicId:"gm-q2-functions-graphs",label:"Functions and Their Graphs",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-FG-1","GM11-FG-2","GM11-FG-3","M11GM-Ia-2","M11GM-Ib-5","M11GM-Id-2","M11GM-Ie-f-1","M11GM-Ii-4"]},{topicId:"gm-q2-piecewise-functions",label:"Piecewise Functions",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-PF-1","GM11-PF-2"]},{topicId:"gm-q2-statistical-variables",label:"Statistical Variables",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-SV-1","GM11-SV-2"]},{topicId:"gm-q3-basic-trigonometry",label:"Basic Trigonometry",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-BT-1","GM11-BT-2"]},{topicId:"gm-q3-practical-applications-measurement",label:"Practical Applications of Measurement",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-PAM-1","GM11-PAM-2","M11GM-IIa-b-1","M11GM-IIa-2","M11GM-IIc-d-1","M11GM-IIf-3"]},{topicId:"gm-q3-transformational-geometry-volume-capacity",label:"Transformational Geometry / Volume and Capacity",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-TGVC-1","GM11-TGVC-2"]},{topicId:"gm-q3-random-variables-sampling",label:"Random Variables and Sampling",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-RVS-1","GM11-RVS-2","GM11-RVS-3"]},{topicId:"gm-q4-compound-interest-annuities-loans",label:"Compound Interest, Annuities, and Loans",subjectId:"gen-math",quarter:4,competencyCodes:["GM11-CIAL-1","GM11-CIAL-2","GM11-CIAL-3"]},{topicId:"gm-q4-hypothesis-testing-regression",label:"Hypothesis Testing and Regression",subjectId:"gen-math",quarter:4,competencyCodes:["GM11-HTR-1","GM11-HTR-2"]},{topicId:"gm-q4-propositions-syllogisms-fallacies",label:"Logical Propositions, Syllogisms, and Fallacies",subjectId:"gen-math",quarter:4,competencyCodes:["GM11-PSF-1","GM11-PSF-2","GM11-PSF-3","M11GM-IIg-1","M11GM-IIh-1","M11GM-IIi-1","M11GM-IIi-2","M11GM-IIj-1"]}];for(const e of ke)for(const n of e.competencyCodes)e.topicId;const zt={};for(const e of ke)zt[e.topicId]=e;const nt={};for(const e of ke)nt[e.topicId]=e.label;function Ut(e){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",n.appendChild(t),t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}const rt=o.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),he=()=>{const e=o.useContext(rt);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};Ut(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not( +import{d as o,r as U,j as r}from"./vendor-react-B4AQeu28.js";import{o as se,h as Qe,m as Ie,y as Se,a as jt,L as Ze,I as et}from"./index-BdLfAeGL.js";import{f as Dt}from"./deepseekRagService-Bke9fSTt.js";import{T as Nt,D as Ot,d as It,b as At,c as _t,P as kt,O as Pt}from"./vendor-radix-C5nwdvGr.js";import{w as $t}from"./moduleWatchService-Ck2BKbab.js";import{C as Lt}from"./circle-alert-ByVTnT3r.js";import{a as Bt,C as Ft}from"./chevron-up-uSn_SWll.js";import{B as Gt}from"./bell-C5_RRTsA.js";import{C as tt}from"./clock-CpBwkoND.js";import{C as Ve}from"./chevron-right-BRRve0zL.js";import{S as Ht}from"./sparkles-DnAkO9TX.js";import{X as qt}from"./x-BLhsirCD.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const ke=[{topicId:"gm-q1-business-finance",label:"Business and Finance",subjectId:"gen-math",quarter:1,competencyCodes:["GM11-BF-1","GM11-BF-2","GM11-BF-3"]},{topicId:"gm-q1-patterns-sequences-series",label:"Patterns, Sequences, and Series",subjectId:"gen-math",quarter:1,competencyCodes:["GM11-PSS-1","GM11-PSS-2","GM11-PSS-3"]},{topicId:"gm-q1-financial-application-sequences-series",label:"Financial Application of Sequences and Series",subjectId:"gen-math",quarter:1,competencyCodes:["GM11-FASS-1","GM11-FASS-2"]},{topicId:"gm-q2-measurement-conversion",label:"Measurement and Conversion",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-MC-1","GM11-MC-2"]},{topicId:"gm-q2-functions-graphs",label:"Functions and Their Graphs",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-FG-1","GM11-FG-2","GM11-FG-3","M11GM-Ia-2","M11GM-Ib-5","M11GM-Id-2","M11GM-Ie-f-1","M11GM-Ii-4"]},{topicId:"gm-q2-piecewise-functions",label:"Piecewise Functions",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-PF-1","GM11-PF-2"]},{topicId:"gm-q2-statistical-variables",label:"Statistical Variables",subjectId:"gen-math",quarter:2,competencyCodes:["GM11-SV-1","GM11-SV-2"]},{topicId:"gm-q3-basic-trigonometry",label:"Basic Trigonometry",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-BT-1","GM11-BT-2"]},{topicId:"gm-q3-practical-applications-measurement",label:"Practical Applications of Measurement",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-PAM-1","GM11-PAM-2","M11GM-IIa-b-1","M11GM-IIa-2","M11GM-IIc-d-1","M11GM-IIf-3"]},{topicId:"gm-q3-transformational-geometry-volume-capacity",label:"Transformational Geometry / Volume and Capacity",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-TGVC-1","GM11-TGVC-2"]},{topicId:"gm-q3-random-variables-sampling",label:"Random Variables and Sampling",subjectId:"gen-math",quarter:3,competencyCodes:["GM11-RVS-1","GM11-RVS-2","GM11-RVS-3"]},{topicId:"gm-q4-compound-interest-annuities-loans",label:"Compound Interest, Annuities, and Loans",subjectId:"gen-math",quarter:4,competencyCodes:["GM11-CIAL-1","GM11-CIAL-2","GM11-CIAL-3"]},{topicId:"gm-q4-hypothesis-testing-regression",label:"Hypothesis Testing and Regression",subjectId:"gen-math",quarter:4,competencyCodes:["GM11-HTR-1","GM11-HTR-2"]},{topicId:"gm-q4-propositions-syllogisms-fallacies",label:"Logical Propositions, Syllogisms, and Fallacies",subjectId:"gen-math",quarter:4,competencyCodes:["GM11-PSF-1","GM11-PSF-2","GM11-PSF-3","M11GM-IIg-1","M11GM-IIh-1","M11GM-IIi-1","M11GM-IIi-2","M11GM-IIj-1"]}];for(const e of ke)for(const n of e.competencyCodes)e.topicId;const zt={};for(const e of ke)zt[e.topicId]=e;const nt={};for(const e of ke)nt[e.topicId]=e.label;function Ut(e){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",n.appendChild(t),t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}const rt=o.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),he=()=>{const e=o.useContext(rt);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};Ut(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not( [data-state=closed] ){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function Wt(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function Vt(){return Pe(/^Mac/)}function Yt(){return Pe(/^iPhone/)}function Ye(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Xt(){return Pe(/^iPad/)||Vt()&&navigator.maxTouchPoints>1}function at(){return Yt()||Xt()}function Pe(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const Kt=24,Jt=typeof window<"u"?U.useLayoutEffect:U.useEffect;function Xe(...e){return(...n)=>{for(let t of e)typeof t=="function"&&t(...n)}}const je=typeof document<"u"&&window.visualViewport;function Ke(e){let n=window.getComputedStyle(e);return/(auto|scroll)/.test(n.overflow+n.overflowX+n.overflowY)}function ot(e){for(Ke(e)&&(e=e.parentElement);e&&!Ke(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Qt=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let be=0,De;function Zt(e={}){let{isDisabled:n}=e;Jt(()=>{if(!n)return be++,be===1&&at()&&(De=en()),()=>{be--,be===0&&De?.()}},[n])}function en(){let e,n=0,t=m=>{e=ot(m.target),!(e===document.documentElement&&e===document.body)&&(n=m.changedTouches[0].pageY)},i=m=>{if(!e||e===document.documentElement||e===document.body){m.preventDefault();return}let c=m.changedTouches[0].pageY,$=e.scrollTop,I=e.scrollHeight-e.clientHeight;I!==0&&(($<=0&&c>n||$>=I&&c{let c=m.target;Ae(c)&&c!==document.activeElement&&(m.preventDefault(),c.style.transform="translateY(-2000px)",c.focus(),requestAnimationFrame(()=>{c.style.transform=""}))},a=m=>{let c=m.target;Ae(c)&&(c.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{c.style.transform="",je&&(je.height{Je(c)}):je.addEventListener("resize",()=>Je(c),{once:!0}))}))},h=()=>{window.scrollTo(0,0)},w=window.pageXOffset,y=window.pageYOffset,S=Xe(tn(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let v=Xe(me(document,"touchstart",t,{passive:!1,capture:!0}),me(document,"touchmove",i,{passive:!1,capture:!0}),me(document,"touchend",s,{passive:!1,capture:!0}),me(document,"focus",a,!0),me(window,"scroll",h));return()=>{S(),v(),window.scrollTo(w,y)}}function tn(e,n,t){let i=e.style[n];return e.style[n]=t,()=>{e.style[n]=i}}function me(e,n,t,i){return e.addEventListener(n,t,i),()=>{e.removeEventListener(n,t,i)}}function Je(e){let n=document.scrollingElement||document.documentElement;for(;e&&e!==n;){let t=ot(e);if(t!==document.documentElement&&t!==document.body&&t!==e){let i=t.getBoundingClientRect().top,s=e.getBoundingClientRect().top,a=e.getBoundingClientRect().bottom;const h=t.getBoundingClientRect().bottom+Kt;a>h&&(t.scrollTop+=s-i)}e=t.parentElement}}function Ae(e){return e instanceof HTMLInputElement&&!Qt.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function nn(e,n){typeof e=="function"?e(n):e!=null&&(e.current=n)}function rn(...e){return n=>e.forEach(t=>nn(t,n))}function it(...e){return U.useCallback(rn(...e),e)}const st=new WeakMap;function L(e,n,t=!1){if(!e||!(e instanceof HTMLElement))return;let i={};Object.entries(n).forEach(([s,a])=>{if(s.startsWith("--")){e.style.setProperty(s,a);return}i[s]=e.style[s],e.style[s]=a}),!t&&st.set(e,i)}function an(e,n){if(!e||!(e instanceof HTMLElement))return;let t=st.get(e);t&&(e.style[n]=t[n])}const P=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function xe(e,n){if(!e)return null;const t=window.getComputedStyle(e),i=t.transform||t.webkitTransform||t.mozTransform;let s=i.match(/^matrix3d\((.+)\)$/);return s?parseFloat(s[1].split(", ")[P(n)?13:12]):(s=i.match(/^matrix\((.+)\)$/),s?parseFloat(s[1].split(", ")[P(n)?5:4]):null)}function on(e){return 8*(Math.log(e+1)-2)}function Ne(e,n){if(!e)return()=>{};const t=e.style.cssText;return Object.assign(e.style,n),()=>{e.style.cssText=t}}function sn(...e){return(...n)=>{for(const t of e)typeof t=="function"&&t(...n)}}const D={DURATION:.5,EASE:[.32,.72,0,1]},lt=.4,ln=.25,cn=100,ct=8,ne=16,_e=26,Oe="vaul-dragging";function ut(e){const n=o.useRef(e);return o.useEffect(()=>{n.current=e}),o.useMemo(()=>(...t)=>n.current==null?void 0:n.current.call(n,...t),[])}function un({defaultProp:e,onChange:n}){const t=o.useState(e),[i]=t,s=o.useRef(i),a=ut(n);return o.useEffect(()=>{s.current!==i&&(a(i),s.current=i)},[i,s,a]),t}function dt({prop:e,defaultProp:n,onChange:t=()=>{}}){const[i,s]=un({defaultProp:n,onChange:t}),a=e!==void 0,h=a?e:i,w=ut(t),y=o.useCallback(S=>{if(a){const m=typeof S=="function"?S(e):S;m!==e&&w(m)}else s(S)},[a,e,s,w]);return[h,y]}function dn({activeSnapPointProp:e,setActiveSnapPointProp:n,snapPoints:t,drawerRef:i,overlayRef:s,fadeFromIndex:a,onSnapPointChange:h,direction:w="bottom",container:y,snapToSequentialPoint:S}){const[v,m]=dt({prop:e,defaultProp:t?.[0],onChange:n}),[c,$]=o.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);o.useEffect(()=>{function p(){$({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]);const I=o.useMemo(()=>v===t?.[t.length-1]||null,[t,v]),M=o.useMemo(()=>{var p;return(p=t?.findIndex(R=>R===v))!=null?p:null},[t,v]),F=t&&t.length>0&&(a||a===0)&&!Number.isNaN(a)&&t[a]===v||!t,f=o.useMemo(()=>{const p=y?{width:y.getBoundingClientRect().width,height:y.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var R;return(R=t?.map(x=>{const G=typeof x=="string";let B=0;if(G&&(B=parseInt(x,10)),P(w)){const u=G?B:c?x*p.height:0;return c?w==="bottom"?p.height-u:-p.height+u:u}const H=G?B:c?x*p.width:0;return c?w==="right"?p.width-H:-p.width+H:H}))!=null?R:[]},[t,c,y]),A=o.useMemo(()=>M!==null?f?.[M]:null,[f,M]),N=o.useCallback(p=>{var R;const x=(R=f?.findIndex(G=>G===p))!=null?R:null;h(x),L(i.current,{transition:`transform ${D.DURATION}s cubic-bezier(${D.EASE.join(",")})`,transform:P(w)?`translate3d(0, ${p}px, 0)`:`translate3d(${p}px, 0, 0)`}),f&&x!==f.length-1&&a!==void 0&&x!==a&&x{if(v||e){var p;const R=(p=t?.findIndex(x=>x===e||x===v))!=null?p:-1;f&&R!==-1&&typeof f[R]=="number"&&N(f[R])}},[v,e,t,f,N]);function l({draggedDistance:p,closeDrawer:R,velocity:x,dismissible:G}){if(a===void 0)return;const B=w==="bottom"||w==="right"?(A??0)-p:(A??0)+p,H=M===a-1,u=M===0,b=p>0;if(H&&L(s.current,{transition:`opacity ${D.DURATION}s cubic-bezier(${D.EASE.join(",")})`}),!S&&x>2&&!b){G?R():N(f[0]);return}if(!S&&x>2&&b&&f&&t){N(f[t.length-1]);return}const j=f?.reduce((_,W)=>typeof _!="number"||typeof W!="number"?_:Math.abs(W-B)lt&&Math.abs(p)0&&I&&t){N(f[t.length-1]);return}if(u&&_<0&&G&&R(),M===null)return;N(f[M+_]);return}N(j)}function V({draggedDistance:p}){if(A===null)return;const R=w==="bottom"||w==="right"?A-p:A+p;(w==="bottom"||w==="right")&&Rf[f.length-1]||L(i.current,{transform:P(w)?`translate3d(0, ${R}px, 0)`:`translate3d(${R}px, 0, 0)`})}function X(p,R){if(!t||typeof M!="number"||!f||a===void 0)return null;const x=M===a-1;if(M>=a&&R)return 0;if(x&&!R)return 1;if(!F&&!x)return null;const B=x?M+1:M-1,H=x?f[B]-f[B-1]:f[B+1]-f[B],u=p/Math.abs(H);return x?1-u:u}return{isLastSnapPoint:I,activeSnapPoint:v,shouldFade:F,getPercentageDragged:X,setActiveSnapPoint:m,activeSnapPointIndex:M,onRelease:l,onDrag:V,snapPointsOffset:f}}const fn=()=>()=>{};function mn(){const{direction:e,isOpen:n,shouldScaleBackground:t,setBackgroundColorOnScale:i,noBodyStyles:s}=he(),a=o.useRef(null),h=U.useMemo(()=>document.body.style.backgroundColor,[]);function w(){return(window.innerWidth-_e)/window.innerWidth}o.useEffect(()=>{if(n&&t){a.current&&clearTimeout(a.current);const y=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!y)return;sn(i&&!s?Ne(document.body,{background:"black"}):fn,Ne(y,{transformOrigin:P(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${D.DURATION}s`,transitionTimingFunction:`cubic-bezier(${D.EASE.join(",")})`}));const S=Ne(y,{borderRadius:`${ct}px`,overflow:"hidden",...P(e)?{transform:`scale(${w()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${w()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{S(),a.current=window.setTimeout(()=>{h?document.body.style.background=h:document.body.style.removeProperty("background")},D.DURATION*1e3)}}},[n,t,h])}let pe=null;function pn({isOpen:e,modal:n,nested:t,hasBeenOpened:i,preventScrollRestoration:s,noBodyStyles:a}){const[h,w]=o.useState(()=>typeof window<"u"?window.location.href:""),y=o.useRef(0),S=o.useCallback(()=>{if(Ye()&&pe===null&&e&&!a){pe={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:m,innerHeight:c}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-y.current}px`,left:`${-m}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const $=c-window.innerHeight;$&&y.current>=c&&(document.body.style.top=`${-(y.current+$)}px`)}),300)}},[e]),v=o.useCallback(()=>{if(Ye()&&pe!==null&&!a){const m=-parseInt(document.body.style.top,10),c=-parseInt(document.body.style.left,10);Object.assign(document.body.style,pe),window.requestAnimationFrame(()=>{if(s&&h!==window.location.href){w(window.location.href);return}window.scrollTo(c,m)}),pe=null}},[h]);return o.useEffect(()=>{function m(){y.current=window.scrollY}return m(),window.addEventListener("scroll",m),()=>{window.removeEventListener("scroll",m)}},[]),o.useEffect(()=>{if(n)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||v()}},[n,v]),o.useEffect(()=>{t||!i||(e?(!window.matchMedia("(display-mode: standalone)").matches&&S(),n||window.setTimeout(()=>{v()},500)):v())},[e,i,h,n,t,S,v]),{restorePositionSetting:v}}function hn({open:e,onOpenChange:n,children:t,onDrag:i,onRelease:s,snapPoints:a,shouldScaleBackground:h=!1,setBackgroundColorOnScale:w=!0,closeThreshold:y=ln,scrollLockTimeout:S=cn,dismissible:v=!0,handleOnly:m=!1,fadeFromIndex:c=a&&a.length-1,activeSnapPoint:$,setActiveSnapPoint:I,fixed:M,modal:F=!0,onClose:f,nested:A,noBodyStyles:N=!1,direction:l="bottom",defaultOpen:V=!1,disablePreventScroll:X=!0,snapToSequentialPoint:p=!1,preventScrollRestoration:R=!1,repositionInputs:x=!0,onAnimationEnd:G,container:B,autoFocus:H=!1}){var u,b;const[j=!1,O]=dt({defaultProp:V,prop:e,onChange:d=>{n?.(d),!d&&!A&&xt(),setTimeout(()=>{G?.(d)},D.DURATION*1e3),d&&!F&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),d||(document.body.style.pointerEvents="auto")}}),[_,W]=o.useState(!1),[Q,le]=o.useState(!1),[pt,$e]=o.useState(!1),ae=o.useRef(null),ge=o.useRef(null),Te=o.useRef(null),Re=o.useRef(null),ce=o.useRef(null),ue=o.useRef(!1),Ce=o.useRef(null),Me=o.useRef(0),oe=o.useRef(!1),Le=o.useRef(!V),Be=o.useRef(0),g=o.useRef(null),Fe=o.useRef(((u=g.current)==null?void 0:u.getBoundingClientRect().height)||0),Ge=o.useRef(((b=g.current)==null?void 0:b.getBoundingClientRect().width)||0),Ee=o.useRef(0),ht=o.useCallback(d=>{a&&d===de.length-1&&(ge.current=new Date)},[]),{activeSnapPoint:gt,activeSnapPointIndex:ie,setActiveSnapPoint:He,onRelease:wt,snapPointsOffset:de,onDrag:vt,shouldFade:qe,getPercentageDragged:bt}=dn({snapPoints:a,activeSnapPointProp:$,setActiveSnapPointProp:I,drawerRef:g,fadeFromIndex:c,overlayRef:ae,onSnapPointChange:ht,direction:l,container:B,snapToSequentialPoint:p});Zt({isDisabled:!j||Q||!F||pt||!_||!x||!X});const{restorePositionSetting:xt}=pn({isOpen:j,modal:F,nested:A??!1,hasBeenOpened:_,preventScrollRestoration:R,noBodyStyles:N});function we(){return(window.innerWidth-_e)/window.innerWidth}function yt(d){var C,E;!v&&!a||g.current&&!g.current.contains(d.target)||(Fe.current=((C=g.current)==null?void 0:C.getBoundingClientRect().height)||0,Ge.current=((E=g.current)==null?void 0:E.getBoundingClientRect().width)||0,le(!0),Te.current=new Date,at()&&window.addEventListener("touchend",()=>ue.current=!1,{once:!0}),d.target.setPointerCapture(d.pointerId),Me.current=P(l)?d.pageY:d.pageX)}function ze(d,C){var E;let T=d;const k=(E=window.getSelection())==null?void 0:E.toString(),z=g.current?xe(g.current,l):null,q=new Date;if(T.tagName==="SELECT"||T.hasAttribute("data-vaul-no-drag")||T.closest("[data-vaul-no-drag]"))return!1;if(l==="right"||l==="left")return!0;if(ge.current&&q.getTime()-ge.current.getTime()<500)return!1;if(z!==null&&(l==="bottom"?z>0:z<0))return!0;if(k&&k.length>0)return!1;if(ce.current&&q.getTime()-ce.current.getTime()T.clientHeight){if(T.scrollTop!==0)return ce.current=new Date,!1;if(T.getAttribute("role")==="dialog")return!0}T=T.parentNode}return!0}function St(d){if(g.current&&Q){const C=l==="bottom"||l==="right"?1:-1,E=(Me.current-(P(l)?d.pageY:d.pageX))*C,T=E>0,k=a&&!v&&!T;if(k&&ie===0)return;const z=Math.abs(E),q=document.querySelector("[data-vaul-drawer-wrapper]"),Z=l==="bottom"||l==="top"?Fe.current:Ge.current;let Y=z/Z;const te=bt(z,T);if(te!==null&&(Y=te),k&&Y>=1||!ue.current&&!ze(d.target,T))return;if(g.current.classList.add(Oe),ue.current=!0,L(g.current,{transition:"none"}),L(ae.current,{transition:"none"}),a&&vt({draggedDistance:E}),T&&!a){const K=on(E),ve=Math.min(K*-1,0)*C;L(g.current,{transform:P(l)?`translate3d(0, ${ve}px, 0)`:`translate3d(${ve}px, 0, 0)`});return}const ee=1-Y;if((qe||c&&ie===c-1)&&(i?.(d,Y),L(ae.current,{opacity:`${ee}`,transition:"none"},!0)),q&&ae.current&&h){const K=Math.min(we()+Y*(1-we()),1),ve=8-Y*8,We=Math.max(0,14-Y*14);L(q,{borderRadius:`${ve}px`,transform:P(l)?`scale(${K}) translate3d(0, ${We}px, 0)`:`scale(${K}) translate3d(${We}px, 0, 0)`,transition:"none"},!0)}if(!a){const K=z*C;L(g.current,{transform:P(l)?`translate3d(0, ${K}px, 0)`:`translate3d(${K}px, 0, 0)`})}}}o.useEffect(()=>{window.requestAnimationFrame(()=>{Le.current=!0})},[]),o.useEffect(()=>{var d;function C(){if(!g.current||!x)return;const E=document.activeElement;if(Ae(E)||oe.current){var T;const k=((T=window.visualViewport)==null?void 0:T.height)||0,z=window.innerHeight;let q=z-k;const Z=g.current.getBoundingClientRect().height||0,Y=Z>z*.8;Ee.current||(Ee.current=Z);const te=g.current.getBoundingClientRect().top;if(Math.abs(Be.current-q)>60&&(oe.current=!oe.current),a&&a.length>0&&de&&ie){const ee=de[ie]||0;q+=ee}if(Be.current=q,Z>k||oe.current){const ee=g.current.getBoundingClientRect().height;let K=ee;ee>k&&(K=k-(Y?te:_e)),M?g.current.style.height=`${ee-Math.max(q,0)}px`:g.current.style.height=`${Math.max(K,k-te)}px`}else Wt()||(g.current.style.height=`${Ee.current}px`);a&&a.length>0&&!oe.current?g.current.style.bottom="0px":g.current.style.bottom=`${Math.max(q,0)}px`}}return(d=window.visualViewport)==null||d.addEventListener("resize",C),()=>{var E;return(E=window.visualViewport)==null?void 0:E.removeEventListener("resize",C)}},[ie,a,de]);function fe(d){Tt(),f?.(),d||O(!1),setTimeout(()=>{a&&He(a[0])},D.DURATION*1e3)}function Ue(){if(!g.current)return;const d=document.querySelector("[data-vaul-drawer-wrapper]"),C=xe(g.current,l);L(g.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${D.DURATION}s cubic-bezier(${D.EASE.join(",")})`}),L(ae.current,{transition:`opacity ${D.DURATION}s cubic-bezier(${D.EASE.join(",")})`,opacity:"1"}),h&&C&&C>0&&j&&L(d,{borderRadius:`${ct}px`,overflow:"hidden",...P(l)?{transform:`scale(${we()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${we()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${D.DURATION}s`,transitionTimingFunction:`cubic-bezier(${D.EASE.join(",")})`},!0)}function Tt(){!Q||!g.current||(g.current.classList.remove(Oe),ue.current=!1,le(!1),Re.current=new Date)}function Rt(d){if(!Q||!g.current)return;g.current.classList.remove(Oe),ue.current=!1,le(!1),Re.current=new Date;const C=xe(g.current,l);if(!d||!ze(d.target,!1)||!C||Number.isNaN(C)||Te.current===null)return;const E=Re.current.getTime()-Te.current.getTime(),T=Me.current-(P(l)?d.pageY:d.pageX),k=Math.abs(T)/E;if(k>.05&&($e(!0),setTimeout(()=>{$e(!1)},200)),a){wt({draggedDistance:T*(l==="bottom"||l==="right"?1:-1),closeDrawer:fe,velocity:k,dismissible:v}),s?.(d,!0);return}if(l==="bottom"||l==="right"?T>0:T<0){Ue(),s?.(d,!0);return}if(k>lt){fe(),s?.(d,!1);return}var z;const q=Math.min((z=g.current.getBoundingClientRect().height)!=null?z:0,window.innerHeight);var Z;const Y=Math.min((Z=g.current.getBoundingClientRect().width)!=null?Z:0,window.innerWidth),te=l==="left"||l==="right";if(Math.abs(C)>=(te?Y:q)*y){fe(),s?.(d,!1);return}s?.(d,!0),Ue()}o.useEffect(()=>(j&&(L(document.documentElement,{scrollBehavior:"auto"}),ge.current=new Date),()=>{an(document.documentElement,"scrollBehavior")}),[j]);function Ct(d){const C=d?(window.innerWidth-ne)/window.innerWidth:1,E=d?-ne:0;Ce.current&&window.clearTimeout(Ce.current),L(g.current,{transition:`transform ${D.DURATION}s cubic-bezier(${D.EASE.join(",")})`,transform:P(l)?`scale(${C}) translate3d(0, ${E}px, 0)`:`scale(${C}) translate3d(${E}px, 0, 0)`}),!d&&g.current&&(Ce.current=setTimeout(()=>{const T=xe(g.current,l);L(g.current,{transition:"none",transform:P(l)?`translate3d(0, ${T}px, 0)`:`translate3d(${T}px, 0, 0)`})},500))}function Mt(d,C){if(C<0)return;const E=(window.innerWidth-ne)/window.innerWidth,T=E+C*(1-E),k=-ne+C*ne;L(g.current,{transform:P(l)?`scale(${T}) translate3d(0, ${k}px, 0)`:`scale(${T}) translate3d(${k}px, 0, 0)`,transition:"none"})}function Et(d,C){const E=P(l)?window.innerHeight:window.innerWidth,T=C?(E-ne)/E:1,k=C?-ne:0;C&&L(g.current,{transition:`transform ${D.DURATION}s cubic-bezier(${D.EASE.join(",")})`,transform:P(l)?`scale(${T}) translate3d(0, ${k}px, 0)`:`scale(${T}) translate3d(${k}px, 0, 0)`})}return o.useEffect(()=>{F||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[F]),o.createElement(At,{defaultOpen:V,onOpenChange:d=>{!v&&!d||(d?W(!0):fe(!0),O(d))},open:j},o.createElement(rt.Provider,{value:{activeSnapPoint:gt,snapPoints:a,setActiveSnapPoint:He,drawerRef:g,overlayRef:ae,onOpenChange:n,onPress:yt,onRelease:Rt,onDrag:St,dismissible:v,shouldAnimate:Le,handleOnly:m,isOpen:j,isDragging:Q,shouldFade:qe,closeDrawer:fe,onNestedDrag:Mt,onNestedOpenChange:Ct,onNestedRelease:Et,keyboardIsOpen:oe,modal:F,snapPointsOffset:de,activeSnapPointIndex:ie,direction:l,shouldScaleBackground:h,setBackgroundColorOnScale:w,noBodyStyles:N,container:B,autoFocus:H}},t))}const ft=o.forwardRef(function({...e},n){const{overlayRef:t,snapPoints:i,onRelease:s,shouldFade:a,isOpen:h,modal:w,shouldAnimate:y}=he(),S=it(n,t),v=i&&i.length>0;if(!w)return null;const m=o.useCallback(c=>s(c),[s]);return o.createElement(Pt,{onMouseUp:m,ref:S,"data-vaul-overlay":"","data-vaul-snap-points":h&&v?"true":"false","data-vaul-snap-points-overlay":h&&a?"true":"false","data-vaul-animate":y?.current?"true":"false",...e})});ft.displayName="Drawer.Overlay";const mt=o.forwardRef(function({onPointerDownOutside:e,style:n,onOpenAutoFocus:t,...i},s){const{drawerRef:a,onPress:h,onRelease:w,onDrag:y,keyboardIsOpen:S,snapPointsOffset:v,activeSnapPointIndex:m,modal:c,isOpen:$,direction:I,snapPoints:M,container:F,handleOnly:f,shouldAnimate:A,autoFocus:N}=he(),[l,V]=o.useState(!1),X=it(s,a),p=o.useRef(null),R=o.useRef(null),x=o.useRef(!1),G=M&&M.length>0;mn();const B=(u,b,j=0)=>{if(x.current)return!0;const O=Math.abs(u.y),_=Math.abs(u.x),W=_>O,Q=["bottom","right"].includes(b)?1:-1;if(b==="left"||b==="right"){if(!(u.x*Q<0)&&_>=0&&_<=j)return W}else if(!(u.y*Q<0)&&O>=0&&O<=j)return!W;return x.current=!0,!0};o.useEffect(()=>{G&&window.requestAnimationFrame(()=>{V(!0)})},[]);function H(u){p.current=null,x.current=!1,w(u)}return o.createElement(_t,{"data-vaul-drawer-direction":I,"data-vaul-drawer":"","data-vaul-delayed-snap-points":l?"true":"false","data-vaul-snap-points":$&&G?"true":"false","data-vaul-custom-container":F?"true":"false","data-vaul-animate":A?.current?"true":"false",...i,ref:X,style:v&&v.length>0?{"--snap-point-height":`${v[m??0]}px`,...n}:n,onPointerDown:u=>{f||(i.onPointerDown==null||i.onPointerDown.call(i,u),p.current={x:u.pageX,y:u.pageY},h(u))},onOpenAutoFocus:u=>{t?.(u),N||u.preventDefault()},onPointerDownOutside:u=>{if(e?.(u),!c||u.defaultPrevented){u.preventDefault();return}S.current&&(S.current=!1)},onFocusOutside:u=>{if(!c){u.preventDefault();return}},onPointerMove:u=>{if(R.current=u,f||(i.onPointerMove==null||i.onPointerMove.call(i,u),!p.current))return;const b=u.pageY-p.current.y,j=u.pageX-p.current.x,O=u.pointerType==="touch"?10:2;B({x:j,y:b},I,O)?y(u):(Math.abs(j)>O||Math.abs(b)>O)&&(p.current=null)},onPointerUp:u=>{i.onPointerUp==null||i.onPointerUp.call(i,u),p.current=null,x.current=!1,w(u)},onPointerOut:u=>{i.onPointerOut==null||i.onPointerOut.call(i,u),H(R.current)},onContextMenu:u=>{i.onContextMenu==null||i.onContextMenu.call(i,u),R.current&&H(R.current)}})});mt.displayName="Drawer.Content";const gn=250,wn=120,vn=o.forwardRef(function({preventCycle:e=!1,children:n,...t},i){const{closeDrawer:s,isDragging:a,snapPoints:h,activeSnapPoint:w,setActiveSnapPoint:y,dismissible:S,handleOnly:v,isOpen:m,onPress:c,onDrag:$}=he(),I=o.useRef(null),M=o.useRef(!1);function F(){if(M.current){N();return}window.setTimeout(()=>{f()},wn)}function f(){if(a||e||M.current){N();return}if(N(),!h||h.length===0){S||s();return}if(w===h[h.length-1]&&S){s();return}const V=h.findIndex(p=>p===w);if(V===-1)return;const X=h[V+1];y(X)}function A(){I.current=window.setTimeout(()=>{M.current=!0},gn)}function N(){I.current&&window.clearTimeout(I.current),M.current=!1}return o.createElement("div",{onClick:F,onPointerCancel:N,onPointerDown:l=>{v&&c(l),A()},onPointerMove:l=>{v&&$(l)},ref:i,"data-vaul-drawer-visible":m?"true":"false","data-vaul-handle":"","aria-hidden":"true",...t},o.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},n))});vn.displayName="Drawer.Handle";function bn(e){const n=he(),{container:t=n.container,...i}=e;return o.createElement(kt,{container:t,...i})}const re={Root:hn,Content:mt,Overlay:ft,Portal:bn,Close:It,Title:Nt,Description:Ot};function xn({...e}){return r.jsx(re.Root,{"data-slot":"drawer",...e})}function yn({...e}){return r.jsx(re.Portal,{"data-slot":"drawer-portal",...e})}function Sn({...e}){return r.jsx(re.Close,{"data-slot":"drawer-close",...e})}function Tn({className:e,...n}){return r.jsx(re.Overlay,{"data-slot":"drawer-overlay",className:se("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...n})}function Rn({className:e,children:n,...t}){return r.jsxs(yn,{"data-slot":"drawer-portal",children:[r.jsx(Tn,{}),r.jsxs(re.Content,{"data-slot":"drawer-content",className:se("group/drawer-content bg-background fixed z-50 flex h-auto flex-col","data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b","data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t","data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm","data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",e),...t,children:[r.jsx("div",{className:"bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block"}),n]})]})}function Cn({className:e,...n}){return r.jsx("div",{"data-slot":"drawer-header",className:se("flex flex-col gap-1.5 p-4",e),...n})}function Mn({className:e,...n}){return r.jsx("div",{"data-slot":"drawer-footer",className:se("mt-auto flex flex-col gap-2 p-4",e),...n})}function En({className:e,...n}){return r.jsx(re.Title,{"data-slot":"drawer-title",className:se("text-foreground font-semibold",e),...n})}function jn({className:e,...n}){return r.jsx(re.Description,{"data-slot":"drawer-description",className:se("text-muted-foreground text-sm",e),...n})}const Dn={coming_soon:{icon:r.jsx(tt,{size:16}),bg:"bg-amber-50 border-amber-200",text:"text-amber-800",message:"The full module for this topic isn't available yet — here's what you can study in the meantime, based on the DepEd curriculum."},progression_locked:{icon:r.jsx(Ze,{size:16}),bg:"bg-purple-50 border-purple-200",text:"text-purple-800",message:"You're flagged as at-risk here, but this module is currently locked behind progression. Study this brief while you work toward unlocking it."},no_module:{icon:r.jsx(Se,{size:16}),bg:"bg-rose-50 border-rose-200",text:"text-rose-800",message:"No module has been created for this topic yet. Here's what the DepEd curriculum says you should know."}},Nn=({open:e,onOpenChange:n,topicName:t,topicId:i,resolutionState:s,fallbackContent:a,moduleId:h,studentId:w,onNavigateToPrerequisite:y,loading:S=!1,error:v=null})=>{const[m,c]=U.useState(!1),[$,I]=U.useState(!1),[M,F]=U.useState(!1),f=Dn[s],A=async()=>{if(!(!w||!h)){I(!0);try{await $t(w,h),F(!0)}catch{}I(!1)}};return r.jsx(xn,{open:e,onOpenChange:n,children:r.jsxs(Rn,{className:"max-h-[85vh]",children:[r.jsxs(Cn,{children:[r.jsx(En,{className:"text-lg",children:t}),r.jsx(jn,{children:"At-Risk Study Brief"})]}),r.jsxs("div",{className:"px-4 pb-4 overflow-y-auto flex-1 space-y-4",children:[r.jsxs("div",{className:`flex items-start gap-2 p-3 rounded-lg border ${f.bg}`,children:[r.jsx("span",{className:`mt-0.5 ${f.text}`,children:f.icon}),r.jsx("p",{className:`text-xs leading-relaxed ${f.text}`,children:f.message})]}),S&&r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx("div",{className:"animate-pulse text-sm text-gray-500",children:"Loading study brief..."})}),v&&r.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-red-50 border border-red-200",children:[r.jsx(Lt,{size:14,className:"text-red-600"}),r.jsx("p",{className:"text-xs text-red-700",children:v})]}),a&&!S&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("h4",{className:"text-sm font-semibold text-gray-900 mb-1",children:"Overview"}),r.jsx("p",{className:"text-sm text-gray-700 leading-relaxed",children:a.summary})]}),a.key_concepts.length>0&&r.jsxs("div",{children:[r.jsx("h4",{className:"text-sm font-semibold text-gray-900 mb-2",children:"Key Concepts"}),r.jsx("ul",{className:"space-y-1.5",children:a.key_concepts.map((N,l)=>r.jsxs("li",{className:"flex items-start gap-2 text-sm text-gray-700",children:[r.jsx("span",{className:"mt-1.5 w-1.5 h-1.5 rounded-full bg-purple-500 flex-shrink-0"}),N]},l))})]}),a.one_worked_example?.problem&&r.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[r.jsxs("button",{onClick:()=>c(!m),className:"w-full flex items-center justify-between px-3 py-2.5 bg-gray-50 hover:bg-gray-100 transition-colors",children:[r.jsx("span",{className:"text-sm font-semibold text-gray-900",children:"Worked Example"}),m?r.jsx(Bt,{size:16}):r.jsx(Ft,{size:16})]}),r.jsx(Qe,{children:m&&r.jsx(Ie.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:r.jsxs("div",{className:"px-3 py-3 space-y-2",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-xs font-bold text-gray-500 uppercase",children:"Problem"}),r.jsx("p",{className:"text-sm text-gray-800 mt-0.5",children:a.one_worked_example.problem})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-xs font-bold text-gray-500 uppercase",children:"Solution"}),r.jsx("p",{className:"text-sm text-gray-800 mt-0.5 whitespace-pre-line",children:a.one_worked_example.solution})]})]})})})]}),a.what_to_focus_on&&r.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[r.jsx("h4",{className:"text-xs font-bold text-blue-800 uppercase mb-1",children:"What to Focus On"}),r.jsx("p",{className:"text-sm text-blue-900 leading-relaxed",children:a.what_to_focus_on})]}),a.rag_confidence==="low"&&r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[r.jsx(Se,{size:12}),r.jsx("span",{children:"Limited curriculum data was available for this topic preview."})]})]})]}),r.jsxs(Mn,{children:[s==="coming_soon"&&h&&r.jsxs("button",{onClick:A,disabled:M||$,className:"flex items-center justify-center gap-2 w-full py-2.5 rounded-lg bg-amber-500 hover:bg-amber-600 text-white text-sm font-semibold disabled:opacity-50 transition-colors",children:[r.jsx(Gt,{size:14}),M?"Subscribed!":$?"Subscribing...":"Notify Me When Available"]}),s==="progression_locked"&&h&&y&&r.jsxs("button",{onClick:()=>{y(h),n(!1)},className:"flex items-center justify-center gap-2 w-full py-2.5 rounded-lg bg-purple-600 hover:bg-purple-700 text-white text-sm font-semibold transition-colors",children:["Go to prerequisite module",r.jsx(jt,{size:14})]}),r.jsx(Sn,{asChild:!0,children:r.jsx("button",{className:"w-full py-2 rounded-lg border border-gray-200 text-sm text-gray-600 hover:bg-gray-50 transition-colors",children:"Close"})})]})]})})},J={pillBg:"#E9D5FF",pillText:"#6B21A8",pillLockedBg:"#EDE9FE",pillLockedText:"#7C3AED",pillComingSoonBg:"#FEF3C7",pillComingSoonText:"#92400E",pillNoModuleBg:"#FFE4E6",pillNoModuleText:"#BE123C",headerText:"#1F2937",arrowBg:"#F3F4F6"},On=new Set(et.map(e=>e.id));function ye(e){return nt[e]||et.find(n=>n.id===e)?.moduleTitle||e.split("-").slice(2).join(" ").replace(/\b\w/g,n=>n.toUpperCase())}function In(e){switch(e){case"coming_soon":return{style:{backgroundColor:J.pillComingSoonBg,color:J.pillComingSoonText,cursor:"pointer"},icon:r.jsx(tt,{size:14})};case"progression_locked":return{style:{backgroundColor:J.pillLockedBg,color:J.pillLockedText,cursor:"pointer"},icon:r.jsx(Ze,{size:14})};case"no_module":return{style:{backgroundColor:J.pillNoModuleBg,color:J.pillNoModuleText,cursor:"pointer"},icon:r.jsx(Se,{size:14})};default:return{style:{backgroundColor:J.pillBg,color:J.pillText,cursor:"pointer"},icon:r.jsx(Se,{size:14})}}}const Qn=({flaggedTopics:e=[],atRiskSubjects:n=[],unlockedModuleIds:t,moduleStatusMap:i={},resolutionStateMap:s={},fallbackContentMap:a={},onTopicClick:h,onNavigateToPrerequisite:w,studentId:y})=>{const S=U.useRef(null),[v,m]=U.useState(!1),[c,$]=U.useState(null),[I,M]=U.useState({}),[F,f]=U.useState(null),[A,N]=U.useState(!1),[l,V]=U.useState(""),X=e.filter(b=>On.has(b));if(X.length===0)return null;const p=()=>{if(S.current){const{scrollLeft:b,scrollWidth:j,clientWidth:O}=S.current;m(b+O{S.current?.scrollBy({left:200,behavior:"smooth"})},x=b=>{if(s[b])return s[b];const j=i[b];return j==="coming_soon"?"coming_soon":j==="unavailable"?"no_module":(j==="available"||j==="teacher_uploaded")&&t&&!t.has(b)?"progression_locked":"accessible"},G=async b=>{if(x(b)==="accessible"){if(c===b){h?.(b);return}if($(b),!I[b]&&y){f(b);try{const O=ye(b),_=await Dt(y,b,O,"General Mathematics",.7);_.generated&&M(W=>({...W,[b]:_.tips}))}catch{}f(null)}}else V(b),N(!0)},B=l?x(l):"no_module",H=l&&a[l]||null,u=l||null;return r.jsxs(r.Fragment,{children:[r.jsxs(Ie.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},className:"mb-4",children:[r.jsx("h3",{className:"text-base font-bold mb-3",style:{color:J.headerText},children:"Recommended for Review"}),r.jsxs("div",{className:"relative flex items-center",children:[r.jsx("div",{ref:S,onScroll:p,className:"flex gap-2 overflow-x-auto scrollbar-hide pb-1",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:X.slice(0,8).map((b,j)=>{const O=x(b),{style:_,icon:W}=In(O);return r.jsxs("button",{onClick:()=>G(b),title:O==="coming_soon"?"Module coming soon — tap for study brief":O==="progression_locked"?"Locked — complete previous module first":O==="no_module"?"No module yet — tap for curriculum brief":void 0,className:"flex items-center gap-1.5 px-4 py-2 rounded-full text-sm font-semibold transition-all whitespace-nowrap hover:scale-[1.02] active:scale-[0.98]",style:_,children:[W,ye(b),O==="accessible"&&r.jsx(Ve,{size:14})]},`${b}-${j}`)})}),v&&r.jsx("button",{onClick:R,className:"flex-shrink-0 ml-2 w-8 h-8 rounded-full flex items-center justify-center transition-colors",style:{backgroundColor:J.arrowBg},"aria-label":"Scroll right",children:r.jsx(Ve,{size:16,className:"text-gray-600"})})]}),r.jsx("style",{children:` .scrollbar-hide::-webkit-scrollbar { display: none; } diff --git a/assets/TeacherDashboard-ttPsdvb8.js b/assets/TeacherDashboard-CqJcvlfm.js similarity index 99% rename from assets/TeacherDashboard-ttPsdvb8.js rename to assets/TeacherDashboard-CqJcvlfm.js index 4d9129057a0991da3fccfdd08b0d4cba8b73dcb1..f06811c165800caec69b50b3ff3ade8f1d8e3855 100644 --- a/assets/TeacherDashboard-ttPsdvb8.js +++ b/assets/TeacherDashboard-CqJcvlfm.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css","assets/jspdf.es.min-CpWaCVL9.js"])))=>i.map(i=>d[i]); -import{e as Rt,t as Fl,f as $n,g as $e,_ as Cs,u as vs,h as zt,m as Re,i as ui,j as le,k as mi,R as xs,l as Ol,n as xt,o as xi,b as Vt,G as pi,B as Ur,Z as Pl,p as rr,q as gt,A as hi,U as hs,r as fs,T as ca,v as Ja,C as Bl,w as Fn,x as Hl,y as da,z as Gr,D as On,E as fi,F as Ul,H as nr,I as Gl,J as Ql,K as Vl,M as Wl,N as Pn,O as ql,P as Yl}from"./index-BvEKrMkD.js";import{d as he,j as e,r as u,c as Qr}from"./vendor-react-B4AQeu28.js";import{B as wt,c as Kl}from"./button-Bfg1pO9T.js";import{I as _s}from"./input-B3TmduBc.js";import Xl from"./ConfirmModal-DE1CbRDa.js";import{collection as St,query as kt,limit as or,where as Nt,getDocs as Lt,doc as ct,getDoc as Is,updateDoc as ns,serverTimestamp as it,setDoc as os,arrayRemove as Jl,deleteDoc as cn,Timestamp as Zl,orderBy as ec,onSnapshot as gi,addDoc as bi}from"./vendor-firebase-firestore-CNv3xXal.js";import{X as qt}from"./x-BYtx1i07.js";import{S as Xs}from"./search-CHZcTJmD.js";import{C as Gt}from"./check-BmWAQELM.js";import{P as ua}from"./plus-IoQaIojF.js";import{F as As,N as tc,A as vi}from"./NotificationDropdown-txVZGqve.js";import{M as sc,L as ac,D as rc,S as nc,a as oc}from"./LogoutActionButton-Cu6gWsBL.js";import{f as ic,V as lc,P as ir,M as wi,a as Za,E as cc,s as Bn,b as Ni,L as lr,d as dc,p as uc,c as mc,A as cr,e as xc}from"./quizService-D6WAd8P5.js";import{C as Ls}from"./clock-0vnF72R6.js";import{S as ra}from"./send-BivcIdIA.js";import{C as La}from"./circle-check-big-mtMsU82c.js";import{S as pc}from"./vendor-radix-C5nwdvGr.js";import{T as hc,a as fc,b as gc}from"./tooltip-DDXcKYaB.js";import{C as bc}from"./circle-help-DeWZHKak.js";import{E as vc,a as wc}from"./eye-DbYh0OO3.js";import{T as ji}from"./trash-2-B056YIHV.js";import{C as br}from"./circle-alert-fPu7cawt.js";import{I as oa}from"./info-CMvRmbQw.js";import{C as Ot,a as Ia}from"./chevron-up-CDr90bpM.js";import{M as Hn}from"./minus-DRsrXXF5.js";import{C as Ds}from"./chart-column-DKW3TTRX.js";import{C as Vr,S as Un}from"./skeleton-CU_hcmX-.js";import{D as Nc}from"./download-BYKPAk50.js";import{C as $s}from"./chevron-left-DFU37_wB.js";import{C as zs}from"./chevron-right-CbKJd0ln.js";import{S as yi}from"./save-DAHVTL2X.js";import{C as Sa}from"./circle-check-E415RSic.js";import{S as bs}from"./sparkles-av0wSNZT.js";import{U as Wr}from"./upload-COEzjD21.js";import{L as jc,C as yc}from"./lightbulb-BpvAgebC.js";import{u as Sc}from"./useQuery-a95tRwQa.js";import{S as Gn,g as kc,G as Cc,s as Qn}from"./subjects-ChEJ6J55.js";import{u as Ic}from"./useCurriculum-CSvqmu2B.js";import Tc from"./ChatMarkdown-Chh6462P.js";import{c as _c,a as Si,C as Ec,f as Rc}from"./formatDistanceToNow-5Jvf3U0l.js";import{H as Vn}from"./history-uiZLfMqH.js";import{B as dr}from"./bell-C57aSZcx.js";import{D as Wn,a as qn,b as Mc,c as Ac,d as zc,S as Lc}from"./dialog-F21mi9j3.js";import{u as ts,r as Dc}from"./vendor-xlsx-uZelXSz_.js";import{s as $c}from"./moduleWatchService-Boczzqau.js";import{r as Fc,u as Oc,a as Pc}from"./vendor-firebase-storage-Bi7H_66d.js";import{C as qr}from"./clipboard-check-jJ306e7q.js";import{R as Yn,B as Kn,C as Xn,X as Jn,Y as Zn,T as eo,a as to,b as so}from"./vendor-charts-CAmziV1y.js";import{B as Bc}from"./badge-check-Dir1sWA0.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";import"./log-out-BDL1J1Fs.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css","assets/jspdf.es.min-CwsrHLQV.js"])))=>i.map(i=>d[i]); +import{e as Rt,t as Fl,f as $n,g as $e,_ as Cs,u as vs,h as zt,m as Re,i as ui,j as le,k as mi,R as xs,l as Ol,n as xt,o as xi,b as Vt,G as pi,B as Ur,Z as Pl,p as rr,q as gt,A as hi,U as hs,r as fs,T as ca,v as Ja,C as Bl,w as Fn,x as Hl,y as da,z as Gr,D as On,E as fi,F as Ul,H as nr,I as Gl,J as Ql,K as Vl,M as Wl,N as Pn,O as ql,P as Yl}from"./index-BdLfAeGL.js";import{d as he,j as e,r as u,c as Qr}from"./vendor-react-B4AQeu28.js";import{B as wt,c as Kl}from"./button-BbJLXpfi.js";import{I as _s}from"./input-CHfZS1wQ.js";import Xl from"./ConfirmModal-DPzAgSP6.js";import{collection as St,query as kt,limit as or,where as Nt,getDocs as Lt,doc as ct,getDoc as Is,updateDoc as ns,serverTimestamp as it,setDoc as os,arrayRemove as Jl,deleteDoc as cn,Timestamp as Zl,orderBy as ec,onSnapshot as gi,addDoc as bi}from"./vendor-firebase-firestore-CNv3xXal.js";import{X as qt}from"./x-BLhsirCD.js";import{S as Xs}from"./search-gQ2OCqgd.js";import{C as Gt}from"./check-DbVe23hB.js";import{P as ua}from"./plus-Z9YkmuN1.js";import{F as As,N as tc,A as vi}from"./NotificationDropdown-DW0msTLi.js";import{M as sc,L as ac,D as rc,S as nc,a as oc}from"./LogoutActionButton-Baak8j6y.js";import{f as ic,V as lc,P as ir,M as wi,a as Za,E as cc,s as Bn,b as Ni,L as lr,d as dc,p as uc,c as mc,A as cr,e as xc}from"./quizService-DxWImmI3.js";import{C as Ls}from"./clock-CpBwkoND.js";import{S as ra}from"./send-CxDLfaHq.js";import{C as La}from"./circle-check-big-B54zXy3k.js";import{S as pc}from"./vendor-radix-C5nwdvGr.js";import{T as hc,a as fc,b as gc}from"./tooltip-Blvwukwg.js";import{C as bc}from"./circle-help-CZDuv1Gp.js";import{E as vc,a as wc}from"./eye-8D1uq8DN.js";import{T as ji}from"./trash-2-f-pq6QuO.js";import{C as br}from"./circle-alert-ByVTnT3r.js";import{I as oa}from"./info-D1mJ7S8g.js";import{C as Ot,a as Ia}from"./chevron-up-uSn_SWll.js";import{M as Hn}from"./minus-rsVFzcwU.js";import{C as Ds}from"./chart-column-Dl7iJ2BC.js";import{C as Vr,S as Un}from"./skeleton-SSuNGBG3.js";import{D as Nc}from"./download-CPe9YOUv.js";import{C as $s}from"./chevron-left-CNwzgiLt.js";import{C as zs}from"./chevron-right-BRRve0zL.js";import{S as yi}from"./save-CUEUjfb0.js";import{C as Sa}from"./circle-check-CuVe-qlS.js";import{S as bs}from"./sparkles-DnAkO9TX.js";import{U as Wr}from"./upload-CbDKucU9.js";import{L as jc,C as yc}from"./lightbulb-W3LO7x3u.js";import{u as Sc}from"./useQuery-fA8_Syr9.js";import{S as Gn,g as kc,G as Cc,s as Qn}from"./subjects-Dw9HR29l.js";import{u as Ic}from"./useCurriculum-DZL96a-v.js";import Tc from"./ChatMarkdown-SgVutDBu.js";import{c as _c,a as Si,C as Ec,f as Rc}from"./formatDistanceToNow-DQ9IJwBi.js";import{H as Vn}from"./history-VIZhCw1O.js";import{B as dr}from"./bell-C5_RRTsA.js";import{D as Wn,a as qn,b as Mc,c as Ac,d as zc,S as Lc}from"./dialog-BW6ddbOv.js";import{u as ts,r as Dc}from"./vendor-xlsx-uZelXSz_.js";import{s as $c}from"./moduleWatchService-Ck2BKbab.js";import{r as Fc,u as Oc,a as Pc}from"./vendor-firebase-storage-Bi7H_66d.js";import{C as qr}from"./clipboard-check-hgJTQlzs.js";import{R as Yn,B as Kn,C as Xn,X as Jn,Y as Zn,T as eo,a as to,b as so}from"./vendor-charts-CAmziV1y.js";import{B as Bc}from"./badge-check-4jI3r8US.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-markdown-yqZQ_iQm.js";import"./log-out-CccGdaTy.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -79,7 +79,7 @@ import{e as Rt,t as Fl,f as $n,g as $e,_ as Cs,u as vs,h as zt,m as Re,i as ui,j * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const ud=[["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"}]],Xr=Rt("wand-sparkles",ud);function md(t,s){const a=Fl(t);return isNaN(s)?_c(t,NaN):(a.setDate(a.getDate()+s),a)}function Ii(t,s){const a=$n(t),r=$n(s);return+a==+r}function ro(t){return Ii(t,Si(t))}function xd(t,s){return md(t,-1)}function no(t){return Ii(t,xd(Si(t)))}const vr=0,Os=1,ma=2,Ti=4;function oo(t){return()=>t}function pd(t){t()}function _i(t,s){return a=>t(s(a))}function io(t,s){return()=>t(s)}function hd(t,s){return a=>t(s,a)}function dn(t){return t!==void 0}function fd(...t){return()=>{t.map(pd)}}function xa(){}function wr(t,s){return s(t),t}function gd(t,s){return s(t)}function at(...t){return t}function Ye(t,s){return t(Os,s)}function Ee(t,s){t(vr,s)}function un(t){t(ma)}function ot(t){return t(Ti)}function be(t,s){return Ye(t,hd(s,vr))}function is(t,s){const a=t(Os,r=>{a(),s(r)});return a}function lo(t){let s,a;return r=>o=>{s=o,a&&clearTimeout(a),a=setTimeout(()=>{r(s)},t)}}function Ei(t,s){return t===s}function st(t=Ei){let s;return a=>r=>{t(s,r)||(s=r,a(r))}}function Se(t){return s=>a=>{t(a)&&s(a)}}function xe(t){return s=>_i(s,t)}function ms(t){return s=>()=>{s(t)}}function Y(t,...s){const a=bd(...s);return((r,o)=>{switch(r){case ma:un(t);return;case Os:return Ye(t,a(o))}})}function ps(t,s){return a=>r=>{a(s=t(s,r))}}function Ks(t){return s=>a=>{t>0?t--:s(a)}}function Ts(t){let s=null,a;return r=>o=>{s=o,!a&&(a=setTimeout(()=>{a=void 0,r(s)},t))}}function Ae(...t){const s=new Array(t.length);let a=0,r=null;const o=2**t.length-1;return t.forEach((n,i)=>{const l=2**i;Ye(n,c=>{const d=a;a|=l,s[i]=c,d!==o&&a===o&&r&&(r(),r=null)})}),n=>i=>{const l=()=>{n([i].concat(s))};a===o?l():r=l}}function bd(...t){return s=>t.reduceRight(gd,s)}function vd(t){let s,a;const r=()=>s?.();return function(o,n){switch(o){case Os:return n?a===n?void 0:(r(),a=n,s=Ye(t,n),s):(r(),xa);case ma:r(),a=null;return}}}function Z(t){let s=t;const a=Be();return((r,o)=>{switch(r){case vr:s=o;break;case Os:{o(s);break}case Ti:return s}return a(r,o)})}function Et(t,s){return wr(Z(s),a=>be(t,a))}function Be(){const t=[];return((s,a)=>{switch(s){case vr:t.slice().forEach(r=>{r(a)});return;case ma:t.splice(0,t.length);return;case Os:return t.push(a),()=>{const r=t.indexOf(a);r>-1&&t.splice(r,1)}}})}function Wt(t){return wr(Be(),s=>be(t,s))}function qe(t,s=[],{singleton:a}={singleton:!0}){return{constructor:t,dependencies:s,id:wd(),singleton:a}}const wd=()=>Symbol();function Nd(t){const s=new Map,a=({constructor:r,dependencies:o,id:n,singleton:i})=>{if(i&&s.has(n))return s.get(n);const l=r(o.map(c=>a(c)));return i&&s.set(n,l),l};return a(t)}function pt(...t){const s=Be(),a=new Array(t.length);let r=0;const o=2**t.length-1;return t.forEach((n,i)=>{const l=2**i;Ye(n,c=>{a[i]=c,r|=l,r===o&&Ee(s,a)})}),function(n,i){switch(n){case ma:{un(s);return}case Os:return r===o&&i(a),Ye(s,i)}}}function ye(t,s=Ei){return Y(t,st(s))}function Jr(...t){return function(s,a){switch(s){case ma:return;case Os:return fd(...t.map(r=>Ye(r,a)))}}}const vt={DEBUG:0,INFO:1,WARN:2,ERROR:3},jd={[vt.DEBUG]:"debug",[vt.ERROR]:"error",[vt.INFO]:"log",[vt.WARN]:"warn"},yd=()=>typeof globalThis>"u"?window:globalThis,Ps=qe(()=>{const t=Z(vt.ERROR);return{log:Z((s,a,r=vt.INFO)=>{const o=yd().VIRTUOSO_LOG_LEVEL??ot(t);r>=o&&console[jd[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",s,a)}),logLevel:t}},[],{singleton:!0});function Js(t,s,a){return mn(t,s,a).callbackRef}function mn(t,s,a){const r=he.useRef(null);let o=i=>{};const n=he.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const l=()=>{const c=i[0].target;c.offsetParent!==null&&t(c)};a?l():requestAnimationFrame(l)}):null,[t,a]);return o=i=>{i&&s?(n?.observe(i),r.current=i):(r.current&&n?.unobserve(r.current),r.current=null)},{callbackRef:o,ref:r}}function Sd(t,s,a,r,o,n,i,l,c){const d=he.useCallback(m=>{const p=kd(m.children,s,l?"offsetWidth":"offsetHeight",o);let h=m.parentElement;for(;h.dataset.virtuosoScroller===void 0;)h=h.parentElement;const v=h.lastElementChild.dataset.viewportType==="window";let y;v&&(y=h.ownerDocument.defaultView);const S=i?l?i.scrollLeft:i.scrollTop:v?l?y.scrollX||y.document.documentElement.scrollLeft:y.scrollY||y.document.documentElement.scrollTop:l?h.scrollLeft:h.scrollTop,N=i?l?i.scrollWidth:i.scrollHeight:v?l?y.document.documentElement.scrollWidth:y.document.documentElement.scrollHeight:l?h.scrollWidth:h.scrollHeight,w=i?l?i.offsetWidth:i.offsetHeight:v?l?y.innerWidth:y.innerHeight:l?h.offsetWidth:h.offsetHeight;r({scrollHeight:N,scrollTop:Math.max(S,0),viewportHeight:w}),n?.(l?co("column-gap",getComputedStyle(m).columnGap,o):co("row-gap",getComputedStyle(m).rowGap,o)),p!==null&&t(p)},[t,s,o,n,i,r,l]);return mn(d,a,c)}function kd(t,s,a,r){const o=t.length;if(o===0)return null;const n=[];for(let i=0;i{if(!c?.offsetParent)return;const d=c.getBoundingClientRect(),m=d.width;let p,h;if(s){const v=s.getBoundingClientRect(),y=d.top-v.top;h=v.height-Math.max(0,y),p=y+s.scrollTop}else{const v=i.current.ownerDocument.defaultView;h=v.innerHeight-Math.max(0,d.top),p=d.top+v.scrollY}r.current={listHeight:d.height,offsetTop:p,visibleHeight:h,visibleWidth:m},t(r.current)},[t,s]),{callbackRef:n,ref:i}=mn(o,!0,a),l=he.useCallback(()=>{o(i.current)},[o,i]);return he.useEffect(()=>{if(s){s.addEventListener("scroll",l);const d=new ResizeObserver(()=>{requestAnimationFrame(l)});return d.observe(s),()=>{s.removeEventListener("scroll",l),d.unobserve(s)}}const c=i.current?.ownerDocument.defaultView;return c?.addEventListener("scroll",l),c?.addEventListener("resize",l),()=>{c?.removeEventListener("scroll",l),c?.removeEventListener("resize",l)}},[l,s,i]),n}const Dt=qe(()=>{const t=Be(),s=Be(),a=Z(0),r=Be(),o=Z(0),n=Be(),i=Be(),l=Z(0),c=Z(0),d=Z(0),m=Z(0),p=Be(),h=Be(),v=Z(!1),y=Z(!1),S=Z(!1);return be(Y(t,xe(({scrollTop:N})=>N)),s),be(Y(t,xe(({scrollHeight:N})=>N)),i),be(s,o),{deviation:a,fixedFooterHeight:d,fixedHeaderHeight:c,footerHeight:m,headerHeight:l,horizontalDirection:y,scrollBy:h,scrollContainerState:t,scrollHeight:i,scrollingInProgress:v,scrollTo:p,scrollTop:s,skipAnimationFrameInResizeObserver:S,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:n}},[],{singleton:!0}),Ta={lvl:0};function Mi(t,s){const a=t.length;if(a===0)return[];let{index:r,value:o}=s(t[0]);const n=[];for(let i=1;is&&(l=l.concat(en(o,s,a))),r>=s&&r<=a&&l.push({k:r,v:i}),r<=a&&(l=l.concat(en(n,s,a))),l}function er(t){const{l:s,lvl:a,r}=t;if(r.lvl>=a-1&&s.lvl>=a-1)return t;if(a>r.lvl+1){if(Rr(s))return Di(bt(t,{lvl:a-1}));if(!et(s)&&!et(s.r))return bt(s.r,{l:bt(s,{r:s.r.l}),lvl:a,r:bt(t,{l:s.r.r,lvl:a-1})});throw new Error("Unexpected empty nodes")}if(Rr(t))return tn(bt(t,{lvl:a-1}));if(!et(r)&&!et(r.l)){const o=r.l,n=Rr(o)?r.lvl-1:r.lvl;return bt(o,{l:bt(t,{lvl:a-1,r:o.l}),lvl:o.lvl+1,r:tn(bt(r,{l:o.r,lvl:n}))})}throw new Error("Unexpected empty nodes")}function bt(t,s){return Li(s.k!==void 0?s.k:t.k,s.v!==void 0?s.v:t.v,s.lvl!==void 0?s.lvl:t.lvl,s.l!==void 0?s.l:t.l,s.r!==void 0?s.r:t.r)}function Ai(t){return et(t.r)?t.l:er(bt(t,{r:Ai(t.r)}))}function Rr(t){return et(t)||t.lvl>t.r.lvl}function zi(t){return et(t.r)?[t.k,t.v]:zi(t.r)}function Li(t,s,a,r=Ta,o=Ta){return{k:t,l:r,lvl:a,r:o,v:s}}function uo(t){return tn(Di(t))}function Di(t){const{l:s}=t;return!et(s)&&s.lvl===t.lvl?bt(s,{r:bt(t,{l:s.r})}):t}function tn(t){const{lvl:s,r:a}=t;return!et(a)&&!et(a.r)&&a.lvl===s&&a.r.lvl===s?bt(a,{l:bt(t,{r:a.l}),lvl:s+1}):t}function Cd(t){return Mi(t,({k:s,v:a})=>({index:s,value:a}))}function $i(t,s){return!!(t&&t.startIndex===s.startIndex&&t.endIndex===s.endIndex)}function Ea(t,s){return!!(t&&t[0]===s[0]&&t[1]===s[1])}const xn=qe(()=>({recalcInProgress:Z(!1)}),[],{singleton:!0});function Fi(t,s,a){return t[mr(t,s,a)]}function mr(t,s,a,r=0){let o=t.length-1;for(;r<=o;){const n=Math.floor((r+o)/2),i=t[n],l=a(i,s);if(l===0)return n;if(l===-1){if(o-r<2)return n-1;o=n-1}else{if(o===r)return n;r=n+1}}throw new Error(`Failed binary finding record in array - ${t.join(",")}, searched for ${s}`)}function Id(t,s,a,r){const o=mr(t,s,r),n=mr(t,a,r,o);return t.slice(o,n+1)}function Fs(t,s){return Math.round(t.getBoundingClientRect()[s])}function Nr(t){return!et(t.groupOffsetTree)}function pn({index:t},s){return s===t?0:s=p||n===h)&&(t=Zr(t,p)):(d=h!==n,c=!0),m>o&&o>=p&&h!==n&&(t=Qt(t,o+1,h));d&&(t=Qt(t,i,n))}return[t,a]}function Ed(t){return typeof t.groupIndex<"u"}function Rd({offset:t},s){return s===t?0:s0?l+a:l}function Oi(t,s){if(!Nr(s))return t;let a=0;for(;s.groupIndices[a]<=t+a;)a++;return t+a}function Pi(t,s,a){if(Ed(t))return s.groupIndices[t.groupIndex]+1;const r=t.index==="LAST"?a:t.index;let o=Oi(r,s);return o=Math.max(0,o,Math.min(a,o)),o}function Md(t,s,a,r=0){return r>0&&(s=Math.max(s,Fi(t,r,pn).offset)),Mi(Id(t,s,a,Rd),Ld)}function Ad(t,[s,a,r,o]){s.length>0&&r("received item sizes",s,vt.DEBUG);const n=t.sizeTree;let i=n,l=0;if(a.length>0&&et(n)&&s.length===2){const h=s[0].size,v=s[1].size;i=a.reduce((y,S)=>Qt(Qt(y,S,h),S+1,v),i)}else[i,l]=_d(i,s);if(i===n)return t;const{lastIndex:c,lastOffset:d,lastSize:m,offsetTree:p}=sn(t.offsetTree,l,i,o);return{groupIndices:a,groupOffsetTree:a.reduce((h,v)=>Qt(h,v,Ra(v,p,o)),ia()),lastIndex:c,lastOffset:d,lastSize:m,offsetTree:p,sizeTree:i}}function zd(t){return Ys(t).map(({k:s,v:a},r,o)=>{const n=o[r+1];return{endIndex:n!==void 0?n.k-1:1/0,size:a,startIndex:s}})}function mo(t,s){let a=0,r=0;for(;ao.start===r&&(o.end===s||o.end===1/0)&&o.value===a}const $d={offsetHeight:"height",offsetWidth:"width"},ws=qe(([{log:t},{recalcInProgress:s}])=>{const a=Be(),r=Be(),o=Et(r,0),n=Be(),i=Be(),l=Z(0),c=Z([]),d=Z(void 0),m=Z(void 0),p=Z(void 0),h=Z(void 0),v=Z((f,C)=>Fs(f,$d[C])),y=Z(void 0),S=Z(0),N=Td(),w=Et(Y(a,Ae(c,t,S),ps(Ad,N),st()),N),g=Et(Y(c,st(),ps((f,C)=>({current:C,prev:f.current}),{current:[],prev:[]}),xe(({prev:f})=>f)),[]);be(Y(c,Se(f=>f.length>0),Ae(w,S),xe(([f,C,b])=>{const F=f.reduce((U,k,D)=>Qt(U,k,Ra(k,C.offsetTree,b)||D),ia());return{...C,groupIndices:f,groupOffsetTree:F}})),w),be(Y(r,Ae(w),Se(([f,{lastIndex:C}])=>f[{endIndex:C,size:b,startIndex:f}])),a),be(d,m);const I=Et(Y(d,xe(f=>f===void 0)),!0);be(Y(m,Se(f=>f!==void 0&&et(ot(w).sizeTree)),xe(f=>{const C=ot(p),b=ot(c).length>0;return C!==void 0&&C!==0?b?[{endIndex:0,size:C,startIndex:0},{endIndex:1,size:f,startIndex:1}]:[]:[{endIndex:0,size:f,startIndex:0}]})),a),be(Y(h,Se(f=>f!==void 0&&f.length>0&&et(ot(w).sizeTree)),xe(f=>{const C=[];let b=f[0],F=0;for(let U=1;Uf!==void 0&&C!==void 0),xe(([f,C,b])=>{const F=[];for(let U=0;U({changed:b!==f,sizes:b}),{changed:!1,sizes:N}),xe(f=>f.changed)));Ye(Y(l,ps((f,C)=>({diff:f.prev-C,prev:C}),{diff:0,prev:0}),xe(f=>f.diff)),f=>{const{groupIndices:C}=ot(w);if(f>0)Ee(s,!0),Ee(n,f+mo(f,C));else if(f<0){const b=ot(g);b.length>0&&(f-=mo(-f,b)),Ee(i,f)}}),Ye(Y(l,Ae(t)),([f,C])=>{f<0&&C("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:l},vt.ERROR)});const A=Wt(n);be(Y(n,Ae(w),xe(([f,C])=>{const b=C.groupIndices.length>0,F=[],U=C.lastSize;if(b){const k=_a(C.sizeTree,0);let D=0,J=0;for(;D{let Ce=ce.ranges;return ce.prevSize!==0&&(Ce=[...ce.ranges,{endIndex:ie+f-1,size:ce.prevSize,startIndex:ce.prevIndex}]),{prevIndex:ie+f,prevSize:fe,ranges:Ce}},{prevIndex:f,prevSize:0,ranges:F}).ranges}return Ys(C.sizeTree).reduce((k,{k:D,v:J})=>({prevIndex:D+f,prevSize:J,ranges:[...k.ranges,{endIndex:D+f-1,size:k.prevSize,startIndex:k.prevIndex}]}),{prevIndex:0,prevSize:U,ranges:[]}).ranges})),a);const W=Wt(Y(i,Ae(w,S),xe(([f,{offsetTree:C},b])=>{const F=-f;return Ra(F,C,b)})));return be(Y(i,Ae(w,S),xe(([f,C,b])=>{if(C.groupIndices.length>0){if(et(C.sizeTree))return C;let U=ia();const k=ot(g);let D=0,J=0,re=0;for(;D<-f;){re=k[J];const ce=k[J+1]-re-1;J++,D+=ce+1}if(U=Ys(C.sizeTree).reduce((ce,{k:ie,v:fe})=>Qt(ce,Math.max(0,ie+f),fe),U),D!==-f){const ce=_a(C.sizeTree,re);U=Qt(U,0,ce);const ie=ls(C.sizeTree,-f+1)[1];U=Qt(U,1,ie)}return{...C,sizeTree:U,...sn(C.offsetTree,0,U,b)}}const F=Ys(C.sizeTree).reduce((U,{k,v:D})=>Qt(U,Math.max(0,k+f),D),ia());return{...C,sizeTree:F,...sn(C.offsetTree,0,F,b)}})),w),{beforeUnshiftWith:A,data:y,defaultItemSize:m,firstItemIndex:l,fixedItemSize:d,fixedGroupSize:p,gap:S,groupIndices:c,heightEstimates:h,itemSize:v,listRefresh:L,shiftWith:i,shiftWithOffset:W,sizeRanges:a,sizes:w,statefulTotalCount:o,totalCount:r,trackItemSizes:I,unshiftWith:n}},at(Ps,xn),{singleton:!0});function Fd(t){return t.reduce((s,a)=>(s.groupIndices.push(s.totalCount),s.totalCount+=a+1,s),{groupIndices:[],totalCount:0})}const Bi=qe(([{groupIndices:t,sizes:s,totalCount:a},{headerHeight:r,scrollTop:o}])=>{const n=Be(),i=Be(),l=Wt(Y(n,xe(Fd)));return be(Y(l,xe(c=>c.totalCount)),a),be(Y(l,xe(c=>c.groupIndices)),t),be(Y(pt(o,s,r),Se(([c,d])=>Nr(d)),xe(([c,d,m])=>ls(d.groupOffsetTree,Math.max(c-m,0),"v")[0]),st(),xe(c=>[c])),i),{groupCounts:n,topItemsIndexes:i}},at(ws,Dt)),Bs=qe(([{log:t}])=>{const s=Z(!1),a=Wt(Y(s,Se(r=>r),st()));return Ye(s,r=>{r&&ot(t)("props updated",{},vt.DEBUG)}),{didMount:a,propsReady:s}},at(Ps),{singleton:!0}),Od=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Hi(t){const s=typeof t=="number"?{index:t}:t;return s.align||(s.align="start"),(!s.behavior||!Od)&&(s.behavior="auto"),s.offset===void 0&&(s.offset=0),s}const Da=qe(([{gap:t,listRefresh:s,sizes:a,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:n,footerHeight:i,headerHeight:l,scrollingInProgress:c,scrollTo:d,smoothScrollTargetReached:m,viewportHeight:p},{log:h}])=>{const v=Be(),y=Be(),S=Z(0);let N=null,w=null,g=null;function I(){N!==null&&(N(),N=null),g!==null&&(g(),g=null),w&&(clearTimeout(w),w=null),Ee(c,!1)}return be(Y(v,Ae(a,p,r,S,l,i,h),Ae(t,n,o),xe(([[L,A,W,f,C,b,F,U],k,D,J])=>{const re=Hi(L),{align:ce,behavior:ie,offset:fe}=re,Ce=f-1,ue=Pi(re,A,Ce);let ge=Ra(ue,A.offsetTree,k)+b;ce==="end"?(ge+=D+ls(A.sizeTree,ue)[1]-W+J,ue===Ce&&(ge+=F)):ce==="center"?ge+=(D+ls(A.sizeTree,ue)[1]-W+J)/2:ge-=C,fe!==void 0&&fe!==0&&(ge+=fe);const B=te=>{I(),te?(U("retrying to scroll to",{location:L},vt.DEBUG),Ee(v,L)):(Ee(y,!0),U("list did not change, scroll successful",{},vt.DEBUG))};if(I(),ie==="smooth"){let te=!1;g=Ye(s,ne=>{te=te||ne}),N=is(m,()=>{B(te)})}else N=is(Y(s,Pd(150)),B);return w=setTimeout(()=>{I()},1200),Ee(c,!0),U("scrolling from index to",{behavior:ie,index:ue,top:ge},vt.DEBUG),{behavior:ie,top:ge}})),d),{scrollTargetReached:y,scrollToIndex:v,topListHeight:S}},at(ws,Dt,Ps),{singleton:!0});function Pd(t){return s=>{const a=setTimeout(()=>{s(!1)},t);return r=>{r&&(s(!0),clearTimeout(a))}}}function hn(t,s){t===0?s():requestAnimationFrame(()=>{hn(t-1,s)})}function fn(t,s){const a=s-1;return typeof t=="number"?t:t.index==="LAST"?a:t.index}const $a=qe(([{defaultItemSize:t,listRefresh:s,sizes:a},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:n},{didMount:i}])=>{const l=Z(!0),c=Z(0),d=Z(!0);return be(Y(i,Ae(c),Se(([m,p])=>p!==0),ms(!1)),l),be(Y(i,Ae(c),Se(([m,p])=>p!==0),ms(!1)),d),Ye(Y(pt(s,i),Ae(l,a,t,d),Se(([[,m],p,{sizeTree:h},v,y])=>m&&(!et(h)||dn(v))&&!p&&!y),Ae(c)),([,m])=>{is(o,()=>{Ee(d,!0)}),hn(4,()=>{is(r,()=>{Ee(l,!0)}),Ee(n,m)})}),{initialItemFinalLocationReached:d,initialTopMostItemIndex:c,scrolledToInitialItem:l}},at(ws,Dt,Da,Bs),{singleton:!0});function Ui(t,s){return Math.abs(t-s)<1.01}const Ma="up",ka="down",Bd="none",Hd={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Ud=0,Fa=qe(([{footerHeight:t,headerHeight:s,scrollBy:a,scrollContainerState:r,scrollTop:o,viewportHeight:n}])=>{const i=Z(!1),l=Z(!0),c=Be(),d=Be(),m=Z(4),p=Z(Ud),h=Et(Y(Jr(Y(ye(o),Ks(1),ms(!0)),Y(ye(o),Ks(1),ms(!1),lo(100))),st()),!1),v=Et(Y(Jr(Y(a,ms(!0)),Y(a,ms(!1),lo(200))),st()),!1);be(Y(pt(ye(o),ye(p)),xe(([g,I])=>g<=I),st()),l),be(Y(l,Ts(50)),d);const y=Wt(Y(pt(r,ye(n),ye(s),ye(t),ye(m)),ps((g,[{scrollHeight:I,scrollTop:L},A,W,f,C])=>{const b=L+A-I>-C,F={scrollHeight:I,scrollTop:L,viewportHeight:A};if(b){let k,D;return L>g.state.scrollTop?(k="SCROLLED_DOWN",D=g.state.scrollTop-L):(k="SIZE_DECREASED",D=g.state.scrollTop-L||g.scrollTopDelta),{atBottom:!0,atBottomBecause:k,scrollTopDelta:D,state:F}}let U;return F.scrollHeight>g.state.scrollHeight?U="SIZE_INCREASED":Ag!==void 0&&g.atBottom===I.atBottom))),S=Et(Y(r,ps((g,{scrollHeight:I,scrollTop:L,viewportHeight:A})=>{if(!Ui(g.scrollHeight,I)){const W=I-(L+A)<1;return g.scrollTop!==L&&W?{changed:!0,jump:g.scrollTop-L,scrollHeight:I,scrollTop:L}:{changed:!0,jump:0,scrollHeight:I,scrollTop:L}}return{changed:!1,jump:0,scrollHeight:I,scrollTop:L}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Se(g=>g.changed),xe(g=>g.jump)),0);be(Y(y,xe(g=>g.atBottom)),i),be(Y(i,Ts(50)),c);const N=Z(ka);be(Y(r,xe(({scrollTop:g})=>g),st(),ps((g,I)=>ot(v)?{direction:g.direction,prevScrollTop:I}:{direction:Ig.direction)),N),be(Y(r,Ts(50),ms(Bd)),N);const w=Z(0);return be(Y(h,Se(g=>!g),ms(0)),w),be(Y(o,Ts(100),Ae(h),Se(([g,I])=>I),ps(([g,I],[L])=>[I,L],[0,0]),xe(([g,I])=>I-g)),w),{atBottomState:y,atBottomStateChange:c,atBottomThreshold:m,atTopStateChange:d,atTopThreshold:p,isAtBottom:i,isAtTop:l,isScrolling:h,lastJumpDueToItemResize:S,scrollDirection:N,scrollVelocity:w}},at(Dt)),Aa="top",za="bottom",xo="none";function po(t,s,a){return typeof t=="number"?a===Ma&&s===Aa||a===ka&&s===za?t:0:a===Ma?s===Aa?t.main:t.reverse:s===za?t.main:t.reverse}function ho(t,s){return typeof t=="number"?t:t[s]??0}const gn=qe(([{deviation:t,fixedHeaderHeight:s,headerHeight:a,scrollTop:r,viewportHeight:o}])=>{const n=Be(),i=Z(0),l=Z(0),c=Z(0),d=Et(Y(pt(ye(r),ye(o),ye(a),ye(n,Ea),ye(c),ye(i),ye(s),ye(t),ye(l)),xe(([m,p,h,[v,y],S,N,w,g,I])=>{const L=m-g,A=N+w,W=Math.max(h-L,0);let f=xo;const C=ho(I,Aa),b=ho(I,za);return v-=g,v+=h+w,y+=h+w,y-=g,v>m+A-C&&(f=Ma),ym!==null),st(Ea)),[0,0]);return{increaseViewportBy:l,listBoundary:n,overscan:c,topListHeight:i,visibleRange:d}},at(Dt),{singleton:!0});function Gd(t,s,a){if(Nr(s)){const r=Oi(t,s);return[{index:ls(s.groupOffsetTree,r)[0],offset:0,size:0},{data:a?.[0],index:r,offset:0,size:0}]}return[{data:a?.[0],index:t,offset:0,size:0}]}const Mr={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function tr(t,s,a,r,o,n){const{lastIndex:i,lastOffset:l,lastSize:c}=o;let d=0,m=0;if(t.length>0){d=t[0].offset;const S=t[t.length-1];m=S.offset+S.size}const p=a-i,h=l+p*c+(p-1)*r,v=d,y=h-m;return{bottom:m,firstItemIndex:n,items:fo(t,o,n),offsetBottom:y,offsetTop:d,top:v,topItems:fo(s,o,n),topListHeight:s.reduce((S,N)=>N.size+S,0),totalCount:a}}function Gi(t,s,a,r,o,n){let i=0;if(a.groupIndices.length>0)for(const m of a.groupIndices){if(m-i>=t)break;i++}const l=t+i,c=fn(s,l),d=Array.from({length:l}).map((m,p)=>({data:n[p+c],index:p+c,offset:0,size:0}));return tr(d,[],l,o,a,r)}function fo(t,s,a){if(t.length===0)return[];if(!Nr(s))return t.map(d=>({...d,index:d.index+a,originalIndex:d.index}));const r=t[0].index,o=t[t.length-1].index,n=[],i=la(s.groupOffsetTree,r,o);let l,c=0;for(const d of t){(!l||l.end{const S=Z([]),N=Z(0),w=Be(),g=Z(0);be(n.topItemsIndexes,S);const I=Et(Y(pt(v,y,ye(c,Ea),ye(o),ye(r),ye(d),m,ye(S),ye(s),ye(a),ye(g),t),Se(([f,C,,b,,,,,,,,F])=>{const U=F!==void 0&&F.length!==b;return f&&!C&&!U}),xe(([,,[f,C],b,F,U,k,D,J,re,ce,ie])=>{const fe=F,{offsetTree:Ce,sizeTree:ue}=fe,ge=ot(N);if(b===0)return{...Mr,totalCount:b};if(f===0&&C===0)return ge===0?{...Mr,totalCount:b}:Gi(ge,U,F,J,re,ie||[]);if(et(ue))return ge>0?null:tr(Gd(fn(U,b),fe,ie),[],b,re,fe,J);const B=[];if(D.length>0){const se=D[0],M=D[D.length-1];let q=0;for(const Q of la(ue,se,M)){const pe=Q.value,$=Math.max(Q.start,se),j=Math.min(Q.end,M);for(let T=$;T<=j;T++)B.push({data:ie?.[T],index:T,offset:q,size:pe}),q+=pe}}if(!k)return tr([],B,b,re,fe,J);const te=D.length>0?D[D.length-1]+1:0,ne=Md(Ce,f,C,te);if(ne.length===0)return null;const ze=b-1,Fe=wr([],se=>{for(const M of ne){const q=M.value;let Q=q.offset,pe=M.start;const $=q.size;if(q.offset=C);T++)se.push({data:ie?.[T],index:T,offset:Q,size:$}),Q+=$+re}}),Pe=go(ce,Aa),G=go(ce,za);if(Fe.length>0&&(Pe>0||G>0)){const se=Fe[0],M=Fe[Fe.length-1];if(Pe>0&&se.index>te){const q=Math.min(Pe,se.index-te),Q=[];let pe=se.offset;for(let $=se.index-1;$>=se.index-q;$--){const j=la(ue,$,$)[0]?.value??se.size;pe-=j+re,Q.unshift({data:ie?.[$],index:$,offset:pe,size:j})}Fe.unshift(...Q)}if(G>0&&M.indexf!==null),st()),Mr);be(Y(t,Se(dn),xe(f=>f?.length)),o),be(Y(I,xe(f=>f.topListHeight)),p),be(p,l),be(Y(I,xe(f=>[f.top,f.bottom])),i),be(Y(I,xe(f=>f.items)),w);const L=Wt(Y(I,Se(({items:f})=>f.length>0),Ae(o,t),Se(([{items:f},C])=>f[f.length-1].originalIndex===C-1),xe(([,f,C])=>[f-1,C]),st(Ea),xe(([f])=>f))),A=Wt(Y(I,Ts(200),Se(({items:f,topItems:C})=>f.length>0&&f[0].originalIndex===C.length),xe(({items:f})=>f[0].index),st())),W=Wt(Y(I,Se(({items:f})=>f.length>0),xe(({items:f})=>{let C=0,b=f.length-1;for(;f[C].type==="group"&&CC;)b--;return{endIndex:f[b].index,startIndex:f[C].index}}),st($i)));return{endReached:L,initialItemCount:N,itemsRendered:w,listState:I,minOverscanItemCount:g,rangeChanged:W,startReached:A,topItemsIndexes:S,...h}},at(ws,Bi,gn,$a,Da,Fa,Bs,xn),{singleton:!0}),Qi=qe(([{fixedFooterHeight:t,fixedHeaderHeight:s,footerHeight:a,headerHeight:r},{listState:o}])=>{const n=Be(),i=Et(Y(pt(a,t,r,s,o),xe(([l,c,d,m,p])=>l+c+d+m+p.offsetBottom+p.bottom)),0);return be(ye(i),n),{totalListHeight:i,totalListHeightChanged:n}},at(Dt,Zs),{singleton:!0}),Qd=qe(([{viewportHeight:t},{totalListHeight:s}])=>{const a=Z(!1),r=Et(Y(pt(a,t,s),Se(([o])=>o),xe(([,o,n])=>Math.max(0,o-n)),Ts(0),st()),0);return{alignToBottom:a,paddingTopAddition:r}},at(Dt,Qi),{singleton:!0}),Vi=qe(()=>({context:Z(null)})),Vd=({itemBottom:t,itemTop:s,locationParams:{align:a,behavior:r,...o},viewportBottom:n,viewportTop:i})=>sn?{...o,align:a??"end",...r!==void 0?{behavior:r}:{}}:null,Wi=qe(([{gap:t,sizes:s,totalCount:a},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:n,scrollingInProgress:i,scrollTop:l,viewportHeight:c},{scrollToIndex:d}])=>{const m=Be();return be(Y(m,Ae(s,c,a,n,o,r,l),Ae(t),xe(([[p,h,v,y,S,N,w,g],I])=>{const{calculateViewLocation:L=Vd,done:A,...W}=p,f=Pi(p,h,y-1),C=Ra(f,h.offsetTree,I)+S+N,b=C+ls(h.sizeTree,f)[1],F=g+N,U=g+v-w,k=L({itemBottom:b,itemTop:C,locationParams:W,viewportBottom:U,viewportTop:F});return k!==null?A&&is(Y(i,Se(D=>!D),Ks(ot(i)?1:2)),A):A?.(),k}),Se(p=>p!==null)),d),{scrollIntoView:m}},at(ws,Dt,Da,Zs,Ps),{singleton:!0});function bo(t){return t===!1?!1:t==="smooth"?"smooth":"auto"}const Wd=(t,s)=>typeof t=="function"?bo(t(s)):s&&bo(t),qd=qe(([{listRefresh:t,totalCount:s,fixedItemSize:a,data:r},{atBottomState:o,isAtBottom:n},{scrollToIndex:i},{scrolledToInitialItem:l},{didMount:c,propsReady:d},{log:m},{scrollingInProgress:p},{context:h},{scrollIntoView:v}])=>{const y=Z(!1),S=Be();let N=null;function w(A){Ee(i,{align:"end",behavior:A,index:"LAST"})}Ye(Y(pt(Y(ye(s),Ks(1)),c),Ae(ye(y),n,l,p),xe(([[A,W],f,C,b,F])=>{let U=W&&b,k="auto";return U&&(k=Wd(f,C||F),U=U&&k!==!1),{followOutputBehavior:k,shouldFollow:U,totalCount:A}}),Se(({shouldFollow:A})=>A)),({followOutputBehavior:A,totalCount:W})=>{N!==null&&(N(),N=null),ot(a)!==void 0?requestAnimationFrame(()=>{ot(m)("following output to ",{totalCount:W},vt.DEBUG),w(A)}):N=is(t,()=>{ot(m)("following output to ",{totalCount:W},vt.DEBUG),w(A),N=null})});function g(A){const W=is(o,f=>{A&&!f.atBottom&&f.notAtBottomBecause==="SIZE_INCREASED"&&N===null&&(ot(m)("scrolling to bottom due to increased size",{},vt.DEBUG),w("auto"))});setTimeout(W,100)}Ye(Y(pt(ye(y),s,d),Se(([A,,W])=>A!==!1&&W),ps(({value:A},[,W])=>({refreshed:A===W,value:W}),{refreshed:!1,value:0}),Se(({refreshed:A})=>A),Ae(y,s)),([,A])=>{ot(l)&&g(A!==!1)}),Ye(S,()=>{g(ot(y)!==!1)}),Ye(pt(ye(y),o),([A,W])=>{A!==!1&&!W.atBottom&&W.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&w("auto")});const I=Z(null),L=Be();return be(Jr(Y(ye(r),xe(A=>A?.length??0)),Y(ye(s))),L),Ye(Y(pt(Y(L,Ks(1)),c),Ae(ye(I),l,p,h),xe(([[A,W],f,C,b,F])=>W&&C&&f?.({context:F,totalCount:A,scrollingInProgress:b})),Se(A=>!!A),Ts(0)),A=>{N!==null&&(N(),N=null),ot(a)!==void 0?requestAnimationFrame(()=>{ot(m)("scrolling into view",{}),Ee(v,A)}):N=is(t,()=>{ot(m)("scrolling into view",{}),Ee(v,A),N=null})}),{autoscrollToBottom:S,followOutput:y,scrollIntoViewOnChange:I}},at(ws,Fa,Da,$a,Bs,Ps,Dt,Vi,Wi)),Yd=qe(([{data:t,firstItemIndex:s,gap:a,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:n,listState:i},{didMount:l}])=>(be(Y(l,Ae(n),Se(([,c])=>c!==0),Ae(o,r,s,a,t),xe(([[,c],d,m,p,h,v=[]])=>Gi(c,d,m,p,h,v))),i),{}),at(ws,$a,Zs,Bs),{singleton:!0}),Kd=qe(([{didMount:t},{scrollTo:s},{listState:a}])=>{const r=Z(0);return Ye(Y(t,Ae(r),Se(([,o])=>o!==0),xe(([,o])=>({top:o}))),o=>{is(Y(a,Ks(1),Se(n=>n.items.length>1)),()=>{requestAnimationFrame(()=>{Ee(s,o)})})}),{initialScrollTop:r}},at(Bs,Dt,Zs),{singleton:!0}),qi=qe(([{scrollVelocity:t}])=>{const s=Z(!1),a=Be(),r=Z(!1);return be(Y(t,Ae(r,s,a),Se(([o,n])=>n!==!1&&n!==void 0),xe(([o,n,i,l])=>{const{enter:c,exit:d}=n;if(i){if(d(o,l))return!1}else if(c(o,l))return!0;return i}),st()),s),Ye(Y(pt(s,t,a),Ae(r)),([[o,n,i],l])=>{o&&l!==!1&&l!==void 0&&l.change&&l.change(n,i)}),{isSeeking:s,scrollSeekConfiguration:r,scrollSeekRangeChanged:a,scrollVelocity:t}},at(Fa),{singleton:!0}),bn=qe(([{scrollContainerState:t,scrollTo:s}])=>{const a=Be(),r=Be(),o=Be(),n=Z(!1),i=Z(void 0);return be(Y(pt(a,r),xe(([{scrollTop:l,viewportHeight:c},{offsetTop:d,listHeight:m}])=>({scrollHeight:m,scrollTop:Math.max(0,l-d),viewportHeight:c}))),t),be(Y(s,Ae(r),xe(([l,{offsetTop:c}])=>({...l,top:l.top+c}))),o),{customScrollParent:i,useWindowScroll:n,windowScrollContainerState:a,windowScrollTo:o,windowViewportRect:r}},at(Dt)),Xd=qe(([{sizeRanges:t,sizes:s},{headerHeight:a,scrollTop:r},{initialTopMostItemIndex:o},{didMount:n},{useWindowScroll:i,windowScrollContainerState:l,windowViewportRect:c}])=>{const d=Be(),m=Z(void 0),p=Z(null),h=Z(null);return be(l,p),be(c,h),Ye(Y(d,Ae(s,r,i,p,h,a)),([v,y,S,N,w,g,I])=>{const L=zd(y.sizeTree);N&&w!==null&&g!==null&&(S=w.scrollTop-g.offsetTop),S-=I,v({ranges:L,scrollTop:S})}),be(Y(m,Se(dn),xe(Jd)),o),be(Y(n,Ae(m),Se(([,v])=>v!==void 0),st(),xe(([,v])=>v.ranges)),t),{getState:d,restoreStateFrom:m}},at(ws,Dt,$a,Bs,bn));function Jd(t){return{align:"start",index:0,offset:t.scrollTop}}const Zd=qe(([{topItemsIndexes:t}])=>{const s=Z(0);return be(Y(s,Se(a=>a>=0),xe(a=>Array.from({length:a}).map((r,o)=>o))),t),{topItemCount:s}},at(Zs));function Yi(t){let s=!1,a;return(()=>(s||(s=!0,a=t()),a))}const eu=Yi(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),tu=qe(([{deviation:t,scrollBy:s,scrollingInProgress:a,scrollTop:r},{isAtBottom:o,isScrolling:n,lastJumpDueToItemResize:i,scrollDirection:l},{listState:c},{beforeUnshiftWith:d,gap:m,shiftWithOffset:p,sizes:h},{log:v},{recalcInProgress:y}])=>{const S=Wt(Y(c,Ae(i),ps(([,w,g,I],[{bottom:L,items:A,offsetBottom:W,totalCount:f},C])=>{const b=L+W;let F=0;return g===f&&w.length>0&&A.length>0&&(A[0].originalIndex===0&&w[0].originalIndex===0||(F=b-I,F!==0&&(F+=C))),[F,A,f,b]},[0,[],0,0]),Se(([w])=>w!==0),Ae(r,l,a,o,v,y),Se(([,w,g,I,,,L])=>!L&&!I&&w!==0&&g===Ma),xe(([[w],,,,,g])=>(g("Upward scrolling compensation",{amount:w},vt.DEBUG),w))));function N(w){w>0?(Ee(s,{behavior:"auto",top:-w}),Ee(t,0)):(Ee(t,0),Ee(s,{behavior:"auto",top:-w}))}return Ye(Y(S,Ae(t,n)),([w,g,I])=>{I&&eu()?Ee(t,g-w):N(-w)}),Ye(Y(pt(Et(n,!1),t,y),Se(([w,g,I])=>!w&&!I&&g!==0),xe(([w,g])=>g),Ts(1)),N),be(Y(p,xe(w=>({top:-w}))),s),Ye(Y(d,Ae(h,m),xe(([w,{groupIndices:g,lastSize:I,sizeTree:L},A])=>{function W(U){return U*(I+A)}if(g.length===0)return W(w);let f=0;const C=_a(L,0);let b=0,F=0;for(;bw&&(f-=C,U=w-b+1),b+=U,f+=W(U),F++}return f})),w=>{Ee(t,w),requestAnimationFrame(()=>{Ee(s,{top:w}),requestAnimationFrame(()=>{Ee(t,0),Ee(y,!1)})})}),{deviation:t}},at(Dt,Fa,Zs,ws,Ps,xn)),su=qe(([t,s,a,r,o,n,i,l,c,d,m])=>({...t,...s,...a,...r,...o,...n,...i,...l,...c,...d,...m}),at(gn,Yd,Bs,qi,Qi,Kd,Qd,bn,Wi,Ps,Vi)),Ki=qe(([{data:t,defaultItemSize:s,firstItemIndex:a,fixedItemSize:r,fixedGroupSize:o,gap:n,groupIndices:i,heightEstimates:l,itemSize:c,sizeRanges:d,sizes:m,statefulTotalCount:p,totalCount:h,trackItemSizes:v},{initialItemFinalLocationReached:y,initialTopMostItemIndex:S,scrolledToInitialItem:N},w,g,I,L,{scrollToIndex:A},W,{topItemCount:f},{groupCounts:C},b])=>{const{listState:F,minOverscanItemCount:U,topItemsIndexes:k,rangeChanged:D,...J}=L;return be(D,b.scrollSeekRangeChanged),be(Y(b.windowViewportRect,xe(re=>re.visibleHeight)),w.viewportHeight),{data:t,defaultItemHeight:s,firstItemIndex:a,fixedItemHeight:r,fixedGroupHeight:o,gap:n,groupCounts:C,heightEstimates:l,initialItemFinalLocationReached:y,initialTopMostItemIndex:S,scrolledToInitialItem:N,sizeRanges:d,topItemCount:f,topItemsIndexes:k,totalCount:h,...I,groupIndices:i,itemSize:c,listState:F,minOverscanItemCount:U,scrollToIndex:A,statefulTotalCount:p,trackItemSizes:v,rangeChanged:D,...J,...b,...w,sizes:m,...g}},at(ws,$a,Dt,Xd,qd,Zs,Da,tu,Zd,Bi,su));function au(t,s){const a={},r={};let o=0;const n=t.length;for(;o(w[g]=I=>{const L=N[s.methods[g]];Ee(L,I)},w),{})}function m(N){return i.reduce((w,g)=>(w[g]=vd(N[s.events[g]]),w),{})}const p=he.forwardRef(function(N,w){const{children:g,...I}=N,[L]=he.useState(()=>wr(Nd(t),f=>{c(f,I)})),[A]=he.useState(io(m,L));Qa(()=>{for(const f of i)f in I&&Ye(A[f],I[f]);return()=>{Object.values(A).map(un)}},[I,A,L]),Qa(()=>{c(L,I)}),he.useImperativeHandle(w,oo(d(L)));const W=a;return e.jsx(l.Provider,{value:L,children:a!==void 0?e.jsx(W,{...au([...r,...o,...i],I),children:g}):g})}),h=N=>{const w=he.useContext(l);return he.useCallback(g=>{Ee(w[N],g)},[w,N])},v=N=>{const w=he.useContext(l)[N],g=he.useCallback(I=>Ye(w,I),[w]);return he.useSyncExternalStore(g,()=>ot(w),()=>ot(w))},y=N=>{const w=he.useContext(l)[N],[g,I]=he.useState(io(ot,w));return Qa(()=>Ye(w,L=>{L!==g&&I(oo(L))}),[w,g]),g},S=parseInt(he.version)>=18?v:y;return{Component:p,useEmitter:(N,w)=>{const g=he.useContext(l)[N];Qa(()=>Ye(g,w),[w,g])},useEmitterValue:S,usePublisher:h}}const Ji=he.createContext(void 0),Zi=he.createContext(void 0),Ar="-webkit-sticky",vo="sticky",vn=Yi(()=>{if(typeof document>"u")return vo;const t=document.createElement("div");return t.style.position=Ar,t.style.position===Ar?Ar:vo}),el=typeof document<"u"?he.useLayoutEffect:he.useEffect;function zr(t){return"self"in t}function ru(t){return"body"in t}function tl(t,s,a,r=xa,o,n){const i=he.useRef(null),l=he.useRef(null),c=he.useRef(null),d=he.useCallback(h=>{let v,y,S;const N=h.target;if(ru(N)||zr(N)){const g=zr(N)?N:N.defaultView;S=n===!0?g.scrollX:g.scrollY,v=n===!0?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight,y=n===!0?g.innerWidth:g.innerHeight}else S=n===!0?N.scrollLeft:N.scrollTop,v=n===!0?N.scrollWidth:N.scrollHeight,y=n===!0?N.offsetWidth:N.offsetHeight;const w=()=>{t({scrollHeight:v,scrollTop:Math.max(S,0),viewportHeight:y})};h.suppressFlushSync===!0?w():Qr.flushSync(w),l.current!==null&&(S===l.current||S<=0||S===v-y)&&(l.current=null,s(!0),c.current&&(clearTimeout(c.current),c.current=null))},[t,s,n]);he.useEffect(()=>{const h=o||i.current;return r(o||i.current),d({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",d,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",d)}},[i,d,a,r,o]);function m(h){const v=i.current;if(!v||(n===!0?"offsetWidth"in v&&v.offsetWidth===0:"offsetHeight"in v&&v.offsetHeight===0))return;const y=h.behavior==="smooth";let S,N,w;zr(v)?(N=Math.max(Fs(v.document.documentElement,n===!0?"width":"height"),n===!0?v.document.documentElement.scrollWidth:v.document.documentElement.scrollHeight),S=n===!0?v.innerWidth:v.innerHeight,w=n===!0?window.scrollX:window.scrollY):(N=v[n===!0?"scrollWidth":"scrollHeight"],S=Fs(v,n===!0?"width":"height"),w=v[n===!0?"scrollLeft":"scrollTop"]);const g=N-S;if(h.top=Math.ceil(Math.max(Math.min(g,h.top),0)),Ui(S,N)||h.top===w){t({scrollHeight:N,scrollTop:w,viewportHeight:S}),y&&s(!0);return}y?(l.current=h.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,l.current=null,s(!0)},1e3)):l.current=null,n===!0&&(h={...h.behavior!==void 0?{behavior:h.behavior}:{},left:h.top}),v.scrollTo(h)}function p(h){n===!0&&(h={...h.behavior!==void 0?{behavior:h.behavior}:{},...h.top!==void 0?{left:h.top}:{}}),i.current.scrollBy(h)}return{scrollByCallback:p,scrollerRef:i,scrollToCallback:m}}function wn(t){return t}const nu=qe(()=>{const t=Z(l=>`Item ${l}`),s=Z(l=>`Group ${l}`),a=Z({}),r=Z(wn),o=Z("div"),n=Z(xa),i=(l,c=null)=>Et(Y(a,xe(d=>d[l]),st()),c);return{components:a,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:s,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:t,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:n,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),ou=qe(([t,s])=>({...t,...s}),at(Ki,nu)),iu=({height:t})=>e.jsx("div",{style:{height:t}}),lu={overflowAnchor:"none",position:vn(),zIndex:1},sl={overflowAnchor:"none"},cu={...sl,display:"inline-block",height:"100%"},wo=he.memo(function({showTopList:t=!1}){const s=Ie("listState"),a=Zt("sizeRanges"),r=Ie("useWindowScroll"),o=Ie("customScrollParent"),n=Zt("windowScrollContainerState"),i=Zt("scrollContainerState"),l=o||r?n:i,c=Ie("itemContent"),d=Ie("context"),m=Ie("groupContent"),p=Ie("trackItemSizes"),h=Ie("itemSize"),v=Ie("log"),y=Zt("gap"),S=Ie("horizontalDirection"),{callbackRef:N}=Sd(a,h,p,t?xa:l,v,y,o,S,Ie("skipAnimationFrameInResizeObserver")),[w,g]=he.useState(0);jn("deviation",J=>{w!==J&&g(J)});const I=Ie("EmptyPlaceholder"),L=Ie("ScrollSeekPlaceholder")??iu,A=Ie("ListComponent"),W=Ie("ItemComponent"),f=Ie("GroupComponent"),C=Ie("computeItemKey"),b=Ie("isSeeking"),F=Ie("groupIndices").length>0,U=Ie("alignToBottom"),k=Ie("initialItemFinalLocationReached"),D=t?{}:{boxSizing:"border-box",...S?{display:"inline-block",height:"100%",marginLeft:w!==0?w:U?"auto":0,paddingLeft:s.offsetTop,paddingRight:s.offsetBottom,whiteSpace:"nowrap"}:{marginTop:w!==0?w:U?"auto":0,paddingBottom:s.offsetBottom,paddingTop:s.offsetTop},...k?{}:{visibility:"hidden"}};return!t&&s.totalCount===0&&I!==null&&I!==void 0?e.jsx(I,{..._t(I,d)}):e.jsx(A,{..._t(A,d),"data-testid":t?"virtuoso-top-item-list":"virtuoso-item-list",ref:N,style:D,children:(t?s.topItems:s.items).map(J=>{const re=J.originalIndex,ce=C(re+s.firstItemIndex,J.data,d);return b?u.createElement(L,{..._t(L,d),height:J.size,index:J.index,key:ce,type:J.type||"item",...J.type==="group"?{}:{groupIndex:J.groupIndex}}):J.type==="group"?u.createElement(f,{..._t(f,d),"data-index":re,"data-item-index":J.index,"data-known-size":J.size,key:ce,style:lu},m(J.index,d)):u.createElement(W,{..._t(W,d),...xu(W,J.data),"data-index":re,"data-item-group-index":J.groupIndex,"data-item-index":J.index,"data-known-size":J.size,key:ce,style:S?cu:sl},F?c(J.index,J.groupIndex,J.data,d):c(J.index,J.data,d))})})}),du={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},uu={outline:"none",overflowX:"auto",position:"relative"},Nn=t=>({height:"100%",position:"absolute",top:0,width:"100%",...t?{display:"flex",flexDirection:"column"}:void 0}),al=(t,s,a=0)=>({...Nn(t),position:s?"relative":"absolute",top:s?-a:0}),mu={position:vn(),top:0,width:"100%",zIndex:1};function _t(t,s){if(typeof t!="string")return{context:s}}function xu(t,s){return{item:typeof t=="string"?void 0:s}}const pu=he.memo(function(){const t=Ie("HeaderComponent"),s=Zt("headerHeight"),a=Ie("HeaderFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,Ie("skipAnimationFrameInResizeObserver")),o=Ie("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null}),hu=he.memo(function(){const t=Ie("FooterComponent"),s=Zt("footerHeight"),a=Ie("HeaderFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,Ie("skipAnimationFrameInResizeObserver")),o=Ie("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null});function rl({useEmitter:t,useEmitterValue:s,usePublisher:a}){return he.memo(function({children:r,style:o,context:n,...i}){const l=a("scrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("scrollerRef"),p=s("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:v,scrollToCallback:y}=tl(l,d,c,m,void 0,p);return t("scrollTo",y),t("scrollBy",h),e.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:v,style:{...p?uu:du,...o},tabIndex:0,...i,..._t(c,n),children:r})})}function nl({useEmitter:t,useEmitterValue:s,usePublisher:a}){return he.memo(function({children:r,style:o,context:n,...i}){const l=a("windowScrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("totalListHeight"),p=s("deviation"),h=s("customScrollParent"),v=he.useRef(null),y=s("scrollerRef"),{scrollByCallback:S,scrollerRef:N,scrollToCallback:w}=tl(l,d,c,y,h);return el(()=>(N.current=h||v.current?.ownerDocument.defaultView,()=>{N.current=null}),[N,h]),t("windowScrollTo",w),t("scrollBy",S),e.jsx(c,{ref:v,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...m!==0?{height:m+p}:void 0},...i,..._t(c,n),children:r})})}const fu=({children:t})=>{const s=he.useContext(Ji),a=Zt("viewportHeight"),r=Zt("fixedItemHeight"),o=Ie("alignToBottom"),n=Ie("horizontalDirection"),i=he.useMemo(()=>_i(a,c=>Fs(c,n?"width":"height")),[a,n]),l=Js(i,!0,Ie("skipAnimationFrameInResizeObserver"));return he.useEffect(()=>{s&&(a(s.viewportHeight),r(s.itemHeight))},[s,a,r]),e.jsx("div",{"data-viewport-type":"element",ref:l,style:Nn(o),children:t})},gu=({children:t})=>{const s=he.useContext(Ji),a=Zt("windowViewportRect"),r=Zt("fixedItemHeight"),o=Ie("customScrollParent"),n=Ie("useWindowScroll"),i=Ie("topListHeight"),l=Ri(a,o,Ie("skipAnimationFrameInResizeObserver")),c=Ie("alignToBottom");return he.useEffect(()=>{s&&(r(s.itemHeight),a({listHeight:0,offsetTop:0,visibleHeight:s.viewportHeight,visibleWidth:100}))},[s,a,r]),e.jsx("div",{"data-viewport-type":"window",ref:l,style:al(c,n,i),children:t})},bu=({children:t})=>{const s=Ie("TopItemListComponent")??"div",a=Ie("headerHeight"),r={...mu,marginTop:`${a}px`},o=Ie("context");return e.jsx(s,{style:r,..._t(s,o),children:t})},vu=he.memo(function(t){const s=Ie("useWindowScroll"),a=Ie("topItemsIndexes").length>0,r=Ie("customScrollParent"),o=Ie("context");return e.jsxs(r||s?ju:Nu,{...t,context:o,children:[a&&e.jsx(bu,{children:e.jsx(wo,{showTopList:!0})}),e.jsxs(r||s?gu:fu,{children:[e.jsx(pu,{}),e.jsx(wo,{}),e.jsx(hu,{})]})]})}),{Component:wu,useEmitter:jn,useEmitterValue:Ie,usePublisher:Zt}=Xi(ou,{optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",minOverscanItemCount:"minOverscanItemCount",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedGroupHeight:"fixedGroupHeight",fixedItemHeight:"fixedItemHeight",heightEstimates:"heightEstimates",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},vu),Nu=rl({useEmitter:jn,useEmitterValue:Ie,usePublisher:Zt}),ju=nl({useEmitter:jn,useEmitterValue:Ie,usePublisher:Zt}),yu=wu,Su=qe(()=>{const t=Z(d=>e.jsxs("td",{children:["Item $",d]})),s=Z(null),a=Z(d=>e.jsxs("td",{colSpan:1e3,children:["Group ",d]})),r=Z(null),o=Z(null),n=Z({}),i=Z(wn),l=Z(xa),c=(d,m=null)=>Et(Y(n,xe(p=>p[d]),st()),m);return{components:n,computeItemKey:i,context:s,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:t,groupContent:a,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder"),TableBodyComponent:c("TableBody","tbody"),TableComponent:c("Table","table"),TableFooterComponent:c("TableFoot","tfoot"),TableHeadComponent:c("TableHead","thead"),TableRowComponent:c("TableRow","tr"),GroupComponent:c("Group","tr")}});at(Ki,Su);vn();const No={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},ku={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:jo,floor:xr,max:Ca,min:Lr,round:yo}=Math;function So(t,s,a){return Array.from({length:s-t+1}).map((r,o)=>({data:a===null?null:a[o+t],index:o+t}))}function Cu(t){return{...ku,items:t}}function Va(t,s){return t!==void 0&&t.width===s.width&&t.height===s.height}function Iu(t,s){return t!==void 0&&t.column===s.column&&t.row===s.row}const Tu=qe(([{increaseViewportBy:t,listBoundary:s,overscan:a,visibleRange:r},{footerHeight:o,headerHeight:n,scrollBy:i,scrollContainerState:l,scrollTo:c,scrollTop:d,smoothScrollTargetReached:m,viewportHeight:p},h,v,{didMount:y,propsReady:S},{customScrollParent:N,useWindowScroll:w,windowScrollContainerState:g,windowScrollTo:I,windowViewportRect:L},A])=>{const W=Z(0),f=Z(0),C=Z(No),b=Z({height:0,width:0}),F=Z({height:0,width:0}),U=Be(),k=Be(),D=Z(0),J=Z(null),re=Z({column:0,row:0}),ce=Be(),ie=Be(),fe=Z(!1),Ce=Z(0),ue=Z(!0),ge=Z(!1),B=Z(!1);Ye(Y(y,Ae(Ce),Se(([G,se])=>se!==0)),()=>{Ee(ue,!1)}),Ye(Y(pt(y,ue,F,b,Ce,ge),Se(([G,se,M,q,,Q])=>G&&!se&&M.height!==0&&q.height!==0&&!Q)),([,,,,G])=>{Ee(ge,!0),hn(1,()=>{Ee(U,G)}),is(Y(d),()=>{Ee(s,[0,0]),Ee(ue,!0)})}),be(Y(ie,Se(G=>G!=null&&G.scrollTop>0),ms(0)),f),Ye(Y(y,Ae(ie),Se(([,G])=>G!=null)),([,G])=>{G&&(Ee(b,G.viewport),Ee(F,G.item),Ee(re,G.gap),G.scrollTop>0&&(Ee(fe,!0),is(Y(d,Ks(1)),se=>{Ee(fe,!1)}),Ee(c,{top:G.scrollTop})))}),be(Y(b,xe(({height:G})=>G)),p),be(Y(pt(ye(b,Va),ye(F,Va),ye(re,(G,se)=>G!==void 0&&G.column===se.column&&G.row===se.row),ye(d)),xe(([G,se,M,q])=>({gap:M,item:se,scrollTop:q,viewport:G}))),ce),be(Y(pt(ye(W),r,ye(re,Iu),ye(F,Va),ye(b,Va),ye(J),ye(f),ye(fe),ye(ue),ye(Ce)),Se(([,,,,,,,G])=>!G),xe(([G,[se,M],q,Q,pe,$,j,,T,_])=>{const{column:V,row:me}=q,{height:oe,width:ae}=Q,{width:je}=pe;if(j===0&&(G===0||je===0))return No;if(ae===0){const At=fn(_,G),It=At+Math.max(j-1,0);return Cu(So(At,It,$))}const we=ol(je,ae,V);let Ke,Ue;T?se===0&&M===0&&j>0?(Ke=0,Ue=j-1):(Ke=we*xr((se+me)/(oe+me)),Ue=we*jo((M+me)/(oe+me))-1,Ue=Lr(G-1,Ca(Ue,we-1)),Ke=Lr(Ue,Ca(0,Ke))):(Ke=0,Ue=-1);const Je=So(Ke,Ue,$),{bottom:ht,top:dt}=ko(pe,q,Q,Je),rt=jo(G/we),Mt=rt*oe+(rt-1)*me-ht;return{bottom:ht,itemHeight:oe,items:Je,itemWidth:ae,offsetBottom:Mt,offsetTop:dt,top:dt}})),C),be(Y(J,Se(G=>G!==null),xe(G=>G.length)),W),be(Y(pt(b,F,C,re),Se(([G,se,{items:M}])=>M.length>0&&se.height!==0&&G.height!==0),xe(([G,se,{items:M},q])=>{const{bottom:Q,top:pe}=ko(G,q,se,M);return[pe,Q]}),st(Ea)),s);const te=Z(!1);be(Y(d,Ae(te),xe(([G,se])=>se||G!==0)),te);const ne=Wt(Y(pt(C,W),Se(([{items:G}])=>G.length>0),Ae(te),Se(([[G,se],M])=>{const q=G.items[G.items.length-1].index===se-1;return(M||G.bottom>0&&G.itemHeight>0&&G.offsetBottom===0&&G.items.length===se)&&q}),xe(([[,G]])=>G-1),st())),ze=Wt(Y(ye(C),Se(({items:G})=>G.length>0&&G[0].index===0),ms(0),st())),Fe=Wt(Y(ye(C),Ae(fe),Se(([{items:G},se])=>G.length>0&&!se),xe(([{items:G}])=>({endIndex:G[G.length-1].index,startIndex:G[0].index})),st($i),Ts(0)));be(Fe,v.scrollSeekRangeChanged),be(Y(U,Ae(b,F,W,re),xe(([G,se,M,q,Q])=>{const pe=Hi(G),{align:$,behavior:j,offset:T}=pe;let _=pe.index;_==="LAST"&&(_=q-1),_=Ca(0,_,Lr(q-1,_));let V=an(se,Q,M,_);return $==="end"?V=yo(V-se.height+M.height):$==="center"&&(V=yo(V-se.height/2+M.height/2)),T!==void 0&&T!==0&&(V+=T),{behavior:j,top:V}})),c);const Pe=Et(Y(C,xe(G=>G.offsetBottom+G.bottom)),0);return be(Y(L,xe(G=>({height:G.visibleHeight,width:G.visibleWidth}))),b),{customScrollParent:N,data:J,deviation:D,footerHeight:o,gap:re,headerHeight:n,increaseViewportBy:t,initialItemCount:f,itemDimensions:F,overscan:a,restoreStateFrom:ie,scrollBy:i,scrollContainerState:l,scrollHeight:k,scrollTo:c,scrollToIndex:U,scrollTop:d,smoothScrollTargetReached:m,totalCount:W,useWindowScroll:w,viewportDimensions:b,windowScrollContainerState:g,windowScrollTo:I,windowViewportRect:L,...v,gridState:C,horizontalDirection:B,initialTopMostItemIndex:Ce,totalListHeight:Pe,...h,endReached:ne,propsReady:S,rangeChanged:Fe,startReached:ze,stateChanged:ce,stateRestoreInProgress:fe,...A}},at(gn,Dt,Fa,qi,Bs,bn,Ps));function ol(t,s,a){return Ca(1,xr((t+a)/(xr(s)+a)))}function ko(t,s,a,r){const{height:o}=a;if(o===void 0||r.length===0)return{bottom:0,top:0};const n=an(t,s,a,r[0].index);return{bottom:an(t,s,a,r[r.length-1].index)+o,top:n}}function an(t,s,a,r){const o=ol(t.width,a.width,s.column),n=xr(r/o),i=n*a.height+Ca(0,n-1)*s.row;return i>0?i+s.row:i}const _u=qe(()=>{const t=Z(p=>`Item ${p}`),s=Z({}),a=Z(null),r=Z("virtuoso-grid-item"),o=Z("virtuoso-grid-list"),n=Z(wn),i=Z("div"),l=Z(xa),c=(p,h=null)=>Et(Y(s,xe(v=>v[p]),st()),h),d=Z(!1),m=Z(!1);return be(ye(m),d),{components:s,computeItemKey:n,context:a,FooterComponent:c("Footer"),HeaderComponent:c("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:c("Item","div"),itemContent:t,listClassName:o,ListComponent:c("List","div"),readyStateChanged:d,reportReadyState:m,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),Eu=qe(([t,s])=>({...t,...s}),at(Tu,_u)),Ru=he.memo(function(){const t=tt("gridState"),s=tt("listClassName"),a=tt("itemClassName"),r=tt("itemContent"),o=tt("computeItemKey"),n=tt("isSeeking"),i=es("scrollHeight"),l=tt("ItemComponent"),c=tt("ListComponent"),d=tt("ScrollSeekPlaceholder"),m=tt("context"),p=es("itemDimensions"),h=es("gap"),v=tt("log"),y=tt("stateRestoreInProgress"),S=es("reportReadyState"),N=Js(he.useMemo(()=>w=>{const g=w.parentElement.parentElement.scrollHeight;i(g);const I=w.firstChild;if(I!==null){const{height:L,width:A}=I.getBoundingClientRect();p({height:L,width:A})}h({column:Co("column-gap",getComputedStyle(w).columnGap,v),row:Co("row-gap",getComputedStyle(w).rowGap,v)})},[i,p,h,v]),!0,!1);return el(()=>{t.itemHeight>0&&t.itemWidth>0&&S(!0)},[t]),y?null:e.jsx(c,{className:s,ref:N,..._t(c,m),"data-testid":"virtuoso-item-list",style:{paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},children:t.items.map(w=>{const g=o(w.index,w.data,m);return n?e.jsx(d,{..._t(d,m),height:t.itemHeight,index:w.index,width:t.itemWidth},g):u.createElement(l,{..._t(l,m),className:a,"data-index":w.index,key:g},r(w.index,w.data,m))})})}),Mu=he.memo(function(){const t=tt("HeaderComponent"),s=es("headerHeight"),a=tt("headerFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,!1),o=tt("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null}),Au=he.memo(function(){const t=tt("FooterComponent"),s=es("footerHeight"),a=tt("headerFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,!1),o=tt("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null}),zu=({children:t})=>{const s=he.useContext(Zi),a=es("itemDimensions"),r=es("viewportDimensions"),o=Js(he.useMemo(()=>n=>{r(n.getBoundingClientRect())},[r]),!0,!1);return he.useEffect(()=>{s&&(r({height:s.viewportHeight,width:s.viewportWidth}),a({height:s.itemHeight,width:s.itemWidth}))},[s,r,a]),e.jsx("div",{ref:o,style:Nn(!1),children:t})},Lu=({children:t})=>{const s=he.useContext(Zi),a=es("windowViewportRect"),r=es("itemDimensions"),o=tt("customScrollParent"),n=tt("useWindowScroll"),i=Ri(a,o,!1);return he.useEffect(()=>{s&&(r({height:s.itemHeight,width:s.itemWidth}),a({listHeight:0,offsetTop:0,visibleHeight:s.viewportHeight,visibleWidth:s.viewportWidth}))},[s,a,r]),e.jsx("div",{ref:i,style:al(!1,n),children:t})},Du=he.memo(function({...t}){const s=tt("useWindowScroll"),a=tt("customScrollParent"),r=a||s?Fu:$u,o=a||s?Lu:zu,n=tt("context");return e.jsx(r,{...t,..._t(r,n),children:e.jsxs(o,{children:[e.jsx(Mu,{}),e.jsx(Ru,{}),e.jsx(Au,{})]})})}),{useEmitter:il,useEmitterValue:tt,usePublisher:es}=Xi(Eu,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},Du),$u=rl({useEmitter:il,useEmitterValue:tt,usePublisher:es}),Fu=nl({useEmitter:il,useEmitterValue:tt,usePublisher:es});function Co(t,s,a){return s!=="normal"&&s?.endsWith("px")!==!0&&a(`${t} was not resolved to pixel value correctly`,s,vt.WARN),s==="normal"?0:parseInt(s??"0",10)}function Io(t){if(Array.isArray(t)){if(t.length<5||t.length>6)throw new Error(`Invalid bone format: expected [x,y,w,h,r,c?] but got ${t.length} elements`);const s=t;return{x:s[0],y:s[1],w:s[2],h:s[3],r:s[4],c:s[5]||void 0}}return t}const To=new Set(["p","h1","h2","h3","h4","h5","h6","li","td","th"]);function Ou(t,s="component",a){const r=t.getBoundingClientRect(),o=[],n=a?.leafTags?new Set([...To,...a.leafTags]):To,i=a?.captureRoundedBorders??!0,l=a?.excludeTags?new Set(a.excludeTags):null,c=a?.excludeSelectors??null;function d(m){const p=getComputedStyle(m);if(p.display==="none"||p.visibility==="hidden"||p.opacity==="0")return;const h=m.tagName.toLowerCase();if(l?.has(h)||c?.some(b=>m.matches(b)))return;const v=[...m.children].filter(b=>{const F=getComputedStyle(b);return F.display!=="none"&&F.visibility!=="hidden"&&F.opacity!=="0"}),y=h==="img"||h==="svg"||h==="video"||h==="canvas",S=h==="input"||h==="button"||h==="textarea"||h==="select",N=v.length===0||y||S||n.has(h),w=p.backgroundColor,g=w!=="rgba(0, 0, 0, 0)"&&w!=="transparent",I=p.backgroundImage!=="none",L=parseFloat(p.borderTopWidth)||0,A=i&&L>0&&p.borderTopColor!=="rgba(0, 0, 0, 0)"&&p.borderTopColor!=="transparent",W=(parseFloat(p.borderTopLeftRadius)||0)>0,f=g||I||A&&W,C=h==="tr"||h==="td"||h==="th"||h==="thead"||h==="tbody"||h==="table";if(N){const b=m.getBoundingClientRect();if(b.width<1||b.height<1)return;const F=y&&b.width>0&&b.height>0&&Math.abs(b.width-b.height)<4,U=C?0:F?"50%":_o(p,m)??8,k=r.width;o.push({x:k>0?+((b.left-r.left)/k*100).toFixed(4):0,y:Math.round(b.top-r.top),w:k>0?+(b.width/k*100).toFixed(4):0,h:Math.round(b.height),r:U});return}if(f){const b=m.getBoundingClientRect();if(b.width>=1&&b.height>=1){const F=C?0:_o(p,m)??8,U=r.width;o.push({x:U>0?+((b.left-r.left)/U*100).toFixed(4):0,y:Math.round(b.top-r.top),w:U>0?+(b.width/U*100).toFixed(4):0,h:Math.round(b.height),r:F,c:!0})}}for(const b of v)d(b)}for(const m of t.children)d(m);return{name:s,viewportWidth:Math.round(r.width),width:Math.round(r.width),height:Math.round(r.height),bones:o}}function _o(t,s){const a=parseFloat(t.borderTopLeftRadius)||0,r=parseFloat(t.borderTopRightRadius)||0,o=parseFloat(t.borderBottomRightRadius)||0,n=parseFloat(t.borderBottomLeftRadius)||0;if(a===0&&r===0&&o===0&&n===0)return;const i=s?(()=>{const d=s.getBoundingClientRect();return d.width>0&&d.height>0&&Math.abs(d.width-d.height)<4})():!1;return t.borderRadius==="50%"?"50%":Math.max(a,r,o,n)>9998?i?"50%":9999:a===r&&r===o&&o===n?a!==8?a:void 0:`${a}px ${r}px ${o}px ${n}px`}const Pu=new Map;function Bu(t){return Pu.get(t)}function Hu(){typeof window<"u"&&window.__BONEYARD_BUILD&&(window.__BONEYARD_SNAPSHOT=Ou)}function Uu(){return typeof window<"u"&&window.__BONEYARD_BUILD===!0}function Gu(t,s){if(!("breakpoints"in t))return t;const a=Object.keys(t.breakpoints).map(Number).sort((o,n)=>o-n);if(a.length===0)return null;const r=[...a].reverse().find(o=>s>=o)??a[0];return t.breakpoints[r]??null}const ta={angle:110,start:30,end:70,speed:"2s",lightHighlight:"#f7f7f7",darkHighlight:"#2c2c2c"},va={speed:"1.8s",lightAdjust:.3,darkAdjust:.02},Eo={web:{light:"#f0f0f0",dark:"#222222"}},Qu=/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+))?\s*\)/;function Ro(t,s){const a=t.match(Qu);if(a){const[,r,o,n,i="1"]=a,l=Math.min(1,parseFloat(i)+s*.5);return`rgba(${r},${o},${n},${l.toFixed(3)})`}if(t.startsWith("#")&&t.length>=7){const r=parseInt(t.slice(1,3),16),o=parseInt(t.slice(3,5),16),n=parseInt(t.slice(5,7),16);if(!isNaN(r)&&!isNaN(o)&&!isNaN(n)){const i=Math.round(r+(255-r)*s),l=Math.round(o+(255-o)*s),c=Math.round(n+(255-n)*s);return`#${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}${c.toString(16).padStart(2,"0")}`}}return t}Hu();let us={};function Mo({loading:t,children:s,name:a,initialBones:r,color:o,darkColor:n,animate:i,stagger:l=!1,transition:c=!1,boneClass:d,className:m,fallback:p,fixture:h,snapshotConfig:v}){const y=u.useRef(null),S=u.useRef(Math.random().toString(36).slice(2,8)).current,[N,w]=u.useState(0),[g,I]=u.useState(0),[L,A]=u.useState(!1);u.useEffect(()=>{if(typeof window>"u")return;const M=()=>{const pe=document.documentElement.classList.contains("dark")||!!y.current?.closest(".dark");A(pe)};M();const q=new MutationObserver(M);q.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const Q=window.matchMedia("(prefers-color-scheme: dark)");return Q.addEventListener("change",M),()=>{q.disconnect(),Q.removeEventListener("change",M)}},[]);const W=o??us.color??Eo.web.light,f=n??us.darkColor??Eo.web.dark,C=L?f:W,b=i??us.animate??"pulse",F=b===!0?"pulse":b===!1?"solid":b;u.useEffect(()=>{const M=y.current;if(!M)return;const q=new ResizeObserver(pe=>{const $=pe[0]?.contentRect;w(Math.round($?.width??0)),$&&$.height>0&&I(Math.round($.height))});q.observe(M);const Q=M.getBoundingClientRect();return w(Math.round(Q.width)),Q.height>0&&I(Math.round(Q.height)),()=>q.disconnect()},[]);const U={};if(a&&(U["data-boneyard"]=a,v&&(U["data-boneyard-config"]=JSON.stringify(v))),Uu())return e.jsx("div",{ref:y,className:m,style:{position:"relative"},...U,children:e.jsx("div",{children:h??s})});const[k,D]=u.useState(!1);u.useLayoutEffect(()=>{D(!0)},[]);const J=r??(a?Bu(a):void 0),re=k&&typeof window<"u"?window.innerWidth:0,ce=N>0?N:re,ie=J&&ce>0?Gu(J,ce):null,fe=d??us.boneClass,Ce=(()=>{const M=l??us.stagger;return M===!0?80:M===!1||!M?0:M})(),ue=(()=>{const M=c??us.transition;return M===!0?300:M===!1||!M?0:M})(),[ge,B]=u.useState(!1),te=u.useRef(t),ne=u.useRef(null);u.useEffect(()=>(te.current&&!t&&ue>0&&ie&&(ne.current&&clearTimeout(ne.current),B(!0),ne.current=setTimeout(()=>{B(!1),ne.current=null},ue)),te.current=t,()=>{ne.current&&clearTimeout(ne.current)}),[t,ue,ie]);const ze=(t||ge)&&ie,Fe=t&&!ie&&!ge,Pe=g>0?g:ie?.height??0,G=ie?.height??0,se=Pe>0&&G>0?Pe/G:1;return e.jsxs("div",{ref:y,className:m,style:{position:"relative"},...U,children:[e.jsx("div",{"data-boneyard-content":"true",style:ze&&!ge?{visibility:"hidden"}:void 0,children:Fe?p:s}),ze&&e.jsx("div",{"data-boneyard-overlay":"true",style:{position:"absolute",inset:0,overflow:"hidden",opacity:ge?0:1,transition:ue>0?`opacity ${ue}ms ease-out`:void 0},children:e.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[ie.bones.filter(M=>!Io(M).c).map((M,q)=>{const Q=Io(M),pe=C;Ro(C,L?va.darkAdjust:va.lightAdjust);const $=Q.w/100*(ie.width??0),j=Q.r==="50%"&&Math.abs($-Q.h)<4,T={position:"absolute",left:`${Q.x}%`,top:Q.y*se,width:j?Q.h*se:`${Q.w}%`,height:Q.h*se,borderRadius:typeof Q.r=="string"?Q.r:`${Q.r}px`,backgroundColor:pe},_=us.speed;if(F==="pulse")T.animation=`bp-${S} ${_??va.speed} ease-in-out infinite`;else if(F==="shimmer"){const V=L?us.darkShimmerColor??ta.darkHighlight:us.shimmerColor??ta.lightHighlight,me=us.shimmerAngle??ta.angle;delete T.backgroundColor,T.backgroundImage=`linear-gradient(${me}deg, ${pe} ${ta.start}%, ${V} 50%, ${pe} ${ta.end}%)`,T.backgroundSize="200% 100%",T.animation=`bs-${S} ${_??ta.speed} linear infinite`}return Ce>0&&(T.opacity=0,T.animation=`${T.animation?T.animation+",":""} by-${S} 0.3s ease-out ${q*Ce}ms forwards`),e.jsx("div",{"data-boneyard-bone":"true",className:fe,style:T},q)}),F==="pulse"&&e.jsx("style",{children:`@keyframes bp-${S}{0%,100%{background-color:${C}}50%{background-color:${Ro(C,L?va.darkAdjust:va.lightAdjust)}}}`}),F==="shimmer"&&e.jsx("style",{children:`@keyframes bs-${S}{0%{background-position:200% 0}100%{background-position:-200% 0}}`}),Ce>0&&e.jsx("style",{children:`@keyframes by-${S}{from{opacity:0}to{opacity:1}}`})]})})]})}async function yn(t){const s=St($e,"managedStudents");try{const n=kt(s,Nt("teacherId","==",t)),i=await Lt(n);if(!i.empty)return i.docs.map(c=>({id:c.id,...c.data()})).sort((c,d)=>String(c.name||"").localeCompare(String(d.name||"")))}catch{}const r=(await cl(t)).map(n=>n.id);if(r.length===0)return[];const o=new Map;for(let n=0;n{o.set(d.id,{id:d.id,...d.data()})})}return Array.from(o.values()).sort((n,i)=>String(n.name||"").localeCompare(String(i.name||"")))}async function Vu(t,s=[]){if(!t)return[];const a=St($e,"users"),r=new Map,o=(i,l)=>String(l.role||"").toLowerCase()!=="student"?null:{uid:i,name:String(l.name||l.displayName||"").trim()||"Student",email:String(l.email||"").trim(),lrn:l.lrn&&String(l.lrn).trim()||void 0,photo:l.photo?String(l.photo).trim()||void 0:l.photoURL&&String(l.photoURL).trim()||void 0,grade:l.grade&&String(l.grade).trim()||void 0,section:l.section&&String(l.section).trim()||void 0,classSectionId:l.classSectionId&&String(l.classSectionId).trim()||void 0,adviserTeacherId:l.adviserTeacherId&&String(l.adviserTeacherId).trim()||void 0,role:"student",createdAt:l.createdAt||void 0};try{const i=kt(a,Nt("role","==","student"),Nt("adviserTeacherId","==",t));(await Lt(i)).docs.forEach(c=>{const d=o(c.id,c.data());d&&r.set(c.id,d)})}catch(i){console.warn("[studentService] adviser-scoped student query failed:",i)}const n=Array.from(new Set((s||[]).map(i=>(i||"").trim()).filter(i=>!!i)));for(let i=0;i{if(r.has(m.id))return;const p=o(m.id,m.data());p&&r.set(m.id,p)})}catch(c){console.warn("[studentService] section-scoped student query failed:",c)}}return Array.from(r.values()).sort((i,l)=>i.name.localeCompare(l.name))}function Wu(t){const s=`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||"Student")}&background=random`,a=Zl.now();return{id:t.uid,accountUid:t.uid,lrn:t.lrn,name:t.name,email:t.email,avatar:t.photo||s,teacherId:t.adviserTeacherId,grade:t.grade,gradeLevel:Ns(t.grade)||void 0,section:t.section,classSectionId:t.classSectionId,riskLevel:"Low",engagementScore:0,avgQuizScore:0,weakestTopic:"N/A",classroomId:t.classSectionId||"",attendance:0,assignmentCompletion:0,lastActive:null,struggles:[],createdAt:t.createdAt||a,updatedAt:a,hasRegisteredAccount:!0,source:"registered"}}function Ao(t){return(t||"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9\s]+/g," ").trim().replace(/\s+/g," ")}async function qu(t){const s=(t.studentId||"").trim();if(!s)throw new Error("Cannot reassign section: studentId is required.");const a=(t.newClassSectionId||"").trim()||Pt(t.newGrade,t.newSection);if(!a)throw new Error("Cannot reassign section: a target class section is required.");const r=(t.teacherId||"").trim(),o=(t.teacherName||"").trim(),n=(t.schoolYear||"").trim(),i=(t.previousClassSectionId||"").trim();try{const l=ct($e,"managedStudents",s),c=await Is(l);c.exists()&&await ns(l,{grade:t.newGrade,section:t.newSection,classSectionId:a,gradeLevel:Ns(t.newGrade)||t.newGrade,teacherId:r||c.data()?.teacherId,updatedAt:it()})}catch(l){console.warn("[studentService] reassignStudentSection: managedStudents update failed:",l)}if(t.isRegisteredAccount)try{await os(ct($e,"users",s),{grade:t.newGrade,section:t.newSection,classSectionId:a,adviserTeacherId:r||void 0,adviserTeacherName:o||void 0,updatedAt:it()},{merge:!0})}catch(l){console.warn("[studentService] reassignStudentSection: users profile update failed:",l)}try{await jr({classSectionId:a,grade:t.newGrade,section:t.newSection,schoolYear:n,ownerTeacherId:r,ownerTeacherName:o,studentUids:[s]})}catch(l){console.warn("[studentService] reassignStudentSection: ownership upsert failed:",l)}if(i&&i!==a)try{const l=ct($e,"classSectionOwnership",i),c=await Is(l);if(c.exists()){const m=(c.data().studentUids||[]).filter(p=>p!==s);await ns(l,{studentUids:m,updatedAt:it()})}}catch(l){console.warn("[studentService] reassignStudentSection: previous-section cleanup failed:",l)}}async function Yu(t){const{apiService:s}=await Cs(async()=>{const{apiService:d}=await import("./index-BvEKrMkD.js").then(m=>m.b8);return{apiService:d}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),a=(t.adviserTeacherId||"").trim();if(!a)throw new Error("createStudentAccountFromRoster requires adviserTeacherId.");const r=(t.email||"").trim().toLowerCase();if(!r)throw new Error("createStudentAccountFromRoster requires an email.");const o=(t.grade||"").trim(),n=(t.section||"").trim(),i=(t.classSectionId||"").trim()||(o&&n?Pt(o,n):""),c=((await s.createStudentAccount({name:(t.name||"").trim()||"Student",email:r,temporaryPassword:t.temporaryPassword,lrn:t.lrn?.trim()||void 0,grade:o||void 0,section:n||void 0,classSectionId:i||void 0,adviserTeacherId:a,adviserTeacherName:t.adviserTeacherName?.trim()||void 0,schoolYear:t.schoolYear?.trim()||void 0})).uid||"").trim();if(!c)throw new Error("Backend did not return a uid for the newly created student.");try{await os(ct($e,"managedStudents",c),pr({accountUid:c,name:(t.name||"").trim()||"Student",email:r,lrn:t.lrn?.trim()||null,teacherId:a,grade:o||null,gradeLevel:Ns(o)||null,section:n||null,classSectionId:i||null,classroomId:i||null,riskLevel:"Low",avgQuizScore:0,engagementScore:0,attendance:0,assignmentCompletion:0,weakestTopic:"",struggles:[],avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||"Student")}&background=random`,hasRegisteredAccount:!0,source:"both",createdAt:it(),updatedAt:it()}))}catch(d){console.warn("[studentService] createStudentAccountFromRoster: managed-student merge failed:",d)}if(i&&o&&n)try{await jr({classSectionId:i,grade:o,section:n,schoolYear:t.schoolYear||"",ownerTeacherId:a,ownerTeacherName:t.adviserTeacherName,studentUids:[c]})}catch(d){console.warn("[studentService] createStudentAccountFromRoster: ownership upsert failed:",d)}return{uid:c,email:r,temporaryPassword:t.temporaryPassword}}async function ll(t,s,a){const r=Pt(s,a),o=ct($e,"managedStudents",t);await ns(o,{grade:s,section:a,classSectionId:r,updatedAt:it()})}async function Ku(t,s){const a=ct($e,"classSectionOwnership",s);await ns(a,{studentUids:Jl(t),updatedAt:it()}).catch(r=>console.warn("[studentService] removeStudentFromClass: ownership update failed:",r)),await cn(ct($e,"managedStudents",t)).catch(r=>console.warn("[studentService] removeStudentFromClass: managedStudents delete failed:",r))}function Pt(t,s){return[t,s].filter(Boolean).join("_").replace(/\s+/g,"_").toLowerCase()}function pr(t){const s=Object.entries(t).filter(([,a])=>a!==void 0);return Object.fromEntries(s)}function Ns(t){const s=(t||"").trim();if(!s)return null;const a=s.match(/(\d{1,2})/);return a?`Grade ${a[1]}`:/^grade\s+/i.test(s)?s.replace(/\s+/g," ").trim().replace(/^grade/i,"Grade"):s}function pa(t){const a=Ns(t)?.match(/(\d{1,2})/),r=a?Number.parseInt(a[1],10):Number.NaN;return Number.isFinite(r)?r>=11?"Senior High School":"Junior High School":null}function ha(t,s){const a=`${t||""} ${s||""}`.toUpperCase();if(!a.trim())return null;const r=["STEM","ABM","HUMSS","GAS","TVL","ICT"];for(const o of r)if(new RegExp(`\\b${o}\\b`).test(a))return o;return null}function gs(t){const s=(t||"").trim();if(!s)return{grade:"Grade 11",section:"Section A"};const[a="Grade 11",r="Section A"]=s.split(" - ").map(o=>o.trim());return{grade:a||"Grade 11",section:r||"Section A"}}function yt(t){const s=t.metadata||{},a=t.className||s.className,r=gs(a),o=(t.grade||s.grade||r.grade||"").trim()||null,n=(t.section||s.section||r.section||"").trim()||null,i=(t.classSectionId||s.classSectionId||"").trim()||(o&&n?Pt(o,n):"")||null,l=(a||"").trim()||(o&&n?`${o} - ${n}`:"")||null,c=Ns(t.gradeLevel||s.gradeLevel||o),d=(t.classification||s.classification||"").trim()||pa(c)||null,m=(t.strand||s.strand||"").trim()||ha(l,n)||null;return{classSectionId:i,className:l,grade:o,section:n,gradeLevel:c,classification:d,strand:m,schoolYear:(t.schoolYear||s.schoolYear||"").trim()||null,ownerTeacherId:(t.ownerTeacherId||s.ownerTeacherId||"").trim()||null,ownerTeacherName:(t.ownerTeacherName||s.ownerTeacherName||"").trim()||null,adviserTeacherId:(t.adviserTeacherId||s.adviserTeacherId||"").trim()||null,adviserTeacherName:(t.adviserTeacherName||s.adviserTeacherName||"").trim()||null,managerId:(t.managerId||s.managerId||"").trim()||null,managerName:(t.managerName||s.managerName||"").trim()||null}}function Xu(t){const s=(t.className||"").trim(),[a="",r=""]=s.split(" - "),o=(t.grade||a||"").trim()||null,n=(t.section||r||"").trim()||null,i=(t.classSectionId||"").trim()||(o&&n?Pt(o,n):"")||null,l=s||(o&&n?`${o} - ${n}`:null),c=Ns(t.gradeLevel||o),d=(t.classification||"").trim()||pa(c),m=(t.strand||"").trim()||ha(l,n);return{classSectionId:i,className:l,grade:o,section:n,gradeLevel:c,classification:d,strand:m,schoolYear:(t.schoolYear||"").trim()||null,ownerTeacherId:(t.ownerTeacherId||"").trim()||null,ownerTeacherName:(t.ownerTeacherName||"").trim()||null,adviserTeacherId:(t.adviserTeacherId||"").trim()||null,adviserTeacherName:(t.adviserTeacherName||"").trim()||null,managerId:(t.managerId||"").trim()||null,managerName:(t.managerName||"").trim()||null}}async function cl(t){const s=St($e,"classrooms"),a=new Map,r=kt(s,Nt("teacherId","==",t));(await Lt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=kt(s,Nt("managerId","==",t));return(await Lt(n)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})}),Array.from(a.values()).sort((l,c)=>String(l.name||"").localeCompare(String(c.name||"")))}async function jr(t){const s=t.classSectionId||Pt(t.grade,t.section),a=ct($e,"classSectionOwnership",s),r=await Is(a),o=r.exists()?r.data().studentUids||[]:[],n=Array.from(new Set([...t.studentUids||[],...o])),i=pr(t);return r.exists()?await ns(a,{...i,classSectionId:s,studentUids:n,updatedAt:it()}):await os(a,{...i,classSectionId:s,studentUids:n,createdAt:it(),updatedAt:it()}),s}async function dl(t){const s=(t.classSectionId||"").trim()||Pt(t.grade,t.section),a=(t.className||"").trim()||`${t.grade} - ${t.section}`,r=Xu({classSectionId:s,className:a,grade:t.grade,section:t.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName,adviserTeacherId:t.ownerTeacherId,adviserTeacherName:t.ownerTeacherName,managerId:t.managerId,managerName:t.managerName,classification:t.classification,strand:t.strand,gradeLevel:t.gradeLevel});await jr({classSectionId:s,className:a,grade:r.grade||t.grade,gradeLevel:r.gradeLevel||t.gradeLevel||t.grade,classification:r.classification||t.classification,strand:r.strand||t.strand,section:r.section||t.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName,managerId:t.managerId,managerName:t.managerName,studentUids:[]});const o=St($e,"classrooms"),n=kt(o,Nt("classSectionId","==",s)),i=await Lt(n);if(i.empty){const l=pr({name:a,teacherId:t.ownerTeacherId,grade:r.grade,gradeLevel:r.gradeLevel,classification:r.classification,strand:r.strand,section:r.section,classSectionId:s,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName||"",adviserTeacherId:t.ownerTeacherId,adviserTeacherName:t.ownerTeacherName||"",managerId:t.managerId,managerName:t.managerName||"",classMetadata:r,schedule:"Mon-Fri",studentCount:0,avgScore:0,atRiskCount:0,createdAt:it(),updatedAt:it()});await os(ct($e,"classrooms",s),l,{merge:!0})}else for(const l of i.docs){const c=pr({name:a,grade:r.grade,gradeLevel:r.gradeLevel,classification:r.classification,strand:r.strand,section:r.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName||"",adviserTeacherId:t.ownerTeacherId,adviserTeacherName:t.ownerTeacherName||"",managerId:t.managerId,managerName:t.managerName||"",classMetadata:r,updatedAt:it()});await ns(l.ref,c)}return s}async function yr(t,s,a,r,o,n){const i=Pt(s,a);await jr({classSectionId:i,grade:s,section:a,schoolYear:o,ownerTeacherId:r,ownerTeacherName:n,studentUids:[t]});const l=await Is(ct($e,"users",t)),c=l.exists()?l.data():{};await os(ct($e,"users",t),{grade:s,section:a,classSectionId:i,adviserTeacherId:r,adviserTeacherName:n||"",updatedAt:it()},{merge:!0}),await os(ct($e,"managedStudents",t),{accountUid:t,name:c.name||c.displayName||"Student",email:c.email||"",lrn:c.lrn||null,teacherId:r,grade:s,gradeLevel:s,section:a,classSectionId:i,classroomId:i,hasRegisteredAccount:!0,source:"registered",updatedAt:it()},{merge:!0})}async function Ju(t){const s=St($e,"classSectionOwnership"),a=new Map,r=kt(s,Nt("ownerTeacherId","==",t));(await Lt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=kt(s,Nt("managerId","==",t));return(await Lt(n)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})}),Array.from(a.values()).sort((l,c)=>String(l.classSectionId||"").localeCompare(String(c.classSectionId||"")))}async function Zu(t="",s=25){const a=St($e,"users"),r=Math.max(1,Math.min(100,s)),o=kt(a,Nt("role","==","teacher"),or(r*4)),n=await Lt(o),i=t.trim().toLowerCase();return n.docs.map(c=>{const d=c.data(),m=String(d.name||"").trim(),p=String(d.email||"").trim();return{uid:c.id,name:m||"Teacher",email:p,photo:String(d.photo||d.photoURL||"").trim()||void 0}}).filter(c=>i?c.name.toLowerCase().includes(i)||c.email.toLowerCase().includes(i):!0).sort((c,d)=>c.name.localeCompare(d.name)).slice(0,r)}function em(t,s,a=20){if(t.length===0)return s([]),()=>{};const r=St($e,"activities"),o=kt(r,Nt("classroomId","in",t),ec("timestamp","desc"));return gi(o,n=>{const i=n.docs.slice(0,a).map(l=>({id:l.id,...l.data()}));s(i)},n=>{console.error("[studentService] subscribeToActivities error:",n),s([])})}const tm=({open:t,onClose:s,onCreated:a,teacherName:r})=>{const{currentUser:o}=vs(),[n,i]=u.useState("details"),[l,c]=u.useState(""),d="Grade 11",[m,p]=u.useState(""),[h,v]=u.useState(!1),[y,S]=u.useState(""),[N,w]=u.useState([]),[g,I]=u.useState(new Set),[L,A]=u.useState(""),[W,f]=u.useState(!1);u.useEffect(()=>{t||(i("details"),c(""),p(""),S(""),I(new Set),A(""))},[t]),u.useEffect(()=>{t&&n==="students"&&C()},[t,n]);const C=async()=>{f(!0);try{const k=St($e,"users"),D=kt(k,Nt("role","==","student")),J=await Lt(D),re=[];J.docs.forEach(ce=>{const ie=ce.data();re.push({uid:ce.id,name:ie.name||ie.displayName||"Student",email:ie.email||"",grade:ie.grade,section:ie.section})}),w(re.sort((ce,ie)=>ce.name.localeCompare(ie.name)))}catch(k){console.error("[CreateClassModal] Failed to load students:",k)}finally{f(!1)}},b=async()=>{if(o){if(!m.trim()){S("Section name is required");return}S(""),v(!0);try{const k=String(new Date().getFullYear());if(await dl({classSectionId:"",grade:d,section:m.trim(),schoolYear:k,ownerTeacherId:o.uid,ownerTeacherName:r||o.displayName||"",managerId:o.uid,managerName:r||o.displayName||"",className:l.trim()||`${d} - ${m.trim()}`}),g.size>0){const D=Array.from(g).map(J=>yr(J,d,m.trim(),o.uid,k,r||o.displayName||""));await Promise.allSettled(D)}a(),s()}catch(k){S(k instanceof Error?k.message:"Failed to create class")}finally{v(!1)}}},F=k=>{I(D=>{const J=new Set(D);return J.has(k)?J.delete(k):J.add(k),J})},U=N.filter(k=>k.name.toLowerCase().includes(L.toLowerCase())||k.email.toLowerCase().includes(L.toLowerCase()));return t?e.jsx(zt,{children:e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 bg-black/40 backdrop-blur-sm",onClick:s}),e.jsxs(Re.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"relative bg-white rounded-2xl shadow-xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-[#f1f5f9]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[#1e293b]",children:n==="details"?"Create New Class":"Add Students"}),e.jsx("button",{onClick:s,className:"p-1 rounded-lg hover:bg-[#f1f5f9] transition-colors",children:e.jsx(qt,{size:20,className:"text-[#64748b]"})})]}),e.jsxs("div",{className:"p-6 overflow-y-auto flex-1",children:[n==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-[#475569] block mb-1.5",children:"Class Name"}),e.jsx(_s,{placeholder:"e.g. Grade 11 - Section A",value:l,onChange:k=>c(k.target.value)}),e.jsx("p",{className:"text-xs text-[#94a3b8] mt-1",children:"Optional. Auto-generated from grade + section if empty."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-[#475569] block mb-1.5",children:"Section"}),e.jsx(_s,{placeholder:"e.g. Section A, STEM-1, Rizal",value:m,onChange:k=>p(k.target.value)})]}),y&&e.jsx("p",{className:"text-sm text-rose-500",children:y})]}),n==="students"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Xs,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(_s,{placeholder:"Search students...",value:L,onChange:k=>A(k.target.value),className:"pl-9"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[g.size," student(s) selected"]}),W?e.jsx("p",{className:"text-sm text-[#64748b] text-center py-4",children:"Loading students..."}):U.length===0?e.jsx("p",{className:"text-sm text-[#64748b] text-center py-4",children:"No students found."}):e.jsx("div",{className:"space-y-1 max-h-[300px] overflow-y-auto",children:U.map(k=>e.jsxs("button",{onClick:()=>F(k.uid),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${g.has(k.uid)?"bg-purple-50 border border-purple-200":"hover:bg-[#f8fafc] border border-transparent"}`,children:[e.jsx("div",{className:`w-5 h-5 rounded-md border-2 flex items-center justify-center ${g.has(k.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:g.has(k.uid)&&e.jsx(Gt,{size:12,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[#1e293b] truncate",children:k.name}),e.jsx("p",{className:"text-xs text-[#64748b] truncate",children:k.email})]}),k.grade&&e.jsx("span",{className:"text-xs text-[#94a3b8]",children:k.grade})]},k.uid))}),y&&e.jsx("p",{className:"text-sm text-rose-500",children:y})]})]}),e.jsx("div",{className:"flex items-center justify-between p-6 border-t border-[#f1f5f9]",children:n==="details"?e.jsxs(e.Fragment,{children:[e.jsx(wt,{variant:"outline",onClick:s,children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(wt,{variant:"outline",onClick:()=>{if(!m.trim()){S("Section is required");return}S(""),i("students")},children:"Add Students"}),e.jsx(wt,{onClick:b,disabled:h||!m.trim(),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:h?"Creating...":"Create Class"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{variant:"outline",onClick:()=>i("details"),children:"Back"}),e.jsxs(wt,{onClick:b,disabled:h,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(ua,{size:16,className:"mr-1"}),h?"Creating...":`Create with ${g.size} Student${g.size!==1?"s":""}`]})]})})]})]})}):null},sm=({open:t,onClose:s,onAdded:a,grade:r,section:o,teacherName:n,existingStudentUids:i=[]})=>{const{currentUser:l}=vs(),[c,d]=u.useState([]),[m,p]=u.useState(new Set),[h,v]=u.useState(""),[y,S]=u.useState(!1),[N,w]=u.useState(!1);u.useEffect(()=>{t&&(p(new Set),v(""),g())},[t]);const g=async()=>{S(!0);try{const A=kt(St($e,"users"),Nt("role","==","student")),f=(await Lt(A)).docs.filter(C=>!i.includes(C.id)).map(C=>{const b=C.data();return{uid:C.id,name:b.name||b.displayName||"Student",email:b.email||""}}).sort((C,b)=>C.name.localeCompare(b.name));d(f)}catch{}S(!1)},I=async()=>{if(!(!l||m.size===0)){w(!0);try{const A=String(new Date().getFullYear()),W=Array.from(m).map(f=>yr(f,r,o,l.uid,A,n||l.displayName||""));await Promise.allSettled(W),le.success(`Added ${m.size} student(s) to class`),a(),s()}catch{le.error("Failed to add students")}w(!1)}},L=c.filter(A=>A.name.toLowerCase().includes(h.toLowerCase())||A.email.toLowerCase().includes(h.toLowerCase()));return t?e.jsx(zt,{children:e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 bg-black/40 backdrop-blur-sm",onClick:s}),e.jsxs(Re.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"relative bg-white rounded-2xl shadow-xl w-full max-w-2xl mx-4 max-h-[80vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-5 border-b border-[#f1f5f9]",children:[e.jsxs("h2",{className:"text-base font-semibold text-[#1e293b]",children:["Add Students to ",r," - ",o]}),e.jsx("button",{onClick:s,className:"p-1 rounded-lg hover:bg-[#f1f5f9]",children:e.jsx(qt,{size:18,className:"text-[#64748b]"})})]}),e.jsxs("div",{className:"p-4 space-y-3 flex-1 overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Xs,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(_s,{placeholder:"Search students...",value:h,onChange:A=>v(A.target.value),className:"pl-8 h-9 text-sm"})]}),e.jsx("button",{onClick:()=>{m.size===L.length?p(new Set):p(new Set(L.map(A=>A.uid)))},className:"text-[11px] font-semibold text-[#9956DE] hover:text-[#7c3aed] bg-[#9956DE]/10 hover:bg-[#9956DE]/20 px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",children:m.size===L.length&&L.length>0?"Deselect All":"Select All"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[m.size," of ",L.length," selected"]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-1 min-h-[300px]",children:y?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"Loading..."}):L.length===0?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"No students available"}):L.map(A=>e.jsxs("button",{onClick:()=>p(W=>{const f=new Set(W);return f.has(A.uid)?f.delete(A.uid):f.add(A.uid),f}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${m.has(A.uid)?"bg-purple-50 border border-purple-200":"hover:bg-[#f8fafc] border border-transparent"}`,children:[e.jsx("div",{className:`w-5 h-5 rounded-md border-2 flex items-center justify-center shrink-0 ${m.has(A.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:m.has(A.uid)&&e.jsx(Gt,{size:12,className:"text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[#1e293b] truncate",children:A.name}),e.jsx("p",{className:"text-[11px] text-[#64748b] truncate",children:A.email})]})]},A.uid))})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-[#f1f5f9]",children:[e.jsx(wt,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),e.jsxs(wt,{size:"sm",onClick:I,disabled:N||m.size===0,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(ui,{size:14,className:"mr-1.5"}),N?"Adding...":`Add ${m.size} Student${m.size!==1?"s":""}`]})]})]})]})}):null},ul="https://deign86-mathpulse-api-v3test.hf.space";async function ml(){const t={"Content-Type":"application/json"},s=mi.currentUser;if(s)try{const a=await s.getIdToken(!1);a&&(t.Authorization=`Bearer ${a}`)}catch{}return t}async function zo(t,s=!1){const a=await ml(),r=`${ul}/api/analytics/class/${encodeURIComponent(t)}${s?"?refresh=true":""}`,o=await fetch(r,{headers:a});if(!o.ok)throw new Error(`GET class analytics failed: ${o.status}`);return o.json()}async function am(t){const s=await ml(),a=await fetch(`${ul}/api/analytics/class/${encodeURIComponent(t)}/refresh-insights`,{method:"POST",headers:s});if(!a.ok)throw a.status===429?new Error("Insights can only be refreshed once every 5 minutes."):new Error(`POST refresh insights failed: ${a.status}`);return a.json()}const Sr="https://deign86-mathpulse-api-v3test.hf.space";async function kr(){const t={"Content-Type":"application/json"},s=mi.currentUser;if(s)try{const a=await s.getIdToken(!1);a&&(t.Authorization=`Bearer ${a}`)}catch{}return t}async function rn(t){const s=await kr(),a=await fetch(`${Sr}/api/intervention/${encodeURIComponent(t)}`,{headers:s});if(!a.ok)throw new Error(`GET intervention failed: ${a.status}`);return a.json()}async function xl(t){const s=await kr(),a=await fetch(`${Sr}/api/intervention/generate`,{method:"POST",headers:s,body:JSON.stringify({student_id:t})});if(!a.ok)throw new Error(`POST intervention/generate failed: ${a.status}`);return a.json()}async function rm(t,s,a,r){const o=await kr(),n=await fetch(`${Sr}/api/intervention/${encodeURIComponent(t)}/step/${s}/complete`,{method:"POST",headers:o,body:JSON.stringify({score:a,time_spent_minutes:r})});if(!n.ok)throw new Error(`POST step complete failed: ${n.status}`);return n.json()}async function nm(t){const s=await kr(),a=await fetch(`${Sr}/api/intervention/${encodeURIComponent(t)}/export-pdf`,{headers:s});if(!a.ok)throw new Error(`GET export-pdf failed: ${a.status}`);return a.json()}async function pl(t,s){const r=(t.learning_path?.steps||[]).map(n=>({title:`Step ${n.step_number}: ${n.title}`,content:`${n.description||n.topic} (${n.type.replace("_"," ")} · ${n.duration_minutes} mins${n.num_items?` · ${n.num_items} items`:""})`,stepType:n.type,stepNumber:n.step_number,topic:n.topic,durationMinutes:n.duration_minutes,numItems:n.num_items||null,difficulty:n.difficulty,competencyTag:n.competency_tag||"",youtubeQuery:n.youtube_query||"",isCompleted:n.is_completed||!1}));return(await bi(St($e,"modules"),{title:`Intervention: ${t.weakest_topic} — ${t.student_name}`,gradeLevel:t.grade_level||"Grade 11",subject:"General Mathematics",quarter:"Q1",strandOrTrack:null,competencyTags:t.weak_topics.slice(0,3),moduleType:"teacher_uploaded",sourceLabel:"Teacher Upload",summary:t.next_steps_summary||`Personalized intervention for ${t.weakest_topic}`,learningObjectives:[t.learning_strengths,t.next_steps_summary].filter(Boolean),sections:r,practice:[],teacherId:s,assignedTo:t.student_id,createdAt:it()})).id}async function hl(t,s,a){return(await bi(St($e,"modules"),{title:t.title,gradeLevel:"Grade 11",subject:"General Mathematics",quarter:"Q1",strandOrTrack:null,competencyTags:[t.competency_tag].filter(Boolean),moduleType:"teacher_uploaded",sourceLabel:"Teacher Upload",summary:t.description||`${t.topic} (${t.difficulty})`,learningObjectives:[t.description].filter(Boolean),sections:[{title:t.title,content:t.description||t.topic}],practice:[],teacherId:a,assignedTo:s,createdAt:it()})).id}async function Sn(t){const s=kt(St($e,"modules"),Nt("assignedTo","==",t),Nt("moduleType","==","teacher_uploaded"));return(await Lt(s)).docs.map(r=>r.id)}async function fl(t){const s=await Sn(t);return await Promise.all(s.map(a=>cn(ct($e,"modules",a)))),s.length}const om=Object.freeze(Object.defineProperty({__proto__:null,assignLearningPathAsModule:pl,assignStepAsModule:hl,completeStep:rm,generateInterventionPlan:xl,getAssignedModuleIds:Sn,getExportPDFData:nm,getInterventionPlan:rn,revokeAssignedModules:fl},Symbol.toStringTag,{value:"Module"}));function im(t,s=!0){const[a,r]=u.useState([]),[o,n]=u.useState(!1),[i,l]=u.useState(null);return u.useEffect(()=>{if(!t||!s){r([]);return}let c=!1;return n(!0),l(null),ic(t).then(d=>{c||r(d)}).catch(d=>{c||l(d.message)}).finally(()=>{c||n(!1)}),()=>{c=!0}},[t,s]),{videos:a,isLoading:o,error:i}}const lm=({step:t,isActive:s})=>{const{videos:a,isLoading:r,error:o}=im(t.youtube_query||`${t.topic} math tutorial Philippines`,s);return s?e.jsxs("div",{className:"mt-4",children:[o&&e.jsxs("p",{className:"text-xs text-red-400 mb-2",children:["Could not load videos: ",o]}),e.jsx(lc,{videos:r?[]:a,topic:t.title})]}):null},gl={"gen-math":{id:"gen-math",name:"General Mathematics",shortLabel:"Gen Math",color:"#3B82F6"},"stats-prob":{id:"stats-prob",name:"Statistics and Probability",shortLabel:"Stats & Prob",color:"#0ea5e9"},"business-math":{id:"business-math",name:"Business Mathematics",shortLabel:"Business Math",color:"#166534"},"pre-calc":{id:"pre-calc",name:"Pre-Calculus",shortLabel:"Pre-Calculus",color:"#F97316"},"basic-calc":{id:"basic-calc",name:"Basic Calculus",shortLabel:"Basic Calculus",color:"#EF4444"}},cm={gm:"gen-math",gen_math:"gen-math","gen math":"gen-math",genmath:"gen-math","general mathematics":"gen-math",sp:"stats-prob",stat:"stats-prob","stat&prob":"stats-prob",statistics:"stats-prob","statistics and probability":"stats-prob",bm:"business-math","business math":"business-math","business mathematics":"business-math",pc:"pre-calc","pre-calculus":"pre-calc",pre_calc:"pre-calc",precalc:"pre-calc",bc:"basic-calc",basic_calc:"basic-calc","basic calculus":"basic-calc",basiccalc:"basic-calc"};function dm(t){const s=t.toLowerCase().trim();return gl[s]?s:cm[s]||null}function um(t){const s=dm(t);return s?gl[s].name:t}function ks(t){if(!t)return t;const s=t.match(/^(Gm|Gen\s*Math|Stat|Stats?(?:\s*&\s*Prob)?|Pre[- ]?Cal(?:c)?|Basic[- ]?Cal(?:c)?|Bm|Business\s*Math)\s*(Q\d)?\s*[-–]?\s*(.*)$/i);if(!s)return t;const[,a,r,o]=s,i=[um(a)];return r&&i.push(r.toUpperCase()),o?.trim()&&i.push(o.trim()),i.join(" – ")}const mm={video_lesson:e.jsx(Za,{className:"w-5 h-5"}),practice:e.jsx(ir,{className:"w-5 h-5"}),assessment:e.jsx(La,{className:"w-5 h-5"}),chat_session:e.jsx(wi,{className:"w-5 h-5"}),review:e.jsx(xs,{className:"w-5 h-5"})},Lo={easy:"bg-emerald-100 text-emerald-700",medium:"bg-amber-100 text-amber-700",hard:"bg-rose-100 text-rose-700"},xm=({step:t,studentId:s,studentName:a,teacherId:r,totalSteps:o,onClose:n,onStepCompleted:i})=>{const[l,c]=u.useState(!1),[d,m]=u.useState([{role:"assistant",content:`Hi ${a}! Let's work on "${ks(t.title)}". ${t.description||`This covers ${ks(t.topic)}.`} Ready to start?`}]),[p,h]=u.useState(""),v=async()=>{c(!0);try{await hl(t,s,r),i(t.step_number),le.success(`Step ${t.step_number} assigned to student!`),n()}catch{le.error("Failed to assign step.")}finally{c(!1)}},y=()=>{if(!p.trim())return;const S=p.trim();m(N=>[...N,{role:"user",content:S}]),h(""),setTimeout(()=>{m(N=>[...N,{role:"assistant",content:`Great question about ${t.topic}! Let me help you understand this step by step. What part are you finding most challenging?`}])},1e3)};return e.jsx(zt,{children:e.jsxs(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] flex items-center justify-center p-4",onClick:n,children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(Re.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.95,opacity:0},className:"relative bg-white rounded-[24px] shadow-[0_24px_64px_rgba(0,0,0,0.18)] w-full max-w-[800px] max-h-[85vh] flex flex-col overflow-hidden z-10",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-slate-100 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-[12px] bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white",children:mm[t.type]||e.jsx(ir,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-bold text-[#1e293b]",children:ks(t.title)}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-[11px] text-[#64748b]",children:["Step ",t.step_number," of ",o]}),t.competency_tag&&e.jsx("span",{className:"px-1.5 py-0.5 bg-indigo-50 text-indigo-600 text-[9px] font-mono rounded",children:t.competency_tag}),e.jsx("span",{className:`px-2 py-0.5 text-[10px] font-semibold rounded-full ${Lo[t.difficulty]||Lo.easy}`,children:t.difficulty})]})]})]}),e.jsx("button",{onClick:n,className:"w-8 h-8 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center transition-colors",children:e.jsx(qt,{className:"w-4 h-4 text-slate-500"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-slate-50 rounded-[14px] p-4 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ls,{className:"w-4 h-4 text-slate-500"}),e.jsxs("span",{className:"text-[12px] font-semibold text-slate-600",children:[t.duration_minutes," minutes"]}),t.num_items&&e.jsxs("span",{className:"text-[12px] text-slate-500",children:["• ",t.num_items," items"]})]}),e.jsx("p",{className:"text-[13px] text-[#475569] leading-relaxed",children:t.description||`Work through ${t.topic} at ${t.difficulty} difficulty.`})]}),t.type==="video_lesson"&&e.jsx(lm,{step:t,isActive:!0}),(t.type==="practice"||t.type==="assessment")&&e.jsxs("div",{className:"bg-purple-50/50 rounded-[14px] p-6 border border-purple-100 flex flex-col items-center justify-center min-h-[160px]",children:[e.jsx(ir,{className:"w-10 h-10 text-purple-400 mb-3"}),e.jsxs("p",{className:"text-[13px] font-semibold text-purple-700",children:[t.type==="assessment"?"Assessment":"Practice"," Questions"]}),e.jsxs("p",{className:"text-[11px] text-purple-500 mt-1",children:[t.num_items||10," questions on ",t.topic]})]})]}),e.jsxs("div",{className:"flex flex-col bg-slate-50 rounded-[14px] border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-slate-100 bg-white",children:e.jsxs("p",{className:"text-[12px] font-semibold text-[#1e293b] flex items-center gap-1.5",children:[e.jsx(wi,{className:"w-3.5 h-3.5 text-indigo-500"})," AI Guide",e.jsx("span",{className:"text-[9px] font-medium text-slate-400 ml-1",children:"(Preview)"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3 min-h-[200px] max-h-[300px]",children:d.map((S,N)=>e.jsx("div",{className:`flex ${S.role==="user"?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[85%] px-3 py-2 rounded-[12px] text-[12px] leading-relaxed ${S.role==="user"?"bg-indigo-500 text-white":"bg-white border border-slate-200 text-[#475569]"}`,children:S.content})},N))}),e.jsxs("div",{className:"p-3 border-t border-slate-100 bg-white flex gap-2",children:[e.jsx("input",{type:"text",value:p,onChange:S=>h(S.target.value),onKeyDown:S=>S.key==="Enter"&&y(),placeholder:"Ask for help...",className:"flex-1 text-[12px] px-3 py-2 rounded-[10px] border border-slate-200 focus:outline-none focus:border-indigo-300"}),e.jsx("button",{onClick:y,className:"w-8 h-8 rounded-full bg-indigo-500 hover:bg-indigo-600 flex items-center justify-center text-white transition-colors",children:e.jsx(ra,{className:"w-3.5 h-3.5"})})]})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-slate-100 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-full bg-slate-200 h-2 rounded-full overflow-hidden",style:{width:120},children:e.jsx("div",{className:"h-full bg-indigo-500 rounded-full",style:{width:`${t.step_number/o*100}%`}})}),e.jsxs("span",{className:"text-[11px] text-slate-500",children:[t.step_number,"/",o]})]}),e.jsxs("button",{onClick:v,disabled:l||t.is_completed,className:"flex items-center gap-2 px-5 py-2.5 bg-indigo-500 hover:bg-indigo-600 text-white text-[13px] font-semibold rounded-full transition-colors disabled:opacity-50 shadow-sm",children:[e.jsx(La,{className:"w-4 h-4"}),t.is_completed?"Assigned ✓":l?"Assigning...":"Assign"]})]})]})]})})};async function pm(t,s,a){const r=ct(St($e,"generatedLessonPlans"));return await os(r,{...t,teacherId:s,teacherName:a?.teacherName||null,studentId:a?.studentId||null,studentName:a?.studentName||null,status:"draft",createdAt:it(),updatedAt:it()}),r.id}async function hm(t){const s=ct($e,"generatedLessonPlans",t),a=await Is(s);if(!a.exists())throw new Error("Lesson draft not found. Save draft before publishing.");if(!a.data().publishReady)throw new Error("Lesson is not publish-ready. Resolve source legitimacy and validation issues first.");await ns(s,{status:"published",publishedAt:it(),updatedAt:it()})}async function Do(t,s=!0){const a=t.learningCompetency||t.lessonTitle||t.focusTopics&&t.focusTopics[0]||"general mathematics",r=t.subject||"general_math",o=t.quarter??1;let n="",i=[],l,c,d,m=!1;if(s)try{const v=await Ol(a,r,o,{lessonTitle:t.lessonTitle,learningCompetency:t.learningCompetency,moduleUnit:t.moduleUnit,learnerLevel:t.learnerLevel});i=v.sources||[],n=v.explanation||"",l=v.retrievalConfidence,c=v.retrievalBand,d=v.retrievalQuery,m=v.needsReview??!1}catch{n="",i=[]}const p={...t,subject:r,quarter:o,curriculumContext:n?`[CURRICULUM CONTEXT] + */const ud=[["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"}]],Xr=Rt("wand-sparkles",ud);function md(t,s){const a=Fl(t);return isNaN(s)?_c(t,NaN):(a.setDate(a.getDate()+s),a)}function Ii(t,s){const a=$n(t),r=$n(s);return+a==+r}function ro(t){return Ii(t,Si(t))}function xd(t,s){return md(t,-1)}function no(t){return Ii(t,xd(Si(t)))}const vr=0,Os=1,ma=2,Ti=4;function oo(t){return()=>t}function pd(t){t()}function _i(t,s){return a=>t(s(a))}function io(t,s){return()=>t(s)}function hd(t,s){return a=>t(s,a)}function dn(t){return t!==void 0}function fd(...t){return()=>{t.map(pd)}}function xa(){}function wr(t,s){return s(t),t}function gd(t,s){return s(t)}function at(...t){return t}function Ye(t,s){return t(Os,s)}function Ee(t,s){t(vr,s)}function un(t){t(ma)}function ot(t){return t(Ti)}function be(t,s){return Ye(t,hd(s,vr))}function is(t,s){const a=t(Os,r=>{a(),s(r)});return a}function lo(t){let s,a;return r=>o=>{s=o,a&&clearTimeout(a),a=setTimeout(()=>{r(s)},t)}}function Ei(t,s){return t===s}function st(t=Ei){let s;return a=>r=>{t(s,r)||(s=r,a(r))}}function Se(t){return s=>a=>{t(a)&&s(a)}}function xe(t){return s=>_i(s,t)}function ms(t){return s=>()=>{s(t)}}function Y(t,...s){const a=bd(...s);return((r,o)=>{switch(r){case ma:un(t);return;case Os:return Ye(t,a(o))}})}function ps(t,s){return a=>r=>{a(s=t(s,r))}}function Ks(t){return s=>a=>{t>0?t--:s(a)}}function Ts(t){let s=null,a;return r=>o=>{s=o,!a&&(a=setTimeout(()=>{a=void 0,r(s)},t))}}function Ae(...t){const s=new Array(t.length);let a=0,r=null;const o=2**t.length-1;return t.forEach((n,i)=>{const l=2**i;Ye(n,c=>{const d=a;a|=l,s[i]=c,d!==o&&a===o&&r&&(r(),r=null)})}),n=>i=>{const l=()=>{n([i].concat(s))};a===o?l():r=l}}function bd(...t){return s=>t.reduceRight(gd,s)}function vd(t){let s,a;const r=()=>s?.();return function(o,n){switch(o){case Os:return n?a===n?void 0:(r(),a=n,s=Ye(t,n),s):(r(),xa);case ma:r(),a=null;return}}}function Z(t){let s=t;const a=Be();return((r,o)=>{switch(r){case vr:s=o;break;case Os:{o(s);break}case Ti:return s}return a(r,o)})}function Et(t,s){return wr(Z(s),a=>be(t,a))}function Be(){const t=[];return((s,a)=>{switch(s){case vr:t.slice().forEach(r=>{r(a)});return;case ma:t.splice(0,t.length);return;case Os:return t.push(a),()=>{const r=t.indexOf(a);r>-1&&t.splice(r,1)}}})}function Wt(t){return wr(Be(),s=>be(t,s))}function qe(t,s=[],{singleton:a}={singleton:!0}){return{constructor:t,dependencies:s,id:wd(),singleton:a}}const wd=()=>Symbol();function Nd(t){const s=new Map,a=({constructor:r,dependencies:o,id:n,singleton:i})=>{if(i&&s.has(n))return s.get(n);const l=r(o.map(c=>a(c)));return i&&s.set(n,l),l};return a(t)}function pt(...t){const s=Be(),a=new Array(t.length);let r=0;const o=2**t.length-1;return t.forEach((n,i)=>{const l=2**i;Ye(n,c=>{a[i]=c,r|=l,r===o&&Ee(s,a)})}),function(n,i){switch(n){case ma:{un(s);return}case Os:return r===o&&i(a),Ye(s,i)}}}function ye(t,s=Ei){return Y(t,st(s))}function Jr(...t){return function(s,a){switch(s){case ma:return;case Os:return fd(...t.map(r=>Ye(r,a)))}}}const vt={DEBUG:0,INFO:1,WARN:2,ERROR:3},jd={[vt.DEBUG]:"debug",[vt.ERROR]:"error",[vt.INFO]:"log",[vt.WARN]:"warn"},yd=()=>typeof globalThis>"u"?window:globalThis,Ps=qe(()=>{const t=Z(vt.ERROR);return{log:Z((s,a,r=vt.INFO)=>{const o=yd().VIRTUOSO_LOG_LEVEL??ot(t);r>=o&&console[jd[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",s,a)}),logLevel:t}},[],{singleton:!0});function Js(t,s,a){return mn(t,s,a).callbackRef}function mn(t,s,a){const r=he.useRef(null);let o=i=>{};const n=he.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const l=()=>{const c=i[0].target;c.offsetParent!==null&&t(c)};a?l():requestAnimationFrame(l)}):null,[t,a]);return o=i=>{i&&s?(n?.observe(i),r.current=i):(r.current&&n?.unobserve(r.current),r.current=null)},{callbackRef:o,ref:r}}function Sd(t,s,a,r,o,n,i,l,c){const d=he.useCallback(m=>{const p=kd(m.children,s,l?"offsetWidth":"offsetHeight",o);let h=m.parentElement;for(;h.dataset.virtuosoScroller===void 0;)h=h.parentElement;const v=h.lastElementChild.dataset.viewportType==="window";let y;v&&(y=h.ownerDocument.defaultView);const S=i?l?i.scrollLeft:i.scrollTop:v?l?y.scrollX||y.document.documentElement.scrollLeft:y.scrollY||y.document.documentElement.scrollTop:l?h.scrollLeft:h.scrollTop,N=i?l?i.scrollWidth:i.scrollHeight:v?l?y.document.documentElement.scrollWidth:y.document.documentElement.scrollHeight:l?h.scrollWidth:h.scrollHeight,w=i?l?i.offsetWidth:i.offsetHeight:v?l?y.innerWidth:y.innerHeight:l?h.offsetWidth:h.offsetHeight;r({scrollHeight:N,scrollTop:Math.max(S,0),viewportHeight:w}),n?.(l?co("column-gap",getComputedStyle(m).columnGap,o):co("row-gap",getComputedStyle(m).rowGap,o)),p!==null&&t(p)},[t,s,o,n,i,r,l]);return mn(d,a,c)}function kd(t,s,a,r){const o=t.length;if(o===0)return null;const n=[];for(let i=0;i{if(!c?.offsetParent)return;const d=c.getBoundingClientRect(),m=d.width;let p,h;if(s){const v=s.getBoundingClientRect(),y=d.top-v.top;h=v.height-Math.max(0,y),p=y+s.scrollTop}else{const v=i.current.ownerDocument.defaultView;h=v.innerHeight-Math.max(0,d.top),p=d.top+v.scrollY}r.current={listHeight:d.height,offsetTop:p,visibleHeight:h,visibleWidth:m},t(r.current)},[t,s]),{callbackRef:n,ref:i}=mn(o,!0,a),l=he.useCallback(()=>{o(i.current)},[o,i]);return he.useEffect(()=>{if(s){s.addEventListener("scroll",l);const d=new ResizeObserver(()=>{requestAnimationFrame(l)});return d.observe(s),()=>{s.removeEventListener("scroll",l),d.unobserve(s)}}const c=i.current?.ownerDocument.defaultView;return c?.addEventListener("scroll",l),c?.addEventListener("resize",l),()=>{c?.removeEventListener("scroll",l),c?.removeEventListener("resize",l)}},[l,s,i]),n}const Dt=qe(()=>{const t=Be(),s=Be(),a=Z(0),r=Be(),o=Z(0),n=Be(),i=Be(),l=Z(0),c=Z(0),d=Z(0),m=Z(0),p=Be(),h=Be(),v=Z(!1),y=Z(!1),S=Z(!1);return be(Y(t,xe(({scrollTop:N})=>N)),s),be(Y(t,xe(({scrollHeight:N})=>N)),i),be(s,o),{deviation:a,fixedFooterHeight:d,fixedHeaderHeight:c,footerHeight:m,headerHeight:l,horizontalDirection:y,scrollBy:h,scrollContainerState:t,scrollHeight:i,scrollingInProgress:v,scrollTo:p,scrollTop:s,skipAnimationFrameInResizeObserver:S,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:n}},[],{singleton:!0}),Ta={lvl:0};function Mi(t,s){const a=t.length;if(a===0)return[];let{index:r,value:o}=s(t[0]);const n=[];for(let i=1;is&&(l=l.concat(en(o,s,a))),r>=s&&r<=a&&l.push({k:r,v:i}),r<=a&&(l=l.concat(en(n,s,a))),l}function er(t){const{l:s,lvl:a,r}=t;if(r.lvl>=a-1&&s.lvl>=a-1)return t;if(a>r.lvl+1){if(Rr(s))return Di(bt(t,{lvl:a-1}));if(!et(s)&&!et(s.r))return bt(s.r,{l:bt(s,{r:s.r.l}),lvl:a,r:bt(t,{l:s.r.r,lvl:a-1})});throw new Error("Unexpected empty nodes")}if(Rr(t))return tn(bt(t,{lvl:a-1}));if(!et(r)&&!et(r.l)){const o=r.l,n=Rr(o)?r.lvl-1:r.lvl;return bt(o,{l:bt(t,{lvl:a-1,r:o.l}),lvl:o.lvl+1,r:tn(bt(r,{l:o.r,lvl:n}))})}throw new Error("Unexpected empty nodes")}function bt(t,s){return Li(s.k!==void 0?s.k:t.k,s.v!==void 0?s.v:t.v,s.lvl!==void 0?s.lvl:t.lvl,s.l!==void 0?s.l:t.l,s.r!==void 0?s.r:t.r)}function Ai(t){return et(t.r)?t.l:er(bt(t,{r:Ai(t.r)}))}function Rr(t){return et(t)||t.lvl>t.r.lvl}function zi(t){return et(t.r)?[t.k,t.v]:zi(t.r)}function Li(t,s,a,r=Ta,o=Ta){return{k:t,l:r,lvl:a,r:o,v:s}}function uo(t){return tn(Di(t))}function Di(t){const{l:s}=t;return!et(s)&&s.lvl===t.lvl?bt(s,{r:bt(t,{l:s.r})}):t}function tn(t){const{lvl:s,r:a}=t;return!et(a)&&!et(a.r)&&a.lvl===s&&a.r.lvl===s?bt(a,{l:bt(t,{r:a.l}),lvl:s+1}):t}function Cd(t){return Mi(t,({k:s,v:a})=>({index:s,value:a}))}function $i(t,s){return!!(t&&t.startIndex===s.startIndex&&t.endIndex===s.endIndex)}function Ea(t,s){return!!(t&&t[0]===s[0]&&t[1]===s[1])}const xn=qe(()=>({recalcInProgress:Z(!1)}),[],{singleton:!0});function Fi(t,s,a){return t[mr(t,s,a)]}function mr(t,s,a,r=0){let o=t.length-1;for(;r<=o;){const n=Math.floor((r+o)/2),i=t[n],l=a(i,s);if(l===0)return n;if(l===-1){if(o-r<2)return n-1;o=n-1}else{if(o===r)return n;r=n+1}}throw new Error(`Failed binary finding record in array - ${t.join(",")}, searched for ${s}`)}function Id(t,s,a,r){const o=mr(t,s,r),n=mr(t,a,r,o);return t.slice(o,n+1)}function Fs(t,s){return Math.round(t.getBoundingClientRect()[s])}function Nr(t){return!et(t.groupOffsetTree)}function pn({index:t},s){return s===t?0:s=p||n===h)&&(t=Zr(t,p)):(d=h!==n,c=!0),m>o&&o>=p&&h!==n&&(t=Qt(t,o+1,h));d&&(t=Qt(t,i,n))}return[t,a]}function Ed(t){return typeof t.groupIndex<"u"}function Rd({offset:t},s){return s===t?0:s0?l+a:l}function Oi(t,s){if(!Nr(s))return t;let a=0;for(;s.groupIndices[a]<=t+a;)a++;return t+a}function Pi(t,s,a){if(Ed(t))return s.groupIndices[t.groupIndex]+1;const r=t.index==="LAST"?a:t.index;let o=Oi(r,s);return o=Math.max(0,o,Math.min(a,o)),o}function Md(t,s,a,r=0){return r>0&&(s=Math.max(s,Fi(t,r,pn).offset)),Mi(Id(t,s,a,Rd),Ld)}function Ad(t,[s,a,r,o]){s.length>0&&r("received item sizes",s,vt.DEBUG);const n=t.sizeTree;let i=n,l=0;if(a.length>0&&et(n)&&s.length===2){const h=s[0].size,v=s[1].size;i=a.reduce((y,S)=>Qt(Qt(y,S,h),S+1,v),i)}else[i,l]=_d(i,s);if(i===n)return t;const{lastIndex:c,lastOffset:d,lastSize:m,offsetTree:p}=sn(t.offsetTree,l,i,o);return{groupIndices:a,groupOffsetTree:a.reduce((h,v)=>Qt(h,v,Ra(v,p,o)),ia()),lastIndex:c,lastOffset:d,lastSize:m,offsetTree:p,sizeTree:i}}function zd(t){return Ys(t).map(({k:s,v:a},r,o)=>{const n=o[r+1];return{endIndex:n!==void 0?n.k-1:1/0,size:a,startIndex:s}})}function mo(t,s){let a=0,r=0;for(;ao.start===r&&(o.end===s||o.end===1/0)&&o.value===a}const $d={offsetHeight:"height",offsetWidth:"width"},ws=qe(([{log:t},{recalcInProgress:s}])=>{const a=Be(),r=Be(),o=Et(r,0),n=Be(),i=Be(),l=Z(0),c=Z([]),d=Z(void 0),m=Z(void 0),p=Z(void 0),h=Z(void 0),v=Z((f,C)=>Fs(f,$d[C])),y=Z(void 0),S=Z(0),N=Td(),w=Et(Y(a,Ae(c,t,S),ps(Ad,N),st()),N),g=Et(Y(c,st(),ps((f,C)=>({current:C,prev:f.current}),{current:[],prev:[]}),xe(({prev:f})=>f)),[]);be(Y(c,Se(f=>f.length>0),Ae(w,S),xe(([f,C,b])=>{const F=f.reduce((U,k,D)=>Qt(U,k,Ra(k,C.offsetTree,b)||D),ia());return{...C,groupIndices:f,groupOffsetTree:F}})),w),be(Y(r,Ae(w),Se(([f,{lastIndex:C}])=>f[{endIndex:C,size:b,startIndex:f}])),a),be(d,m);const I=Et(Y(d,xe(f=>f===void 0)),!0);be(Y(m,Se(f=>f!==void 0&&et(ot(w).sizeTree)),xe(f=>{const C=ot(p),b=ot(c).length>0;return C!==void 0&&C!==0?b?[{endIndex:0,size:C,startIndex:0},{endIndex:1,size:f,startIndex:1}]:[]:[{endIndex:0,size:f,startIndex:0}]})),a),be(Y(h,Se(f=>f!==void 0&&f.length>0&&et(ot(w).sizeTree)),xe(f=>{const C=[];let b=f[0],F=0;for(let U=1;Uf!==void 0&&C!==void 0),xe(([f,C,b])=>{const F=[];for(let U=0;U({changed:b!==f,sizes:b}),{changed:!1,sizes:N}),xe(f=>f.changed)));Ye(Y(l,ps((f,C)=>({diff:f.prev-C,prev:C}),{diff:0,prev:0}),xe(f=>f.diff)),f=>{const{groupIndices:C}=ot(w);if(f>0)Ee(s,!0),Ee(n,f+mo(f,C));else if(f<0){const b=ot(g);b.length>0&&(f-=mo(-f,b)),Ee(i,f)}}),Ye(Y(l,Ae(t)),([f,C])=>{f<0&&C("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:l},vt.ERROR)});const A=Wt(n);be(Y(n,Ae(w),xe(([f,C])=>{const b=C.groupIndices.length>0,F=[],U=C.lastSize;if(b){const k=_a(C.sizeTree,0);let D=0,J=0;for(;D{let Ce=ce.ranges;return ce.prevSize!==0&&(Ce=[...ce.ranges,{endIndex:ie+f-1,size:ce.prevSize,startIndex:ce.prevIndex}]),{prevIndex:ie+f,prevSize:fe,ranges:Ce}},{prevIndex:f,prevSize:0,ranges:F}).ranges}return Ys(C.sizeTree).reduce((k,{k:D,v:J})=>({prevIndex:D+f,prevSize:J,ranges:[...k.ranges,{endIndex:D+f-1,size:k.prevSize,startIndex:k.prevIndex}]}),{prevIndex:0,prevSize:U,ranges:[]}).ranges})),a);const W=Wt(Y(i,Ae(w,S),xe(([f,{offsetTree:C},b])=>{const F=-f;return Ra(F,C,b)})));return be(Y(i,Ae(w,S),xe(([f,C,b])=>{if(C.groupIndices.length>0){if(et(C.sizeTree))return C;let U=ia();const k=ot(g);let D=0,J=0,re=0;for(;D<-f;){re=k[J];const ce=k[J+1]-re-1;J++,D+=ce+1}if(U=Ys(C.sizeTree).reduce((ce,{k:ie,v:fe})=>Qt(ce,Math.max(0,ie+f),fe),U),D!==-f){const ce=_a(C.sizeTree,re);U=Qt(U,0,ce);const ie=ls(C.sizeTree,-f+1)[1];U=Qt(U,1,ie)}return{...C,sizeTree:U,...sn(C.offsetTree,0,U,b)}}const F=Ys(C.sizeTree).reduce((U,{k,v:D})=>Qt(U,Math.max(0,k+f),D),ia());return{...C,sizeTree:F,...sn(C.offsetTree,0,F,b)}})),w),{beforeUnshiftWith:A,data:y,defaultItemSize:m,firstItemIndex:l,fixedItemSize:d,fixedGroupSize:p,gap:S,groupIndices:c,heightEstimates:h,itemSize:v,listRefresh:L,shiftWith:i,shiftWithOffset:W,sizeRanges:a,sizes:w,statefulTotalCount:o,totalCount:r,trackItemSizes:I,unshiftWith:n}},at(Ps,xn),{singleton:!0});function Fd(t){return t.reduce((s,a)=>(s.groupIndices.push(s.totalCount),s.totalCount+=a+1,s),{groupIndices:[],totalCount:0})}const Bi=qe(([{groupIndices:t,sizes:s,totalCount:a},{headerHeight:r,scrollTop:o}])=>{const n=Be(),i=Be(),l=Wt(Y(n,xe(Fd)));return be(Y(l,xe(c=>c.totalCount)),a),be(Y(l,xe(c=>c.groupIndices)),t),be(Y(pt(o,s,r),Se(([c,d])=>Nr(d)),xe(([c,d,m])=>ls(d.groupOffsetTree,Math.max(c-m,0),"v")[0]),st(),xe(c=>[c])),i),{groupCounts:n,topItemsIndexes:i}},at(ws,Dt)),Bs=qe(([{log:t}])=>{const s=Z(!1),a=Wt(Y(s,Se(r=>r),st()));return Ye(s,r=>{r&&ot(t)("props updated",{},vt.DEBUG)}),{didMount:a,propsReady:s}},at(Ps),{singleton:!0}),Od=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Hi(t){const s=typeof t=="number"?{index:t}:t;return s.align||(s.align="start"),(!s.behavior||!Od)&&(s.behavior="auto"),s.offset===void 0&&(s.offset=0),s}const Da=qe(([{gap:t,listRefresh:s,sizes:a,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:n,footerHeight:i,headerHeight:l,scrollingInProgress:c,scrollTo:d,smoothScrollTargetReached:m,viewportHeight:p},{log:h}])=>{const v=Be(),y=Be(),S=Z(0);let N=null,w=null,g=null;function I(){N!==null&&(N(),N=null),g!==null&&(g(),g=null),w&&(clearTimeout(w),w=null),Ee(c,!1)}return be(Y(v,Ae(a,p,r,S,l,i,h),Ae(t,n,o),xe(([[L,A,W,f,C,b,F,U],k,D,J])=>{const re=Hi(L),{align:ce,behavior:ie,offset:fe}=re,Ce=f-1,ue=Pi(re,A,Ce);let ge=Ra(ue,A.offsetTree,k)+b;ce==="end"?(ge+=D+ls(A.sizeTree,ue)[1]-W+J,ue===Ce&&(ge+=F)):ce==="center"?ge+=(D+ls(A.sizeTree,ue)[1]-W+J)/2:ge-=C,fe!==void 0&&fe!==0&&(ge+=fe);const B=te=>{I(),te?(U("retrying to scroll to",{location:L},vt.DEBUG),Ee(v,L)):(Ee(y,!0),U("list did not change, scroll successful",{},vt.DEBUG))};if(I(),ie==="smooth"){let te=!1;g=Ye(s,ne=>{te=te||ne}),N=is(m,()=>{B(te)})}else N=is(Y(s,Pd(150)),B);return w=setTimeout(()=>{I()},1200),Ee(c,!0),U("scrolling from index to",{behavior:ie,index:ue,top:ge},vt.DEBUG),{behavior:ie,top:ge}})),d),{scrollTargetReached:y,scrollToIndex:v,topListHeight:S}},at(ws,Dt,Ps),{singleton:!0});function Pd(t){return s=>{const a=setTimeout(()=>{s(!1)},t);return r=>{r&&(s(!0),clearTimeout(a))}}}function hn(t,s){t===0?s():requestAnimationFrame(()=>{hn(t-1,s)})}function fn(t,s){const a=s-1;return typeof t=="number"?t:t.index==="LAST"?a:t.index}const $a=qe(([{defaultItemSize:t,listRefresh:s,sizes:a},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:n},{didMount:i}])=>{const l=Z(!0),c=Z(0),d=Z(!0);return be(Y(i,Ae(c),Se(([m,p])=>p!==0),ms(!1)),l),be(Y(i,Ae(c),Se(([m,p])=>p!==0),ms(!1)),d),Ye(Y(pt(s,i),Ae(l,a,t,d),Se(([[,m],p,{sizeTree:h},v,y])=>m&&(!et(h)||dn(v))&&!p&&!y),Ae(c)),([,m])=>{is(o,()=>{Ee(d,!0)}),hn(4,()=>{is(r,()=>{Ee(l,!0)}),Ee(n,m)})}),{initialItemFinalLocationReached:d,initialTopMostItemIndex:c,scrolledToInitialItem:l}},at(ws,Dt,Da,Bs),{singleton:!0});function Ui(t,s){return Math.abs(t-s)<1.01}const Ma="up",ka="down",Bd="none",Hd={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Ud=0,Fa=qe(([{footerHeight:t,headerHeight:s,scrollBy:a,scrollContainerState:r,scrollTop:o,viewportHeight:n}])=>{const i=Z(!1),l=Z(!0),c=Be(),d=Be(),m=Z(4),p=Z(Ud),h=Et(Y(Jr(Y(ye(o),Ks(1),ms(!0)),Y(ye(o),Ks(1),ms(!1),lo(100))),st()),!1),v=Et(Y(Jr(Y(a,ms(!0)),Y(a,ms(!1),lo(200))),st()),!1);be(Y(pt(ye(o),ye(p)),xe(([g,I])=>g<=I),st()),l),be(Y(l,Ts(50)),d);const y=Wt(Y(pt(r,ye(n),ye(s),ye(t),ye(m)),ps((g,[{scrollHeight:I,scrollTop:L},A,W,f,C])=>{const b=L+A-I>-C,F={scrollHeight:I,scrollTop:L,viewportHeight:A};if(b){let k,D;return L>g.state.scrollTop?(k="SCROLLED_DOWN",D=g.state.scrollTop-L):(k="SIZE_DECREASED",D=g.state.scrollTop-L||g.scrollTopDelta),{atBottom:!0,atBottomBecause:k,scrollTopDelta:D,state:F}}let U;return F.scrollHeight>g.state.scrollHeight?U="SIZE_INCREASED":Ag!==void 0&&g.atBottom===I.atBottom))),S=Et(Y(r,ps((g,{scrollHeight:I,scrollTop:L,viewportHeight:A})=>{if(!Ui(g.scrollHeight,I)){const W=I-(L+A)<1;return g.scrollTop!==L&&W?{changed:!0,jump:g.scrollTop-L,scrollHeight:I,scrollTop:L}:{changed:!0,jump:0,scrollHeight:I,scrollTop:L}}return{changed:!1,jump:0,scrollHeight:I,scrollTop:L}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Se(g=>g.changed),xe(g=>g.jump)),0);be(Y(y,xe(g=>g.atBottom)),i),be(Y(i,Ts(50)),c);const N=Z(ka);be(Y(r,xe(({scrollTop:g})=>g),st(),ps((g,I)=>ot(v)?{direction:g.direction,prevScrollTop:I}:{direction:Ig.direction)),N),be(Y(r,Ts(50),ms(Bd)),N);const w=Z(0);return be(Y(h,Se(g=>!g),ms(0)),w),be(Y(o,Ts(100),Ae(h),Se(([g,I])=>I),ps(([g,I],[L])=>[I,L],[0,0]),xe(([g,I])=>I-g)),w),{atBottomState:y,atBottomStateChange:c,atBottomThreshold:m,atTopStateChange:d,atTopThreshold:p,isAtBottom:i,isAtTop:l,isScrolling:h,lastJumpDueToItemResize:S,scrollDirection:N,scrollVelocity:w}},at(Dt)),Aa="top",za="bottom",xo="none";function po(t,s,a){return typeof t=="number"?a===Ma&&s===Aa||a===ka&&s===za?t:0:a===Ma?s===Aa?t.main:t.reverse:s===za?t.main:t.reverse}function ho(t,s){return typeof t=="number"?t:t[s]??0}const gn=qe(([{deviation:t,fixedHeaderHeight:s,headerHeight:a,scrollTop:r,viewportHeight:o}])=>{const n=Be(),i=Z(0),l=Z(0),c=Z(0),d=Et(Y(pt(ye(r),ye(o),ye(a),ye(n,Ea),ye(c),ye(i),ye(s),ye(t),ye(l)),xe(([m,p,h,[v,y],S,N,w,g,I])=>{const L=m-g,A=N+w,W=Math.max(h-L,0);let f=xo;const C=ho(I,Aa),b=ho(I,za);return v-=g,v+=h+w,y+=h+w,y-=g,v>m+A-C&&(f=Ma),ym!==null),st(Ea)),[0,0]);return{increaseViewportBy:l,listBoundary:n,overscan:c,topListHeight:i,visibleRange:d}},at(Dt),{singleton:!0});function Gd(t,s,a){if(Nr(s)){const r=Oi(t,s);return[{index:ls(s.groupOffsetTree,r)[0],offset:0,size:0},{data:a?.[0],index:r,offset:0,size:0}]}return[{data:a?.[0],index:t,offset:0,size:0}]}const Mr={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function tr(t,s,a,r,o,n){const{lastIndex:i,lastOffset:l,lastSize:c}=o;let d=0,m=0;if(t.length>0){d=t[0].offset;const S=t[t.length-1];m=S.offset+S.size}const p=a-i,h=l+p*c+(p-1)*r,v=d,y=h-m;return{bottom:m,firstItemIndex:n,items:fo(t,o,n),offsetBottom:y,offsetTop:d,top:v,topItems:fo(s,o,n),topListHeight:s.reduce((S,N)=>N.size+S,0),totalCount:a}}function Gi(t,s,a,r,o,n){let i=0;if(a.groupIndices.length>0)for(const m of a.groupIndices){if(m-i>=t)break;i++}const l=t+i,c=fn(s,l),d=Array.from({length:l}).map((m,p)=>({data:n[p+c],index:p+c,offset:0,size:0}));return tr(d,[],l,o,a,r)}function fo(t,s,a){if(t.length===0)return[];if(!Nr(s))return t.map(d=>({...d,index:d.index+a,originalIndex:d.index}));const r=t[0].index,o=t[t.length-1].index,n=[],i=la(s.groupOffsetTree,r,o);let l,c=0;for(const d of t){(!l||l.end{const S=Z([]),N=Z(0),w=Be(),g=Z(0);be(n.topItemsIndexes,S);const I=Et(Y(pt(v,y,ye(c,Ea),ye(o),ye(r),ye(d),m,ye(S),ye(s),ye(a),ye(g),t),Se(([f,C,,b,,,,,,,,F])=>{const U=F!==void 0&&F.length!==b;return f&&!C&&!U}),xe(([,,[f,C],b,F,U,k,D,J,re,ce,ie])=>{const fe=F,{offsetTree:Ce,sizeTree:ue}=fe,ge=ot(N);if(b===0)return{...Mr,totalCount:b};if(f===0&&C===0)return ge===0?{...Mr,totalCount:b}:Gi(ge,U,F,J,re,ie||[]);if(et(ue))return ge>0?null:tr(Gd(fn(U,b),fe,ie),[],b,re,fe,J);const B=[];if(D.length>0){const se=D[0],M=D[D.length-1];let q=0;for(const Q of la(ue,se,M)){const pe=Q.value,$=Math.max(Q.start,se),j=Math.min(Q.end,M);for(let T=$;T<=j;T++)B.push({data:ie?.[T],index:T,offset:q,size:pe}),q+=pe}}if(!k)return tr([],B,b,re,fe,J);const te=D.length>0?D[D.length-1]+1:0,ne=Md(Ce,f,C,te);if(ne.length===0)return null;const ze=b-1,Fe=wr([],se=>{for(const M of ne){const q=M.value;let Q=q.offset,pe=M.start;const $=q.size;if(q.offset=C);T++)se.push({data:ie?.[T],index:T,offset:Q,size:$}),Q+=$+re}}),Pe=go(ce,Aa),G=go(ce,za);if(Fe.length>0&&(Pe>0||G>0)){const se=Fe[0],M=Fe[Fe.length-1];if(Pe>0&&se.index>te){const q=Math.min(Pe,se.index-te),Q=[];let pe=se.offset;for(let $=se.index-1;$>=se.index-q;$--){const j=la(ue,$,$)[0]?.value??se.size;pe-=j+re,Q.unshift({data:ie?.[$],index:$,offset:pe,size:j})}Fe.unshift(...Q)}if(G>0&&M.indexf!==null),st()),Mr);be(Y(t,Se(dn),xe(f=>f?.length)),o),be(Y(I,xe(f=>f.topListHeight)),p),be(p,l),be(Y(I,xe(f=>[f.top,f.bottom])),i),be(Y(I,xe(f=>f.items)),w);const L=Wt(Y(I,Se(({items:f})=>f.length>0),Ae(o,t),Se(([{items:f},C])=>f[f.length-1].originalIndex===C-1),xe(([,f,C])=>[f-1,C]),st(Ea),xe(([f])=>f))),A=Wt(Y(I,Ts(200),Se(({items:f,topItems:C})=>f.length>0&&f[0].originalIndex===C.length),xe(({items:f})=>f[0].index),st())),W=Wt(Y(I,Se(({items:f})=>f.length>0),xe(({items:f})=>{let C=0,b=f.length-1;for(;f[C].type==="group"&&CC;)b--;return{endIndex:f[b].index,startIndex:f[C].index}}),st($i)));return{endReached:L,initialItemCount:N,itemsRendered:w,listState:I,minOverscanItemCount:g,rangeChanged:W,startReached:A,topItemsIndexes:S,...h}},at(ws,Bi,gn,$a,Da,Fa,Bs,xn),{singleton:!0}),Qi=qe(([{fixedFooterHeight:t,fixedHeaderHeight:s,footerHeight:a,headerHeight:r},{listState:o}])=>{const n=Be(),i=Et(Y(pt(a,t,r,s,o),xe(([l,c,d,m,p])=>l+c+d+m+p.offsetBottom+p.bottom)),0);return be(ye(i),n),{totalListHeight:i,totalListHeightChanged:n}},at(Dt,Zs),{singleton:!0}),Qd=qe(([{viewportHeight:t},{totalListHeight:s}])=>{const a=Z(!1),r=Et(Y(pt(a,t,s),Se(([o])=>o),xe(([,o,n])=>Math.max(0,o-n)),Ts(0),st()),0);return{alignToBottom:a,paddingTopAddition:r}},at(Dt,Qi),{singleton:!0}),Vi=qe(()=>({context:Z(null)})),Vd=({itemBottom:t,itemTop:s,locationParams:{align:a,behavior:r,...o},viewportBottom:n,viewportTop:i})=>sn?{...o,align:a??"end",...r!==void 0?{behavior:r}:{}}:null,Wi=qe(([{gap:t,sizes:s,totalCount:a},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:n,scrollingInProgress:i,scrollTop:l,viewportHeight:c},{scrollToIndex:d}])=>{const m=Be();return be(Y(m,Ae(s,c,a,n,o,r,l),Ae(t),xe(([[p,h,v,y,S,N,w,g],I])=>{const{calculateViewLocation:L=Vd,done:A,...W}=p,f=Pi(p,h,y-1),C=Ra(f,h.offsetTree,I)+S+N,b=C+ls(h.sizeTree,f)[1],F=g+N,U=g+v-w,k=L({itemBottom:b,itemTop:C,locationParams:W,viewportBottom:U,viewportTop:F});return k!==null?A&&is(Y(i,Se(D=>!D),Ks(ot(i)?1:2)),A):A?.(),k}),Se(p=>p!==null)),d),{scrollIntoView:m}},at(ws,Dt,Da,Zs,Ps),{singleton:!0});function bo(t){return t===!1?!1:t==="smooth"?"smooth":"auto"}const Wd=(t,s)=>typeof t=="function"?bo(t(s)):s&&bo(t),qd=qe(([{listRefresh:t,totalCount:s,fixedItemSize:a,data:r},{atBottomState:o,isAtBottom:n},{scrollToIndex:i},{scrolledToInitialItem:l},{didMount:c,propsReady:d},{log:m},{scrollingInProgress:p},{context:h},{scrollIntoView:v}])=>{const y=Z(!1),S=Be();let N=null;function w(A){Ee(i,{align:"end",behavior:A,index:"LAST"})}Ye(Y(pt(Y(ye(s),Ks(1)),c),Ae(ye(y),n,l,p),xe(([[A,W],f,C,b,F])=>{let U=W&&b,k="auto";return U&&(k=Wd(f,C||F),U=U&&k!==!1),{followOutputBehavior:k,shouldFollow:U,totalCount:A}}),Se(({shouldFollow:A})=>A)),({followOutputBehavior:A,totalCount:W})=>{N!==null&&(N(),N=null),ot(a)!==void 0?requestAnimationFrame(()=>{ot(m)("following output to ",{totalCount:W},vt.DEBUG),w(A)}):N=is(t,()=>{ot(m)("following output to ",{totalCount:W},vt.DEBUG),w(A),N=null})});function g(A){const W=is(o,f=>{A&&!f.atBottom&&f.notAtBottomBecause==="SIZE_INCREASED"&&N===null&&(ot(m)("scrolling to bottom due to increased size",{},vt.DEBUG),w("auto"))});setTimeout(W,100)}Ye(Y(pt(ye(y),s,d),Se(([A,,W])=>A!==!1&&W),ps(({value:A},[,W])=>({refreshed:A===W,value:W}),{refreshed:!1,value:0}),Se(({refreshed:A})=>A),Ae(y,s)),([,A])=>{ot(l)&&g(A!==!1)}),Ye(S,()=>{g(ot(y)!==!1)}),Ye(pt(ye(y),o),([A,W])=>{A!==!1&&!W.atBottom&&W.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&w("auto")});const I=Z(null),L=Be();return be(Jr(Y(ye(r),xe(A=>A?.length??0)),Y(ye(s))),L),Ye(Y(pt(Y(L,Ks(1)),c),Ae(ye(I),l,p,h),xe(([[A,W],f,C,b,F])=>W&&C&&f?.({context:F,totalCount:A,scrollingInProgress:b})),Se(A=>!!A),Ts(0)),A=>{N!==null&&(N(),N=null),ot(a)!==void 0?requestAnimationFrame(()=>{ot(m)("scrolling into view",{}),Ee(v,A)}):N=is(t,()=>{ot(m)("scrolling into view",{}),Ee(v,A),N=null})}),{autoscrollToBottom:S,followOutput:y,scrollIntoViewOnChange:I}},at(ws,Fa,Da,$a,Bs,Ps,Dt,Vi,Wi)),Yd=qe(([{data:t,firstItemIndex:s,gap:a,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:n,listState:i},{didMount:l}])=>(be(Y(l,Ae(n),Se(([,c])=>c!==0),Ae(o,r,s,a,t),xe(([[,c],d,m,p,h,v=[]])=>Gi(c,d,m,p,h,v))),i),{}),at(ws,$a,Zs,Bs),{singleton:!0}),Kd=qe(([{didMount:t},{scrollTo:s},{listState:a}])=>{const r=Z(0);return Ye(Y(t,Ae(r),Se(([,o])=>o!==0),xe(([,o])=>({top:o}))),o=>{is(Y(a,Ks(1),Se(n=>n.items.length>1)),()=>{requestAnimationFrame(()=>{Ee(s,o)})})}),{initialScrollTop:r}},at(Bs,Dt,Zs),{singleton:!0}),qi=qe(([{scrollVelocity:t}])=>{const s=Z(!1),a=Be(),r=Z(!1);return be(Y(t,Ae(r,s,a),Se(([o,n])=>n!==!1&&n!==void 0),xe(([o,n,i,l])=>{const{enter:c,exit:d}=n;if(i){if(d(o,l))return!1}else if(c(o,l))return!0;return i}),st()),s),Ye(Y(pt(s,t,a),Ae(r)),([[o,n,i],l])=>{o&&l!==!1&&l!==void 0&&l.change&&l.change(n,i)}),{isSeeking:s,scrollSeekConfiguration:r,scrollSeekRangeChanged:a,scrollVelocity:t}},at(Fa),{singleton:!0}),bn=qe(([{scrollContainerState:t,scrollTo:s}])=>{const a=Be(),r=Be(),o=Be(),n=Z(!1),i=Z(void 0);return be(Y(pt(a,r),xe(([{scrollTop:l,viewportHeight:c},{offsetTop:d,listHeight:m}])=>({scrollHeight:m,scrollTop:Math.max(0,l-d),viewportHeight:c}))),t),be(Y(s,Ae(r),xe(([l,{offsetTop:c}])=>({...l,top:l.top+c}))),o),{customScrollParent:i,useWindowScroll:n,windowScrollContainerState:a,windowScrollTo:o,windowViewportRect:r}},at(Dt)),Xd=qe(([{sizeRanges:t,sizes:s},{headerHeight:a,scrollTop:r},{initialTopMostItemIndex:o},{didMount:n},{useWindowScroll:i,windowScrollContainerState:l,windowViewportRect:c}])=>{const d=Be(),m=Z(void 0),p=Z(null),h=Z(null);return be(l,p),be(c,h),Ye(Y(d,Ae(s,r,i,p,h,a)),([v,y,S,N,w,g,I])=>{const L=zd(y.sizeTree);N&&w!==null&&g!==null&&(S=w.scrollTop-g.offsetTop),S-=I,v({ranges:L,scrollTop:S})}),be(Y(m,Se(dn),xe(Jd)),o),be(Y(n,Ae(m),Se(([,v])=>v!==void 0),st(),xe(([,v])=>v.ranges)),t),{getState:d,restoreStateFrom:m}},at(ws,Dt,$a,Bs,bn));function Jd(t){return{align:"start",index:0,offset:t.scrollTop}}const Zd=qe(([{topItemsIndexes:t}])=>{const s=Z(0);return be(Y(s,Se(a=>a>=0),xe(a=>Array.from({length:a}).map((r,o)=>o))),t),{topItemCount:s}},at(Zs));function Yi(t){let s=!1,a;return(()=>(s||(s=!0,a=t()),a))}const eu=Yi(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),tu=qe(([{deviation:t,scrollBy:s,scrollingInProgress:a,scrollTop:r},{isAtBottom:o,isScrolling:n,lastJumpDueToItemResize:i,scrollDirection:l},{listState:c},{beforeUnshiftWith:d,gap:m,shiftWithOffset:p,sizes:h},{log:v},{recalcInProgress:y}])=>{const S=Wt(Y(c,Ae(i),ps(([,w,g,I],[{bottom:L,items:A,offsetBottom:W,totalCount:f},C])=>{const b=L+W;let F=0;return g===f&&w.length>0&&A.length>0&&(A[0].originalIndex===0&&w[0].originalIndex===0||(F=b-I,F!==0&&(F+=C))),[F,A,f,b]},[0,[],0,0]),Se(([w])=>w!==0),Ae(r,l,a,o,v,y),Se(([,w,g,I,,,L])=>!L&&!I&&w!==0&&g===Ma),xe(([[w],,,,,g])=>(g("Upward scrolling compensation",{amount:w},vt.DEBUG),w))));function N(w){w>0?(Ee(s,{behavior:"auto",top:-w}),Ee(t,0)):(Ee(t,0),Ee(s,{behavior:"auto",top:-w}))}return Ye(Y(S,Ae(t,n)),([w,g,I])=>{I&&eu()?Ee(t,g-w):N(-w)}),Ye(Y(pt(Et(n,!1),t,y),Se(([w,g,I])=>!w&&!I&&g!==0),xe(([w,g])=>g),Ts(1)),N),be(Y(p,xe(w=>({top:-w}))),s),Ye(Y(d,Ae(h,m),xe(([w,{groupIndices:g,lastSize:I,sizeTree:L},A])=>{function W(U){return U*(I+A)}if(g.length===0)return W(w);let f=0;const C=_a(L,0);let b=0,F=0;for(;bw&&(f-=C,U=w-b+1),b+=U,f+=W(U),F++}return f})),w=>{Ee(t,w),requestAnimationFrame(()=>{Ee(s,{top:w}),requestAnimationFrame(()=>{Ee(t,0),Ee(y,!1)})})}),{deviation:t}},at(Dt,Fa,Zs,ws,Ps,xn)),su=qe(([t,s,a,r,o,n,i,l,c,d,m])=>({...t,...s,...a,...r,...o,...n,...i,...l,...c,...d,...m}),at(gn,Yd,Bs,qi,Qi,Kd,Qd,bn,Wi,Ps,Vi)),Ki=qe(([{data:t,defaultItemSize:s,firstItemIndex:a,fixedItemSize:r,fixedGroupSize:o,gap:n,groupIndices:i,heightEstimates:l,itemSize:c,sizeRanges:d,sizes:m,statefulTotalCount:p,totalCount:h,trackItemSizes:v},{initialItemFinalLocationReached:y,initialTopMostItemIndex:S,scrolledToInitialItem:N},w,g,I,L,{scrollToIndex:A},W,{topItemCount:f},{groupCounts:C},b])=>{const{listState:F,minOverscanItemCount:U,topItemsIndexes:k,rangeChanged:D,...J}=L;return be(D,b.scrollSeekRangeChanged),be(Y(b.windowViewportRect,xe(re=>re.visibleHeight)),w.viewportHeight),{data:t,defaultItemHeight:s,firstItemIndex:a,fixedItemHeight:r,fixedGroupHeight:o,gap:n,groupCounts:C,heightEstimates:l,initialItemFinalLocationReached:y,initialTopMostItemIndex:S,scrolledToInitialItem:N,sizeRanges:d,topItemCount:f,topItemsIndexes:k,totalCount:h,...I,groupIndices:i,itemSize:c,listState:F,minOverscanItemCount:U,scrollToIndex:A,statefulTotalCount:p,trackItemSizes:v,rangeChanged:D,...J,...b,...w,sizes:m,...g}},at(ws,$a,Dt,Xd,qd,Zs,Da,tu,Zd,Bi,su));function au(t,s){const a={},r={};let o=0;const n=t.length;for(;o(w[g]=I=>{const L=N[s.methods[g]];Ee(L,I)},w),{})}function m(N){return i.reduce((w,g)=>(w[g]=vd(N[s.events[g]]),w),{})}const p=he.forwardRef(function(N,w){const{children:g,...I}=N,[L]=he.useState(()=>wr(Nd(t),f=>{c(f,I)})),[A]=he.useState(io(m,L));Qa(()=>{for(const f of i)f in I&&Ye(A[f],I[f]);return()=>{Object.values(A).map(un)}},[I,A,L]),Qa(()=>{c(L,I)}),he.useImperativeHandle(w,oo(d(L)));const W=a;return e.jsx(l.Provider,{value:L,children:a!==void 0?e.jsx(W,{...au([...r,...o,...i],I),children:g}):g})}),h=N=>{const w=he.useContext(l);return he.useCallback(g=>{Ee(w[N],g)},[w,N])},v=N=>{const w=he.useContext(l)[N],g=he.useCallback(I=>Ye(w,I),[w]);return he.useSyncExternalStore(g,()=>ot(w),()=>ot(w))},y=N=>{const w=he.useContext(l)[N],[g,I]=he.useState(io(ot,w));return Qa(()=>Ye(w,L=>{L!==g&&I(oo(L))}),[w,g]),g},S=parseInt(he.version)>=18?v:y;return{Component:p,useEmitter:(N,w)=>{const g=he.useContext(l)[N];Qa(()=>Ye(g,w),[w,g])},useEmitterValue:S,usePublisher:h}}const Ji=he.createContext(void 0),Zi=he.createContext(void 0),Ar="-webkit-sticky",vo="sticky",vn=Yi(()=>{if(typeof document>"u")return vo;const t=document.createElement("div");return t.style.position=Ar,t.style.position===Ar?Ar:vo}),el=typeof document<"u"?he.useLayoutEffect:he.useEffect;function zr(t){return"self"in t}function ru(t){return"body"in t}function tl(t,s,a,r=xa,o,n){const i=he.useRef(null),l=he.useRef(null),c=he.useRef(null),d=he.useCallback(h=>{let v,y,S;const N=h.target;if(ru(N)||zr(N)){const g=zr(N)?N:N.defaultView;S=n===!0?g.scrollX:g.scrollY,v=n===!0?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight,y=n===!0?g.innerWidth:g.innerHeight}else S=n===!0?N.scrollLeft:N.scrollTop,v=n===!0?N.scrollWidth:N.scrollHeight,y=n===!0?N.offsetWidth:N.offsetHeight;const w=()=>{t({scrollHeight:v,scrollTop:Math.max(S,0),viewportHeight:y})};h.suppressFlushSync===!0?w():Qr.flushSync(w),l.current!==null&&(S===l.current||S<=0||S===v-y)&&(l.current=null,s(!0),c.current&&(clearTimeout(c.current),c.current=null))},[t,s,n]);he.useEffect(()=>{const h=o||i.current;return r(o||i.current),d({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",d,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",d)}},[i,d,a,r,o]);function m(h){const v=i.current;if(!v||(n===!0?"offsetWidth"in v&&v.offsetWidth===0:"offsetHeight"in v&&v.offsetHeight===0))return;const y=h.behavior==="smooth";let S,N,w;zr(v)?(N=Math.max(Fs(v.document.documentElement,n===!0?"width":"height"),n===!0?v.document.documentElement.scrollWidth:v.document.documentElement.scrollHeight),S=n===!0?v.innerWidth:v.innerHeight,w=n===!0?window.scrollX:window.scrollY):(N=v[n===!0?"scrollWidth":"scrollHeight"],S=Fs(v,n===!0?"width":"height"),w=v[n===!0?"scrollLeft":"scrollTop"]);const g=N-S;if(h.top=Math.ceil(Math.max(Math.min(g,h.top),0)),Ui(S,N)||h.top===w){t({scrollHeight:N,scrollTop:w,viewportHeight:S}),y&&s(!0);return}y?(l.current=h.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,l.current=null,s(!0)},1e3)):l.current=null,n===!0&&(h={...h.behavior!==void 0?{behavior:h.behavior}:{},left:h.top}),v.scrollTo(h)}function p(h){n===!0&&(h={...h.behavior!==void 0?{behavior:h.behavior}:{},...h.top!==void 0?{left:h.top}:{}}),i.current.scrollBy(h)}return{scrollByCallback:p,scrollerRef:i,scrollToCallback:m}}function wn(t){return t}const nu=qe(()=>{const t=Z(l=>`Item ${l}`),s=Z(l=>`Group ${l}`),a=Z({}),r=Z(wn),o=Z("div"),n=Z(xa),i=(l,c=null)=>Et(Y(a,xe(d=>d[l]),st()),c);return{components:a,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:s,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:t,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:n,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),ou=qe(([t,s])=>({...t,...s}),at(Ki,nu)),iu=({height:t})=>e.jsx("div",{style:{height:t}}),lu={overflowAnchor:"none",position:vn(),zIndex:1},sl={overflowAnchor:"none"},cu={...sl,display:"inline-block",height:"100%"},wo=he.memo(function({showTopList:t=!1}){const s=Ie("listState"),a=Zt("sizeRanges"),r=Ie("useWindowScroll"),o=Ie("customScrollParent"),n=Zt("windowScrollContainerState"),i=Zt("scrollContainerState"),l=o||r?n:i,c=Ie("itemContent"),d=Ie("context"),m=Ie("groupContent"),p=Ie("trackItemSizes"),h=Ie("itemSize"),v=Ie("log"),y=Zt("gap"),S=Ie("horizontalDirection"),{callbackRef:N}=Sd(a,h,p,t?xa:l,v,y,o,S,Ie("skipAnimationFrameInResizeObserver")),[w,g]=he.useState(0);jn("deviation",J=>{w!==J&&g(J)});const I=Ie("EmptyPlaceholder"),L=Ie("ScrollSeekPlaceholder")??iu,A=Ie("ListComponent"),W=Ie("ItemComponent"),f=Ie("GroupComponent"),C=Ie("computeItemKey"),b=Ie("isSeeking"),F=Ie("groupIndices").length>0,U=Ie("alignToBottom"),k=Ie("initialItemFinalLocationReached"),D=t?{}:{boxSizing:"border-box",...S?{display:"inline-block",height:"100%",marginLeft:w!==0?w:U?"auto":0,paddingLeft:s.offsetTop,paddingRight:s.offsetBottom,whiteSpace:"nowrap"}:{marginTop:w!==0?w:U?"auto":0,paddingBottom:s.offsetBottom,paddingTop:s.offsetTop},...k?{}:{visibility:"hidden"}};return!t&&s.totalCount===0&&I!==null&&I!==void 0?e.jsx(I,{..._t(I,d)}):e.jsx(A,{..._t(A,d),"data-testid":t?"virtuoso-top-item-list":"virtuoso-item-list",ref:N,style:D,children:(t?s.topItems:s.items).map(J=>{const re=J.originalIndex,ce=C(re+s.firstItemIndex,J.data,d);return b?u.createElement(L,{..._t(L,d),height:J.size,index:J.index,key:ce,type:J.type||"item",...J.type==="group"?{}:{groupIndex:J.groupIndex}}):J.type==="group"?u.createElement(f,{..._t(f,d),"data-index":re,"data-item-index":J.index,"data-known-size":J.size,key:ce,style:lu},m(J.index,d)):u.createElement(W,{..._t(W,d),...xu(W,J.data),"data-index":re,"data-item-group-index":J.groupIndex,"data-item-index":J.index,"data-known-size":J.size,key:ce,style:S?cu:sl},F?c(J.index,J.groupIndex,J.data,d):c(J.index,J.data,d))})})}),du={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},uu={outline:"none",overflowX:"auto",position:"relative"},Nn=t=>({height:"100%",position:"absolute",top:0,width:"100%",...t?{display:"flex",flexDirection:"column"}:void 0}),al=(t,s,a=0)=>({...Nn(t),position:s?"relative":"absolute",top:s?-a:0}),mu={position:vn(),top:0,width:"100%",zIndex:1};function _t(t,s){if(typeof t!="string")return{context:s}}function xu(t,s){return{item:typeof t=="string"?void 0:s}}const pu=he.memo(function(){const t=Ie("HeaderComponent"),s=Zt("headerHeight"),a=Ie("HeaderFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,Ie("skipAnimationFrameInResizeObserver")),o=Ie("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null}),hu=he.memo(function(){const t=Ie("FooterComponent"),s=Zt("footerHeight"),a=Ie("HeaderFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,Ie("skipAnimationFrameInResizeObserver")),o=Ie("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null});function rl({useEmitter:t,useEmitterValue:s,usePublisher:a}){return he.memo(function({children:r,style:o,context:n,...i}){const l=a("scrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("scrollerRef"),p=s("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:v,scrollToCallback:y}=tl(l,d,c,m,void 0,p);return t("scrollTo",y),t("scrollBy",h),e.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:v,style:{...p?uu:du,...o},tabIndex:0,...i,..._t(c,n),children:r})})}function nl({useEmitter:t,useEmitterValue:s,usePublisher:a}){return he.memo(function({children:r,style:o,context:n,...i}){const l=a("windowScrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("totalListHeight"),p=s("deviation"),h=s("customScrollParent"),v=he.useRef(null),y=s("scrollerRef"),{scrollByCallback:S,scrollerRef:N,scrollToCallback:w}=tl(l,d,c,y,h);return el(()=>(N.current=h||v.current?.ownerDocument.defaultView,()=>{N.current=null}),[N,h]),t("windowScrollTo",w),t("scrollBy",S),e.jsx(c,{ref:v,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...m!==0?{height:m+p}:void 0},...i,..._t(c,n),children:r})})}const fu=({children:t})=>{const s=he.useContext(Ji),a=Zt("viewportHeight"),r=Zt("fixedItemHeight"),o=Ie("alignToBottom"),n=Ie("horizontalDirection"),i=he.useMemo(()=>_i(a,c=>Fs(c,n?"width":"height")),[a,n]),l=Js(i,!0,Ie("skipAnimationFrameInResizeObserver"));return he.useEffect(()=>{s&&(a(s.viewportHeight),r(s.itemHeight))},[s,a,r]),e.jsx("div",{"data-viewport-type":"element",ref:l,style:Nn(o),children:t})},gu=({children:t})=>{const s=he.useContext(Ji),a=Zt("windowViewportRect"),r=Zt("fixedItemHeight"),o=Ie("customScrollParent"),n=Ie("useWindowScroll"),i=Ie("topListHeight"),l=Ri(a,o,Ie("skipAnimationFrameInResizeObserver")),c=Ie("alignToBottom");return he.useEffect(()=>{s&&(r(s.itemHeight),a({listHeight:0,offsetTop:0,visibleHeight:s.viewportHeight,visibleWidth:100}))},[s,a,r]),e.jsx("div",{"data-viewport-type":"window",ref:l,style:al(c,n,i),children:t})},bu=({children:t})=>{const s=Ie("TopItemListComponent")??"div",a=Ie("headerHeight"),r={...mu,marginTop:`${a}px`},o=Ie("context");return e.jsx(s,{style:r,..._t(s,o),children:t})},vu=he.memo(function(t){const s=Ie("useWindowScroll"),a=Ie("topItemsIndexes").length>0,r=Ie("customScrollParent"),o=Ie("context");return e.jsxs(r||s?ju:Nu,{...t,context:o,children:[a&&e.jsx(bu,{children:e.jsx(wo,{showTopList:!0})}),e.jsxs(r||s?gu:fu,{children:[e.jsx(pu,{}),e.jsx(wo,{}),e.jsx(hu,{})]})]})}),{Component:wu,useEmitter:jn,useEmitterValue:Ie,usePublisher:Zt}=Xi(ou,{optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",minOverscanItemCount:"minOverscanItemCount",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedGroupHeight:"fixedGroupHeight",fixedItemHeight:"fixedItemHeight",heightEstimates:"heightEstimates",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},vu),Nu=rl({useEmitter:jn,useEmitterValue:Ie,usePublisher:Zt}),ju=nl({useEmitter:jn,useEmitterValue:Ie,usePublisher:Zt}),yu=wu,Su=qe(()=>{const t=Z(d=>e.jsxs("td",{children:["Item $",d]})),s=Z(null),a=Z(d=>e.jsxs("td",{colSpan:1e3,children:["Group ",d]})),r=Z(null),o=Z(null),n=Z({}),i=Z(wn),l=Z(xa),c=(d,m=null)=>Et(Y(n,xe(p=>p[d]),st()),m);return{components:n,computeItemKey:i,context:s,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:t,groupContent:a,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder"),TableBodyComponent:c("TableBody","tbody"),TableComponent:c("Table","table"),TableFooterComponent:c("TableFoot","tfoot"),TableHeadComponent:c("TableHead","thead"),TableRowComponent:c("TableRow","tr"),GroupComponent:c("Group","tr")}});at(Ki,Su);vn();const No={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},ku={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:jo,floor:xr,max:Ca,min:Lr,round:yo}=Math;function So(t,s,a){return Array.from({length:s-t+1}).map((r,o)=>({data:a===null?null:a[o+t],index:o+t}))}function Cu(t){return{...ku,items:t}}function Va(t,s){return t!==void 0&&t.width===s.width&&t.height===s.height}function Iu(t,s){return t!==void 0&&t.column===s.column&&t.row===s.row}const Tu=qe(([{increaseViewportBy:t,listBoundary:s,overscan:a,visibleRange:r},{footerHeight:o,headerHeight:n,scrollBy:i,scrollContainerState:l,scrollTo:c,scrollTop:d,smoothScrollTargetReached:m,viewportHeight:p},h,v,{didMount:y,propsReady:S},{customScrollParent:N,useWindowScroll:w,windowScrollContainerState:g,windowScrollTo:I,windowViewportRect:L},A])=>{const W=Z(0),f=Z(0),C=Z(No),b=Z({height:0,width:0}),F=Z({height:0,width:0}),U=Be(),k=Be(),D=Z(0),J=Z(null),re=Z({column:0,row:0}),ce=Be(),ie=Be(),fe=Z(!1),Ce=Z(0),ue=Z(!0),ge=Z(!1),B=Z(!1);Ye(Y(y,Ae(Ce),Se(([G,se])=>se!==0)),()=>{Ee(ue,!1)}),Ye(Y(pt(y,ue,F,b,Ce,ge),Se(([G,se,M,q,,Q])=>G&&!se&&M.height!==0&&q.height!==0&&!Q)),([,,,,G])=>{Ee(ge,!0),hn(1,()=>{Ee(U,G)}),is(Y(d),()=>{Ee(s,[0,0]),Ee(ue,!0)})}),be(Y(ie,Se(G=>G!=null&&G.scrollTop>0),ms(0)),f),Ye(Y(y,Ae(ie),Se(([,G])=>G!=null)),([,G])=>{G&&(Ee(b,G.viewport),Ee(F,G.item),Ee(re,G.gap),G.scrollTop>0&&(Ee(fe,!0),is(Y(d,Ks(1)),se=>{Ee(fe,!1)}),Ee(c,{top:G.scrollTop})))}),be(Y(b,xe(({height:G})=>G)),p),be(Y(pt(ye(b,Va),ye(F,Va),ye(re,(G,se)=>G!==void 0&&G.column===se.column&&G.row===se.row),ye(d)),xe(([G,se,M,q])=>({gap:M,item:se,scrollTop:q,viewport:G}))),ce),be(Y(pt(ye(W),r,ye(re,Iu),ye(F,Va),ye(b,Va),ye(J),ye(f),ye(fe),ye(ue),ye(Ce)),Se(([,,,,,,,G])=>!G),xe(([G,[se,M],q,Q,pe,$,j,,T,_])=>{const{column:V,row:me}=q,{height:oe,width:ae}=Q,{width:je}=pe;if(j===0&&(G===0||je===0))return No;if(ae===0){const At=fn(_,G),It=At+Math.max(j-1,0);return Cu(So(At,It,$))}const we=ol(je,ae,V);let Ke,Ue;T?se===0&&M===0&&j>0?(Ke=0,Ue=j-1):(Ke=we*xr((se+me)/(oe+me)),Ue=we*jo((M+me)/(oe+me))-1,Ue=Lr(G-1,Ca(Ue,we-1)),Ke=Lr(Ue,Ca(0,Ke))):(Ke=0,Ue=-1);const Je=So(Ke,Ue,$),{bottom:ht,top:dt}=ko(pe,q,Q,Je),rt=jo(G/we),Mt=rt*oe+(rt-1)*me-ht;return{bottom:ht,itemHeight:oe,items:Je,itemWidth:ae,offsetBottom:Mt,offsetTop:dt,top:dt}})),C),be(Y(J,Se(G=>G!==null),xe(G=>G.length)),W),be(Y(pt(b,F,C,re),Se(([G,se,{items:M}])=>M.length>0&&se.height!==0&&G.height!==0),xe(([G,se,{items:M},q])=>{const{bottom:Q,top:pe}=ko(G,q,se,M);return[pe,Q]}),st(Ea)),s);const te=Z(!1);be(Y(d,Ae(te),xe(([G,se])=>se||G!==0)),te);const ne=Wt(Y(pt(C,W),Se(([{items:G}])=>G.length>0),Ae(te),Se(([[G,se],M])=>{const q=G.items[G.items.length-1].index===se-1;return(M||G.bottom>0&&G.itemHeight>0&&G.offsetBottom===0&&G.items.length===se)&&q}),xe(([[,G]])=>G-1),st())),ze=Wt(Y(ye(C),Se(({items:G})=>G.length>0&&G[0].index===0),ms(0),st())),Fe=Wt(Y(ye(C),Ae(fe),Se(([{items:G},se])=>G.length>0&&!se),xe(([{items:G}])=>({endIndex:G[G.length-1].index,startIndex:G[0].index})),st($i),Ts(0)));be(Fe,v.scrollSeekRangeChanged),be(Y(U,Ae(b,F,W,re),xe(([G,se,M,q,Q])=>{const pe=Hi(G),{align:$,behavior:j,offset:T}=pe;let _=pe.index;_==="LAST"&&(_=q-1),_=Ca(0,_,Lr(q-1,_));let V=an(se,Q,M,_);return $==="end"?V=yo(V-se.height+M.height):$==="center"&&(V=yo(V-se.height/2+M.height/2)),T!==void 0&&T!==0&&(V+=T),{behavior:j,top:V}})),c);const Pe=Et(Y(C,xe(G=>G.offsetBottom+G.bottom)),0);return be(Y(L,xe(G=>({height:G.visibleHeight,width:G.visibleWidth}))),b),{customScrollParent:N,data:J,deviation:D,footerHeight:o,gap:re,headerHeight:n,increaseViewportBy:t,initialItemCount:f,itemDimensions:F,overscan:a,restoreStateFrom:ie,scrollBy:i,scrollContainerState:l,scrollHeight:k,scrollTo:c,scrollToIndex:U,scrollTop:d,smoothScrollTargetReached:m,totalCount:W,useWindowScroll:w,viewportDimensions:b,windowScrollContainerState:g,windowScrollTo:I,windowViewportRect:L,...v,gridState:C,horizontalDirection:B,initialTopMostItemIndex:Ce,totalListHeight:Pe,...h,endReached:ne,propsReady:S,rangeChanged:Fe,startReached:ze,stateChanged:ce,stateRestoreInProgress:fe,...A}},at(gn,Dt,Fa,qi,Bs,bn,Ps));function ol(t,s,a){return Ca(1,xr((t+a)/(xr(s)+a)))}function ko(t,s,a,r){const{height:o}=a;if(o===void 0||r.length===0)return{bottom:0,top:0};const n=an(t,s,a,r[0].index);return{bottom:an(t,s,a,r[r.length-1].index)+o,top:n}}function an(t,s,a,r){const o=ol(t.width,a.width,s.column),n=xr(r/o),i=n*a.height+Ca(0,n-1)*s.row;return i>0?i+s.row:i}const _u=qe(()=>{const t=Z(p=>`Item ${p}`),s=Z({}),a=Z(null),r=Z("virtuoso-grid-item"),o=Z("virtuoso-grid-list"),n=Z(wn),i=Z("div"),l=Z(xa),c=(p,h=null)=>Et(Y(s,xe(v=>v[p]),st()),h),d=Z(!1),m=Z(!1);return be(ye(m),d),{components:s,computeItemKey:n,context:a,FooterComponent:c("Footer"),HeaderComponent:c("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:c("Item","div"),itemContent:t,listClassName:o,ListComponent:c("List","div"),readyStateChanged:d,reportReadyState:m,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),Eu=qe(([t,s])=>({...t,...s}),at(Tu,_u)),Ru=he.memo(function(){const t=tt("gridState"),s=tt("listClassName"),a=tt("itemClassName"),r=tt("itemContent"),o=tt("computeItemKey"),n=tt("isSeeking"),i=es("scrollHeight"),l=tt("ItemComponent"),c=tt("ListComponent"),d=tt("ScrollSeekPlaceholder"),m=tt("context"),p=es("itemDimensions"),h=es("gap"),v=tt("log"),y=tt("stateRestoreInProgress"),S=es("reportReadyState"),N=Js(he.useMemo(()=>w=>{const g=w.parentElement.parentElement.scrollHeight;i(g);const I=w.firstChild;if(I!==null){const{height:L,width:A}=I.getBoundingClientRect();p({height:L,width:A})}h({column:Co("column-gap",getComputedStyle(w).columnGap,v),row:Co("row-gap",getComputedStyle(w).rowGap,v)})},[i,p,h,v]),!0,!1);return el(()=>{t.itemHeight>0&&t.itemWidth>0&&S(!0)},[t]),y?null:e.jsx(c,{className:s,ref:N,..._t(c,m),"data-testid":"virtuoso-item-list",style:{paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},children:t.items.map(w=>{const g=o(w.index,w.data,m);return n?e.jsx(d,{..._t(d,m),height:t.itemHeight,index:w.index,width:t.itemWidth},g):u.createElement(l,{..._t(l,m),className:a,"data-index":w.index,key:g},r(w.index,w.data,m))})})}),Mu=he.memo(function(){const t=tt("HeaderComponent"),s=es("headerHeight"),a=tt("headerFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,!1),o=tt("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null}),Au=he.memo(function(){const t=tt("FooterComponent"),s=es("footerHeight"),a=tt("headerFooterTag"),r=Js(he.useMemo(()=>n=>{s(Fs(n,"height"))},[s]),!0,!1),o=tt("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{..._t(t,o)})}):null}),zu=({children:t})=>{const s=he.useContext(Zi),a=es("itemDimensions"),r=es("viewportDimensions"),o=Js(he.useMemo(()=>n=>{r(n.getBoundingClientRect())},[r]),!0,!1);return he.useEffect(()=>{s&&(r({height:s.viewportHeight,width:s.viewportWidth}),a({height:s.itemHeight,width:s.itemWidth}))},[s,r,a]),e.jsx("div",{ref:o,style:Nn(!1),children:t})},Lu=({children:t})=>{const s=he.useContext(Zi),a=es("windowViewportRect"),r=es("itemDimensions"),o=tt("customScrollParent"),n=tt("useWindowScroll"),i=Ri(a,o,!1);return he.useEffect(()=>{s&&(r({height:s.itemHeight,width:s.itemWidth}),a({listHeight:0,offsetTop:0,visibleHeight:s.viewportHeight,visibleWidth:s.viewportWidth}))},[s,a,r]),e.jsx("div",{ref:i,style:al(!1,n),children:t})},Du=he.memo(function({...t}){const s=tt("useWindowScroll"),a=tt("customScrollParent"),r=a||s?Fu:$u,o=a||s?Lu:zu,n=tt("context");return e.jsx(r,{...t,..._t(r,n),children:e.jsxs(o,{children:[e.jsx(Mu,{}),e.jsx(Ru,{}),e.jsx(Au,{})]})})}),{useEmitter:il,useEmitterValue:tt,usePublisher:es}=Xi(Eu,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},Du),$u=rl({useEmitter:il,useEmitterValue:tt,usePublisher:es}),Fu=nl({useEmitter:il,useEmitterValue:tt,usePublisher:es});function Co(t,s,a){return s!=="normal"&&s?.endsWith("px")!==!0&&a(`${t} was not resolved to pixel value correctly`,s,vt.WARN),s==="normal"?0:parseInt(s??"0",10)}function Io(t){if(Array.isArray(t)){if(t.length<5||t.length>6)throw new Error(`Invalid bone format: expected [x,y,w,h,r,c?] but got ${t.length} elements`);const s=t;return{x:s[0],y:s[1],w:s[2],h:s[3],r:s[4],c:s[5]||void 0}}return t}const To=new Set(["p","h1","h2","h3","h4","h5","h6","li","td","th"]);function Ou(t,s="component",a){const r=t.getBoundingClientRect(),o=[],n=a?.leafTags?new Set([...To,...a.leafTags]):To,i=a?.captureRoundedBorders??!0,l=a?.excludeTags?new Set(a.excludeTags):null,c=a?.excludeSelectors??null;function d(m){const p=getComputedStyle(m);if(p.display==="none"||p.visibility==="hidden"||p.opacity==="0")return;const h=m.tagName.toLowerCase();if(l?.has(h)||c?.some(b=>m.matches(b)))return;const v=[...m.children].filter(b=>{const F=getComputedStyle(b);return F.display!=="none"&&F.visibility!=="hidden"&&F.opacity!=="0"}),y=h==="img"||h==="svg"||h==="video"||h==="canvas",S=h==="input"||h==="button"||h==="textarea"||h==="select",N=v.length===0||y||S||n.has(h),w=p.backgroundColor,g=w!=="rgba(0, 0, 0, 0)"&&w!=="transparent",I=p.backgroundImage!=="none",L=parseFloat(p.borderTopWidth)||0,A=i&&L>0&&p.borderTopColor!=="rgba(0, 0, 0, 0)"&&p.borderTopColor!=="transparent",W=(parseFloat(p.borderTopLeftRadius)||0)>0,f=g||I||A&&W,C=h==="tr"||h==="td"||h==="th"||h==="thead"||h==="tbody"||h==="table";if(N){const b=m.getBoundingClientRect();if(b.width<1||b.height<1)return;const F=y&&b.width>0&&b.height>0&&Math.abs(b.width-b.height)<4,U=C?0:F?"50%":_o(p,m)??8,k=r.width;o.push({x:k>0?+((b.left-r.left)/k*100).toFixed(4):0,y:Math.round(b.top-r.top),w:k>0?+(b.width/k*100).toFixed(4):0,h:Math.round(b.height),r:U});return}if(f){const b=m.getBoundingClientRect();if(b.width>=1&&b.height>=1){const F=C?0:_o(p,m)??8,U=r.width;o.push({x:U>0?+((b.left-r.left)/U*100).toFixed(4):0,y:Math.round(b.top-r.top),w:U>0?+(b.width/U*100).toFixed(4):0,h:Math.round(b.height),r:F,c:!0})}}for(const b of v)d(b)}for(const m of t.children)d(m);return{name:s,viewportWidth:Math.round(r.width),width:Math.round(r.width),height:Math.round(r.height),bones:o}}function _o(t,s){const a=parseFloat(t.borderTopLeftRadius)||0,r=parseFloat(t.borderTopRightRadius)||0,o=parseFloat(t.borderBottomRightRadius)||0,n=parseFloat(t.borderBottomLeftRadius)||0;if(a===0&&r===0&&o===0&&n===0)return;const i=s?(()=>{const d=s.getBoundingClientRect();return d.width>0&&d.height>0&&Math.abs(d.width-d.height)<4})():!1;return t.borderRadius==="50%"?"50%":Math.max(a,r,o,n)>9998?i?"50%":9999:a===r&&r===o&&o===n?a!==8?a:void 0:`${a}px ${r}px ${o}px ${n}px`}const Pu=new Map;function Bu(t){return Pu.get(t)}function Hu(){typeof window<"u"&&window.__BONEYARD_BUILD&&(window.__BONEYARD_SNAPSHOT=Ou)}function Uu(){return typeof window<"u"&&window.__BONEYARD_BUILD===!0}function Gu(t,s){if(!("breakpoints"in t))return t;const a=Object.keys(t.breakpoints).map(Number).sort((o,n)=>o-n);if(a.length===0)return null;const r=[...a].reverse().find(o=>s>=o)??a[0];return t.breakpoints[r]??null}const ta={angle:110,start:30,end:70,speed:"2s",lightHighlight:"#f7f7f7",darkHighlight:"#2c2c2c"},va={speed:"1.8s",lightAdjust:.3,darkAdjust:.02},Eo={web:{light:"#f0f0f0",dark:"#222222"}},Qu=/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+))?\s*\)/;function Ro(t,s){const a=t.match(Qu);if(a){const[,r,o,n,i="1"]=a,l=Math.min(1,parseFloat(i)+s*.5);return`rgba(${r},${o},${n},${l.toFixed(3)})`}if(t.startsWith("#")&&t.length>=7){const r=parseInt(t.slice(1,3),16),o=parseInt(t.slice(3,5),16),n=parseInt(t.slice(5,7),16);if(!isNaN(r)&&!isNaN(o)&&!isNaN(n)){const i=Math.round(r+(255-r)*s),l=Math.round(o+(255-o)*s),c=Math.round(n+(255-n)*s);return`#${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}${c.toString(16).padStart(2,"0")}`}}return t}Hu();let us={};function Mo({loading:t,children:s,name:a,initialBones:r,color:o,darkColor:n,animate:i,stagger:l=!1,transition:c=!1,boneClass:d,className:m,fallback:p,fixture:h,snapshotConfig:v}){const y=u.useRef(null),S=u.useRef(Math.random().toString(36).slice(2,8)).current,[N,w]=u.useState(0),[g,I]=u.useState(0),[L,A]=u.useState(!1);u.useEffect(()=>{if(typeof window>"u")return;const M=()=>{const pe=document.documentElement.classList.contains("dark")||!!y.current?.closest(".dark");A(pe)};M();const q=new MutationObserver(M);q.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const Q=window.matchMedia("(prefers-color-scheme: dark)");return Q.addEventListener("change",M),()=>{q.disconnect(),Q.removeEventListener("change",M)}},[]);const W=o??us.color??Eo.web.light,f=n??us.darkColor??Eo.web.dark,C=L?f:W,b=i??us.animate??"pulse",F=b===!0?"pulse":b===!1?"solid":b;u.useEffect(()=>{const M=y.current;if(!M)return;const q=new ResizeObserver(pe=>{const $=pe[0]?.contentRect;w(Math.round($?.width??0)),$&&$.height>0&&I(Math.round($.height))});q.observe(M);const Q=M.getBoundingClientRect();return w(Math.round(Q.width)),Q.height>0&&I(Math.round(Q.height)),()=>q.disconnect()},[]);const U={};if(a&&(U["data-boneyard"]=a,v&&(U["data-boneyard-config"]=JSON.stringify(v))),Uu())return e.jsx("div",{ref:y,className:m,style:{position:"relative"},...U,children:e.jsx("div",{children:h??s})});const[k,D]=u.useState(!1);u.useLayoutEffect(()=>{D(!0)},[]);const J=r??(a?Bu(a):void 0),re=k&&typeof window<"u"?window.innerWidth:0,ce=N>0?N:re,ie=J&&ce>0?Gu(J,ce):null,fe=d??us.boneClass,Ce=(()=>{const M=l??us.stagger;return M===!0?80:M===!1||!M?0:M})(),ue=(()=>{const M=c??us.transition;return M===!0?300:M===!1||!M?0:M})(),[ge,B]=u.useState(!1),te=u.useRef(t),ne=u.useRef(null);u.useEffect(()=>(te.current&&!t&&ue>0&&ie&&(ne.current&&clearTimeout(ne.current),B(!0),ne.current=setTimeout(()=>{B(!1),ne.current=null},ue)),te.current=t,()=>{ne.current&&clearTimeout(ne.current)}),[t,ue,ie]);const ze=(t||ge)&&ie,Fe=t&&!ie&&!ge,Pe=g>0?g:ie?.height??0,G=ie?.height??0,se=Pe>0&&G>0?Pe/G:1;return e.jsxs("div",{ref:y,className:m,style:{position:"relative"},...U,children:[e.jsx("div",{"data-boneyard-content":"true",style:ze&&!ge?{visibility:"hidden"}:void 0,children:Fe?p:s}),ze&&e.jsx("div",{"data-boneyard-overlay":"true",style:{position:"absolute",inset:0,overflow:"hidden",opacity:ge?0:1,transition:ue>0?`opacity ${ue}ms ease-out`:void 0},children:e.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[ie.bones.filter(M=>!Io(M).c).map((M,q)=>{const Q=Io(M),pe=C;Ro(C,L?va.darkAdjust:va.lightAdjust);const $=Q.w/100*(ie.width??0),j=Q.r==="50%"&&Math.abs($-Q.h)<4,T={position:"absolute",left:`${Q.x}%`,top:Q.y*se,width:j?Q.h*se:`${Q.w}%`,height:Q.h*se,borderRadius:typeof Q.r=="string"?Q.r:`${Q.r}px`,backgroundColor:pe},_=us.speed;if(F==="pulse")T.animation=`bp-${S} ${_??va.speed} ease-in-out infinite`;else if(F==="shimmer"){const V=L?us.darkShimmerColor??ta.darkHighlight:us.shimmerColor??ta.lightHighlight,me=us.shimmerAngle??ta.angle;delete T.backgroundColor,T.backgroundImage=`linear-gradient(${me}deg, ${pe} ${ta.start}%, ${V} 50%, ${pe} ${ta.end}%)`,T.backgroundSize="200% 100%",T.animation=`bs-${S} ${_??ta.speed} linear infinite`}return Ce>0&&(T.opacity=0,T.animation=`${T.animation?T.animation+",":""} by-${S} 0.3s ease-out ${q*Ce}ms forwards`),e.jsx("div",{"data-boneyard-bone":"true",className:fe,style:T},q)}),F==="pulse"&&e.jsx("style",{children:`@keyframes bp-${S}{0%,100%{background-color:${C}}50%{background-color:${Ro(C,L?va.darkAdjust:va.lightAdjust)}}}`}),F==="shimmer"&&e.jsx("style",{children:`@keyframes bs-${S}{0%{background-position:200% 0}100%{background-position:-200% 0}}`}),Ce>0&&e.jsx("style",{children:`@keyframes by-${S}{from{opacity:0}to{opacity:1}}`})]})})]})}async function yn(t){const s=St($e,"managedStudents");try{const n=kt(s,Nt("teacherId","==",t)),i=await Lt(n);if(!i.empty)return i.docs.map(c=>({id:c.id,...c.data()})).sort((c,d)=>String(c.name||"").localeCompare(String(d.name||"")))}catch{}const r=(await cl(t)).map(n=>n.id);if(r.length===0)return[];const o=new Map;for(let n=0;n{o.set(d.id,{id:d.id,...d.data()})})}return Array.from(o.values()).sort((n,i)=>String(n.name||"").localeCompare(String(i.name||"")))}async function Vu(t,s=[]){if(!t)return[];const a=St($e,"users"),r=new Map,o=(i,l)=>String(l.role||"").toLowerCase()!=="student"?null:{uid:i,name:String(l.name||l.displayName||"").trim()||"Student",email:String(l.email||"").trim(),lrn:l.lrn&&String(l.lrn).trim()||void 0,photo:l.photo?String(l.photo).trim()||void 0:l.photoURL&&String(l.photoURL).trim()||void 0,grade:l.grade&&String(l.grade).trim()||void 0,section:l.section&&String(l.section).trim()||void 0,classSectionId:l.classSectionId&&String(l.classSectionId).trim()||void 0,adviserTeacherId:l.adviserTeacherId&&String(l.adviserTeacherId).trim()||void 0,role:"student",createdAt:l.createdAt||void 0};try{const i=kt(a,Nt("role","==","student"),Nt("adviserTeacherId","==",t));(await Lt(i)).docs.forEach(c=>{const d=o(c.id,c.data());d&&r.set(c.id,d)})}catch(i){console.warn("[studentService] adviser-scoped student query failed:",i)}const n=Array.from(new Set((s||[]).map(i=>(i||"").trim()).filter(i=>!!i)));for(let i=0;i{if(r.has(m.id))return;const p=o(m.id,m.data());p&&r.set(m.id,p)})}catch(c){console.warn("[studentService] section-scoped student query failed:",c)}}return Array.from(r.values()).sort((i,l)=>i.name.localeCompare(l.name))}function Wu(t){const s=`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||"Student")}&background=random`,a=Zl.now();return{id:t.uid,accountUid:t.uid,lrn:t.lrn,name:t.name,email:t.email,avatar:t.photo||s,teacherId:t.adviserTeacherId,grade:t.grade,gradeLevel:Ns(t.grade)||void 0,section:t.section,classSectionId:t.classSectionId,riskLevel:"Low",engagementScore:0,avgQuizScore:0,weakestTopic:"N/A",classroomId:t.classSectionId||"",attendance:0,assignmentCompletion:0,lastActive:null,struggles:[],createdAt:t.createdAt||a,updatedAt:a,hasRegisteredAccount:!0,source:"registered"}}function Ao(t){return(t||"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9\s]+/g," ").trim().replace(/\s+/g," ")}async function qu(t){const s=(t.studentId||"").trim();if(!s)throw new Error("Cannot reassign section: studentId is required.");const a=(t.newClassSectionId||"").trim()||Pt(t.newGrade,t.newSection);if(!a)throw new Error("Cannot reassign section: a target class section is required.");const r=(t.teacherId||"").trim(),o=(t.teacherName||"").trim(),n=(t.schoolYear||"").trim(),i=(t.previousClassSectionId||"").trim();try{const l=ct($e,"managedStudents",s),c=await Is(l);c.exists()&&await ns(l,{grade:t.newGrade,section:t.newSection,classSectionId:a,gradeLevel:Ns(t.newGrade)||t.newGrade,teacherId:r||c.data()?.teacherId,updatedAt:it()})}catch(l){console.warn("[studentService] reassignStudentSection: managedStudents update failed:",l)}if(t.isRegisteredAccount)try{await os(ct($e,"users",s),{grade:t.newGrade,section:t.newSection,classSectionId:a,adviserTeacherId:r||void 0,adviserTeacherName:o||void 0,updatedAt:it()},{merge:!0})}catch(l){console.warn("[studentService] reassignStudentSection: users profile update failed:",l)}try{await jr({classSectionId:a,grade:t.newGrade,section:t.newSection,schoolYear:n,ownerTeacherId:r,ownerTeacherName:o,studentUids:[s]})}catch(l){console.warn("[studentService] reassignStudentSection: ownership upsert failed:",l)}if(i&&i!==a)try{const l=ct($e,"classSectionOwnership",i),c=await Is(l);if(c.exists()){const m=(c.data().studentUids||[]).filter(p=>p!==s);await ns(l,{studentUids:m,updatedAt:it()})}}catch(l){console.warn("[studentService] reassignStudentSection: previous-section cleanup failed:",l)}}async function Yu(t){const{apiService:s}=await Cs(async()=>{const{apiService:d}=await import("./index-BdLfAeGL.js").then(m=>m.b8);return{apiService:d}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),a=(t.adviserTeacherId||"").trim();if(!a)throw new Error("createStudentAccountFromRoster requires adviserTeacherId.");const r=(t.email||"").trim().toLowerCase();if(!r)throw new Error("createStudentAccountFromRoster requires an email.");const o=(t.grade||"").trim(),n=(t.section||"").trim(),i=(t.classSectionId||"").trim()||(o&&n?Pt(o,n):""),c=((await s.createStudentAccount({name:(t.name||"").trim()||"Student",email:r,temporaryPassword:t.temporaryPassword,lrn:t.lrn?.trim()||void 0,grade:o||void 0,section:n||void 0,classSectionId:i||void 0,adviserTeacherId:a,adviserTeacherName:t.adviserTeacherName?.trim()||void 0,schoolYear:t.schoolYear?.trim()||void 0})).uid||"").trim();if(!c)throw new Error("Backend did not return a uid for the newly created student.");try{await os(ct($e,"managedStudents",c),pr({accountUid:c,name:(t.name||"").trim()||"Student",email:r,lrn:t.lrn?.trim()||null,teacherId:a,grade:o||null,gradeLevel:Ns(o)||null,section:n||null,classSectionId:i||null,classroomId:i||null,riskLevel:"Low",avgQuizScore:0,engagementScore:0,attendance:0,assignmentCompletion:0,weakestTopic:"",struggles:[],avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||"Student")}&background=random`,hasRegisteredAccount:!0,source:"both",createdAt:it(),updatedAt:it()}))}catch(d){console.warn("[studentService] createStudentAccountFromRoster: managed-student merge failed:",d)}if(i&&o&&n)try{await jr({classSectionId:i,grade:o,section:n,schoolYear:t.schoolYear||"",ownerTeacherId:a,ownerTeacherName:t.adviserTeacherName,studentUids:[c]})}catch(d){console.warn("[studentService] createStudentAccountFromRoster: ownership upsert failed:",d)}return{uid:c,email:r,temporaryPassword:t.temporaryPassword}}async function ll(t,s,a){const r=Pt(s,a),o=ct($e,"managedStudents",t);await ns(o,{grade:s,section:a,classSectionId:r,updatedAt:it()})}async function Ku(t,s){const a=ct($e,"classSectionOwnership",s);await ns(a,{studentUids:Jl(t),updatedAt:it()}).catch(r=>console.warn("[studentService] removeStudentFromClass: ownership update failed:",r)),await cn(ct($e,"managedStudents",t)).catch(r=>console.warn("[studentService] removeStudentFromClass: managedStudents delete failed:",r))}function Pt(t,s){return[t,s].filter(Boolean).join("_").replace(/\s+/g,"_").toLowerCase()}function pr(t){const s=Object.entries(t).filter(([,a])=>a!==void 0);return Object.fromEntries(s)}function Ns(t){const s=(t||"").trim();if(!s)return null;const a=s.match(/(\d{1,2})/);return a?`Grade ${a[1]}`:/^grade\s+/i.test(s)?s.replace(/\s+/g," ").trim().replace(/^grade/i,"Grade"):s}function pa(t){const a=Ns(t)?.match(/(\d{1,2})/),r=a?Number.parseInt(a[1],10):Number.NaN;return Number.isFinite(r)?r>=11?"Senior High School":"Junior High School":null}function ha(t,s){const a=`${t||""} ${s||""}`.toUpperCase();if(!a.trim())return null;const r=["STEM","ABM","HUMSS","GAS","TVL","ICT"];for(const o of r)if(new RegExp(`\\b${o}\\b`).test(a))return o;return null}function gs(t){const s=(t||"").trim();if(!s)return{grade:"Grade 11",section:"Section A"};const[a="Grade 11",r="Section A"]=s.split(" - ").map(o=>o.trim());return{grade:a||"Grade 11",section:r||"Section A"}}function yt(t){const s=t.metadata||{},a=t.className||s.className,r=gs(a),o=(t.grade||s.grade||r.grade||"").trim()||null,n=(t.section||s.section||r.section||"").trim()||null,i=(t.classSectionId||s.classSectionId||"").trim()||(o&&n?Pt(o,n):"")||null,l=(a||"").trim()||(o&&n?`${o} - ${n}`:"")||null,c=Ns(t.gradeLevel||s.gradeLevel||o),d=(t.classification||s.classification||"").trim()||pa(c)||null,m=(t.strand||s.strand||"").trim()||ha(l,n)||null;return{classSectionId:i,className:l,grade:o,section:n,gradeLevel:c,classification:d,strand:m,schoolYear:(t.schoolYear||s.schoolYear||"").trim()||null,ownerTeacherId:(t.ownerTeacherId||s.ownerTeacherId||"").trim()||null,ownerTeacherName:(t.ownerTeacherName||s.ownerTeacherName||"").trim()||null,adviserTeacherId:(t.adviserTeacherId||s.adviserTeacherId||"").trim()||null,adviserTeacherName:(t.adviserTeacherName||s.adviserTeacherName||"").trim()||null,managerId:(t.managerId||s.managerId||"").trim()||null,managerName:(t.managerName||s.managerName||"").trim()||null}}function Xu(t){const s=(t.className||"").trim(),[a="",r=""]=s.split(" - "),o=(t.grade||a||"").trim()||null,n=(t.section||r||"").trim()||null,i=(t.classSectionId||"").trim()||(o&&n?Pt(o,n):"")||null,l=s||(o&&n?`${o} - ${n}`:null),c=Ns(t.gradeLevel||o),d=(t.classification||"").trim()||pa(c),m=(t.strand||"").trim()||ha(l,n);return{classSectionId:i,className:l,grade:o,section:n,gradeLevel:c,classification:d,strand:m,schoolYear:(t.schoolYear||"").trim()||null,ownerTeacherId:(t.ownerTeacherId||"").trim()||null,ownerTeacherName:(t.ownerTeacherName||"").trim()||null,adviserTeacherId:(t.adviserTeacherId||"").trim()||null,adviserTeacherName:(t.adviserTeacherName||"").trim()||null,managerId:(t.managerId||"").trim()||null,managerName:(t.managerName||"").trim()||null}}async function cl(t){const s=St($e,"classrooms"),a=new Map,r=kt(s,Nt("teacherId","==",t));(await Lt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=kt(s,Nt("managerId","==",t));return(await Lt(n)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})}),Array.from(a.values()).sort((l,c)=>String(l.name||"").localeCompare(String(c.name||"")))}async function jr(t){const s=t.classSectionId||Pt(t.grade,t.section),a=ct($e,"classSectionOwnership",s),r=await Is(a),o=r.exists()?r.data().studentUids||[]:[],n=Array.from(new Set([...t.studentUids||[],...o])),i=pr(t);return r.exists()?await ns(a,{...i,classSectionId:s,studentUids:n,updatedAt:it()}):await os(a,{...i,classSectionId:s,studentUids:n,createdAt:it(),updatedAt:it()}),s}async function dl(t){const s=(t.classSectionId||"").trim()||Pt(t.grade,t.section),a=(t.className||"").trim()||`${t.grade} - ${t.section}`,r=Xu({classSectionId:s,className:a,grade:t.grade,section:t.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName,adviserTeacherId:t.ownerTeacherId,adviserTeacherName:t.ownerTeacherName,managerId:t.managerId,managerName:t.managerName,classification:t.classification,strand:t.strand,gradeLevel:t.gradeLevel});await jr({classSectionId:s,className:a,grade:r.grade||t.grade,gradeLevel:r.gradeLevel||t.gradeLevel||t.grade,classification:r.classification||t.classification,strand:r.strand||t.strand,section:r.section||t.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName,managerId:t.managerId,managerName:t.managerName,studentUids:[]});const o=St($e,"classrooms"),n=kt(o,Nt("classSectionId","==",s)),i=await Lt(n);if(i.empty){const l=pr({name:a,teacherId:t.ownerTeacherId,grade:r.grade,gradeLevel:r.gradeLevel,classification:r.classification,strand:r.strand,section:r.section,classSectionId:s,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName||"",adviserTeacherId:t.ownerTeacherId,adviserTeacherName:t.ownerTeacherName||"",managerId:t.managerId,managerName:t.managerName||"",classMetadata:r,schedule:"Mon-Fri",studentCount:0,avgScore:0,atRiskCount:0,createdAt:it(),updatedAt:it()});await os(ct($e,"classrooms",s),l,{merge:!0})}else for(const l of i.docs){const c=pr({name:a,grade:r.grade,gradeLevel:r.gradeLevel,classification:r.classification,strand:r.strand,section:r.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId,ownerTeacherName:t.ownerTeacherName||"",adviserTeacherId:t.ownerTeacherId,adviserTeacherName:t.ownerTeacherName||"",managerId:t.managerId,managerName:t.managerName||"",classMetadata:r,updatedAt:it()});await ns(l.ref,c)}return s}async function yr(t,s,a,r,o,n){const i=Pt(s,a);await jr({classSectionId:i,grade:s,section:a,schoolYear:o,ownerTeacherId:r,ownerTeacherName:n,studentUids:[t]});const l=await Is(ct($e,"users",t)),c=l.exists()?l.data():{};await os(ct($e,"users",t),{grade:s,section:a,classSectionId:i,adviserTeacherId:r,adviserTeacherName:n||"",updatedAt:it()},{merge:!0}),await os(ct($e,"managedStudents",t),{accountUid:t,name:c.name||c.displayName||"Student",email:c.email||"",lrn:c.lrn||null,teacherId:r,grade:s,gradeLevel:s,section:a,classSectionId:i,classroomId:i,hasRegisteredAccount:!0,source:"registered",updatedAt:it()},{merge:!0})}async function Ju(t){const s=St($e,"classSectionOwnership"),a=new Map,r=kt(s,Nt("ownerTeacherId","==",t));(await Lt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=kt(s,Nt("managerId","==",t));return(await Lt(n)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})}),Array.from(a.values()).sort((l,c)=>String(l.classSectionId||"").localeCompare(String(c.classSectionId||"")))}async function Zu(t="",s=25){const a=St($e,"users"),r=Math.max(1,Math.min(100,s)),o=kt(a,Nt("role","==","teacher"),or(r*4)),n=await Lt(o),i=t.trim().toLowerCase();return n.docs.map(c=>{const d=c.data(),m=String(d.name||"").trim(),p=String(d.email||"").trim();return{uid:c.id,name:m||"Teacher",email:p,photo:String(d.photo||d.photoURL||"").trim()||void 0}}).filter(c=>i?c.name.toLowerCase().includes(i)||c.email.toLowerCase().includes(i):!0).sort((c,d)=>c.name.localeCompare(d.name)).slice(0,r)}function em(t,s,a=20){if(t.length===0)return s([]),()=>{};const r=St($e,"activities"),o=kt(r,Nt("classroomId","in",t),ec("timestamp","desc"));return gi(o,n=>{const i=n.docs.slice(0,a).map(l=>({id:l.id,...l.data()}));s(i)},n=>{console.error("[studentService] subscribeToActivities error:",n),s([])})}const tm=({open:t,onClose:s,onCreated:a,teacherName:r})=>{const{currentUser:o}=vs(),[n,i]=u.useState("details"),[l,c]=u.useState(""),d="Grade 11",[m,p]=u.useState(""),[h,v]=u.useState(!1),[y,S]=u.useState(""),[N,w]=u.useState([]),[g,I]=u.useState(new Set),[L,A]=u.useState(""),[W,f]=u.useState(!1);u.useEffect(()=>{t||(i("details"),c(""),p(""),S(""),I(new Set),A(""))},[t]),u.useEffect(()=>{t&&n==="students"&&C()},[t,n]);const C=async()=>{f(!0);try{const k=St($e,"users"),D=kt(k,Nt("role","==","student")),J=await Lt(D),re=[];J.docs.forEach(ce=>{const ie=ce.data();re.push({uid:ce.id,name:ie.name||ie.displayName||"Student",email:ie.email||"",grade:ie.grade,section:ie.section})}),w(re.sort((ce,ie)=>ce.name.localeCompare(ie.name)))}catch(k){console.error("[CreateClassModal] Failed to load students:",k)}finally{f(!1)}},b=async()=>{if(o){if(!m.trim()){S("Section name is required");return}S(""),v(!0);try{const k=String(new Date().getFullYear());if(await dl({classSectionId:"",grade:d,section:m.trim(),schoolYear:k,ownerTeacherId:o.uid,ownerTeacherName:r||o.displayName||"",managerId:o.uid,managerName:r||o.displayName||"",className:l.trim()||`${d} - ${m.trim()}`}),g.size>0){const D=Array.from(g).map(J=>yr(J,d,m.trim(),o.uid,k,r||o.displayName||""));await Promise.allSettled(D)}a(),s()}catch(k){S(k instanceof Error?k.message:"Failed to create class")}finally{v(!1)}}},F=k=>{I(D=>{const J=new Set(D);return J.has(k)?J.delete(k):J.add(k),J})},U=N.filter(k=>k.name.toLowerCase().includes(L.toLowerCase())||k.email.toLowerCase().includes(L.toLowerCase()));return t?e.jsx(zt,{children:e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 bg-black/40 backdrop-blur-sm",onClick:s}),e.jsxs(Re.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"relative bg-white rounded-2xl shadow-xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-[#f1f5f9]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[#1e293b]",children:n==="details"?"Create New Class":"Add Students"}),e.jsx("button",{onClick:s,className:"p-1 rounded-lg hover:bg-[#f1f5f9] transition-colors",children:e.jsx(qt,{size:20,className:"text-[#64748b]"})})]}),e.jsxs("div",{className:"p-6 overflow-y-auto flex-1",children:[n==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-[#475569] block mb-1.5",children:"Class Name"}),e.jsx(_s,{placeholder:"e.g. Grade 11 - Section A",value:l,onChange:k=>c(k.target.value)}),e.jsx("p",{className:"text-xs text-[#94a3b8] mt-1",children:"Optional. Auto-generated from grade + section if empty."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-[#475569] block mb-1.5",children:"Section"}),e.jsx(_s,{placeholder:"e.g. Section A, STEM-1, Rizal",value:m,onChange:k=>p(k.target.value)})]}),y&&e.jsx("p",{className:"text-sm text-rose-500",children:y})]}),n==="students"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Xs,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(_s,{placeholder:"Search students...",value:L,onChange:k=>A(k.target.value),className:"pl-9"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[g.size," student(s) selected"]}),W?e.jsx("p",{className:"text-sm text-[#64748b] text-center py-4",children:"Loading students..."}):U.length===0?e.jsx("p",{className:"text-sm text-[#64748b] text-center py-4",children:"No students found."}):e.jsx("div",{className:"space-y-1 max-h-[300px] overflow-y-auto",children:U.map(k=>e.jsxs("button",{onClick:()=>F(k.uid),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${g.has(k.uid)?"bg-purple-50 border border-purple-200":"hover:bg-[#f8fafc] border border-transparent"}`,children:[e.jsx("div",{className:`w-5 h-5 rounded-md border-2 flex items-center justify-center ${g.has(k.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:g.has(k.uid)&&e.jsx(Gt,{size:12,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[#1e293b] truncate",children:k.name}),e.jsx("p",{className:"text-xs text-[#64748b] truncate",children:k.email})]}),k.grade&&e.jsx("span",{className:"text-xs text-[#94a3b8]",children:k.grade})]},k.uid))}),y&&e.jsx("p",{className:"text-sm text-rose-500",children:y})]})]}),e.jsx("div",{className:"flex items-center justify-between p-6 border-t border-[#f1f5f9]",children:n==="details"?e.jsxs(e.Fragment,{children:[e.jsx(wt,{variant:"outline",onClick:s,children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(wt,{variant:"outline",onClick:()=>{if(!m.trim()){S("Section is required");return}S(""),i("students")},children:"Add Students"}),e.jsx(wt,{onClick:b,disabled:h||!m.trim(),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:h?"Creating...":"Create Class"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{variant:"outline",onClick:()=>i("details"),children:"Back"}),e.jsxs(wt,{onClick:b,disabled:h,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(ua,{size:16,className:"mr-1"}),h?"Creating...":`Create with ${g.size} Student${g.size!==1?"s":""}`]})]})})]})]})}):null},sm=({open:t,onClose:s,onAdded:a,grade:r,section:o,teacherName:n,existingStudentUids:i=[]})=>{const{currentUser:l}=vs(),[c,d]=u.useState([]),[m,p]=u.useState(new Set),[h,v]=u.useState(""),[y,S]=u.useState(!1),[N,w]=u.useState(!1);u.useEffect(()=>{t&&(p(new Set),v(""),g())},[t]);const g=async()=>{S(!0);try{const A=kt(St($e,"users"),Nt("role","==","student")),f=(await Lt(A)).docs.filter(C=>!i.includes(C.id)).map(C=>{const b=C.data();return{uid:C.id,name:b.name||b.displayName||"Student",email:b.email||""}}).sort((C,b)=>C.name.localeCompare(b.name));d(f)}catch{}S(!1)},I=async()=>{if(!(!l||m.size===0)){w(!0);try{const A=String(new Date().getFullYear()),W=Array.from(m).map(f=>yr(f,r,o,l.uid,A,n||l.displayName||""));await Promise.allSettled(W),le.success(`Added ${m.size} student(s) to class`),a(),s()}catch{le.error("Failed to add students")}w(!1)}},L=c.filter(A=>A.name.toLowerCase().includes(h.toLowerCase())||A.email.toLowerCase().includes(h.toLowerCase()));return t?e.jsx(zt,{children:e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 bg-black/40 backdrop-blur-sm",onClick:s}),e.jsxs(Re.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"relative bg-white rounded-2xl shadow-xl w-full max-w-2xl mx-4 max-h-[80vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-5 border-b border-[#f1f5f9]",children:[e.jsxs("h2",{className:"text-base font-semibold text-[#1e293b]",children:["Add Students to ",r," - ",o]}),e.jsx("button",{onClick:s,className:"p-1 rounded-lg hover:bg-[#f1f5f9]",children:e.jsx(qt,{size:18,className:"text-[#64748b]"})})]}),e.jsxs("div",{className:"p-4 space-y-3 flex-1 overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Xs,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(_s,{placeholder:"Search students...",value:h,onChange:A=>v(A.target.value),className:"pl-8 h-9 text-sm"})]}),e.jsx("button",{onClick:()=>{m.size===L.length?p(new Set):p(new Set(L.map(A=>A.uid)))},className:"text-[11px] font-semibold text-[#9956DE] hover:text-[#7c3aed] bg-[#9956DE]/10 hover:bg-[#9956DE]/20 px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",children:m.size===L.length&&L.length>0?"Deselect All":"Select All"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[m.size," of ",L.length," selected"]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-1 min-h-[300px]",children:y?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"Loading..."}):L.length===0?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"No students available"}):L.map(A=>e.jsxs("button",{onClick:()=>p(W=>{const f=new Set(W);return f.has(A.uid)?f.delete(A.uid):f.add(A.uid),f}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${m.has(A.uid)?"bg-purple-50 border border-purple-200":"hover:bg-[#f8fafc] border border-transparent"}`,children:[e.jsx("div",{className:`w-5 h-5 rounded-md border-2 flex items-center justify-center shrink-0 ${m.has(A.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:m.has(A.uid)&&e.jsx(Gt,{size:12,className:"text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[#1e293b] truncate",children:A.name}),e.jsx("p",{className:"text-[11px] text-[#64748b] truncate",children:A.email})]})]},A.uid))})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-[#f1f5f9]",children:[e.jsx(wt,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),e.jsxs(wt,{size:"sm",onClick:I,disabled:N||m.size===0,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(ui,{size:14,className:"mr-1.5"}),N?"Adding...":`Add ${m.size} Student${m.size!==1?"s":""}`]})]})]})]})}):null},ul="https://deign86-mathpulse-api-v3test.hf.space";async function ml(){const t={"Content-Type":"application/json"},s=mi.currentUser;if(s)try{const a=await s.getIdToken(!1);a&&(t.Authorization=`Bearer ${a}`)}catch{}return t}async function zo(t,s=!1){const a=await ml(),r=`${ul}/api/analytics/class/${encodeURIComponent(t)}${s?"?refresh=true":""}`,o=await fetch(r,{headers:a});if(!o.ok)throw new Error(`GET class analytics failed: ${o.status}`);return o.json()}async function am(t){const s=await ml(),a=await fetch(`${ul}/api/analytics/class/${encodeURIComponent(t)}/refresh-insights`,{method:"POST",headers:s});if(!a.ok)throw a.status===429?new Error("Insights can only be refreshed once every 5 minutes."):new Error(`POST refresh insights failed: ${a.status}`);return a.json()}const Sr="https://deign86-mathpulse-api-v3test.hf.space";async function kr(){const t={"Content-Type":"application/json"},s=mi.currentUser;if(s)try{const a=await s.getIdToken(!1);a&&(t.Authorization=`Bearer ${a}`)}catch{}return t}async function rn(t){const s=await kr(),a=await fetch(`${Sr}/api/intervention/${encodeURIComponent(t)}`,{headers:s});if(!a.ok)throw new Error(`GET intervention failed: ${a.status}`);return a.json()}async function xl(t){const s=await kr(),a=await fetch(`${Sr}/api/intervention/generate`,{method:"POST",headers:s,body:JSON.stringify({student_id:t})});if(!a.ok)throw new Error(`POST intervention/generate failed: ${a.status}`);return a.json()}async function rm(t,s,a,r){const o=await kr(),n=await fetch(`${Sr}/api/intervention/${encodeURIComponent(t)}/step/${s}/complete`,{method:"POST",headers:o,body:JSON.stringify({score:a,time_spent_minutes:r})});if(!n.ok)throw new Error(`POST step complete failed: ${n.status}`);return n.json()}async function nm(t){const s=await kr(),a=await fetch(`${Sr}/api/intervention/${encodeURIComponent(t)}/export-pdf`,{headers:s});if(!a.ok)throw new Error(`GET export-pdf failed: ${a.status}`);return a.json()}async function pl(t,s){const r=(t.learning_path?.steps||[]).map(n=>({title:`Step ${n.step_number}: ${n.title}`,content:`${n.description||n.topic} (${n.type.replace("_"," ")} · ${n.duration_minutes} mins${n.num_items?` · ${n.num_items} items`:""})`,stepType:n.type,stepNumber:n.step_number,topic:n.topic,durationMinutes:n.duration_minutes,numItems:n.num_items||null,difficulty:n.difficulty,competencyTag:n.competency_tag||"",youtubeQuery:n.youtube_query||"",isCompleted:n.is_completed||!1}));return(await bi(St($e,"modules"),{title:`Intervention: ${t.weakest_topic} — ${t.student_name}`,gradeLevel:t.grade_level||"Grade 11",subject:"General Mathematics",quarter:"Q1",strandOrTrack:null,competencyTags:t.weak_topics.slice(0,3),moduleType:"teacher_uploaded",sourceLabel:"Teacher Upload",summary:t.next_steps_summary||`Personalized intervention for ${t.weakest_topic}`,learningObjectives:[t.learning_strengths,t.next_steps_summary].filter(Boolean),sections:r,practice:[],teacherId:s,assignedTo:t.student_id,createdAt:it()})).id}async function hl(t,s,a){return(await bi(St($e,"modules"),{title:t.title,gradeLevel:"Grade 11",subject:"General Mathematics",quarter:"Q1",strandOrTrack:null,competencyTags:[t.competency_tag].filter(Boolean),moduleType:"teacher_uploaded",sourceLabel:"Teacher Upload",summary:t.description||`${t.topic} (${t.difficulty})`,learningObjectives:[t.description].filter(Boolean),sections:[{title:t.title,content:t.description||t.topic}],practice:[],teacherId:a,assignedTo:s,createdAt:it()})).id}async function Sn(t){const s=kt(St($e,"modules"),Nt("assignedTo","==",t),Nt("moduleType","==","teacher_uploaded"));return(await Lt(s)).docs.map(r=>r.id)}async function fl(t){const s=await Sn(t);return await Promise.all(s.map(a=>cn(ct($e,"modules",a)))),s.length}const om=Object.freeze(Object.defineProperty({__proto__:null,assignLearningPathAsModule:pl,assignStepAsModule:hl,completeStep:rm,generateInterventionPlan:xl,getAssignedModuleIds:Sn,getExportPDFData:nm,getInterventionPlan:rn,revokeAssignedModules:fl},Symbol.toStringTag,{value:"Module"}));function im(t,s=!0){const[a,r]=u.useState([]),[o,n]=u.useState(!1),[i,l]=u.useState(null);return u.useEffect(()=>{if(!t||!s){r([]);return}let c=!1;return n(!0),l(null),ic(t).then(d=>{c||r(d)}).catch(d=>{c||l(d.message)}).finally(()=>{c||n(!1)}),()=>{c=!0}},[t,s]),{videos:a,isLoading:o,error:i}}const lm=({step:t,isActive:s})=>{const{videos:a,isLoading:r,error:o}=im(t.youtube_query||`${t.topic} math tutorial Philippines`,s);return s?e.jsxs("div",{className:"mt-4",children:[o&&e.jsxs("p",{className:"text-xs text-red-400 mb-2",children:["Could not load videos: ",o]}),e.jsx(lc,{videos:r?[]:a,topic:t.title})]}):null},gl={"gen-math":{id:"gen-math",name:"General Mathematics",shortLabel:"Gen Math",color:"#3B82F6"},"stats-prob":{id:"stats-prob",name:"Statistics and Probability",shortLabel:"Stats & Prob",color:"#0ea5e9"},"business-math":{id:"business-math",name:"Business Mathematics",shortLabel:"Business Math",color:"#166534"},"pre-calc":{id:"pre-calc",name:"Pre-Calculus",shortLabel:"Pre-Calculus",color:"#F97316"},"basic-calc":{id:"basic-calc",name:"Basic Calculus",shortLabel:"Basic Calculus",color:"#EF4444"}},cm={gm:"gen-math",gen_math:"gen-math","gen math":"gen-math",genmath:"gen-math","general mathematics":"gen-math",sp:"stats-prob",stat:"stats-prob","stat&prob":"stats-prob",statistics:"stats-prob","statistics and probability":"stats-prob",bm:"business-math","business math":"business-math","business mathematics":"business-math",pc:"pre-calc","pre-calculus":"pre-calc",pre_calc:"pre-calc",precalc:"pre-calc",bc:"basic-calc",basic_calc:"basic-calc","basic calculus":"basic-calc",basiccalc:"basic-calc"};function dm(t){const s=t.toLowerCase().trim();return gl[s]?s:cm[s]||null}function um(t){const s=dm(t);return s?gl[s].name:t}function ks(t){if(!t)return t;const s=t.match(/^(Gm|Gen\s*Math|Stat|Stats?(?:\s*&\s*Prob)?|Pre[- ]?Cal(?:c)?|Basic[- ]?Cal(?:c)?|Bm|Business\s*Math)\s*(Q\d)?\s*[-–]?\s*(.*)$/i);if(!s)return t;const[,a,r,o]=s,i=[um(a)];return r&&i.push(r.toUpperCase()),o?.trim()&&i.push(o.trim()),i.join(" – ")}const mm={video_lesson:e.jsx(Za,{className:"w-5 h-5"}),practice:e.jsx(ir,{className:"w-5 h-5"}),assessment:e.jsx(La,{className:"w-5 h-5"}),chat_session:e.jsx(wi,{className:"w-5 h-5"}),review:e.jsx(xs,{className:"w-5 h-5"})},Lo={easy:"bg-emerald-100 text-emerald-700",medium:"bg-amber-100 text-amber-700",hard:"bg-rose-100 text-rose-700"},xm=({step:t,studentId:s,studentName:a,teacherId:r,totalSteps:o,onClose:n,onStepCompleted:i})=>{const[l,c]=u.useState(!1),[d,m]=u.useState([{role:"assistant",content:`Hi ${a}! Let's work on "${ks(t.title)}". ${t.description||`This covers ${ks(t.topic)}.`} Ready to start?`}]),[p,h]=u.useState(""),v=async()=>{c(!0);try{await hl(t,s,r),i(t.step_number),le.success(`Step ${t.step_number} assigned to student!`),n()}catch{le.error("Failed to assign step.")}finally{c(!1)}},y=()=>{if(!p.trim())return;const S=p.trim();m(N=>[...N,{role:"user",content:S}]),h(""),setTimeout(()=>{m(N=>[...N,{role:"assistant",content:`Great question about ${t.topic}! Let me help you understand this step by step. What part are you finding most challenging?`}])},1e3)};return e.jsx(zt,{children:e.jsxs(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] flex items-center justify-center p-4",onClick:n,children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(Re.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.95,opacity:0},className:"relative bg-white rounded-[24px] shadow-[0_24px_64px_rgba(0,0,0,0.18)] w-full max-w-[800px] max-h-[85vh] flex flex-col overflow-hidden z-10",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-slate-100 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-[12px] bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white",children:mm[t.type]||e.jsx(ir,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-bold text-[#1e293b]",children:ks(t.title)}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-[11px] text-[#64748b]",children:["Step ",t.step_number," of ",o]}),t.competency_tag&&e.jsx("span",{className:"px-1.5 py-0.5 bg-indigo-50 text-indigo-600 text-[9px] font-mono rounded",children:t.competency_tag}),e.jsx("span",{className:`px-2 py-0.5 text-[10px] font-semibold rounded-full ${Lo[t.difficulty]||Lo.easy}`,children:t.difficulty})]})]})]}),e.jsx("button",{onClick:n,className:"w-8 h-8 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center transition-colors",children:e.jsx(qt,{className:"w-4 h-4 text-slate-500"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-slate-50 rounded-[14px] p-4 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ls,{className:"w-4 h-4 text-slate-500"}),e.jsxs("span",{className:"text-[12px] font-semibold text-slate-600",children:[t.duration_minutes," minutes"]}),t.num_items&&e.jsxs("span",{className:"text-[12px] text-slate-500",children:["• ",t.num_items," items"]})]}),e.jsx("p",{className:"text-[13px] text-[#475569] leading-relaxed",children:t.description||`Work through ${t.topic} at ${t.difficulty} difficulty.`})]}),t.type==="video_lesson"&&e.jsx(lm,{step:t,isActive:!0}),(t.type==="practice"||t.type==="assessment")&&e.jsxs("div",{className:"bg-purple-50/50 rounded-[14px] p-6 border border-purple-100 flex flex-col items-center justify-center min-h-[160px]",children:[e.jsx(ir,{className:"w-10 h-10 text-purple-400 mb-3"}),e.jsxs("p",{className:"text-[13px] font-semibold text-purple-700",children:[t.type==="assessment"?"Assessment":"Practice"," Questions"]}),e.jsxs("p",{className:"text-[11px] text-purple-500 mt-1",children:[t.num_items||10," questions on ",t.topic]})]})]}),e.jsxs("div",{className:"flex flex-col bg-slate-50 rounded-[14px] border border-slate-100 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-slate-100 bg-white",children:e.jsxs("p",{className:"text-[12px] font-semibold text-[#1e293b] flex items-center gap-1.5",children:[e.jsx(wi,{className:"w-3.5 h-3.5 text-indigo-500"})," AI Guide",e.jsx("span",{className:"text-[9px] font-medium text-slate-400 ml-1",children:"(Preview)"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3 min-h-[200px] max-h-[300px]",children:d.map((S,N)=>e.jsx("div",{className:`flex ${S.role==="user"?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[85%] px-3 py-2 rounded-[12px] text-[12px] leading-relaxed ${S.role==="user"?"bg-indigo-500 text-white":"bg-white border border-slate-200 text-[#475569]"}`,children:S.content})},N))}),e.jsxs("div",{className:"p-3 border-t border-slate-100 bg-white flex gap-2",children:[e.jsx("input",{type:"text",value:p,onChange:S=>h(S.target.value),onKeyDown:S=>S.key==="Enter"&&y(),placeholder:"Ask for help...",className:"flex-1 text-[12px] px-3 py-2 rounded-[10px] border border-slate-200 focus:outline-none focus:border-indigo-300"}),e.jsx("button",{onClick:y,className:"w-8 h-8 rounded-full bg-indigo-500 hover:bg-indigo-600 flex items-center justify-center text-white transition-colors",children:e.jsx(ra,{className:"w-3.5 h-3.5"})})]})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-slate-100 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-full bg-slate-200 h-2 rounded-full overflow-hidden",style:{width:120},children:e.jsx("div",{className:"h-full bg-indigo-500 rounded-full",style:{width:`${t.step_number/o*100}%`}})}),e.jsxs("span",{className:"text-[11px] text-slate-500",children:[t.step_number,"/",o]})]}),e.jsxs("button",{onClick:v,disabled:l||t.is_completed,className:"flex items-center gap-2 px-5 py-2.5 bg-indigo-500 hover:bg-indigo-600 text-white text-[13px] font-semibold rounded-full transition-colors disabled:opacity-50 shadow-sm",children:[e.jsx(La,{className:"w-4 h-4"}),t.is_completed?"Assigned ✓":l?"Assigning...":"Assign"]})]})]})]})})};async function pm(t,s,a){const r=ct(St($e,"generatedLessonPlans"));return await os(r,{...t,teacherId:s,teacherName:a?.teacherName||null,studentId:a?.studentId||null,studentName:a?.studentName||null,status:"draft",createdAt:it(),updatedAt:it()}),r.id}async function hm(t){const s=ct($e,"generatedLessonPlans",t),a=await Is(s);if(!a.exists())throw new Error("Lesson draft not found. Save draft before publishing.");if(!a.data().publishReady)throw new Error("Lesson is not publish-ready. Resolve source legitimacy and validation issues first.");await ns(s,{status:"published",publishedAt:it(),updatedAt:it()})}async function Do(t,s=!0){const a=t.learningCompetency||t.lessonTitle||t.focusTopics&&t.focusTopics[0]||"general mathematics",r=t.subject||"general_math",o=t.quarter??1;let n="",i=[],l,c,d,m=!1;if(s)try{const v=await Ol(a,r,o,{lessonTitle:t.lessonTitle,learningCompetency:t.learningCompetency,moduleUnit:t.moduleUnit,learnerLevel:t.learnerLevel});i=v.sources||[],n=v.explanation||"",l=v.retrievalConfidence,c=v.retrievalBand,d=v.retrievalQuery,m=v.needsReview??!1}catch{n="",i=[]}const p={...t,subject:r,quarter:o,curriculumContext:n?`[CURRICULUM CONTEXT] ${n}`:void 0,curriculumRetrievalConfidence:l,curriculumRetrievalBand:c,curriculumRetrievalQuery:d,needsReview:m};return{...await xt.generateLessonPlan(p),curriculumSources:i,curriculumContext:n}}const fm=Kl("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function gm({className:t,variant:s,asChild:a=!1,...r}){const o=a?pc:"span";return e.jsx(o,{"data-slot":"badge",className:xi(fm({variant:s}),t),...r})}function bm(t){return t.length<=42?t:`${t.slice(0,18)}...${t.slice(-20)}`}const $o=({sources:t=[],className:s})=>t.length?e.jsxs(hc,{children:[e.jsx(fc,{asChild:!0,children:e.jsxs(gm,{className:["bg-[#75D06A]/15 text-[#2E7D32] border-[#75D06A]/40 font-body font-semibold text-[11px] px-2.5 py-1 rounded-full cursor-help",s||""].join(" "),variant:"outline",children:[e.jsx(Vt,{size:12}),"DepEd Aligned"]})}),e.jsxs(gc,{side:"top",sideOffset:6,className:"max-w-sm bg-white border border-[#dde3eb] text-[#0a1628] shadow-lg p-3",children:[e.jsx("p",{className:"text-[11px] font-display font-bold uppercase tracking-wide text-[#5a6578] mb-2",children:"Curriculum Sources"}),e.jsx("div",{className:"space-y-2",children:t.slice(0,5).map((a,r)=>e.jsxs("div",{className:"text-xs leading-relaxed",children:[e.jsxs("p",{className:"font-semibold text-[#0a1628]",children:[a.subject," | Q",a.quarter]}),e.jsxs("p",{className:"text-[#5a6578]",children:[bm(a.sourceFile)," | p.",a.page]}),e.jsxs("p",{className:"text-[#5a6578]",children:["Similarity: ",(a.score*100).toFixed(1),"%"]})]},`${a.sourceFile}-${a.page}-${r}`))})]})]}):null,vm=[{level:"Remember",icon:Ur,bgColor:"bg-sky-500/20",borderColor:"border-sky-500/40",textColor:"text-sky-400",description:"Recall facts, formulas, definitions, and basic procedures.",mathExample:"State the quadratic formula.",mapsTo:"Identification, Enumeration",defaultWeight:"Included by default"},{level:"Understand",icon:Vt,bgColor:"bg-sky-500/20",borderColor:"border-sky-500/40",textColor:"text-sky-400",description:"Explain concepts, interpret graphs, classify mathematical objects.",mathExample:"Explain why the discriminant determines the number of roots.",mapsTo:"Multiple Choice, Identification",defaultWeight:"Included by default"},{level:"Apply",icon:Pl,bgColor:"bg-green-500/20",borderColor:"border-green-500/40",textColor:"text-green-400",description:"Use formulas and procedures to solve routine problems.",mathExample:"Solve: 2x² + 5x - 3 = 0 using the quadratic formula.",mapsTo:"Equation-Based, Word Problem",defaultWeight:"Included by default"},{level:"Analyze",icon:Vc,bgColor:"bg-orange-500/20",borderColor:"border-orange-500/40",textColor:"text-orange-400",description:"Break down problems, compare solution methods, identify patterns.",mathExample:"Given f(x) = x³ - 3x, find and classify all critical points.",mapsTo:"Word Problem, Equation-Based",defaultWeight:"Included by default"}],wm=({isOpen:t,onClose:s})=>t?e.jsx(zt,{children:t&&e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-[70] flex items-center justify-center p-4",onClick:s,children:e.jsxs(Re.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.95,opacity:0},className:"bg-white border border-slate-200 rounded-2xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col overflow-hidden",onClick:a=>a.stopPropagation(),children:[e.jsxs("div",{className:"bg-gradient-to-r from-sky-600 to-sky-500 px-6 py-4 flex items-center justify-between flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center",children:e.jsx(pi,{size:22,className:"text-white"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Bloom's Taxonomy in MathPulse AI"}),e.jsx("p",{className:"text-cyan-200 text-xs",children:"Understanding cognitive levels in assessments"})]})]}),e.jsx("button",{onClick:s,className:"w-8 h-8 bg-white/20 hover:bg-white/30 rounded-lg flex items-center justify-center transition-colors",children:e.jsx(qt,{size:16,className:"text-white"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-rose-400 uppercase tracking-wide mb-2",children:"What is Bloom's Taxonomy?"}),e.jsx("p",{className:"text-sm text-slate-500 leading-relaxed",children:"Bloom's Taxonomy is an educational framework developed by Benjamin Bloom in 1956 and revised in 2001. It classifies learning objectives into six cognitive levels, from basic recall of facts up to complex evaluation and creation. MathPulse AI uses the first four levels most relevant to Senior High School mathematics."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-rose-400 uppercase tracking-wide mb-2",children:"Why MathPulse AI Uses It"}),e.jsx("p",{className:"text-sm text-slate-500 leading-relaxed",children:"Using Bloom's Taxonomy ensures that assessments do not only test memorization. A well-balanced math quiz should challenge students at multiple cognitive levels: remembering formulas, understanding concepts, applying procedures, and analyzing relationships. This mirrors the DepEd K-12 competency framework which requires higher-order thinking skills (HOTS) alongside foundational knowledge."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-rose-400 uppercase tracking-wide mb-3",children:"Level-by-Level Breakdown"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:vm.map(a=>{const r=a.icon;return e.jsxs("div",{className:`${a.bgColor} border ${a.borderColor} rounded-xl p-4 space-y-2`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r,{size:18,className:a.textColor}),e.jsx("span",{className:`font-bold text-sm ${a.textColor}`,children:a.level})]}),e.jsx("p",{className:"text-xs text-slate-500",children:a.description}),e.jsxs("div",{className:"bg-black/20 rounded-lg p-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide mb-0.5",children:"Math Example"}),e.jsx("p",{className:"text-xs text-[#dde3eb] italic",children:a.mathExample})]}),e.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[e.jsxs("span",{className:"text-slate-500",children:["Maps to: ",e.jsx("span",{className:"text-slate-500 font-medium",children:a.mapsTo})]}),e.jsx("span",{className:"text-green-400 font-medium",children:a.defaultWeight})]})]},a.level)})})]}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-xl p-4",children:e.jsxs("p",{className:"text-xs text-slate-500 leading-relaxed",children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Note:"})," ","All four levels are selected by default to produce a balanced, HOTS-aligned assessment. Deselecting a level will remove questions of that cognitive depth from the generated quiz."]})})]}),e.jsxs("div",{className:"border-t border-slate-200 px-6 py-3 flex items-center justify-between flex-shrink-0 bg-slate-50",children:[e.jsxs("a",{href:"https://cft.vanderbilt.edu/guides-sub-pages/blooms-taxonomy/",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-xs text-rose-400 hover:text-rose-300 font-medium transition-colors",children:[e.jsx(cc,{size:12}),"Learn More"]}),e.jsx("button",{onClick:s,className:"px-5 py-2 bg-sky-600 hover:bg-rose-500 text-white text-sm font-bold rounded-xl transition-colors",children:"Got it"})]})]})})}):null,Nm={draft:"bg-[#edf1f7] text-[#5a6578]",published:"bg-green-100 text-green-700",assigned:"bg-sky-100 text-sky-700",completed:"bg-rose-100 text-rose-700"},Wa={identification:{label:"Identification",icon:e.jsx(As,{size:16}),description:"Define or identify concepts"},enumeration:{label:"Enumeration",icon:e.jsx(lr,{size:16}),description:"List steps or properties"},multiple_choice:{label:"Multiple Choice",icon:e.jsx(Gt,{size:16}),description:"Choose from 4 options"},word_problem:{label:"Word Problem",icon:e.jsx(Vt,{size:16}),description:"Real-world scenarios"},equation_based:{label:"Equation-Based",icon:e.jsx(Bl,{size:16}),description:"Solve equations"}},Fo={remember:{label:"Remember",color:"bg-sky-100 text-sky-700 border-sky-300",description:"Recall facts & formulas"},understand:{label:"Understand",color:"bg-emerald-100 text-emerald-700 border-emerald-300",description:"Explain concepts"},apply:{label:"Apply",color:"bg-rose-100 text-rose-700 border-rose-300",description:"Use in new contexts"},analyze:{label:"Analyze",color:"bg-rose-100 text-rose-700 border-rose-300",description:"Examine & compare"}},jm=["Grade 11","Grade 12"],Dr=t=>{const s=(t||"").trim().toLowerCase();return s==="grade 12"||s==="12"||s.includes("12")?"Grade 12":"Grade 11"},ym={"Grade 11":{"General Mathematics - Patterns, Relations, and Functions":["Patterns and Real-Life Relationships","Functions as Mathematical Models","Function Notation and Evaluation","Domain and Range of Functions","Operations on Functions","Composite Functions","Inverse Functions","Graphs of Rational Functions","Graphs of Exponential Functions","Graphs of Logarithmic Functions"],"General Mathematics - Financial Mathematics":["Simple and Compound Interest","Simple and General Annuities","Present and Future Value","Loans, Amortization, and Sinking Funds","Stocks, Bonds, and Market Indices","Business Decision-Making with Mathematical Models"],"General Mathematics - Logic and Mathematical Reasoning":["Propositions and Logical Connectives","Truth Values and Truth Tables","Logical Equivalence and Implication","Quantifiers and Negation","Validity of Arguments"]},"Grade 12":{"Pre-Calculus - Analytic Geometry":["Conic Sections - Parabola","Conic Sections - Ellipse","Conic Sections - Hyperbola","Conic Sections - Circle","Systems of Nonlinear Equations"],"Pre-Calculus - Series and Induction":["Sequences and Series","Arithmetic Sequences","Geometric Sequences","Mathematical Induction","Binomial Theorem"],"Pre-Calculus - Trigonometry":["Angles and Unit Circle","Trigonometric Functions","Trigonometric Identities","Sum and Difference Formulas","Inverse Trigonometric Functions","Polar Coordinates"],"Basic Calculus - Limits":["Limits of Functions","Limit Theorems","One-Sided Limits","Infinite Limits and Limits at Infinity","Continuity of Functions"],"Basic Calculus - Derivatives":["Definition of the Derivative","Differentiation Rules","Chain Rule","Implicit Differentiation","Higher-Order Derivatives","Related Rates","Extrema and the First Derivative Test","Concavity and the Second Derivative Test","Optimization Problems"],"Basic Calculus - Integration":["Antiderivatives and Indefinite Integrals","Definite Integrals and the FTC","Integration by Substitution","Area Under a Curve"]}},Sm={"Grade 11":["General Mathematics - "],"Grade 12":["Pre-Calculus - ","Basic Calculus - "]},Oo=(t,s)=>{const a=Sm[s];return Object.fromEntries(Object.entries(t).filter(([r])=>a.some(o=>r.startsWith(o))))},wa=30,Na=12,$r="mathpulse:quiz-maker:active-task",km={easy:"text-green-600",medium:"text-rose-600",hard:"text-red-600"},bl=({onBack:t,gradeLevel:s,selectedClassId:a,selectedClassName:r,onOpenNotifications:o,onOpenProfile:n,onOpenInsightModal:i,userPhoto:l,teacherName:c,drawerMode:d=!1,onQuizSaved:m,onQuizGenerating:p})=>{const{currentUser:h,loading:v}=vs(),y=u.useMemo(()=>xt.getImportGroundedRolloutFlags(),[]),[S,N]=u.useState("create"),[w,g]=u.useState("setup"),[I,L]=u.useState(Dr(s)),[A,W]=u.useState(10),[f,C]=u.useState([]),[b,F]=u.useState([]),[U,k]=u.useState(["multiple_choice","word_problem","identification"]),[D,J]=u.useState(["remember","understand","apply","analyze"]),[re,ce]=u.useState(!1),[ie,fe]=u.useState({easy:30,medium:50,hard:20}),[Ce,ue]=u.useState({}),[ge,B]=u.useState(!1),[te,ne]=u.useState([]),[ze,Fe]=u.useState(!1),[Pe,G]=u.useState(""),[se,M]=u.useState(!1),[q,Q]=u.useState(!1),[pe,$]=u.useState(null),[j,T]=u.useState(0),[_,V]=u.useState("queued"),[me,oe]=u.useState("Waiting to start generation..."),[ae,je]=u.useState(null),[we,Ke]=u.useState(null),[Ue,Je]=u.useState(""),[ht,dt]=u.useState(!1),rt=u.useRef(!1),[Mt,At]=u.useState("topics"),[It,cs]=u.useState(null),[Us,Yt]=u.useState(!1),[ds,js]=u.useState("all"),[Kt,Gs]=u.useState("all"),[Es,Rs]=u.useState(!1),[Ge,z]=u.useState(null),[de,E]=u.useState(!1),[R,ve]=u.useState(!1),[ee,Me]=u.useState(!1),[K,Xe]=u.useState([]),[nt,ke]=u.useState(!1),[jt,Bt]=u.useState(""),[$t,Le]=u.useState(null),[ft,ut]=u.useState([]),[Ft,ss]=u.useState(!1),[Qs,Pa]=u.useState("all"),[Ba,Ha]=u.useState(null),[Ua,Vs]=u.useState(null),fa=u.useCallback(async()=>{B(!0);const x=Dr(I);try{const O=await xt.getQuizTopics(x);O.topics&&ue(Oo(O.topics,x))}catch{ue(Oo(ym[x],x))}finally{B(!1)}},[I]),P=u.useCallback(async()=>{if(!y.quizEnabled){ne([]),G("Import-grounded quiz generation is disabled by rollout flag; using curriculum defaults."),Fe(!1);return}Fe(!0),G("");try{const x=await xt.getCourseMaterialTopics({classSectionId:a,limit:20}),O=(x.topics||[]).filter(H=>H.title?.trim());ne(O),x.warnings&&x.warnings.length>0&&G(x.warnings.join(" "))}catch{ne([]),G("Imported topics are currently unavailable; quiz generation will use curriculum defaults.")}finally{Fe(!1)}},[a,y.quizEnabled]);u.useEffect(()=>{fa(),C([]),F([])},[fa]),u.useEffect(()=>{P()},[P]);const X=u.useMemo(()=>{const x=Array.from(new Set(te.map(O=>O.title.trim()).filter(Boolean)));return x.length===0?Ce:{"Imported Course Materials":x,...Ce}},[Ce,te]);u.useEffect(()=>{js("all"),Gs("all")},[ae]);const _e=u.useMemo(()=>{if(!ae)return[];const x=ae.questions.map(H=>H.provenance?.sourceFile?.trim()).filter(H=>!!H),O=(ae.metadata.topicProvenance||[]).map(H=>H.sourceFile?.trim()).filter(H=>!!H);return Array.from(new Set([...x,...O])).sort((H,Ne)=>H.localeCompare(Ne))},[ae]),Oe=u.useMemo(()=>{if(!ae)return[];const x=ae.questions.map(H=>H.provenance?.materialId?.trim()).filter(H=>!!H),O=(ae.metadata.topicProvenance||[]).map(H=>H.materialId?.trim()).filter(H=>!!H);return Array.from(new Set([...x,...O])).sort((H,Ne)=>H.localeCompare(Ne))},[ae]),Ht=u.useMemo(()=>ae?ae.questions.filter(x=>{const O=ds==="all"||(x.provenance?.sourceFile||"").trim()===ds,H=Kt==="all"||(x.provenance?.materialId||"").trim()===Kt;return O&&H}):[],[ae,ds,Kt]),De=(x,O)=>{const H={...ie},Ne=Math.max(0,Math.min(100,H[x]+O)),Qe=Ne-H[x];H[x]=Ne;const Ze=Object.keys(H).filter(mt=>mt!==x),Xt=Ze.reduce((mt,as)=>mt+H[as],0);if(Xt>0)for(const mt of Ze)H[mt]=Math.max(0,Math.round(H[mt]-Qe*H[mt]/Xt));const ea=Object.values(H).reduce((mt,as)=>mt+as,0);if(ea!==100){const mt=Ze.reduce((as,Dn)=>H[as]>=H[Dn]?as:Dn);H[mt]+=100-ea}fe(H)},Ga=x=>{C(O=>O.includes(x)?O.filter(H=>H!==x):[...O,x]),F(O=>O.filter(H=>H!==x))},Ut=x=>{k(O=>O.includes(x)?O.length>1?O.filter(H=>H!==x):O:[...O,x])},We=x=>{J(O=>O.includes(x)?O.length>1?O.filter(H=>H!==x):O:[...O,x])},ga=()=>{let x=f.length>0?f.filter(H=>!b.includes(H)):Object.values(X).flat().filter(H=>!b.includes(H)).slice(0,3);x.length>Na&&(x=x.slice(0,Na));const O=Math.min(A,wa);return{topics:x,gradeLevel:I,numQuestions:O,questionTypes:U,includeGraphs:re,difficultyDistribution:ie,bloomLevels:D,excludeTopics:b,classSectionId:a,className:r,preferImportedTopics:y.quizEnabled}},ba=u.useCallback((x,O)=>{const H={taskId:x,request:O,createdAt:new Date().toISOString(),ownerUid:h?.uid};try{sessionStorage.setItem($r,JSON.stringify(H))}catch{}},[h]),ys=u.useCallback(()=>{try{sessionStorage.removeItem($r)}catch{}},[]),Cr=u.useCallback(x=>{const O=Math.max(0,Math.min(100,Math.round(typeof x.progressPercent=="number"?x.progressPercent:x.status==="queued"?10:x.status==="running"?65:x.status==="completed"?100:x.status==="cancelling"?95:100)));T(H=>{let Ne=Math.max(H,O);if(x.status==="running"&&O<=H){const Qe=String(x.progressStage||"").toLowerCase(),Ze=Qe.includes("assembling")||Qe.includes("final")?97:Qe.includes("generating")?89:95;Ne=Math.min(Ze,H+1)}return Ne}),V(x.progressStage||x.status),oe(x.progressMessage||(x.status==="queued"?"Task queued for generation.":x.status==="running"?"Generating quiz in the background...":x.status==="completed"?"Generation complete.":x.status==="cancelling"?"Cancelling generation...":"Generation finished with an error."))},[]);u.useEffect(()=>{if(v||rt.current)return;if(rt.current=!0,!h){ys();return}let x=!1;const O=sessionStorage.getItem($r);if(!O)return;let H=null;try{H=JSON.parse(O)}catch{ys();return}if(!H?.taskId){ys();return}if(H.ownerUid&&H.ownerUid!==h.uid){ys();return}return M(!0),$(H.taskId),Je(""),xt.waitForTaskResult(H.taskId,{timeoutMs:24e4,pollIntervalMs:1500,onProgress:Cr}).then(async Ne=>{if(x)return;const Qe=Ne.result;if(!Qe||typeof Qe!="object")throw new Error("Quiz generation completed without a valid result payload.");const Ze=Qe;je(Ze),g("results"),T(100),V("completed"),oe("Generation complete."),$(null),ys();try{await Rn(Ze,H.request),le.success("Quiz auto-saved to your library as draft.")}catch(Xt){le.error(Xt instanceof Error?Xt.message:"Quiz generated but failed to save to library")}}).catch(Ne=>{if(!x){if(Ne instanceof rr&&(Ne.status===401||Ne.status===403)){rt.current=!1,M(!1);return}Je(Ne instanceof Error?Ne.message:"Failed to resume quiz generation"),$(null),ys()}}).finally(()=>{x||M(!1)}),()=>{x=!0}},[Cr,v,ys,h]);const Tn=()=>{if(se){window.confirm("Quiz generation is in progress. Are you sure you want to leave?")&&(g("setup"),je(null),Je(""),t());return}g("setup"),je(null),Je(""),t()},_l=async()=>{p?.(),Je(""),M(!0),Vs(null),T(8),V("queued"),oe("Submitting quiz generation task..."),je(null);const x=ga();try{const O=await xt.generateQuiz(x,{onTaskCreated:H=>{$(H),ba(H,x),T(Ne=>Math.max(Ne,12)),V("queued"),oe("Task queued. Generation is running in the background.")},onProgress:H=>{Cr(H),H.taskId&&H.taskId!==pe&&$(H.taskId)}});je(O),g("results"),T(100),V("completed"),oe("Generation complete."),$(null),ys();try{await Rn(O,x),le.success("Quiz auto-saved to your library as draft.")}catch(H){le.error(H instanceof Error?H.message:"Quiz generated but failed to save to library")}xt.reportImportGroundedFeedback({flow:"quiz",status:"success",classSectionId:x.classSectionId,className:x.className,metadata:{totalQuestions:O.metadata.totalQuestions,usedImportedTopics:!!O.metadata.usedImportedTopics,importedTopicCount:O.metadata.importedTopicCount??0,importGroundingEnabled:y.quizEnabled}})}catch(O){Je(O instanceof Error?O.message:"Quiz generation failed"),T(100),V("failed"),oe("Generation failed."),$(null),ys(),xt.reportImportGroundedFeedback({flow:"quiz",status:"failed",classSectionId:x.classSectionId,className:x.className,metadata:{error:O instanceof Error?O.message:"Quiz generation failed",importGroundingEnabled:y.quizEnabled}})}finally{M(!1)}},El=()=>{if(!ae)return;const x=ae.questions.map((O,H)=>{let Ne=`${H+1}. [${O.difficulty.toUpperCase()}] [${O.bloomLevel}] (${O.points} pts) `;return Ne+=` ${O.question} `,O.options&&(Ne+=O.options.map(Qe=>` ${Qe}`).join(` @@ -88,9 +88,9 @@ ${n}`:void 0,curriculumRetrievalConfidence:l,curriculumRetrievalBand:c,curriculu `,Ne+=` Explanation: ${O.explanation} `,Ne}).join(` `);navigator.clipboard.writeText(x),dt(!0),setTimeout(()=>dt(!1),2e3)},Rl=()=>{if(!ae)return;const x=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),O=URL.createObjectURL(x),H=document.createElement("a");H.href=O,H.download=`quiz_${I.replace(/\s/g,"_")}_${Date.now()}.json`,H.click(),URL.revokeObjectURL(O)};f.length>0||Object.values(X).flat().length>0;const _n=(x,O)=>{const H=O?.gradeLevel||I,Ne=O?.topics||f,Qe=x.questions.map((Ze,Xt)=>({id:`q_${Date.now()}_${Xt}`,questionType:Ze.questionType||"identification",question:Ze.question,...Ze.options?{options:Ze.options}:{},correctAnswer:Ze.correctAnswer,bloomLevel:Ze.bloomLevel||"understand",difficulty:Ze.difficulty||"medium",topic:Ze.topic,subject:H,points:Ze.points,explanation:Ze.explanation}));return{title:`${H} Quiz – ${Ne.length>0?Ne.slice(0,2).join(", "):"Mixed Topics"}`,gradeLevel:H,questions:Qe,totalPoints:x.totalPoints,metadata:{topicsCovered:Object.keys(x.metadata.topicsCovered),difficultyBreakdown:{easy:x.metadata.difficultyBreakdown.easy??0,medium:x.metadata.difficultyBreakdown.medium??0,hard:x.metadata.difficultyBreakdown.hard??0},bloomDistribution:x.metadata.bloomTaxonomyDistribution,questionTypeBreakdown:x.metadata.questionTypeBreakdown,supplementalPurpose:x.metadata.supplementalPurpose,recommendedTeacherActions:x.metadata.recommendedTeacherActions??[],generatedAt:new Date().toISOString(),generatedBy:"teacher_generated"},status:"draft",source:"teacher_generated"}},En=u.useCallback(x=>{ut(O=>[x,...O.filter(H=>H.id!==x.id)])},[]);async function Rn(x,O){if(!h)return null;const H=_n(x,O),Ne=await Bn(H,h.uid,Ge?{documentId:Ge}:void 0);return z(Ne),En({id:Ne,...H,teacherId:h.uid}),Ne}const Ml=async()=>{if(!ae){le.error("No quiz to save. Generate a quiz first.");return}if(!h){le.error("You must be signed in to save quizzes.");return}Rs(!0);try{const x=_n(ae),O=await Bn(x,h.uid,Ge?{documentId:Ge}:void 0);z(O),En({id:O,...x,teacherId:h.uid}),le.success("Quiz saved to your library!"),m?.(O)}catch(x){le.error(x instanceof Error?x.message:"Failed to save quiz")}finally{Rs(!1)}},Al=async()=>{if(Ge){E(!0);try{await uc(Ge),ut(x=>x.map(O=>O.id===Ge?{...O,status:"published"}:O)),le.success("Quiz published to Quiz Bank!")}catch(x){le.error(x instanceof Error?x.message:"Failed to publish quiz")}finally{E(!1)}}},Ir=async x=>{const O=x??Ge;if(!O){le.error("Save the quiz first before assigning.");return}if(Ha(O),ve(!0),Le(null),Bt(""),K.length===0&&h){ke(!0);try{const H=await yn(h.uid);Xe(H)}catch{le.error("Failed to load students")}finally{ke(!1)}}},zl=async()=>{const x=Ba??Ge;if(!(!$t||!x||!h)){Me(!0);try{await mc(x,$t,h.uid),ut(O=>O.map(H=>H.id===x?{...H,status:"assigned",metadata:{...H.metadata,assignedTo:$t}}:H)),le.success("Quiz assigned to student!"),ve(!1),Ha(null),S==="bank"&&Tr()}catch(O){le.error(O instanceof Error?O.message:"Failed to assign quiz")}finally{Me(!1)}}},Tr=u.useCallback(async()=>{if(h){ss(!0);try{const x=await Ni(h.uid);ut(x)}catch{le.error("Failed to load quiz bank")}finally{ss(!1)}}},[h]);u.useEffect(()=>{S==="bank"&&Tr()},[S,Tr]);const Ll=async x=>{try{await dc(x),ut(O=>O.filter(H=>H.id!==x)),le.success("Quiz deleted")}catch{le.error("Failed to delete quiz")}},Mn=K.filter(x=>x.name.toLowerCase().includes(jt.toLowerCase())||x.email.toLowerCase().includes(jt.toLowerCase())),An=Qs==="all"?ft:ft.filter(x=>x.status===Qs),Dl=x=>{const O=(x.metadata.topicsCovered||[]).reduce((H,Ne)=>(H[Ne]=(H[Ne]||0)+1,H),{});return{questions:x.questions.map(H=>({questionType:H.questionType,question:H.question,correctAnswer:H.correctAnswer,options:H.options??null,bloomLevel:H.bloomLevel,difficulty:H.difficulty,topic:H.topic,points:H.points,explanation:H.explanation})),totalPoints:x.totalPoints,metadata:{topicsCovered:O,difficultyBreakdown:x.metadata.difficultyBreakdown,bloomTaxonomyDistribution:x.metadata.bloomDistribution,questionTypeBreakdown:x.metadata.questionTypeBreakdown,gradeLevel:x.gradeLevel,totalQuestions:x.questions.length,includesGraphQuestions:!1,supplementalPurpose:x.metadata.supplementalPurpose,bloomTaxonomyRationale:"Loaded from saved quiz bank entry.",recommendedTeacherActions:x.metadata.recommendedTeacherActions||[]}}},_r=x=>{z(x.id),je(Dl(x)),Ke(null),Vs(x.id),js("all"),Gs("all"),cs(null),g("results"),N("create")},zn={remember:{badge:"border-purple-200 text-purple-700 bg-purple-50",card:"from-[#a855f7] to-[#9333ea]",num:"text-purple-700 bg-purple-100 border-purple-200"},understand:{badge:"border-blue-200 text-blue-700 bg-blue-50",card:"from-[#3b82f6] to-[#2563eb]",num:"text-blue-700 bg-blue-100 border-blue-200"},apply:{badge:"border-amber-200 text-amber-700 bg-amber-50",card:"from-[#f59e0b] to-[#d97706]",num:"text-amber-700 bg-amber-100 border-amber-200"},analyze:{badge:"border-orange-200 text-orange-700 bg-orange-50",card:"from-[#f97316] to-[#ea580c]",num:"text-orange-700 bg-orange-100 border-orange-200"},evaluate:{badge:"border-rose-200 text-rose-700 bg-rose-50",card:"from-[#f43f5e] to-[#e11d48]",num:"text-rose-700 bg-rose-100 border-rose-200"},create:{badge:"border-emerald-200 text-emerald-700 bg-emerald-50",card:"from-[#10b981] to-[#059669]",num:"text-emerald-700 bg-emerald-100 border-emerald-200"}},$l=(x,O,H)=>{const Ne=It===O,Qe=zn[x.bloomLevel?.toLowerCase()]||zn.remember,Ze=x.bloomLevel?.toLowerCase()==="remember"?"hover:border-purple-200":x.bloomLevel?.toLowerCase()==="understand"?"hover:border-blue-200":x.bloomLevel?.toLowerCase()==="apply"?"hover:border-amber-200":"hover:border-slate-200";return e.jsxs(Re.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:O*.05},className:`border border-[#e2e8f0] rounded-[20px] overflow-hidden bg-white shadow-sm hover:shadow-md ${Ze} transition-all duration-300`,children:[e.jsxs("div",{className:"p-6 flex justify-between items-start cursor-pointer hover:bg-slate-50/50 transition-colors",onClick:()=>cs(Ne?null:O),children:[e.jsxs("div",{className:"space-y-3 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap mb-1",children:[e.jsxs("span",{className:`w-8 h-8 rounded-lg bg-gradient-to-br ${Qe.card} text-white flex items-center justify-center font-bold text-[13px] shadow-sm`,children:["Q",O+1]}),e.jsx("span",{className:`px-2.5 py-1 rounded-md border text-[10px] font-bold uppercase tracking-wider shadow-sm ${Qe.badge}`,children:x.bloomLevel}),e.jsx("span",{className:`px-2.5 py-1 rounded-md border text-[10px] font-bold uppercase tracking-wider shadow-sm ${x.difficulty==="easy"?"border-emerald-200 text-emerald-700 bg-emerald-50":x.difficulty==="hard"?"border-rose-200 text-rose-700 bg-rose-50":"border-amber-200 text-amber-700 bg-amber-50"}`,children:x.difficulty}),e.jsxs("span",{className:"text-[12px] font-bold text-[#64748b] bg-slate-100 px-2 py-1 rounded-md",children:[x.points," pts"]}),x.topic&&e.jsx("span",{className:"text-[12px] font-semibold text-[#64748b] px-2 py-1 hidden sm:inline-block border-l border-slate-200",children:x.topic})]}),e.jsx("p",{className:"text-[16px] font-bold text-[#1e293b] pr-4 leading-relaxed",children:x.question})]}),e.jsxs("div",{className:"flex flex-col items-end justify-between h-full gap-4 shrink-0 mt-1",children:[e.jsx("span",{className:`px-3 py-1.5 rounded-md text-[10px] font-bold uppercase tracking-widest hidden sm:block border shadow-sm ${Qe.badge}`,children:x.bloomLevel}),e.jsx("div",{className:"w-8 h-8 rounded-full bg-slate-50 flex items-center justify-center border border-slate-200 mt-2",children:Ne?e.jsx(Ia,{size:16,className:"text-[#64748b] transition-transform duration-300"}):e.jsx(Ot,{size:16,className:"text-[#64748b]"})})]})]}),e.jsx(zt,{children:Ne&&e.jsx(Re.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:e.jsxs("div",{className:"p-6 pt-0 bg-white",children:[e.jsx("div",{className:"h-px w-full bg-gradient-to-r from-transparent via-[#e2e8f0] to-transparent mb-6"}),x.options&&e.jsxs("div",{className:"mb-6",children:[e.jsx("p",{className:"text-[13px] font-bold text-[#64748b] mb-3 uppercase tracking-wider",children:"Options:"}),e.jsx("div",{className:"space-y-3",children:x.options.map((Xt,ea)=>{const mt=Xt.includes(x.correctAnswer);return e.jsxs("div",{className:`rounded-[12px] p-4 text-[14px] font-medium transition-all cursor-pointer relative overflow-hidden ${mt?"bg-gradient-to-r from-emerald-50 to-emerald-100/30 border-2 border-emerald-400 text-emerald-800 font-bold shadow-sm":"bg-white border border-[#e2e8f0] text-[#475569] hover:border-[#a855f7] hover:shadow-[0_2px_8px_rgba(168,85,247,0.1)]"}`,children:[mt&&e.jsx("div",{className:"absolute left-0 top-0 w-1 h-full bg-emerald-500"}),e.jsx("span",{className:mt?"pl-2":"",children:Xt}),mt&&e.jsx("div",{className:"w-6 h-6 rounded-full bg-emerald-500 text-white flex items-center justify-center shadow-sm absolute right-4 top-1/2 -translate-y-1/2",children:e.jsx(Gt,{size:13})})]},ea)})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-5",children:[e.jsxs("div",{className:"bg-emerald-50/80 border border-emerald-200/60 rounded-[16px] p-5 shadow-sm",children:[e.jsxs("p",{className:"text-[11px] font-bold text-emerald-700 uppercase tracking-wider mb-2 flex items-center gap-1.5",children:[e.jsx(Sa,{size:14})," Correct Answer"]}),e.jsx("p",{className:"text-[16px] font-bold text-[#1e293b]",children:x.correctAnswer})]}),e.jsxs("div",{className:"bg-purple-50/80 border border-purple-200/60 rounded-[16px] p-5 shadow-sm",children:[e.jsxs("p",{className:"text-[11px] font-bold text-purple-700 uppercase tracking-wider mb-2 flex items-center gap-1.5",children:[e.jsx(bs,{size:14})," AI Explanation"]}),e.jsx("p",{className:"text-[13px] text-[#475569] leading-relaxed font-medium",children:x.explanation})]})]}),e.jsxs("div",{className:"flex gap-6 text-[12px] font-medium text-[#64748b] mt-5 pt-4 border-t border-slate-100",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(As,{size:14})," ",e.jsx("strong",{className:"text-[#1e293b]",children:"Type:"})," ",Wa[x.questionType]?.label||x.questionType]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ur,{size:14})," ",e.jsx("strong",{className:"text-[#1e293b]",children:"Bloom:"})," ",x.bloomLevel]})]})]})})})]},O)},Ln=e.jsxs("div",{className:"w-full h-full flex flex-col overflow-y-auto bg-gradient-to-br from-[#eef2ff] via-[#f5f3ff] to-[#fff7ed]",children:[e.jsx("div",{className:"w-full px-[24px] xl:px-[32px] pt-[12px] pb-4",children:e.jsxs("div",{className:"flex items-center gap-1 bg-white/50 backdrop-blur-md p-1.5 rounded-full border border-white shadow-[0_2px_8px_rgba(0,0,0,0.04)] w-max",children:[e.jsxs("button",{onClick:()=>N("create"),className:`px-6 py-2 rounded-full text-[13px] font-bold flex items-center gap-2 transition-all duration-300 ease-out ${S==="create"?"bg-white text-[#a855f7] shadow-[0_2px_8px_rgba(168,85,247,0.15)] scale-100":"bg-transparent text-[#64748b] hover:text-[#1e293b] hover:bg-white/60 scale-95 hover:scale-100"}`,children:[e.jsx(Xr,{size:16})," Create Quiz"]}),e.jsxs("button",{onClick:()=>N("bank"),className:`px-6 py-2 rounded-full text-[13px] font-bold flex items-center gap-2 transition-all duration-300 ease-out ${S==="bank"?"bg-white text-[#a855f7] shadow-[0_2px_8px_rgba(168,85,247,0.15)] scale-100":"bg-transparent text-[#64748b] hover:text-[#1e293b] hover:bg-white/60 scale-95 hover:scale-100"}`,children:[e.jsx(ur,{size:16})," Quiz Bank"]})]})}),e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] pb-[32px] flex-1",children:[S==="bank"&&e.jsxs("div",{className:"w-full space-y-[24px]",children:[e.jsx("div",{className:"flex items-center gap-3 overflow-x-auto pb-2 border-b border-[#e2e8f0] mb-6",style:{scrollbarWidth:"none"},children:["all","draft","published","assigned","completed"].map(x=>e.jsx("button",{onClick:()=>Pa(x),className:`px-5 py-2 text-[13px] font-bold rounded-full whitespace-nowrap transition-all duration-300 mb-4 capitalize ${Qs===x?"bg-purple-50 text-[#9333ea] border border-purple-200 shadow-[0_2px_8px_rgba(168,85,247,0.15)] hover:scale-105":"bg-white/80 text-[#64748b] border border-white hover:border-[#e2e8f0] hover:bg-white shadow-sm hover:shadow-md hover:-translate-y-0.5"}`,children:x==="all"?"All":x.charAt(0).toUpperCase()+x.slice(1)},x))}),Ft?e.jsxs("div",{className:"flex items-center justify-center py-16",children:[e.jsx(gt,{size:24,className:"animate-spin text-sky-500"}),e.jsx("span",{className:"ml-2 text-sm text-[#5a6578]",children:"Loading quiz bank…"})]}):An.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(ur,{size:40,className:"mb-3"}),e.jsx("p",{className:"font-medium",children:"No quizzes found"}),e.jsx("p",{className:"text-xs mt-1",children:"Generate your first quiz in the Create tab"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:An.map(x=>e.jsxs(Re.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},onClick:()=>_r(x),role:"button",tabIndex:0,onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),_r(x))},className:`relative bg-white/80 backdrop-blur-md rounded-[20px] p-6 shadow-sm border flex flex-col group hover:-translate-y-1 transition-all duration-300 cursor-pointer overflow-hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#a855f7] ${x.status==="assigned"||x.status==="published"?"border-white hover:border-purple-100 hover:shadow-[0_8px_24px_rgba(168,85,247,0.1)]":"border-white hover:border-slate-200 hover:shadow-[0_8px_24px_rgba(0,0,0,0.06)]"}`,children:[e.jsx("div",{className:`absolute top-0 left-0 w-[6px] h-full transition-colors duration-300 ${x.status==="assigned"||x.status==="published"?"bg-purple-300 group-hover:bg-[#a855f7]":"bg-slate-200 group-hover:bg-slate-400"}`}),e.jsxs("div",{className:"flex justify-between items-start mb-4 gap-4 pl-3",children:[e.jsx("h3",{className:`font-bold text-[15px] text-[#1e293b] leading-tight transition-colors ${x.status==="assigned"||x.status==="published"?"group-hover:text-[#9333ea]":"group-hover:text-slate-700"}`,children:x.title}),e.jsx("span",{className:`px-2.5 py-1 rounded-[6px] text-[10px] font-bold uppercase tracking-wider shrink-0 shadow-sm ${Nm[x.status]}`,children:x.status})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-5 pl-3",children:x.metadata.topicsCovered.slice(0,3).map(O=>e.jsx("span",{className:"px-2.5 py-1 bg-[#f8fafc] text-slate-600 text-[11px] font-medium rounded-md border border-slate-200 group-hover:border-slate-300 transition-colors",children:O},O))}),e.jsxs("div",{className:"flex items-center gap-5 text-[13px] text-[#64748b] font-medium mb-6 pl-3",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(bc,{size:14})," ",x.questions.length," questions"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(hi,{size:14})," ",x.totalPoints," pts"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(hs,{size:14})," ",x.gradeLevel]})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-auto pt-5 border-t border-[#f1f5f9] pl-3",children:[e.jsxs("button",{onClick:O=>{O.stopPropagation(),_r(x)},className:"flex items-center gap-1.5 text-[13px] font-semibold text-[#64748b] hover:text-[#1e293b] transition-colors bg-slate-50 hover:bg-slate-100 border border-slate-200 px-4 py-2 rounded-full shadow-sm",children:[e.jsx(vc,{size:14})," View"]}),e.jsxs("button",{onClick:O=>{O.stopPropagation(),Ir(x.id)},className:"flex items-center gap-1.5 text-[13px] font-bold text-[#a855f7] hover:text-[#9333ea] transition-colors",children:[e.jsx(ra,{size:14})," Assign"]}),e.jsxs("button",{onClick:O=>{O.stopPropagation(),Ll(x.id)},className:"flex items-center gap-1.5 text-[13px] font-semibold text-rose-500 hover:text-rose-700 transition-colors ml-auto opacity-60 group-hover:opacity-100",children:[e.jsx(ji,{size:14})," Delete"]})]})]},x.id))})]}),S==="create"&&e.jsxs(e.Fragment,{children:[Ue&&e.jsx("div",{className:"w-full px-[24px] xl:px-[32px] pt-4",children:e.jsxs(Re.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"bg-red-50 border border-red-200 rounded-xl p-4 flex items-start gap-3",children:[e.jsx(br,{size:18,className:"text-red-500 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-red-800 font-medium",children:"Error"}),e.jsx("p",{className:"text-sm text-red-600",children:Ue})]}),e.jsx("button",{onClick:()=>Je(""),className:"ml-auto",children:e.jsx(qt,{size:14,className:"text-red-400"})})]})}),se&&e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-[24px] xl:p-[32px]",children:[e.jsxs("div",{className:"bg-white p-8 rounded-[16px] shadow-sm border border-[#e2e8f0] w-full max-w-3xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-[16px] font-bold text-[#1e293b] flex items-center gap-3",children:[e.jsx(gt,{size:20,className:"animate-spin text-[#a855f7]"}),"Generating Quiz in Background"]}),e.jsxs("span",{className:"text-[14px] font-extrabold text-[#9333ea]",children:[j,"%"]})]}),e.jsx("div",{className:"w-full bg-slate-100 h-2.5 rounded-full overflow-hidden mb-6",children:e.jsx(Re.div,{animate:{width:`${j}%`},transition:{duration:.35,ease:"easeOut"},className:"bg-gradient-to-r from-sky-400 via-indigo-500 to-purple-500 h-full rounded-full"})}),e.jsxs("div",{className:"text-[13px] text-[#64748b]",children:[e.jsxs("p",{className:"font-medium text-[#475569] mb-1",children:["Stage: ",e.jsx("span",{className:"font-bold text-[#1e293b] capitalize",children:_.replace(/_/g," ")})]}),e.jsx("p",{children:me}),pe&&e.jsxs("p",{className:"text-[11px] mt-3 opacity-60 font-mono",children:["Task ID: ",pe]})]})]}),e.jsxs("p",{className:"mt-8 text-[14px] font-medium text-[#64748b] flex items-center gap-2 animate-pulse",children:[e.jsx(gt,{size:16,className:"animate-spin"})," Generating quiz... Please wait."]})]}),!se&&w!=="results"&&e.jsx("div",{className:"w-full px-[24px] xl:px-[32px] mb-8",children:e.jsx("div",{className:"flex items-center justify-between bg-white/80 backdrop-blur-[12px] rounded-2xl border border-white shadow-[0_4px_16px_rgba(0,0,0,0.03)] p-1.5",children:[{id:"setup",label:"Setup"},{id:"topics",label:"Topics"},{id:"style",label:"Question Style"},{id:"preview",label:"Preview"}].map((x,O)=>{const Ne=["setup","topics","style","preview"].indexOf(w),Qe=Ne>O,Ze=Ne===O;return e.jsxs("div",{className:`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl transition-all duration-500 ${Ze?"bg-purple-50/80 shadow-[0_1px_3px_rgba(168,85,247,0.1)]":Qe?"bg-transparent":"bg-transparent opacity-60"}`,children:[e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-[12px] font-bold shrink-0 ${Ze?"bg-gradient-to-br from-[#a855f7] to-[#9333ea] text-white shadow-md":Qe?"bg-emerald-500 text-white shadow-sm":"bg-slate-100 text-[#64748b]"}`,children:Qe?e.jsx(Gt,{size:13,strokeWidth:3}):O+1}),e.jsx("span",{className:`text-[13px] font-bold whitespace-nowrap ${Ze?"text-[#9333ea]":Qe?"text-[#1e293b]":"text-[#64748b]"}`,children:x.label})]},x.id)})})}),w==="setup"&&!se&&e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] flex-1 space-y-[24px] pb-8",children:[e.jsxs("div",{className:"bg-gradient-to-r from-purple-50/80 to-indigo-50/80 backdrop-blur-sm border border-purple-100/50 rounded-[16px] p-5 flex items-start gap-4 shadow-sm hover:shadow-md transition-shadow duration-300",children:[e.jsx("div",{className:"bg-white p-2 rounded-full shadow-sm shrink-0",children:e.jsx(oa,{size:18,className:"text-[#9333ea]"})}),e.jsxs("p",{className:"text-[13px] text-[#475569] leading-relaxed pt-0.5",children:["This quiz maker generates ",e.jsx("span",{className:"font-bold text-[#9333ea]",children:"supplemental assessments"})," to support classroom instruction. Questions follow Bloom's Taxonomy for comprehensive skill evaluation. Generation limit: up to ",wa," questions and ",Na," topics per quiz."]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[20px] border border-white shadow-[0_4px_16px_rgba(0,0,0,0.03)] overflow-hidden hover:shadow-[0_8px_24px_rgba(0,0,0,0.06)] transition-all duration-300",children:[e.jsx("div",{className:"p-5 border-b border-[#f1f5f9] bg-white/50",children:e.jsx("h3",{className:"text-[11px] font-bold text-[#64748b] uppercase tracking-wider",children:"Basic Settings"})}),e.jsxs("div",{className:"p-8 flex flex-col md:flex-row gap-8",children:[e.jsxs("div",{className:"flex-1 group",children:[e.jsx("label",{htmlFor:"quiz-grade-level",className:"text-[13px] font-bold text-[#1e293b] mb-2 block group-hover:text-[#a855f7] transition-colors",children:"Grade level"}),e.jsxs("div",{className:"relative",children:[e.jsx("select",{id:"quiz-grade-level",value:I,onChange:x=>L(Dr(x.target.value)),className:"appearance-none w-full bg-white border border-[#e2e8f0] hover:border-[#cbd5e1] text-[#475569] text-[14px] font-medium rounded-xl px-4 py-3.5 outline-none focus:border-[#a855f7] focus:ring-4 focus:ring-[#a855f7]/10 cursor-pointer transition-all duration-200 shadow-sm",children:jm.map(x=>e.jsx("option",{value:x,children:x},x))}),e.jsx(Ot,{size:18,className:"text-[#64748b] absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none"})]})]}),e.jsxs("div",{className:"flex-1 group",children:[e.jsx("label",{htmlFor:"quiz-num-questions",className:"text-[13px] font-bold text-[#1e293b] mb-2 block group-hover:text-[#a855f7] transition-colors",children:"Number of questions"}),e.jsxs("div",{className:"flex items-center bg-white border border-[#e2e8f0] rounded-xl overflow-hidden focus-within:border-[#a855f7] focus-within:ring-4 focus-within:ring-[#a855f7]/10 transition-all duration-200 h-[50px] shadow-sm hover:border-[#cbd5e1]",children:[e.jsx("button",{onClick:()=>W(Math.max(1,A-1)),className:"w-14 h-full flex items-center justify-center text-[#64748b] bg-slate-50 hover:bg-slate-100 hover:text-[#1e293b] transition-colors border-r border-[#e2e8f0] active:bg-slate-200",children:e.jsx(Hn,{size:16})}),e.jsx("input",{id:"quiz-num-questions",type:"number",min:1,max:wa,value:A,onChange:x=>W(Math.min(wa,Math.max(1,parseInt(x.target.value)||1))),className:"flex-1 text-center font-bold text-[16px] text-[#1e293b] border-none outline-none focus:ring-0 w-full h-full p-0"}),e.jsx("button",{onClick:()=>W(Math.min(wa,A+1)),className:"w-14 h-full flex items-center justify-center text-[#64748b] bg-slate-50 hover:bg-slate-100 hover:text-[#1e293b] transition-colors border-l border-[#e2e8f0] active:bg-slate-200",children:e.jsx(ua,{size:16})})]})]})]})]})]}),w==="topics"&&!se&&e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] flex-1 space-y-[24px] pb-8",children:[e.jsxs("div",{className:"flex items-end justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-[20px] font-bold text-[#1e293b] mb-1",children:"Select topics"}),e.jsxs("p",{className:"text-[13px] text-[#64748b]",children:["Choose up to ",Na," topics across all strands"]})]}),e.jsxs("div",{className:"bg-purple-50 border border-purple-100 px-3 py-1.5 rounded-full flex items-center gap-2 shadow-sm",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-[#a855f7] animate-pulse"}),e.jsxs("span",{className:"text-[12px] font-bold text-[#a855f7]",children:[f.filter(x=>!b.includes(x)).length," of ",Na," selected"]})]})]}),ge?e.jsxs("div",{className:"flex items-center justify-center py-10 text-sm text-[#5a6578]",children:[e.jsx(gt,{size:24,className:"animate-spin text-[#9b51e0] mr-2"})," Loading topics..."]}):e.jsx("div",{className:"space-y-3",children:Object.entries(X).map(([x,O])=>{const H=O.filter(Qe=>f.includes(Qe)&&!b.includes(Qe)).length,Ne=Mt===x;return e.jsxs("div",{className:"border border-[#dde3eb] rounded-xl bg-white overflow-hidden shadow-sm",children:[e.jsxs("button",{onClick:()=>At(Ne?null:x),className:"w-full flex items-center justify-between p-4 hover:bg-[#f7f9fc] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-1 h-6 bg-[#9b51e0] rounded-full"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-bold text-[#0a1628] text-sm",children:x}),e.jsxs("p",{className:"text-xs text-slate-500",children:[O.length," topics"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"bg-purple-100 text-[#9b51e0] px-2.5 py-0.5 rounded-full text-xs font-semibold",children:[H," selected"]}),Ne?e.jsx(Ia,{size:18,className:"text-slate-400"}):e.jsx(Ot,{size:18,className:"text-slate-400"})]})]}),e.jsx(zt,{children:Ne&&e.jsx(Re.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},className:"overflow-hidden border-t border-[#edf1f7]",children:e.jsx("div",{className:"py-2",children:O.map((Qe,Ze)=>{const Xt=f.includes(Qe),ea=b.includes(Qe),mt=Xt&&!ea;let as="Core";return Ze%3===0&&(as="Foundation"),Ze%3===2&&(as="Advanced"),e.jsxs("div",{className:"flex items-center justify-between px-6 py-3 hover:bg-[#f7f9fc]",children:[e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer flex-1",children:[e.jsx("div",{className:`w-5 h-5 rounded flex items-center justify-center transition-colors ${mt?"bg-[#9b51e0] border-[#9b51e0]":"border-2 border-[#dde3eb] bg-white"}`,children:mt&&e.jsx(Gt,{size:14,className:"text-white"})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:mt,onChange:()=>Ga(Qe)}),e.jsx("span",{className:`text-sm font-semibold ${mt?"text-[#0a1628]":"text-[#5a6578]"}`,children:Qe})]}),e.jsx("span",{className:`border px-3 py-1 rounded-full text-[10px] uppercase font-bold tracking-wider ${as==="Advanced"?"bg-white text-slate-400 border-[#dde3eb]":"bg-purple-50 text-[#9b51e0] border-purple-100"}`,children:as})]},Qe)})})})})]},x)})})]}),w==="style"&&!se&&e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] flex-1 space-y-[24px] pb-8",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[20px] border border-[#e2e8f0] shadow-sm overflow-hidden hover:shadow-[0_8px_24px_rgba(0,0,0,0.04)] transition-shadow duration-300",children:[e.jsx("div",{className:"p-5 border-b border-[#f1f5f9] bg-white/50",children:e.jsx("h3",{className:"text-[11px] font-bold text-[#64748b] uppercase tracking-wider",children:"Question Types"})}),e.jsx("div",{className:"p-4 grid grid-cols-2 sm:grid-cols-5 gap-3",children:Object.entries(Wa).map(([x,O])=>{const H=U.includes(x);return e.jsxs("button",{onClick:()=>Ut(x),className:`border-2 rounded-[16px] p-4 flex flex-col items-center justify-center text-center cursor-pointer transition-all duration-300 relative overflow-hidden group hover:-translate-y-1 ${H?"border-[#a855f7] bg-gradient-to-b from-purple-50/80 to-white/80 shadow-[0_4px_12px_rgba(168,85,247,0.12)]":"border-slate-100 bg-slate-50/50 shadow-sm hover:shadow-md hover:border-purple-200"}`,children:[H&&e.jsx("div",{className:"absolute top-2 right-2 w-5 h-5 bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-full flex items-center justify-center shadow-md",children:e.jsx(Gt,{size:11,className:"text-white"})}),e.jsx("div",{className:`w-12 h-12 rounded-full flex items-center justify-center mb-3 group-hover:scale-110 transition-transform duration-300 ${H?"bg-white border border-purple-200 shadow-md":"bg-white border border-slate-200 shadow-sm group-hover:shadow-md"}`,children:e.jsx("span",{className:H?"text-[#a855f7]":"text-slate-500",children:O.icon})}),e.jsx("span",{className:`font-bold text-[12px] leading-tight ${H?"text-[#9333ea]":"text-slate-700"}`,children:O.label})]},x)})})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[20px] border border-[#e2e8f0] shadow-sm overflow-hidden hover:shadow-[0_8px_24px_rgba(0,0,0,0.04)] transition-shadow duration-300",children:[e.jsx("div",{className:"p-5 border-b border-[#f1f5f9] bg-white/50",children:e.jsx("h3",{className:"text-[11px] font-bold text-[#64748b] uppercase tracking-wider",children:"Bloom's Taxonomy Levels"})}),e.jsx("div",{className:"p-6 flex flex-wrap gap-4",children:Object.entries(Fo).map(([x,O])=>{const H=D.includes(x);return e.jsx("button",{onClick:()=>We(x),className:`px-6 py-2.5 rounded-full border-2 font-bold text-[13px] transition-all duration-200 hover:-translate-y-0.5 capitalize ${H?"border-[#a855f7] text-[#9333ea] bg-purple-50/80 shadow-[0_2px_8px_rgba(168,85,247,0.15)]":"border-slate-200 text-[#64748b] bg-white shadow-sm hover:border-slate-300 hover:bg-slate-50"}`,children:x},x)})})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[20px] border border-[#e2e8f0] shadow-sm overflow-hidden hover:shadow-[0_8px_24px_rgba(0,0,0,0.04)] transition-shadow duration-300",children:[e.jsx("div",{className:"p-5 border-b border-[#f1f5f9] bg-white/50",children:e.jsx("h3",{className:"text-[11px] font-bold text-[#64748b] uppercase tracking-wider",children:"Difficulty Distribution"})}),e.jsx("div",{className:"p-8 space-y-8",children:Object.entries(ie).map(([x,O])=>{const H={easy:"bg-emerald-400",medium:"bg-amber-400",hard:"bg-rose-400"},Ne={easy:"text-emerald-600",medium:"text-amber-500",hard:"text-rose-500"},Qe={easy:"group-hover:border-emerald-200",medium:"group-hover:border-amber-200",hard:"group-hover:border-rose-200"};return e.jsxs("div",{className:"flex items-center gap-6 group",children:[e.jsx("span",{className:`w-16 text-[13px] font-bold text-[#475569] capitalize group-hover:${Ne[x]} transition-colors`,children:x}),e.jsx("div",{className:"flex-1 bg-slate-100 h-3 rounded-full overflow-hidden shadow-inner",children:e.jsx(Re.div,{animate:{width:`${O}%`},className:`h-full rounded-full transition-all duration-500 ease-out ${H[x]}`})}),e.jsxs("div",{className:`flex items-center bg-white border border-[#e2e8f0] rounded-xl shadow-sm overflow-hidden p-0.5 w-28 h-10 transition-colors ${Qe[x]}`,children:[e.jsx("button",{onClick:()=>De(x,-5),className:`w-8 h-full flex items-center justify-center text-[#64748b] hover:bg-slate-50 hover:${Ne[x]} rounded-lg transition-colors`,children:e.jsx(Hn,{className:"w-3.5 h-3.5"})}),e.jsx("input",{type:"text",value:`${O}%`,readOnly:!0,className:"flex-1 text-center font-bold text-[14px] text-[#1e293b] border-none outline-none focus:ring-0 w-full p-0 pointer-events-none"}),e.jsx("button",{onClick:()=>De(x,5),className:`w-8 h-full flex items-center justify-center text-[#64748b] hover:bg-slate-50 hover:${Ne[x]} rounded-lg transition-colors`,children:e.jsx(ua,{className:"w-3.5 h-3.5"})})]})]},x)})})]})]}),w==="preview"&&!se&&!ae&&e.jsx("div",{className:"w-full px-[24px] xl:px-[32px] flex-1 space-y-[24px] pb-8",children:e.jsxs("div",{className:"bg-white/80 backdrop-blur-md rounded-[20px] border border-[#e2e8f0] shadow-[0_8px_24px_rgba(0,0,0,0.04)] overflow-hidden p-8",children:[e.jsxs("h3",{className:"text-[12px] font-bold text-[#64748b] uppercase tracking-wider mb-6 flex items-center gap-2",children:[e.jsx(Ds,{size:16,className:"text-[#a855f7]"})," Quiz Summary"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-6",children:[{label:"Questions",value:A},{label:"Topics",value:f.filter(x=>!b.includes(x)).length},{label:"Level",value:I.replace("Grade ","Gr. ")}].map(x=>e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-purple-50 to-indigo-50 rounded-[16px] p-6 text-center border border-purple-100/50 shadow-sm flex flex-col items-center justify-center group hover:-translate-y-1 transition-transform",children:[e.jsx("div",{className:"absolute -right-4 -top-4 w-16 h-16 bg-purple-200/30 rounded-full group-hover:scale-150 transition-transform duration-500"}),e.jsx("span",{className:"text-[36px] font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-[#a855f7] to-[#9333ea] leading-none mb-1 relative z-10",children:x.value}),e.jsx("span",{className:"text-[13px] font-bold text-[#64748b] relative z-10",children:x.label})]},x.label))}),e.jsxs("div",{className:"bg-slate-50/80 rounded-[14px] p-5 border border-slate-200/60 text-[#475569] text-[14px] leading-relaxed flex gap-4 items-start shadow-inner",children:[e.jsx(oa,{size:18,className:"text-[#94a3b8] shrink-0 mt-0.5"}),e.jsxs("p",{children:[U.map(x=>Wa[x]?.label).join(" and ")," questions across"," ",e.jsxs("span",{className:"font-bold text-[#1e293b]",children:[f.filter(x=>!b.includes(x)).length," topics"]})," ","— aligned to ",e.jsx("span",{className:"font-semibold",children:D.map(x=>Fo[x]?.label).join(", ")})," levels of Bloom's Taxonomy."," ",e.jsxs("span",{className:"font-semibold text-emerald-600",children:["Easy ",ie.easy,"%"]})," • ",e.jsxs("span",{className:"font-semibold text-amber-500",children:["Medium ",ie.medium,"%"]})," • ",e.jsxs("span",{className:"font-semibold text-rose-500",children:["Hard ",ie.hard,"%"]}),"."]})]})]})}),w==="results"&&ae&&e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] space-y-[24px] pb-8",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-md rounded-[20px] border border-[#e2e8f0] shadow-[0_8px_24px_rgba(0,0,0,0.04)] p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-bold font-display text-[#0a1628]",children:"Quiz Generated"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:El,className:"flex items-center gap-1.5 px-3 py-1.5 bg-white border border-[#dde3eb] rounded-lg text-xs font-medium text-[#5a6578] hover:bg-[#edf1f7] transition-colors",children:[ht?e.jsx(Gt,{size:14,className:"text-green-500"}):e.jsx(Vr,{size:14}),ht?"Copied!":"Copy All"]}),e.jsxs("button",{onClick:Rl,className:"flex items-center gap-1.5 px-3 py-1.5 bg-white border border-[#dde3eb] rounded-lg text-xs font-medium text-[#5a6578] hover:bg-[#edf1f7] transition-colors",children:[e.jsx(Nc,{size:14}),"Export JSON"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] text-white shadow-[0_8px_16px_rgba(168,85,247,0.25)] rounded-[20px] p-6 text-center flex flex-col items-center justify-center group hover:-translate-y-1 transition-transform",children:[e.jsx("div",{className:"absolute -right-4 -top-4 w-20 h-20 bg-white/10 rounded-full group-hover:scale-150 transition-transform duration-500"}),e.jsx(As,{size:22,className:"text-white/80 mb-2 relative z-10"}),e.jsx("span",{className:"text-[32px] font-extrabold leading-none mb-1 relative z-10 drop-shadow-sm",children:ae.questions.length}),e.jsx("span",{className:"text-[12px] font-bold text-white/90 uppercase tracking-widest relative z-10",children:"Questions"})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f43f5e] to-[#e11d48] text-white shadow-[0_8px_16px_rgba(244,63,94,0.25)] rounded-[20px] p-6 text-center flex flex-col items-center justify-center group hover:-translate-y-1 transition-transform",children:[e.jsx("div",{className:"absolute -right-4 -top-4 w-20 h-20 bg-white/10 rounded-full group-hover:scale-150 transition-transform duration-500"}),e.jsx(fs,{size:22,className:"text-white/80 mb-2 relative z-10"}),e.jsx("span",{className:"text-[32px] font-extrabold leading-none mb-1 relative z-10 drop-shadow-sm",children:ae.totalPoints}),e.jsx("span",{className:"text-[12px] font-bold text-white/90 uppercase tracking-widest relative z-10",children:"Total Points"})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f59e0b] to-[#d97706] text-white shadow-[0_8px_16px_rgba(245,158,11,0.25)] rounded-[20px] p-6 text-center flex flex-col items-center justify-center group hover:-translate-y-1 transition-transform",children:[e.jsx("div",{className:"absolute -right-4 -top-4 w-20 h-20 bg-white/10 rounded-full group-hover:scale-150 transition-transform duration-500"}),e.jsx(Vt,{size:22,className:"text-white/80 mb-2 relative z-10"}),e.jsx("span",{className:"text-[32px] font-extrabold leading-none mb-1 relative z-10 drop-shadow-sm",children:Object.keys(ae.metadata.topicsCovered).length}),e.jsx("span",{className:"text-[12px] font-bold text-white/90 uppercase tracking-widest relative z-10",children:"Topics"})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#10b981] to-[#059669] text-white shadow-[0_8px_16px_rgba(16,185,129,0.25)] rounded-[20px] p-6 text-center flex flex-col items-center justify-center group hover:-translate-y-1 transition-transform",children:[e.jsx("div",{className:"absolute -right-4 -top-4 w-20 h-20 bg-white/10 rounded-full group-hover:scale-150 transition-transform duration-500"}),e.jsx(lr,{size:22,className:"text-white/80 mb-2 relative z-10"}),e.jsx("span",{className:"text-[32px] font-extrabold leading-none mb-1 relative z-10 drop-shadow-sm",children:Object.keys(ae.metadata.bloomTaxonomyDistribution).length}),e.jsx("span",{className:"text-[12px] font-bold text-white/90 uppercase tracking-widest relative z-10",children:"Bloom Levels"})]})]}),(ae.metadata.usedImportedTopics||(ae.metadata.topicProvenance||[]).length>0)&&e.jsxs("div",{className:"mt-4 bg-white rounded-lg p-3 border border-[#dde3eb]",children:[e.jsx("p",{className:"text-xs font-semibold text-[#5a6578] mb-2",children:"Imported Topic Provenance"}),e.jsxs("p",{className:"text-xs text-[#5a6578] mb-2",children:["Imported topics used: ",ae.metadata.usedImportedTopics?"Yes":"No"," • ","Materials: ",ae.metadata.importedMaterialsCount??0," • ","Topics: ",ae.metadata.importedTopicCount??0]}),(ae.metadata.topicProvenance||[]).slice(0,5).map((x,O)=>e.jsxs("div",{className:"text-xs text-[#5a6578]",children:[x.title||"Untitled topic",x.sourceFile?` • ${x.sourceFile}`:""]},`${x.topicId||x.title||"topic"}_${O}`)),(_e.length>0||Oe.length>0)&&e.jsxs("div",{className:"mt-3 grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsxs("label",{className:"text-xs text-[#5a6578] flex flex-col gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Filter by Source File"}),e.jsxs("select",{value:ds,onChange:x=>js(x.target.value),className:"bg-white border border-[#dde3eb] rounded-md px-2 py-1.5 text-xs",children:[e.jsx("option",{value:"all",children:"All sources"}),_e.map(x=>e.jsx("option",{value:x,children:x},x))]})]}),e.jsxs("label",{className:"text-xs text-[#5a6578] flex flex-col gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Filter by Material ID"}),e.jsxs("select",{value:Kt,onChange:x=>Gs(x.target.value),className:"bg-white border border-[#dde3eb] rounded-md px-2 py-1.5 text-xs",children:[e.jsx("option",{value:"all",children:"All materials"}),Oe.map(x=>e.jsx("option",{value:x,children:x},x))]})]})]}),e.jsxs("p",{className:"text-[11px] text-[#5a6578] mt-2",children:["Showing ",Ht.length," of ",ae.questions.length," questions after provenance filters."]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mt-8 mb-10",children:[e.jsxs("div",{className:"bg-white border border-[#e2e8f0] rounded-[16px] p-6 shadow-sm border-t-[4px] border-t-[#10b981] hover:shadow-md transition-shadow",children:[e.jsxs("h4",{className:"text-[12px] font-bold text-[#64748b] uppercase tracking-wider mb-5 flex items-center gap-2",children:[e.jsx(Ds,{size:14})," Difficulty"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(ae.metadata.difficultyBreakdown).map(([x,O])=>e.jsxs("div",{className:"flex justify-between items-center bg-slate-50 px-3 py-2 rounded-lg",children:[e.jsx("span",{className:`font-bold capitalize ${km[x]||"text-[#475569]"}`,children:x}),e.jsx("span",{className:"font-bold text-[#1e293b] bg-white px-2 py-0.5 rounded shadow-sm border border-slate-100",children:O})]},x))})]}),e.jsxs("div",{className:"bg-white border border-[#e2e8f0] rounded-[16px] p-6 shadow-sm border-t-[4px] border-t-[#a855f7] hover:shadow-md transition-shadow",children:[e.jsxs("h4",{className:"text-[12px] font-bold text-[#64748b] uppercase tracking-wider mb-5 flex items-center gap-2",children:[e.jsx(Ur,{size:14})," Bloom's Taxonomy"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(ae.metadata.bloomTaxonomyDistribution).map(([x,O])=>e.jsxs("div",{className:"flex justify-between items-center bg-slate-50 px-3 py-2 rounded-lg",children:[e.jsx("span",{className:"text-[#1e293b] font-semibold capitalize",children:x}),e.jsx("span",{className:"font-bold text-[#1e293b] bg-white px-2 py-0.5 rounded shadow-sm border border-slate-100",children:O})]},x))})]}),e.jsxs("div",{className:"bg-white border border-[#e2e8f0] rounded-[16px] p-6 shadow-sm border-t-[4px] border-t-[#0ea5e9] hover:shadow-md transition-shadow",children:[e.jsxs("h4",{className:"text-[12px] font-bold text-[#64748b] uppercase tracking-wider mb-5 flex items-center gap-2",children:[e.jsx(lr,{size:14})," Question Types"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(ae.metadata.questionTypeBreakdown).map(([x,O])=>e.jsxs("div",{className:"flex justify-between items-center bg-slate-50 px-3 py-2 rounded-lg",children:[e.jsx("span",{className:"text-[#1e293b] font-semibold",children:Wa[x]?.label||x}),e.jsx("span",{className:"font-bold text-[#1e293b] bg-white px-2 py-0.5 rounded shadow-sm border border-slate-100",children:O})]},x))})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-purple-50 to-indigo-50/50 border border-purple-100 rounded-[16px] p-6 mb-10 flex items-start gap-4 shadow-sm relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full bg-[#a855f7]"}),e.jsx("div",{className:"bg-white p-2 rounded-full shadow-sm shrink-0",children:e.jsx(oa,{size:18,className:"text-[#9333ea]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-bold text-[#9333ea] mb-3",children:ae.metadata.supplementalPurpose||"This quiz is designed to supplement classroom instruction, not replace teacher-led learning."}),ae.metadata.recommendedTeacherActions&&ae.metadata.recommendedTeacherActions.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] font-bold text-[#1e293b] mb-2",children:"Recommended Actions:"}),e.jsx("ul",{className:"list-disc pl-5 text-[13px] font-medium text-[#475569] space-y-1.5",children:ae.metadata.recommendedTeacherActions.map((x,O)=>e.jsx("li",{children:x},O))})]})]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("h3",{className:"text-[18px] font-bold text-[#1e293b] flex items-center gap-2",children:[e.jsx(ki,{size:20,className:"text-[#a855f7]"})," Review Questions"]}),e.jsx("div",{className:"space-y-4",children:Ht.length>0?Ht.map((x,O)=>$l(x,O)):e.jsx("div",{className:"border border-[#dde3eb] rounded-xl p-4 bg-white text-sm text-[#5a6578]",children:"No questions match the selected provenance filters. Clear one or both filters to view all questions."})})]})]})]})]}),S==="create"&&e.jsx("div",{className:"sticky bottom-0 mt-auto w-full bg-white/90 backdrop-blur-[12px] border-t border-[#e2e8f0] z-30 shadow-[0_-4px_12px_rgba(0,0,0,0.03)]",children:e.jsxs("div",{className:"w-full px-6 xl:px-8 py-4 flex items-center justify-between",children:[e.jsxs("div",{children:[w==="topics"&&!se&&e.jsx("button",{onClick:()=>{C([]),F([])},className:"text-[13px] font-semibold text-[#a855f7] hover:underline",children:"Clear all"}),(w==="style"||w==="preview")&&!se&&e.jsxs("button",{onClick:()=>g(w==="preview"?"style":"topics"),className:"bg-white hover:bg-slate-50 border border-slate-200 text-[#475569] text-[14px] font-semibold rounded-full px-6 py-2.5 shadow-sm transition-transform hover:scale-[1.02] flex items-center gap-2",children:[e.jsx($s,{size:16})," Back"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[w==="setup"&&!se&&e.jsxs("button",{onClick:()=>g("topics"),className:"bg-[#a855f7] hover:bg-[#9333ea] text-white text-[14px] font-semibold rounded-full px-8 py-2.5 shadow-[0_4px_12px_rgba(168,85,247,0.3)] transition-transform hover:scale-[1.02] flex items-center gap-2",children:["Next: Topics ",e.jsx(zs,{size:16})]}),w==="topics"&&!se&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>g("setup"),className:"bg-white hover:bg-slate-50 border border-slate-200 text-[#475569] text-[14px] font-semibold rounded-full px-6 py-2.5 shadow-sm transition-transform hover:scale-[1.02] flex items-center gap-2",children:[e.jsx($s,{size:16})," Back"]}),e.jsxs("button",{onClick:()=>g("style"),className:"bg-[#a855f7] hover:bg-[#9333ea] text-white text-[14px] font-semibold rounded-full px-6 py-2.5 shadow-[0_4px_12px_rgba(168,85,247,0.3)] transition-transform hover:scale-[1.02] flex items-center gap-2",children:["Next: Question Style ",e.jsx(zs,{size:16})]})]}),w==="style"&&!se&&e.jsxs("button",{onClick:()=>g("preview"),className:"bg-[#a855f7] hover:bg-[#9333ea] text-white text-[14px] font-semibold rounded-full px-8 py-2.5 shadow-[0_4px_12px_rgba(168,85,247,0.3)] transition-transform hover:scale-[1.02] flex items-center gap-2",children:["Next: Preview ",e.jsx(zs,{size:16})]}),w==="preview"&&!se&&!ae&&e.jsxs("button",{onClick:_l,className:"bg-[#a855f7] hover:bg-[#9333ea] text-white text-[14px] font-bold rounded-full px-8 py-2.5 shadow-[0_4px_12px_rgba(168,85,247,0.3)] transition-all hover:scale-[1.02] flex items-center gap-2",children:[e.jsx(Gt,{size:16})," Generate Quiz"]}),se&&e.jsxs("div",{className:"flex items-center gap-3 text-slate-500 font-medium text-sm",children:[e.jsx(gt,{size:16,className:"animate-spin"})," Generating quiz... Please wait."]}),w==="results"&&(Ua?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{N("bank"),Vs(null)},className:"bg-white hover:bg-slate-50 border border-slate-200 text-[#475569] text-[14px] font-semibold rounded-full px-6 py-2.5 shadow-sm transition-transform hover:scale-[1.02]",children:"Back to Quiz Bank"}),e.jsxs("button",{onClick:()=>Ir(Ua),className:"bg-white border border-[#a855f7] text-[#9333ea] hover:bg-purple-50 text-[14px] font-bold rounded-full px-8 py-2.5 shadow-sm transition-transform hover:scale-[1.02] flex items-center gap-2",children:[e.jsx(ra,{size:16})," Assign"]}),e.jsx("button",{onClick:Tn,className:"bg-[#a855f7] hover:bg-[#9333ea] text-white text-[14px] font-bold rounded-full px-10 py-2.5 shadow-[0_4px_12px_rgba(168,85,247,0.3)] transition-transform hover:scale-[1.02]",children:"Done"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{g("setup"),je(null),Ke(null),z(null),Vs(null)},className:"bg-white hover:bg-slate-50 border border-slate-200 text-[#475569] text-[14px] font-semibold rounded-full px-6 py-2.5 shadow-sm transition-transform hover:scale-[1.02]",children:"Create Another"}),Ge?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:Al,disabled:de,className:"bg-white border border-[#a855f7] text-[#9333ea] hover:bg-purple-50 text-[14px] font-bold rounded-full px-8 py-2.5 shadow-sm transition-transform hover:scale-[1.02] flex items-center gap-2",children:[de?e.jsx(gt,{size:16,className:"animate-spin"}):e.jsx(ca,{size:16})," Publish"]}),e.jsxs("button",{onClick:()=>Ir(),className:"bg-[#a855f7] hover:bg-[#9333ea] text-white text-[14px] font-bold rounded-full px-8 py-2.5 shadow-[0_4px_12px_rgba(168,85,247,0.3)] transition-transform hover:scale-[1.02] flex items-center gap-2",children:[e.jsx(ra,{size:16})," Assign to Class"]})]}):e.jsxs("button",{onClick:Ml,disabled:Es,className:"bg-emerald-600 hover:bg-emerald-700 text-white px-8 py-2.5 rounded-full font-bold shadow-lg shadow-emerald-500/30 hover:-translate-y-1 transition-all flex items-center gap-2 text-[14px]",children:[Es?e.jsx(gt,{size:16,className:"animate-spin"}):e.jsx(yi,{size:16})," Save to Library"]}),e.jsx("button",{onClick:Tn,className:"bg-[#a855f7] hover:bg-[#9333ea] text-white text-[14px] font-bold rounded-full px-10 py-2.5 shadow-[0_4px_12px_rgba(168,85,247,0.3)] transition-transform hover:scale-[1.02]",children:"Done"})]}))]})]})}),e.jsx(wm,{isOpen:Us,onClose:()=>Yt(!1)}),e.jsx(zt,{children:R&&e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/40 z-[60] flex items-center justify-center p-4",onClick:()=>ve(!1),children:e.jsxs(Re.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.95,opacity:0},className:"bg-[#f7f9fc] rounded-2xl shadow-2xl w-full max-w-md max-h-[70vh] flex flex-col overflow-hidden border border-[#dde3eb]",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-[#dde3eb] flex items-center justify-between",children:[e.jsxs("h3",{className:"text-base font-bold font-display text-[#0a1628] flex items-center gap-2",children:[e.jsx(hs,{size:18,className:"text-sky-600"}),"Assign to Student"]}),e.jsx("button",{onClick:()=>ve(!1),className:"p-1 hover:bg-[#edf1f7] rounded-lg transition-colors",children:e.jsx(qt,{size:16,className:"text-slate-500"})})]}),e.jsx("div",{className:"px-5 py-3 border-b border-[#dde3eb]",children:e.jsxs("div",{className:"flex items-center gap-2 bg-[#edf1f7] rounded-xl px-3 py-2",children:[e.jsx(Xs,{size:14,className:"text-slate-500"}),e.jsx("input",{type:"text",placeholder:"Search students…",value:jt,onChange:x=>Bt(x.target.value),className:"flex-1 bg-transparent text-sm outline-none placeholder:text-slate-500"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-1",children:nt?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(gt,{size:20,className:"animate-spin text-sky-500"})}):Mn.length===0?e.jsx("p",{className:"text-center text-sm text-slate-500 py-10",children:"No students found"}):Mn.map(x=>e.jsxs("button",{onClick:()=>Le(x.id),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-left transition-colors ${$t===x.id?"bg-sky-50 border border-sky-300":"hover:bg-[#edf1f7] border border-transparent"}`,children:[e.jsx("img",{src:x.avatar&&!x.avatar.includes("ui-avatars.com")?x.avatar:Ja(x.gender),alt:x.name,className:"w-8 h-8 rounded-lg object-cover"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-[#0a1628] truncate",children:x.name}),e.jsx("p",{className:"text-xs text-slate-500 truncate",children:x.email})]}),$t===x.id&&e.jsx(Gt,{size:16,className:"text-sky-600 flex-shrink-0"})]},x.id))}),e.jsxs("div",{className:"px-5 py-3 border-t border-[#dde3eb] flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>ve(!1),className:"px-4 py-2 text-sm font-medium text-[#5a6578] hover:bg-[#edf1f7] rounded-xl transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:zl,disabled:!$t||ee,className:`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold transition-all ${$t&&!ee?"bg-gradient-to-r from-sky-600 to-sky-500 text-white shadow-sm":"bg-[#dde3eb] text-slate-500 cursor-not-allowed"}`,children:[ee?e.jsx(gt,{size:14,className:"animate-spin"}):e.jsx(ra,{size:14}),"Assign"]})]})]})})})]});return d?e.jsx("div",{className:"w-full h-full flex flex-col overflow-hidden bg-white",children:Ln}):Ln},Cm=({onOpenNotifications:t,onOpenProfile:s,onOpenInsightModal:a,userPhoto:r,teacherName:o})=>{const[n,i]=u.useState([]),[l,c]=u.useState(!1),[d,m]=u.useState(!1),[p,h]=u.useState(""),[v,y]=u.useState(11),[S,N]=u.useState("general_mathematics"),[w,g]=u.useState([]),[I,L]=u.useState(!1),[A,W]=u.useState(null),f=u.useCallback(async()=>{L(!0);try{const k=kt(St($e,"question_bank",String(v),S,"questions","questions"),or(50));let J=(await Lt(k)).docs.map(re=>{const ce=re.data();return{id:re.id,question:ce.question||"",choices:ce.choices||[],correct_answer:ce.correct_answer||"",explanation:ce.explanation||"",topic:ce.topic||"",difficulty:ce.difficulty||"medium",grade_level:ce.grade_level||11}});if(J.length===0){const re=kt(St($e,"quizBattleQuestionBank"),or(50));J=(await Lt(re)).docs.map(ie=>{const fe=ie.data();return{id:ie.id,question:fe.question||"",choices:fe.choices||[],correct_answer:fe.correct_answer||"",explanation:fe.explanation||"",topic:fe.topic||"",difficulty:fe.difficulty||"medium",grade_level:fe.grade_level||11}})}g(J)}catch(k){console.warn("[QuestionBankPanel] Failed to load questions:",k)}finally{L(!1)}},[v,S]);u.useEffect(()=>{f()},[f]);const C=u.useCallback(async()=>{c(!0);try{const k=await Fn("/api/quiz-battle/bank-status");i(k.pdfs)}catch(k){const D=k instanceof rr?k.message:"Failed to load bank status";le.error(D)}finally{c(!1)}},[]);u.useEffect(()=>{C()},[C]);const b=async()=>{if(!p.trim()){le.error("Please enter a storage path");return}m(!0);try{await Fn("/api/quiz-battle/ingest-pdf",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storage_path:p.trim(),grade_level:v,topic:S.trim(),force_reingest:!1})}),le.success("PDF ingestion completed"),await C(),h("")}catch(k){const D=k instanceof rr?k.message:"Ingestion failed";le.error(D)}finally{m(!1)}},F=n.reduce((k,D)=>k+D.question_count,0),U=n.filter(k=>k.processed).length;return e.jsxs("div",{className:"w-full h-full flex flex-col overflow-y-auto bg-gradient-to-br from-[#f8fafc] to-[#f1f5f9]",children:[e.jsx("div",{className:"w-full px-[24px] xl:px-[32px] pt-[12px] pb-2"}),e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] pb-[32px] space-y-[32px]",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#3b82f6] to-[#2563eb] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(59,130,246,0.2)] hover:shadow-[0_8px_24px_rgba(59,130,246,0.3)] hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Total PDFs"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(As,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:n.length})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(168,85,247,0.2)] hover:shadow-[0_8px_24px_rgba(168,85,247,0.3)] hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Total Questions"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(Vt,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:F})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#10b981] to-[#059669] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(16,185,129,0.2)] hover:shadow-[0_8px_24px_rgba(16,185,129,0.3)] hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Processed"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(xs,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:U})]})]}),e.jsx("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] border border-white shadow-[0_8px_32px_rgba(0,0,0,0.04)] overflow-hidden",children:e.jsxs("div",{className:"p-[24px] sm:p-[32px]",children:[e.jsxs("h2",{className:"text-[20px] font-bold text-[#1e293b] mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-[10px] bg-gradient-to-br from-[#a855f7] to-[#9333ea] flex items-center justify-center shadow-md shadow-purple-500/20",children:e.jsx(Wr,{className:"w-4 h-4 text-white"})}),"Ingest New PDF"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-6 items-end",children:[e.jsxs("div",{className:"md:col-span-6 group",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] mb-2 block group-hover:text-[#a855f7] transition-colors",children:"Firebase Storage Path"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none",children:e.jsx(As,{className:"h-4 w-4 text-[#94a3b8] group-hover:text-[#a855f7] transition-colors"})}),e.jsx("input",{type:"text",placeholder:"quiz_pdfs/grade_11/gen_math_q1.pdf",value:p,onChange:k=>h(k.target.value),className:"w-full bg-slate-50 border border-slate-200 hover:border-[#cbd5e1] text-[#475569] text-[14px] font-medium rounded-xl pl-11 pr-4 py-3.5 outline-none focus:bg-white focus:border-[#a855f7] focus:ring-4 focus:ring-[#a855f7]/10 transition-all shadow-inner"})]})]}),e.jsxs("div",{className:"md:col-span-2 group",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] mb-2 block group-hover:text-[#a855f7] transition-colors",children:"Grade Level"}),e.jsx("input",{type:"number",placeholder:"11",min:7,max:12,value:v,onChange:k=>y(Number(k.target.value)),className:"w-full bg-slate-50 border border-slate-200 hover:border-[#cbd5e1] text-[#475569] text-[14px] font-medium rounded-xl px-4 py-3.5 outline-none focus:bg-white focus:border-[#a855f7] focus:ring-4 focus:ring-[#a855f7]/10 transition-all shadow-inner"})]}),e.jsxs("div",{className:"md:col-span-4 group",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] mb-2 block group-hover:text-[#a855f7] transition-colors",children:"Topic Slug"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none",children:e.jsx(Vt,{className:"h-4 w-4 text-[#94a3b8] group-hover:text-[#a855f7] transition-colors"})}),e.jsx("input",{type:"text",placeholder:"general_mathematics",value:S,onChange:k=>N(k.target.value),className:"w-full bg-slate-50 border border-slate-200 hover:border-[#cbd5e1] text-[#475569] text-[14px] font-medium rounded-xl pl-11 pr-4 py-3.5 outline-none focus:bg-white focus:border-[#a855f7] focus:ring-4 focus:ring-[#a855f7]/10 transition-all shadow-inner"})]})]})]}),e.jsx("div",{className:"mt-6 flex justify-end pt-6 border-t border-slate-100",children:e.jsxs("button",{onClick:b,disabled:d,className:"bg-gradient-to-r from-[#a855f7] to-[#9333ea] hover:from-[#9333ea] hover:to-[#7e22ce] text-white text-[14px] font-bold rounded-full px-8 py-3 shadow-[0_4px_16px_rgba(168,85,247,0.3)] transition-all hover:scale-[1.02] flex items-center gap-2 hover:shadow-[0_8px_24px_rgba(168,85,247,0.4)] disabled:opacity-50 disabled:hover:scale-100",children:[d?e.jsx(gt,{className:"w-4 h-4 animate-spin"}):e.jsx(Wr,{className:"w-4 h-4"}),"Ingest PDF"]})})]})}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] border border-white shadow-[0_8px_32px_rgba(0,0,0,0.04)] p-[24px] sm:p-[32px]",children:[e.jsxs("div",{className:"flex justify-between items-center mb-6",children:[e.jsx("h2",{className:"text-[20px] font-bold text-[#1e293b]",children:"Processing Status"}),e.jsx("button",{onClick:C,disabled:l,className:"w-9 h-9 rounded-full bg-white border border-slate-200 flex items-center justify-center text-[#64748b] hover:text-[#9333ea] hover:border-purple-200 shadow-sm transition-all hover:scale-105 active:scale-95 disabled:opacity-50",children:e.jsx(xs,{className:`w-4 h-4 ${l?"animate-spin":""}`})})]}),e.jsx("div",{className:"bg-white rounded-[16px] border border-[#f1f5f9] overflow-hidden shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[#9956DE] border-b border-[#8b5cf6] shadow-md relative z-10",children:[e.jsx("th",{className:"h-12 px-6 text-[11px] font-bold text-white uppercase tracking-wider whitespace-nowrap",children:"Filename"}),e.jsx("th",{className:"h-12 px-6 text-[11px] font-bold text-white uppercase tracking-wider whitespace-nowrap",children:"Grade"}),e.jsx("th",{className:"h-12 px-6 text-[11px] font-bold text-white uppercase tracking-wider whitespace-nowrap",children:"Topic"}),e.jsx("th",{className:"h-12 px-6 text-[11px] font-bold text-white uppercase tracking-wider whitespace-nowrap text-center",children:"Questions"}),e.jsx("th",{className:"h-12 px-6 text-[11px] font-bold text-white uppercase tracking-wider whitespace-nowrap",children:"Status"}),e.jsx("th",{className:"h-12 px-6 text-[11px] font-bold text-white uppercase tracking-wider whitespace-nowrap",children:"Processed At"})]})}),e.jsxs("tbody",{className:"divide-y divide-[#f1f5f9] bg-white",children:[n.map(k=>e.jsxs("tr",{className:"hover:bg-slate-50/50 transition-colors group",children:[e.jsx("td",{className:"py-4 px-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${k.processed?"bg-indigo-50 text-indigo-500":"bg-amber-50 text-amber-500"}`,children:e.jsx(As,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-[13px] font-bold text-[#1e293b] group-hover:text-purple-600 transition-colors line-clamp-1",children:k.filename})]})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-semibold text-[#475569]",children:k.grade_level}),e.jsx("td",{className:"py-4 px-6",children:e.jsx("span",{className:"text-[12px] font-medium bg-slate-100 text-slate-600 px-2.5 py-1 rounded-md line-clamp-1",children:k.topic})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-bold text-[#1e293b] text-center",children:k.question_count||"-"}),e.jsx("td",{className:"py-4 px-6",children:e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-3 py-1 text-[11px] font-bold rounded-full border shadow-sm ${k.processed?"bg-emerald-50 text-emerald-600 border-emerald-200/50":"bg-amber-50 text-amber-600 border-amber-200/50"}`,children:[k.processed?e.jsx(xs,{className:"w-3 h-3"}):e.jsx(gt,{className:"w-3 h-3 animate-spin"}),k.processed?"Completed":"Processing..."]})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-medium text-[#64748b]",children:k.timestamp?new Date(k.timestamp).toLocaleDateString():"-"})]},k.filename)),n.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"py-12 px-6 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center text-[#64748b]",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4 border border-slate-100",children:e.jsx(As,{className:"w-8 h-8 text-slate-300"})}),e.jsx("p",{className:"text-[14px] font-bold text-[#1e293b] mb-1",children:"No PDFs processed yet"}),e.jsx("p",{className:"text-[13px]",children:"Upload a PDF using the form above to get started."})]})})})]})]})})})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] border border-white shadow-[0_8px_32px_rgba(0,0,0,0.04)] p-[24px] sm:p-[32px]",children:[e.jsxs("div",{className:"flex justify-between items-center mb-6",children:[e.jsxs("h2",{className:"text-[20px] font-bold text-[#1e293b] flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-[10px] bg-gradient-to-br from-[#3b82f6] to-[#2563eb] flex items-center justify-center shadow-md shadow-blue-500/20",children:e.jsx(Vt,{className:"w-4 h-4 text-white"})}),"Question Bank (",w.length,")"]}),e.jsx("button",{onClick:f,disabled:I,className:"w-9 h-9 rounded-full bg-white border border-slate-200 flex items-center justify-center text-[#64748b] hover:text-[#9333ea] hover:border-purple-200 shadow-sm transition-all hover:scale-105 active:scale-95 disabled:opacity-50",children:e.jsx(xs,{className:`w-4 h-4 ${I?"animate-spin":""}`})})]}),I?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(gt,{className:"w-6 h-6 animate-spin text-[#9956DE]"})}):w.length===0?e.jsxs("div",{className:"text-center py-12 text-[#64748b]",children:[e.jsx(Vt,{className:"w-10 h-10 mx-auto mb-3 text-slate-300"}),e.jsx("p",{className:"text-[14px] font-bold text-[#1e293b] mb-1",children:"No questions in the bank yet"}),e.jsx("p",{className:"text-[13px]",children:"Ingest a PDF above to populate the question bank."})]}):e.jsx("div",{className:"space-y-2 max-h-[500px] overflow-y-auto",children:w.map(k=>e.jsxs("div",{className:"border border-[#f1f5f9] rounded-xl p-4 hover:border-purple-200 transition-colors bg-white",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 cursor-pointer",onClick:()=>W(A===k.id?null:k.id),children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[13px] font-medium text-[#1e293b] line-clamp-2",children:k.question}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs("span",{className:"text-[11px] px-2 py-0.5 rounded-md bg-blue-50 text-blue-600 font-semibold",children:["Grade ",k.grade_level]}),e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-md bg-slate-100 text-slate-600 font-medium",children:k.topic}),e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-md font-semibold ${k.difficulty==="easy"?"bg-green-50 text-green-600":k.difficulty==="hard"?"bg-rose-50 text-rose-600":"bg-amber-50 text-amber-600"}`,children:k.difficulty})]})]}),A===k.id?e.jsx(Ia,{size:16,className:"text-[#94a3b8] shrink-0"}):e.jsx(Ot,{size:16,className:"text-[#94a3b8] shrink-0"})]}),A===k.id&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-[#f1f5f9] space-y-2",children:[e.jsx("div",{className:"space-y-1",children:k.choices.map((D,J)=>e.jsxs("p",{className:`text-[12px] px-3 py-1.5 rounded-lg ${D===k.correct_answer?"bg-green-50 text-green-700 font-semibold border border-green-200":"bg-slate-50 text-[#475569]"}`,children:[String.fromCharCode(65+J),". ",D]},J))}),k.explanation&&e.jsxs("p",{className:"text-[12px] text-[#64748b] italic mt-2 flex items-center gap-1",children:[e.jsx(jc,{size:12})," ",k.explanation]})]})]},k.id))})]})]})]})},Po={totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:0},Im={"gen-math":{label:"General Mathematics",color:"bg-sky-100 text-sky-700"},"stats-prob":{label:"Statistics & Probability",color:"bg-sky-100 text-sky-700"},"pre-calc":{label:"Pre-Calculus",color:"bg-orange-100 text-orange-700"},"basic-calc":{label:"Basic Calculus",color:"bg-red-100 text-red-700"}},Bo={mastered:{label:"Mastered",color:"text-emerald-600 bg-emerald-50 border-emerald-100"},on_track:{label:"On Track",color:"text-amber-600 bg-amber-50 border-amber-100"},needs_attention:{label:"Needs Work",color:"text-rose-600 bg-rose-50 border-rose-100"},no_data:{label:"No Data",color:"text-slate-600 bg-slate-50 border-slate-200"}},Ho={needs_attention:0,on_track:1,no_data:2,mastered:3},Tm=({classSectionId:t,onOpenNotifications:s,onOpenProfile:a})=>{const{currentUser:r,userProfile:o}=vs(),[n,i]=u.useState([]),[l,c]=u.useState(Po),[d,m]=u.useState(!0),[p,h]=u.useState("all"),[v,y]=u.useState("all"),[S,N]=u.useState(""),[w,g]=u.useState("classAverage"),[I,L]=u.useState("asc"),A=Gn.map(B=>B.id),W=Gn.reduce((B,te)=>(B[te.id]=te.name,B),{}),{isLoading:f,refetch:C}=Ic();u.useEffect(()=>{f||(console.log("[TopicMasteryView] Curriculum ready"),C())},[f,C]);const[b,F]=u.useState(new Set),[U,k]=u.useState([]),D=Sc({queryKey:Hl.topicMastery(r?.uid||"anonymous",t),enabled:!!r,staleTime:120*1e3,gcTime:900*1e3,queryFn:async()=>{try{if(!r)return{excluded:[],topics:[],summary:{totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:0}};const B=ct($e,"teachers",r.uid,"settings","quizSettings"),te=await Is(B),ne=te.exists()?te.data()?.excludedTopics||[]:[],ze="https://deign86-mathpulse-api-v3test.hf.space",Fe=new URLSearchParams({teacherId:r.uid});t&&Fe.set("classSectionId",t);const Pe=await r.getIdToken(),G=await fetch(`${ze}/api/analytics/topic-mastery?${Fe.toString()}`,{headers:{Authorization:`Bearer ${Pe}`}});if(!G.ok)return{excluded:ne,topics:[],summary:{totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:ne.length}};const se=await G.json(),M=(se.topics||[]).map(q=>({...q,isExcluded:ne.includes(q.topicName)}));return{excluded:ne,topics:M,summary:se.summary||{totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:ne.length}}}catch{return{excluded:[],topics:[],summary:{totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:0}}}}});u.useEffect(()=>{if(m(D.isLoading||D.isFetching),!D.data){k([]),i([]),c(Po),F(new Set);return}k(D.data.excluded),i(D.data.topics),c(D.data.summary)},[D.data,D.isFetching,D.isLoading]);const J=async B=>{if(!r)return;const te=U.includes(B)?U.filter(ne=>ne!==B):[...U,B];k(te),i(ne=>ne.map(ze=>ze.topicName===B?{...ze,isExcluded:!ze.isExcluded}:ze)),c(ne=>({...ne,excludedCount:te.length}));try{const ne=ct($e,"teachers",r.uid,"settings","quizSettings");(await Is(ne)).exists()?await ns(ne,{excludedTopics:te}):await os(ne,{excludedTopics:te})}catch{le.error("Failed to update excluded topics")}},re=async()=>{if(!r)return;const B=[...new Set([...U,...b])];k(B),i(te=>te.map(ne=>b.has(ne.topicName)?{...ne,isExcluded:!0}:ne)),c(te=>({...te,excludedCount:B.length})),F(new Set);try{const te=ct($e,"teachers",r.uid,"settings","quizSettings");(await Is(te)).exists()?await ns(te,{excludedTopics:B}):await os(te,{excludedTopics:B}),le.success(`${b.size} topics excluded from quizzes`)}catch{le.error("Failed to update")}},ce=async()=>{if(!r)return;const B=U.filter(te=>!b.has(te));k(B),i(te=>te.map(ne=>b.has(ne.topicName)?{...ne,isExcluded:!1}:ne)),c(te=>({...te,excludedCount:B.length})),F(new Set);try{const te=ct($e,"teachers",r.uid,"settings","quizSettings");(await Is(te)).exists()?await ns(te,{excludedTopics:B}):await os(te,{excludedTopics:B}),le.success(`${b.size} topics re-included in quizzes`)}catch{le.error("Failed to update")}},ie=B=>{w===B?L(te=>te==="asc"?"desc":"asc"):(g(B),L("asc"))},fe=v==="all"?A:kc(v);u.useEffect(()=>{p!=="all"&&(fe.includes(p)||h("all"))},[fe,p]);const Ce=n.filter(B=>!(p!=="all"&&B.subjectId!==p||!fe.includes(B.subjectId)||S&&!B.topicName.toLowerCase().includes(S.toLowerCase()))).sort((B,te)=>{const ne=I==="asc"?1:-1;switch(w){case"topicName":return ne*B.topicName.localeCompare(te.topicName);case"classAverage":return ne*(B.classAverage-te.classAverage);case"studentsAttempted":return ne*(B.studentsAttempted-te.studentsAttempted);case"masteryStatus":return ne*((Ho[B.masteryStatus]||0)-(Ho[te.masteryStatus]||0));default:return 0}}),ue=()=>{b.size===Ce.length?F(new Set):F(new Set(Ce.map(B=>B.topicName)))},ge=({field:B})=>w!==B?e.jsx(Ot,{size:14,className:"text-white/40"}):I==="asc"?e.jsx(Ia,{size:14,className:"text-white font-bold"}):e.jsx(Ot,{size:14,className:"text-white font-bold"});return d?e.jsxs("div",{className:"flex items-center justify-center py-20",children:[e.jsx(gt,{size:24,className:"animate-spin text-indigo-500"}),e.jsx("span",{className:"ml-2 text-[#64748b]",children:"Loading topic mastery data..."})]}):e.jsxs(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-full p-[24px] xl:p-[32px] space-y-[24px]",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-[16px]",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(168,85,247,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Total Topics Tracked"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(Ds,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:l.totalTopicsTracked})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#10b981] to-[#059669] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(16,185,129,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Mastered by Class"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(La,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:l.masteredCount})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f43f5e] to-[#e11d48] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(244,63,94,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Needs Work"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(da,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:l.needsAttentionCount})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#64748b] to-[#475569] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(100,116,139,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Excluded Topics"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(wc,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:l.excludedCount})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white",children:[e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 mb-6",children:[e.jsxs("div",{className:"flex items-center bg-white px-4 py-2.5 rounded-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-[#e2e8f0] group focus-within:ring-2 focus-within:ring-indigo-500/20 transition-all w-full md:w-64",children:[e.jsx(Xs,{size:16,className:"text-[#64748b] shrink-0 group-focus-within:text-[#4f46e5] transition-colors"}),e.jsx("input",{type:"text",placeholder:"Search topics...",value:S,onChange:B=>N(B.target.value),className:"bg-transparent border-none focus:outline-none ml-2 text-[13px] w-full text-[#475569] placeholder:text-[#94a3b8]"})]}),e.jsxs("div",{className:"relative w-full md:w-48",children:[e.jsxs("select",{value:p,onChange:B=>h(B.target.value),className:"appearance-none w-full bg-white border border-[#e2e8f0] text-[#475569] text-[13px] font-medium rounded-[12px] pl-4 pr-10 py-2.5 outline-none focus:border-[#a855f7] focus:ring-2 focus:ring-[#a855f7]/20 shadow-[0_1px_4px_rgba(0,0,0,0.02)] cursor-pointer",children:[e.jsx("option",{value:"all",children:"All Subjects"}),fe.map(B=>e.jsx("option",{value:B,children:W[B]||B},B))]}),e.jsx(Ot,{size:16,className:"text-[#64748b] absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]}),e.jsxs("div",{className:"relative w-full md:w-48",children:[e.jsxs("select",{value:v,onChange:B=>y(B.target.value),className:"appearance-none w-full bg-white border border-[#e2e8f0] text-[#475569] text-[13px] font-medium rounded-[12px] pl-4 pr-10 py-2.5 outline-none focus:border-[#a855f7] focus:ring-2 focus:ring-[#a855f7]/20 shadow-[0_1px_4px_rgba(0,0,0,0.02)] cursor-pointer",children:[e.jsx("option",{value:"all",children:"All Grades"}),Cc.map(B=>e.jsx("option",{value:B,children:B},B))]}),e.jsx(Ot,{size:16,className:"text-[#64748b] absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]})]}),e.jsx(zt,{children:b.size>0&&e.jsxs(Re.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"mb-4 bg-indigo-50 border border-indigo-200 rounded-[12px] p-3 flex items-center gap-3 flex-wrap overflow-hidden",children:[e.jsxs("span",{className:"text-[13px] font-semibold text-indigo-700",children:[b.size," topics selected"]}),e.jsx("button",{onClick:re,className:"px-4 py-1.5 bg-[#475569] text-white text-[11px] font-bold rounded-full hover:bg-[#334155] transition-colors shadow-sm",children:"Exclude Selected"}),e.jsx("button",{onClick:ce,className:"px-4 py-1.5 bg-emerald-600 text-white text-[11px] font-bold rounded-full hover:bg-emerald-700 transition-colors shadow-sm",children:"Include Selected"}),e.jsx("button",{onClick:()=>F(new Set),className:"px-4 py-1.5 bg-white border border-[#e2e8f0] text-[#64748b] text-[11px] font-bold rounded-full hover:bg-[#f8fafc] transition-colors shadow-sm",children:"Clear Selection"})]})}),e.jsx("div",{className:"bg-white rounded-[16px] border border-[#f1f5f9] overflow-hidden shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("div",{className:"min-w-[800px]",children:[e.jsxs("div",{className:"bg-[#9956DE] grid grid-cols-12 gap-4 p-4 border-b border-[#8b5cf6] items-center text-[11px] font-bold text-white tracking-wider uppercase shadow-md relative z-10 h-12",children:[e.jsx("div",{className:"col-span-1 flex justify-center",children:e.jsx("input",{type:"checkbox",checked:b.size===Ce.length&&Ce.length>0,onChange:ue,className:"rounded text-[#4f46e5] focus:ring-[#4f46e5] w-4 h-4 border-white/30 bg-white/10 cursor-pointer"})}),e.jsxs("div",{className:"col-span-3 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ie("topicName"),children:["TOPIC NAME ",e.jsx(ge,{field:"topicName"})]}),e.jsx("div",{className:"col-span-2",children:"UNIT"}),e.jsxs("div",{className:"col-span-2 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ie("classAverage"),children:["CLASS AVG % ",e.jsx(ge,{field:"classAverage"})]}),e.jsxs("div",{className:"col-span-2 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ie("studentsAttempted"),children:["STUDENTS ",e.jsx(ge,{field:"studentsAttempted"})]}),e.jsxs("div",{className:"col-span-1 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ie("masteryStatus"),children:["STATUS ",e.jsx(ge,{field:"masteryStatus"})]}),e.jsx("div",{className:"col-span-1 text-center",children:"EXCLUDE"})]}),e.jsx("div",{className:"flex flex-col",children:Ce.length===0?e.jsx("div",{className:"p-16 text-center border-b border-[#f1f5f9]",children:n.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Ds,{size:32,className:"text-[#cbd5e1]"}),e.jsx("p",{className:"text-[13px] font-semibold text-[#64748b]",children:"No topic data available yet"}),e.jsx("p",{className:"text-[11px] text-[#94a3b8]",children:"Import student quiz data to see class topic mastery analytics."})]}):e.jsx("span",{className:"text-[13px] text-[#64748b]",children:"No topics match the current filters."})}):Ce.map(B=>{const te=b.has(B.topicName),ne=Bo[B.masteryStatus]||Bo.no_data,ze=Im[B.subjectId]||{label:B.subjectId.toUpperCase(),color:"bg-[#f8fafc] text-[#64748b]"},Fe=B.classAverage<60?"bg-rose-500":B.classAverage<85?"bg-amber-500":"bg-emerald-500",Pe=B.isExcluded?"bg-slate-50/60 opacity-70":B.masteryStatus==="needs_attention"?"bg-rose-50/30":B.masteryStatus==="mastered"?"bg-emerald-50/20":"";return e.jsxs("div",{className:`grid grid-cols-12 gap-4 p-4 border-b border-[#f1f5f9] items-center hover:bg-slate-50/80 transition-colors group ${Pe} ${B.isExcluded?"line-through decoration-slate-400":""}`,children:[e.jsx("div",{className:"col-span-1 flex justify-center",children:e.jsx("input",{type:"checkbox",checked:te,onChange:()=>{const G=new Set(b);te?G.delete(B.topicName):G.add(B.topicName),F(G)},className:"rounded text-[#4f46e5] focus:ring-[#4f46e5] w-4 h-4 border-gray-300 cursor-pointer"})}),e.jsxs("div",{className:"col-span-3 flex flex-col sm:flex-row sm:items-center gap-1.5 pr-2 min-w-0",children:[e.jsx("span",{className:"font-semibold text-[#1e293b] text-[13px] truncate",children:B.topicName}),e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded shrink-0 ${ze.color}`,children:ze.label})]}),e.jsx("div",{className:"col-span-2 text-[#475569] text-[13px] truncate pr-2",children:B.unit}),e.jsx("div",{className:"col-span-2",children:e.jsxs("span",{className:"font-bold text-[#1e293b] text-[14px]",children:[B.classAverage,"%"]})}),e.jsxs("div",{className:"col-span-2 pr-4",children:[e.jsx("div",{className:"flex justify-between items-center text-[11px] mb-1",children:e.jsxs("span",{className:"font-semibold text-[#1e293b]",children:[B.studentsAttempted," / ",B.totalStudents]})}),e.jsx("div",{className:"w-full bg-[#f1f5f9] h-1.5 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${Fe}`,style:{width:`${B.classAverage}%`}})})]}),e.jsx("div",{className:"col-span-1",children:e.jsx("span",{className:`text-[10px] font-bold px-2.5 py-1 rounded-full border whitespace-nowrap ${ne.color}`,children:ne.label})}),e.jsxs("div",{className:"col-span-1 flex justify-center relative",children:[e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer group/toggle",children:[e.jsx("input",{type:"checkbox",checked:B.isExcluded,onChange:()=>J(B.topicName),className:"sr-only peer"}),e.jsx("div",{className:"w-9 h-5 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#4f46e5]"})]}),e.jsx("div",{className:"hidden group-hover/toggle:block absolute z-20 bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-slate-800 text-white text-[10px] rounded whitespace-nowrap shadow-lg",children:B.isExcluded?"Include in generation":"Exclude from generation"})]})]},B.topicName)})})]})})})]})]})};function vl(t){return(t||"").trim().toLowerCase()}function Uo(t){const s=(t.lrn||"").trim().toLowerCase();if(s)return`lrn:${s}`;const a=(t.email||"").trim().toLowerCase();if(a)return`email:${a}`;const r=t.name.trim().toLowerCase();if(r)return`name:${r}`;const o=vl(t.classSectionId),n=(t.id||"").trim().toLowerCase();return o&&n?`${o}|id:${n}`:n?`id:${n}`:`${o}|anonymous`}function _m(t,s){const a=[],r=(t.lrn||"").trim().toLowerCase(),o=(t.email||"").trim().toLowerCase(),n=t.name.trim().toLowerCase(),i=(t.id||"").trim().toLowerCase();return r&&a.push(`${s}|lrn:${r}`),o&&a.push(`${s}|email:${o}`),n&&a.push(`${s}|name:${n}`),i&&a.push(`${s}|id:${i}`),a.length===0&&a.push(`${s}|anonymous`),a}function Em(t,s){const a=[t.riskLevel,s.riskLevel].includes("High")?"High":[t.riskLevel,s.riskLevel].includes("Medium")?"Medium":"Low";return{...t,lrn:t.lrn||s.lrn,classSectionId:t.classSectionId??s.classSectionId,avgQuizScore:s.avgQuizScore>0?s.avgQuizScore:t.avgQuizScore,engagementScore:s.engagementScore>0?s.engagementScore:t.engagementScore,weakestTopic:t.weakestTopic&&t.weakestTopic!=="Foundational Skills"?t.weakestTopic:s.weakestTopic,riskLevel:a}}function wl(t,s){const a=new Map,r=new Map,o=s?vl(s):"all";return t.forEach(n=>{const i=_m(n,o),l=i.map(m=>r.get(m)).find(Boolean)||i[0],c=a.get(l),d=c?Em(c,n):n;a.set(l,d),i.forEach(m=>r.set(m,l))}),Array.from(a.values())}function Go(t,s){return wl([...t,...s])}function sa(t){return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function Rm(t){if(!t)return null;const s="gen-math",a=Qn.find(i=>i.id===s)?.modules||[];if(a.length===0)return null;const r={mastery:0,concept:0,application:0,engagement:0,consistency:0},o=t.lessons??{};a.forEach(i=>{const l=Qn.find(N=>N.modules.some(w=>w.id===i.id)),c=l?t?.subjects?.[l.id]?.modulesProgress?.[i.id]:null,d=sa(c?.progress||0),m=i.lessons.length?i.lessons.reduce((N,w)=>{const g=o?.[w.id]?.score;if(typeof g=="number"&&Number.isFinite(g))return N+sa(g);const I=!!c?.lessonsCompleted?.includes?.(w.id);return N+(I?100:0)},0)/i.lessons.length:0,p=i.quizzes.length?(c?.quizzesCompleted?.length||0)/i.quizzes.length*100:0,h=sa(m),v=sa(p),y=sa(Math.min(100,(h+v*2)/1.5)),S=sa(Math.min(100,40+d*.6));r.mastery+=d,r.concept+=h,r.application+=v,r.engagement+=y,r.consistency+=S});const n=a.length;return{mastery:Math.round(r.mastery/n),concept:Math.round(r.concept/n),application:Math.round(r.application/n),engagement:Math.round(r.engagement/n),consistency:Math.round(r.consistency/n)}}const Qo={advanced:{bg:"bg-emerald-100",text:"text-emerald-700",bar:"bg-emerald-500"},proficient:{bg:"bg-sky-100",text:"text-sky-700",bar:"bg-sky-500"},developing:{bg:"bg-rose-100",text:"text-rose-700",bar:"bg-rose-500"},beginner:{bg:"bg-red-100",text:"text-red-700",bar:"bg-red-500"}},Fr=[{key:"mastery",short:"M",label:"Overall Mastery",header:"Mastery"},{key:"concept",short:"C",label:"Concept Grasp",header:"Concept"},{key:"application",short:"A",label:"Application",header:"Applications"},{key:"consistency",short:"S",label:"Consistency",header:"Consistency"}],Mm=({classSectionId:t,className:s,fallbackStudents:a=[],onBack:r,onOpenNotifications:o,onOpenProfile:n,insightDismissed:i,onOpenInsightModal:l})=>{const{currentUser:c,userProfile:d}=vs(),m=u.useRef(0),[p,h]=u.useState([]),[v,y]=u.useState(!0),[S,N]=u.useState(""),[w,g]=u.useState("riskLevel"),[I,L]=u.useState("desc"),[A,W]=u.useState("all"),[f,C]=u.useState([]),[b,F]=u.useState(!1),[U,k]=u.useState(""),[D,J]=u.useState(""),re=u.useCallback(M=>({id:M.id,lrn:M.lrn||void 0,name:M.name,email:M.email||"",avatar:Ja(M.gender),classSectionId:M.classSectionId??null,riskLevel:M.riskLevel||"Low",engagementScore:M.engagementScore,avgQuizScore:M.avgQuizScore,weakestTopic:M.weakestTopic||"Foundational Skills"}),[]),ce=u.useCallback(M=>({id:M.id,lrn:M.lrn,name:M.name,email:M.email||"",avatar:M.avatar&&!M.avatar.includes("ui-avatars.com")?M.avatar:Ja(M.gender),classSectionId:M.classSectionId??null,riskLevel:String(M.riskLevel).charAt(0).toUpperCase()+String(M.riskLevel).slice(1).toLowerCase(),engagementScore:Number(M.engagementScore)||0,avgQuizScore:Number(M.avgQuizScore??M.avgScore??0)||0,weakestTopic:M.weakestTopic||"Foundational Skills",accountUid:M.accountUid}),[]),ie=u.useCallback(async(M,q)=>{const Q=new Map,pe=new Map;M.forEach(j=>Q.set(j.id,null));const $=25;for(let j=0;j{const me=V.accountUid||V.id;try{const oe=await Gr(me),ae=oe?.averageScore||0;return{studentId:V.id,summary:Rm(oe),avgScore:ae}}catch{return{studentId:V.id,summary:null,avgScore:0}}}))).forEach((V,me)=>{const oe=T[me]?.id;oe&&(V.status==="fulfilled"?(Q.set(oe,V.value.summary),V.value.avgScore>0&&pe.set(oe,V.value.avgScore)):Q.set(oe,null))})}m.current===q&&h(j=>j.map(T=>{if(!Q.has(T.student.id))return T;const _=pe.get(T.student.id);return{...T,student:_!=null&&_>T.student.avgQuizScore?{...T.student,avgQuizScore:Math.round(_)}:T.student,competencyMatrix:Q.get(T.student.id)??null,competencyMatrixLoading:!1}}))},[]),fe=u.useCallback(async()=>{if(c?.uid){y(!0),J("");try{let q=(await yn(c.uid)).map(j=>({id:j.id,name:j.name,email:j.email||"",avatar:j.avatar&&!j.avatar.includes("ui-avatars.com")?j.avatar:Ja(j.gender),classSectionId:j.classSectionId??null,riskLevel:j.riskLevel,engagementScore:Number(j.engagementScore)||0,avgQuizScore:Number(j.avgQuizScore)||0,weakestTopic:j.weakestTopic||"Foundational Skills",accountUid:j.accountUid}));a.length>0&&(q=Go(q,a.map(ce))),t&&(q=q.filter(j=>j.classSectionId===t));const Q=await xt.getImportedClassOverview({classSectionId:t,limit:3e3});Q.warnings.length>0&&J(Q.warnings.join(" ")),q=Go(q,Q.students.map(re));const pe=wl(q,t),$=m.current+=1;h(pe.map((j,T)=>({rowKey:`${Uo(j)}|row:${T}`,student:j,competency:null,competencyMatrix:null,competencyMatrixLoading:!0,loading:!1,expanded:!1}))),ie(pe,$)}catch(M){if(console.error("Failed to load students:",M),a.length>0){const q=a.map(ce).filter(Q=>!t||Q.classSectionId===t).map((Q,pe)=>({rowKey:`${Uo(Q)}|row:${pe}`,student:Q,competency:null,competencyMatrix:null,competencyMatrixLoading:!1,loading:!1,expanded:!1}));h(q),J("Showing recently imported students while backend roster sync catches up.")}else h([]),J("Student competency roster is unavailable right now.")}finally{y(!1)}}},[t,c?.uid,a,ie,ce,re]);u.useEffect(()=>{fe()},[fe]),u.useEffect(()=>{(async()=>{if(!t){C([]),k("");return}F(!0),k("");try{const q=await xt.getCourseMaterialTopics({classSectionId:t,limit:20}),Q=(q.topics||[]).filter(pe=>pe.title?.trim());C(Q),q.warnings.length>0&&k(q.warnings.join(" "))}catch{C([]),k("Imported topic context is unavailable right now.")}finally{F(!1)}})()},[t]);const Ce=async M=>{h(q=>q.map(Q=>{if(Q.rowKey!==M)return Q;const pe=!Q.expanded,$=Q.student.id,j={weakestTopic:Q.student.weakestTopic,avgQuizScore:Q.student.avgQuizScore};return pe&&!Q.competency&&!Q.loading?(ue(M,$,j),{...Q,expanded:!0,loading:!0}):{...Q,expanded:pe}}))},ue=async(M,q,Q)=>{try{const $=((await Gr(q))?.quizAttempts??[]).map(T=>({topic:T.quizId,score:T.score,total:100,timeTaken:T.timeSpent})),j=await xt.getStudentCompetency(q,$.length>0?$:void 0);h(T=>T.map(_=>_.rowKey===M?{..._,competency:j,loading:!1}:_))}catch{const $=Q.avgQuizScore||50,j={studentId:q,competencies:[{topic:Q.weakestTopic||"Unknown",efficiencyScore:Math.max(15,$-20),competencyLevel:$<50?"beginner":"developing",perspective:`Student needs focused practice in ${Q.weakestTopic}.`},{topic:"Functions and Relations",efficiencyScore:Math.min(95,$+10),competencyLevel:$>70?"proficient":"developing",perspective:"Shows solid understanding of function concepts."},{topic:"Problem Solving",efficiencyScore:$,competencyLevel:$>80?"advanced":$>60?"proficient":"developing",perspective:"Applies mathematical reasoning consistently."}],recommendedTopics:[Q.weakestTopic||"Review fundamentals"],excludeTopics:[]};h(T=>T.map(_=>_.rowKey===M?{..._,competency:j,loading:!1}:_))}},ge=M=>{w===M?L(q=>q==="asc"?"desc":"asc"):(g(M),L("asc"))},B={High:0,Medium:1,Low:2},te=p.filter(M=>{if(A!=="all"&&M.student.riskLevel!==A)return!1;if(S){const q=S.toLowerCase();return M.student.name.toLowerCase().includes(q)||M.student.email.toLowerCase().includes(q)}return!0}).sort((M,q)=>{let Q=0;switch(w){case"name":Q=M.student.name.localeCompare(q.student.name);break;case"avgQuizScore":Q=M.student.avgQuizScore-q.student.avgQuizScore;break;case"riskLevel":Q=B[M.student.riskLevel]-B[q.student.riskLevel];break;case"engagementScore":Q=M.student.engagementScore-q.student.engagementScore;break}return I==="asc"?Q:-Q}),ne=p.length,ze=p.filter(M=>M.student.riskLevel==="High").length,Fe=ne>0?Math.round(p.reduce((M,q)=>M+(Number(q.student.avgQuizScore)||0),0)/ne):0,Pe=ne>0?Math.round(p.reduce((M,q)=>M+(Number(q.student.engagementScore)||0),0)/ne):0,G=Array.from(new Set(f.map(M=>M.title).filter(Boolean))).slice(0,10),se=({field:M})=>w!==M?e.jsx(Ot,{size:14,className:"text-white/40"}):I==="asc"?e.jsx(Ia,{size:14,className:"text-white font-bold"}):e.jsx(Ot,{size:14,className:"text-white font-bold"});return v?e.jsxs("div",{className:"flex items-center justify-center py-20 p-6",children:[e.jsx(gt,{size:32,className:"animate-spin text-[var(--primary)]"}),e.jsx("span",{className:"ml-3 text-muted-foreground",children:"Loading student data..."})]}):e.jsxs(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-6 space-y-6",children:[r&&e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsxs("button",{onClick:r,className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors bg-white/60 hover:bg-white/80 px-[18px] py-2 rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50",children:[e.jsx($s,{className:"w-4 h-4"}),"Back to Classes"]})}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-[16px] mb-6",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-[16px] p-5 shadow-[0_4px_12px_rgba(168,85,247,0.2)] hover:shadow-[0_8px_24px_rgba(168,85,247,0.3)] hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between group text-white",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-2",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Total Students"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(On,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:ne}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3 mt-auto",children:e.jsx("span",{className:"text-[12px] font-medium text-white/90",children:"Evaluated in this class"})})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f97316] to-[#ea580c] rounded-[16px] p-5 shadow-[0_4px_12px_rgba(249,115,22,0.2)] hover:shadow-[0_8px_24px_rgba(249,115,22,0.3)] hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between group text-white",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-2",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"At-Risk Students"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(da,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:ze}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3 mt-auto",children:e.jsx("span",{className:"text-[12px] font-medium text-white/90",children:"Need immediate intervention"})})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#0ea5e9] to-[#0284c7] rounded-[16px] p-5 shadow-[0_4px_12px_rgba(14,165,233,0.2)] hover:shadow-[0_8px_24px_rgba(14,165,233,0.3)] hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between group text-white",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-2",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Class Average"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(Ds,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:[Fe,"%"]}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3 mt-auto",children:e.jsx("span",{className:"text-[12px] font-medium text-white/90",children:"Vs. expected benchmark"})})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#10b981] to-[#059669] rounded-[16px] p-5 shadow-[0_4px_12px_rgba(16,185,129,0.2)] hover:shadow-[0_8px_24px_rgba(16,185,129,0.3)] hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between group text-white",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-[1.8] group-hover:-translate-y-4 group-hover:-translate-x-4"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-2",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Avg. Engagement"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(ca,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:[Pe,"%"]}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3 mt-auto",children:e.jsx("span",{className:"text-[12px] font-medium text-white/90",children:"Activity completion rate"})})]})]}),e.jsx("div",{className:"sticky top-0 z-30 py-4 -my-4 bg-[#f8fafc]/80 backdrop-blur-[16px] border-b border-slate-200/50 shadow-[0_4px_20px_rgba(0,0,0,0.02)] px-2 sm:-mx-6 sm:px-6 mb-6 rounded-b-[18px]",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 w-full md:w-auto items-center",children:[e.jsxs("div",{className:"flex items-center bg-white px-4 py-2.5 rounded-full shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#e2e8f0] group focus-within:ring-2 focus-within:ring-indigo-500/20 transition-all w-full sm:w-64",children:[e.jsx(Xs,{className:"w-4 h-4 text-[#64748b] shrink-0 group-focus-within:text-[#9956DE] transition-colors"}),e.jsx("input",{type:"text",placeholder:"Search students...",value:S,onChange:M=>N(M.target.value),className:"bg-transparent border-none focus:outline-none ml-2 text-[13px] w-full text-[#475569] placeholder:text-[#94a3b8]"})]}),e.jsx("div",{className:"flex items-center gap-2 overflow-x-auto no-scrollbar w-full sm:w-auto p-2 -m-2",children:["all","High","Medium","Low"].map(M=>e.jsx("button",{onClick:()=>W(M),className:`px-4 py-1.5 text-[13px] font-semibold rounded-full whitespace-nowrap transition-colors shadow-md ${A===M?"bg-[#9956DE] text-white":"bg-white text-slate-500 hover:text-slate-700 hover:bg-slate-50"}`,children:M==="all"?"All":`${M} Risk`},M))})]}),e.jsxs("button",{onClick:fe,className:"flex items-center gap-2 text-[13px] font-semibold text-slate-500 hover:text-slate-700 transition-colors shrink-0 bg-white px-4 py-2 rounded-full shadow-md hover:bg-slate-50 self-end sm:self-auto",children:[e.jsx(xs,{className:"w-4 h-4"})," Refresh"]})]})}),e.jsxs("div",{className:"bg-[#f5f3ff]/60 border border-[#e0e7ff] rounded-[14px] px-5 py-3 mb-6 flex items-start sm:items-center gap-3",children:[e.jsx("div",{className:"mt-0.5 sm:mt-0 shrink-0",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-[#9956DE]",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 16v-4"}),e.jsx("path",{d:"M12 8h.01"})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center flex-1",children:[e.jsxs("span",{className:"text-[#9956DE] font-semibold text-[13px] whitespace-nowrap mr-1",children:["Imported Topic Context",s?` for ${s}`:"",":"]}),b?e.jsx("span",{className:"text-[#8b5cf6] text-[13px]",children:"Loading class-scoped imported topics..."}):G.length>0?e.jsx("div",{className:"flex flex-wrap items-center gap-1.5 mt-1 sm:mt-0",children:G.map((M,q)=>e.jsxs(he.Fragment,{children:[e.jsx("span",{className:"text-[#8b5cf6] text-[13px]",children:M}),qge("name"),children:["Student ",e.jsx(se,{field:"name"})]}),e.jsxs("div",{className:"w-[120px] shrink-0 px-4 flex justify-center cursor-pointer hover:text-white/80 transition-colors",onClick:()=>ge("riskLevel"),children:["Risk Level ",e.jsx(se,{field:"riskLevel"})]}),e.jsxs("div",{className:"w-[200px] shrink-0 px-4 flex items-center gap-1 cursor-pointer hover:text-white/80 transition-colors",onClick:()=>ge("avgQuizScore"),children:["Avg. Score ",e.jsx(se,{field:"avgQuizScore"})]}),e.jsxs("div",{className:"w-[180px] shrink-0 px-4 flex items-center gap-1 cursor-pointer hover:text-white/80 transition-colors",onClick:()=>ge("engagementScore"),children:["Engagement ",e.jsx(se,{field:"engagementScore"})]}),e.jsx("div",{className:"w-[160px] shrink-0 px-4 flex justify-center cursor-pointer hover:text-white/80 transition-colors",children:"Weakest Topic"}),Fr.map((M,q)=>e.jsx("div",{className:`w-[100px] shrink-0 px-2 flex justify-center ${q===Fr.length-1?"border-r border-transparent":""}`,children:M.header},M.key))]}),te.length===0?e.jsxs("div",{className:"py-12 text-center text-slate-500",children:[e.jsx(On,{size:32,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No students match the current filters"})]}):e.jsx("div",{className:"divide-y divide-border",children:te.map(M=>(M.student.riskLevel==="High"||M.student.riskLevel,e.jsxs("div",{className:"flex flex-col border-b border-slate-100 group",children:[e.jsxs("div",{className:"flex items-center min-h-[64px] hover:bg-slate-50/60 transition-colors cursor-pointer relative",onClick:()=>void Ce(M.rowKey),children:[e.jsxs("div",{className:"w-[260px] shrink-0 sticky left-0 z-10 bg-white group-hover:bg-slate-50/90 transition-colors px-5 h-full min-h-[64px] flex items-center border-r border-slate-100 shadow-[2px_0_4px_rgba(0,0,0,0.01)]",children:[e.jsx("div",{className:`transition-transform duration-200 mr-3 shrink-0 ${M.expanded?"rotate-90":""}`,children:e.jsx(zs,{className:"w-4 h-4 text-slate-400"})}),e.jsx("img",{src:M.student.avatar,alt:M.student.name,className:"w-8 h-8 rounded-full bg-border object-cover shrink-0 mr-3"}),e.jsx("span",{className:"font-semibold text-slate-800 text-[14px] truncate",children:M.student.name})]}),e.jsx("div",{className:"w-[120px] shrink-0 px-4 flex justify-center",children:e.jsx("span",{className:`px-3 py-1 rounded-full border text-[11px] font-bold uppercase tracking-wider ${M.student.riskLevel==="High"?"bg-rose-50 text-rose-600 border-rose-200":M.student.riskLevel==="Medium"?"bg-amber-50 text-amber-600 border-amber-200":"bg-emerald-50 text-emerald-600 border-emerald-200"}`,children:M.student.riskLevel})}),e.jsxs("div",{className:"w-[200px] shrink-0 px-4 flex items-center gap-3",children:[e.jsx("div",{className:"flex-1 bg-slate-100 h-2.5 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${M.student.avgQuizScore>=80?"bg-emerald-500":M.student.avgQuizScore>=60?"bg-amber-400":"bg-rose-500"}`,style:{width:`${M.student.avgQuizScore}%`}})}),e.jsxs("span",{className:"text-[13px] font-bold text-slate-800 w-8",children:[M.student.avgQuizScore,"%"]})]}),e.jsxs("div",{className:"w-[180px] shrink-0 px-4 flex items-center gap-3",children:[e.jsx("div",{className:"flex-1 bg-slate-100 h-2.5 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[#9956DE]",style:{width:`${M.student.engagementScore}%`}})}),e.jsxs("span",{className:"text-[13px] font-bold text-slate-800 w-8",children:[M.student.engagementScore,"%"]})]}),e.jsx("div",{className:"w-[160px] shrink-0 px-4 flex justify-center",children:e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-600 text-[11px] font-medium rounded-full truncate max-w-full border border-slate-200",children:M.student.weakestTopic})}),Fr.map(q=>{const Q=M.competencyMatrix?.[q.key]??0;return e.jsx("div",{className:"w-[100px] shrink-0 px-2 flex justify-center",children:M.competencyMatrixLoading?e.jsx(gt,{size:12,className:"animate-spin text-muted-foreground"}):M.competencyMatrix?e.jsxs("span",{className:`text-[12px] font-medium px-2 rounded-full border ${Q>=80?"text-emerald-600 bg-emerald-50 border-emerald-100":Q>=60?"text-amber-600 bg-amber-50 border-amber-100":"text-rose-500 bg-rose-50 border-rose-100"}`,children:[Q,"%"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})},q.key)})]}),e.jsx(zt,{children:M.expanded&&e.jsx(Re.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden bg-slate-50/80 border-t border-slate-100 shadow-inner",children:e.jsxs("div",{className:"flex min-w-[1320px]",children:[e.jsx("div",{className:"w-[260px] shrink-0 sticky left-0 z-10 bg-slate-50/90 border-r border-slate-100 flex items-start justify-end pr-4 py-4",children:e.jsx("div",{className:"w-1.5 h-full rounded-full bg-[#9956DE]/30"})}),e.jsx("div",{className:"flex-1 py-4 pl-6 pr-6",children:M.loading?e.jsxs("div",{className:"flex items-center py-4",children:[e.jsx(gt,{size:16,className:"animate-spin text-indigo-500 mr-2"}),e.jsx("span",{className:"text-sm text-slate-500",children:"Analyzing competency data..."})]}):M.competency?e.jsxs("div",{className:"space-y-4 max-w-4xl",children:[M.competency.recommendedTopics.length>0&&e.jsxs("div",{className:"bg-[#f5f3ff] rounded-[12px] p-4 border border-[#e0e7ff] inline-block shadow-sm mb-4",children:[e.jsxs("h4",{className:"text-[#7274ED] font-semibold text-[13px] flex items-center gap-2 mb-1.5",children:[e.jsx(Vt,{className:"w-4 h-4"})," Recommended Focus Areas"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2",children:M.competency.recommendedTopics.map((q,Q)=>e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full border border-indigo-100 bg-white text-indigo-700 text-xs font-medium shadow-sm",children:q},Q))})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:M.competency.competencies.map((q,Q)=>e.jsx(Am,{competency:q},Q))})]}):e.jsx("div",{className:"text-sm text-slate-500 py-4",children:"Failed to load competency details."})})]})})})]},M.rowKey)))})]})})]})},Am=({competency:t})=>{const s=Qo[t.competencyLevel]||Qo.developing;return e.jsxs("div",{className:"bg-card rounded-lg border border-border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h6",{className:"text-xs font-bold text-foreground truncate flex-1",children:t.topic}),e.jsx("span",{className:`ml-2 px-2 py-0.5 rounded text-[10px] font-bold uppercase ${s.bg} ${s.text}`,children:t.competencyLevel})]}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-slate-500",children:"Efficiency"}),e.jsxs("span",{className:"font-bold text-muted-foreground",children:[t.efficiencyScore,"%"]})]}),e.jsx("div",{className:"h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx(Re.div,{initial:{width:0},animate:{width:`${t.efficiencyScore}%`},transition:{duration:.6,delay:.1},className:`h-full rounded-full ${s.bar}`})})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug line-clamp-2",children:t.perspective})]})},zm=()=>{const{notifications:t,unreadCount:s,isLoading:a,markAsRead:r,markAllAsRead:o}=fi(),[n,i]=u.useState("all"),l=["streak_reminder","daily_checkin","streak_milestone","achievement_unlocked","level_up","xp_earned","quiz_result"],c=t.filter(y=>!y.isRead&&!l.includes(y.type)).length,d=y=>{switch(y){case"achievement_unlocked":case"achievement":return Ul;case"message":return sc;case"grade":case"quiz_result":return pi;case"reminder":case"streak_reminder":case"daily_checkin":return Ls;case"risk_alert":return da;case"sparkles":case"lesson_plan_ready":return bs;case"users":case"student_import":return hs;default:return dr}},m=(y,S)=>{switch(y){case"risk_alert":return"bg-rose-50/30 text-rose-500 border-rose-100";case"sparkles":case"lesson_plan_ready":return"bg-purple-50/30 text-[#a855f7] border-purple-100";case"daily_checkin":return"bg-amber-50/20 text-amber-500 border-amber-100";case"users":case"student_import":return"bg-blue-50/30 text-blue-500 border-blue-100";default:return"bg-slate-50 text-slate-500 border-slate-100"}},p=y=>{switch(y){case"risk_alert":return"from-rose-400 to-rose-600 shadow-[0_4px_12px_rgba(244,63,94,0.3)]";case"sparkles":case"lesson_plan_ready":return"from-[#a855f7] to-[#9333ea] shadow-[0_4px_12px_rgba(168,85,247,0.3)]";case"daily_checkin":return"from-amber-300 to-amber-500 shadow-[0_4px_12px_rgba(245,158,11,0.3)]";case"users":case"student_import":return"from-blue-400 to-blue-600 shadow-[0_4px_12px_rgba(59,130,246,0.3)]";default:return"from-slate-400 to-slate-600 shadow-[0_4px_12px_rgba(100,116,139,0.3)]"}},h=u.useMemo(()=>{let y=t.filter(S=>!l.includes(S.type));return n==="unread"&&(y=y.filter(S=>!S.isRead)),n==="important"&&(y=y.filter(S=>S.type==="risk_alert")),y},[t,n]),v=u.useMemo(()=>{const y=[],S=h.filter(g=>ro(g.createdAt)),N=h.filter(g=>no(g.createdAt)),w=h.filter(g=>!ro(g.createdAt)&&!no(g.createdAt));return S.length>0&&y.push({title:"Today",icon:Ls,items:S}),N.length>0&&y.push({title:"Yesterday",icon:Vn,items:N}),w.length>0&&y.push({title:"Earlier",icon:Vn,items:w}),y},[h]);return e.jsx("div",{className:"w-full h-full flex flex-col bg-[#f8fafc]/50",children:e.jsxs("div",{className:"max-w-[900px] mx-auto w-full p-[24px] xl:p-[32px] space-y-[24px] flex-1 overflow-y-auto no-scrollbar pb-12",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("button",{onClick:()=>i("all"),className:`px-6 py-2.5 text-[13px] rounded-full whitespace-nowrap transition-all duration-300 border ${n==="all"?"bg-purple-50 text-[#9333ea] border-purple-200 shadow-md font-bold":"bg-white/80 text-[#64748b] border-white hover:border-[#e2e8f0] shadow-sm font-medium"}`,children:"All"}),e.jsxs("button",{onClick:()=>i("unread"),className:`px-6 py-2.5 text-[13px] rounded-full whitespace-nowrap transition-all duration-300 border flex items-center gap-2 ${n==="unread"?"bg-purple-50 text-[#9333ea] border-purple-200 shadow-md font-bold":"bg-white/80 text-[#64748b] border-white hover:border-[#e2e8f0] shadow-sm font-medium"}`,children:["Unread",e.jsx("span",{className:"w-5 h-5 rounded-full bg-slate-100 text-[10px] font-bold flex items-center justify-center text-slate-500",children:c})]}),e.jsxs("button",{onClick:()=>i("important"),className:`px-6 py-2.5 text-[13px] rounded-full whitespace-nowrap transition-all duration-300 border flex items-center gap-2 ${n==="important"?"bg-purple-50 text-[#9333ea] border-purple-200 shadow-md font-bold":"bg-white/80 text-[#64748b] border-white hover:border-[#e2e8f0] shadow-sm font-medium"}`,children:["Important",t.some(y=>y.type==="risk_alert"&&!y.isRead)&&e.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-rose-500 shadow-[0_0_8px_rgba(244,63,94,0.6)]"})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-3 shrink-0",children:[e.jsx("span",{className:"text-[13px] font-bold text-[#64748b]",children:c>0?`${c} unread`:"No unread"}),e.jsxs("button",{onClick:o,disabled:c===0,className:"bg-white hover:bg-slate-50 border border-slate-200 text-[#475569] text-[13px] font-bold rounded-full px-5 py-2 shadow-sm transition-all hover:shadow-md hover:-translate-y-0.5 flex items-center gap-2 group disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:translate-y-0 disabled:hover:shadow-sm",children:[e.jsx(Ec,{className:"w-4 h-4 text-[#94a3b8] group-hover:text-emerald-500 transition-colors"}),"Mark all as read"]})]})]}),e.jsx("div",{className:"space-y-8",children:a?e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] border border-white p-12 flex flex-col items-center justify-center gap-4",children:[e.jsx(gt,{className:"w-8 h-8 text-[#a855f7] animate-spin"}),e.jsx("p",{className:"text-[14px] font-medium text-[#64748b]",children:"Syncing notifications..."})]}):v.length===0?e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] border border-white p-16 flex flex-col items-center justify-center text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-slate-50 rounded-full flex items-center justify-center mb-6 border border-slate-100",children:e.jsx(dr,{className:"w-10 h-10 text-slate-300"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:"All clear!"}),e.jsx("p",{className:"text-[14px] text-[#64748b] max-w-sm",children:"No notifications found for this filter. New alerts will appear here automatically."})]}):v.map(y=>e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[12px] font-bold text-[#94a3b8] uppercase tracking-wider mb-3 ml-2 flex items-center gap-2",children:[e.jsx(y.icon,{className:"w-4 h-4"})," ",y.title]}),e.jsx("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] border border-white shadow-[0_4px_24px_rgba(0,0,0,0.03)] overflow-hidden divide-y divide-[#f1f5f9]",children:y.items.map(S=>{const N=d(S.type),w=S.type==="risk_alert";return e.jsxs(Re.div,{layout:!0,onClick:()=>!S.isRead&&r(S.id),className:`relative p-5 flex gap-5 group cursor-pointer hover:bg-white transition-all duration-300 ${S.isRead?"opacity-80":m(S.type)}`,children:[e.jsx("div",{className:`absolute left-0 top-0 w-1.5 h-full transition-colors ${S.isRead?"bg-transparent":w?"bg-rose-500":"bg-[#a855f7]"}`}),e.jsx("div",{className:`w-12 h-12 rounded-full flex items-center justify-center text-white shrink-0 group-hover:scale-110 transition-transform bg-gradient-to-br ${p(S.type)}`,children:e.jsx(N,{className:"w-6 h-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex justify-between items-start mb-1",children:[e.jsxs("h4",{className:"text-[15px] font-bold text-[#1e293b] flex items-center gap-2 truncate pr-4",children:[S.title,!S.isRead&&e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${w?"bg-rose-500 shadow-[0_0_6px_rgba(244,63,94,0.8)]":"bg-[#a855f7] shadow-[0_0_6px_rgba(168,85,247,0.8)]"}`})]}),e.jsxs("span",{className:`text-[12px] font-bold whitespace-nowrap ${S.isRead?"text-[#94a3b8]":w?"text-rose-600":"text-[#a855f7]"}`,children:[Rc(S.createdAt)," ago"]})]}),e.jsx("p",{className:"text-[14px] text-[#475569] font-medium leading-relaxed",children:S.message}),!S.isRead&&S.actionUrl&&e.jsx("div",{className:"mt-3 flex gap-2",children:e.jsx("button",{className:`px-5 py-2 bg-white border rounded-full text-[12px] font-bold shadow-sm transition-all hover:-translate-y-0.5 ${w?"border-rose-200 text-rose-600 hover:bg-rose-50":"border-purple-200 text-[#9333ea] hover:bg-purple-50"}`,children:"Review Plan"})})]}),e.jsx("button",{className:"opacity-0 group-hover:opacity-100 p-2 text-slate-400 hover:text-slate-600 transition-all rounded-full hover:bg-slate-100 shrink-0 self-start",children:e.jsx(qc,{size:18})})]},S.id)})})]},y.title))})]})})},Lm=t=>{const s=t.data(),a=s.startTime,r=s.endTime,o=s.createdAt,n=s.updatedAt,i=l=>{if(l){if(typeof l?.toDate=="function")return l.toDate();if(l instanceof Date)return l}};return{...s,id:t.id,startTime:i(a)||new Date,endTime:i(r),createdAt:i(o)||new Date,updatedAt:i(n)}},Dm=async(t,s)=>{const a=ct(St($e,"calendarEvents")),r={id:a.id,userId:t,title:s.title,description:s.description,startTime:s.startTime,endTime:s.endTime,color:s.color,createdAt:new Date};return await os(a,{...r,createdAt:it(),updatedAt:it()}),r},$m=async(t,s)=>{const a=ct($e,"calendarEvents",t);await ns(a,{...s,updatedAt:it()})},Fm=async t=>{await cn(ct($e,"calendarEvents",t))},Nl=(t,s={},a,r)=>{if(!t)return a([]),()=>{};const{limitCount:o=500}=s,n=kt(St($e,"calendarEvents"),Nt("userId","==",t),or(o));return gi(n,i=>{a(i.docs.map(l=>Lm(l)))},i=>{console.error("Error subscribing to calendar events:",i),r?.(i)})};function Om({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:xi("resize-none border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-input-background px-3 py-2 text-base transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),...s})}const na=t=>String(t).padStart(2,"0"),Ws=t=>`${t.getFullYear()}-${na(t.getMonth()+1)}-${na(t.getDate())}`,nn=t=>new Date(t.getFullYear(),t.getMonth(),1),Vo=t=>new Date(t.getFullYear(),t.getMonth()+1,0),Pm=t=>{const s=nn(t),a=s.getDay(),r=new Date(s);return r.setDate(s.getDate()-a),r.setHours(0,0,0,0),r},Bm=(t,s)=>{const a=new Date(t);return a.setDate(a.getDate()+s),a},Wo=(t,s)=>t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate(),Hm=(t,s)=>t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth(),Um=t=>t.toLocaleDateString(void 0,{month:"long",year:"numeric"}),qa=t=>t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),qo=(t,s)=>{const[a,r,o]=t.split("-").map(l=>parseInt(l,10)),[n,i]=s.split(":").map(l=>parseInt(l,10));return new Date(a,(r||1)-1,o||1,n||0,i||0,0,0)},Gm=["purple","blue","emerald","amber","rose"],Or=t=>{switch(t){case"blue":return"#3b82f6";case"emerald":return"#10b981";case"amber":return"#f59e0b";case"rose":return"#f43f5e";case"purple":default:return"#a855f7"}},Qm=(t,s=!1)=>{if(s)return"bg-blue-50 text-blue-700 border-blue-100 opacity-80";switch(t){case"blue":return"bg-blue-50 text-blue-700 border-blue-100 opacity-90 hover:bg-blue-100";case"emerald":return"bg-emerald-50 text-emerald-700 border-emerald-100 opacity-90 hover:bg-emerald-100";case"amber":return"bg-amber-50 text-amber-700 border-amber-100 opacity-90 hover:bg-amber-100";case"rose":return"bg-rose-50 text-rose-700 border-rose-100 opacity-90 hover:bg-rose-100";case"purple":default:return"bg-purple-50 text-purple-700 border-purple-100 opacity-90 hover:bg-purple-100"}},Vm=(t,s=!1)=>{if(s)return{dot:"bg-[#3b82f6]",border:"border-l-blue-400",time:"text-blue-600 border-blue-50"};switch(t){case"blue":return{dot:"bg-blue-500",border:"border-l-blue-400",time:"text-blue-600 border-blue-50"};case"emerald":return{dot:"bg-emerald-500",border:"border-l-emerald-400",time:"text-emerald-600 border-emerald-50"};case"amber":return{dot:"bg-amber-500",border:"border-l-amber-400",time:"text-amber-600 border-amber-50"};case"rose":return{dot:"bg-rose-500",border:"border-l-rose-400",time:"text-rose-600 border-rose-50"};case"purple":default:return{dot:"bg-[#a855f7]",border:"border-l-[#a855f7]",time:"text-[#a855f7] border-purple-50"}}},Pr=[{names:["sun","sunday"],day:0},{names:["mon","monday"],day:1},{names:["tue","tues","tuesday"],day:2},{names:["wed","wednesday"],day:3},{names:["thu","thurs","thursday"],day:4},{names:["fri","friday"],day:5},{names:["sat","saturday"],day:6}];function Wm(t){const s=t.toLowerCase(),a=new Set;if(s.includes("daily")||s.includes("everyday"))return[0,1,2,3,4,5,6];if(s.includes("weekends"))return[0,6];if(s.includes("weekdays"))return[1,2,3,4,5];const r=s.match(/(mon|tue|wed|thu|fri|sat|sun)[\s/-]*(mon|tue|wed|thu|fri|sat|sun)/);if(r){const o=Pr.find(i=>i.names.includes(r[1]))?.day,n=Pr.find(i=>i.names.includes(r[2]))?.day;if(o!==void 0&&n!==void 0){let i=o;for(;a.add(i),i!==n;)i=(i+1)%7;return Array.from(a)}}return Pr.forEach(({names:o,day:n})=>{o.some(i=>s.includes(i))&&a.add(n)}),Array.from(a).sort((o,n)=>o-n)}const qm=({classes:t,teacherId:s})=>{const{currentUser:a}=vs(),[r,o]=u.useState([]),[n,i]=u.useState(!0),[l,c]=u.useState(""),[d,m]=u.useState(!0),[p,h]=u.useState(()=>{const _=new Date;return _.setHours(0,0,0,0),_}),[v,y]=u.useState(()=>{const _=new Date;return _.setHours(0,0,0,0),_}),[S,N]=u.useState(new Set),[w,g]=u.useState(!1),[I,L]=u.useState(null),[A,W]=u.useState(!1),[f,C]=u.useState(""),[b,F]=u.useState(""),[U,k]=u.useState(()=>Ws(new Date)),[D,J]=u.useState("09:00"),[re,ce]=u.useState(""),[ie,fe]=u.useState("purple"),[Ce,ue]=u.useState(!1),[ge,B]=u.useState(null);u.useEffect(()=>{if(!a?.uid){o([]),i(!1);return}c(""),i(!0);const _=Nl(a.uid,{limitCount:500},V=>{o(V),i(!1)},()=>{c("Unable to load calendar events right now."),i(!1)});return()=>_()},[a?.uid]);const te=u.useMemo(()=>{const _=nn(p);return _.setHours(0,0,0,0),_},[p]),ne=u.useMemo(()=>{const _=Vo(p);return _.setHours(23,59,59,999),_},[p]),ze=u.useMemo(()=>{if(!t||t.length===0)return[];const _=[],V=nn(p),me=Vo(p),oe=new Date(V);for(;oe<=me;){const ae=oe.getDay();t.forEach(je=>{if(Wm(je.schedule).includes(ae)){const Ke=`schedule-${je.id}-${Ws(oe)}`;S.has(Ke)||_.push({id:Ke,userId:s||"",title:je.name,startTime:new Date(oe),createdAt:new Date})}}),oe.setDate(oe.getDate()+1)}return _},[t,p,s,S]),Fe=u.useMemo(()=>[...r,...ze],[r,ze]),Pe=u.useMemo(()=>Fe.filter(_=>_.startTime>=te&&_.startTime<=ne).sort((_,V)=>_.startTime.getTime()-V.startTime.getTime()),[Fe,te,ne]),G=u.useMemo(()=>{const _=new Map;for(const V of Pe){const me=Ws(V.startTime),oe=_.get(me)||[];oe.push(V),_.set(me,oe)}return _},[Pe]),se=u.useMemo(()=>Ws(v),[v]),M=u.useMemo(()=>[...G.get(se)||[]].sort((V,me)=>V.startTime.getTime()-me.startTime.getTime()),[G,se]),q=u.useMemo(()=>{const _=Pm(p);return Array.from({length:42}).map((V,me)=>Bm(_,me))},[p]),Q=_=>{const V=Ws(_);L(null),C(""),F(""),k(V),J("09:00"),ce(""),fe("purple"),g(!0)},pe=_=>{_.id.startsWith("schedule-")?(N(V=>new Set(V).add(_.id)),L(null)):L(_.id),C(_.title),F(_.description||""),k(Ws(_.startTime)),J(na(_.startTime.getHours())+":"+na(_.startTime.getMinutes())),ce(_.endTime?na(_.endTime.getHours())+":"+na(_.endTime.getMinutes()):""),fe(_.color||"purple"),ue(!1),g(!0)},$=(_,V)=>{_.stopPropagation(),B(V),ue(!0)},j=async()=>{const _=a?.uid||s||"local-user";if(!f.trim()){c("Event title is required.");return}W(!0),c("");const V=qo(U,D),me=re?qo(U,re):void 0,oe={title:f.trim(),description:b.trim()?b.trim():void 0,startTime:V,endTime:me&&me.getTime()>V.getTime()?me:void 0,color:ie};try{if(I)o(ae=>ae.map(je=>je.id===I?{...je,...oe}:je)),await $m(I,oe);else{const ae=`temp-${Date.now()}`;o(je=>[...je,{id:ae,userId:_,createdAt:new Date,...oe}]),await Dm(_,oe)}g(!1)}catch(ae){console.error(ae),g(!1)}finally{W(!1)}},T=async _=>{if(_.startsWith("schedule-")){N(V=>new Set(V).add(_)),ge?.id===_&&ue(!1);return}c(""),o(V=>V.filter(me=>me.id!==_)),ge?.id===_&&ue(!1);try{await Fm(_)}catch(V){console.error(V)}};return e.jsxs("div",{className:"w-full h-full flex flex-col px-[24px] xl:px-[32px] py-[24px] xl:py-[32px] overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 flex-1 min-h-0 w-full max-w-[1400px] mx-auto",children:[e.jsx("div",{className:`flex flex-col flex-1 min-w-0 transition-all duration-500 ${d?"lg:w-[65%] xl:w-[70%]":"lg:w-full"}`,children:e.jsxs("div",{className:"bg-white/90 backdrop-blur-[12px] rounded-[24px] border border-white shadow-[0_8px_32px_rgba(0,0,0,0.04)] overflow-hidden flex flex-col h-full",children:[e.jsxs("div",{className:"p-6 border-b border-[#a855f7] bg-[#a855f7] shrink-0 flex justify-between items-center rounded-t-[24px] relative overflow-hidden group",children:[e.jsx("div",{className:"absolute -bottom-24 -right-12 w-64 h-64 bg-white/10 rounded-full"}),e.jsx("div",{className:"absolute -top-20 left-1/4 w-40 h-40 bg-white/5 rounded-full"}),e.jsxs("div",{className:"flex items-center gap-5 relative z-10",children:[e.jsx("button",{onClick:()=>h(new Date(p.getFullYear(),p.getMonth()-1,1)),"aria-label":"Previous month",className:"w-9 h-9 rounded-full flex items-center justify-center text-[#6d28d9] bg-white hover:bg-slate-50 transition-colors shadow-sm hover:shadow-md active:scale-90",children:e.jsx($s,{className:"w-5 h-5"})}),e.jsx("h2",{className:"text-[22px] font-bold text-white w-44 text-center tracking-tight",children:Um(p)}),e.jsx("button",{onClick:()=>h(new Date(p.getFullYear(),p.getMonth()+1,1)),"aria-label":"Next month",className:"w-9 h-9 rounded-full flex items-center justify-center text-[#6d28d9] bg-white hover:bg-slate-50 transition-colors shadow-sm hover:shadow-md active:scale-90",children:e.jsx(zs,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"flex items-center gap-3 relative z-10",children:[e.jsxs("span",{className:"text-[13px] font-bold text-[#6d28d9] bg-white px-4 py-1.5 rounded-full shadow-sm",children:[Pe.length," events"]}),e.jsx("button",{onClick:()=>m(!d),className:`w-9 h-9 rounded-full flex items-center justify-center transition-all shadow-sm hover:shadow-md border ${d?"text-[#6d28d9] bg-white border-white":"text-white bg-white/20 border-white/30 backdrop-blur-md"}`,title:d?"Hide Sidebar":"Show Sidebar","aria-label":d?"Hide Sidebar":"Show Sidebar",children:e.jsx(td,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-h-0 overflow-y-auto custom-scrollbar",children:[e.jsx("div",{className:"grid grid-cols-7 text-center border-b border-slate-200/60 pb-5 shrink-0 sticky top-0 bg-white z-20 shadow-[0_10px_10px_-10px_rgba(0,0,0,0.05)] px-4 pt-6",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(_=>e.jsx("div",{className:"text-[12px] font-bold text-[#475569] uppercase tracking-widest",children:_},_))}),e.jsx("div",{className:"grid grid-cols-7 gap-2 pb-6 px-4",children:q.map(_=>{const V=Ws(_),me=G.get(V)||[],oe=Wo(_,v),ae=Wo(_,new Date),je=Hm(_,p);return e.jsxs("div",{onClick:()=>y(new Date(_)),className:`group p-2 rounded-lg transition-all cursor-pointer border-2 flex flex-col relative min-h-[100px] xl:min-h-[120px] ${oe?"bg-purple-50/50 border-[#a855f7] shadow-sm z-10":ae?"bg-purple-50/20 border-purple-300 shadow-[inset_0_0_20px_rgba(168,85,247,0.05)] hover:bg-purple-50/40 hover:border-purple-400":"border-transparent hover:bg-slate-50 hover:border-slate-200"} ${je?"":"opacity-30 grayscale"}`,children:[e.jsx("div",{className:"flex justify-between items-start",children:e.jsx("span",{className:`w-7 h-7 rounded-full flex items-center justify-center font-bold text-[14px] transition-all ${ae?"bg-gradient-to-br from-[#a855f7] to-[#9333ea] text-white shadow-md":oe?"text-[#9333ea]":"text-[#1e293b]"}`,children:_.getDate()})}),e.jsxs("div",{className:"mt-1 space-y-1",children:[me.slice(0,3).map(we=>{const Ke=we.id.startsWith("schedule-");return e.jsx("div",{onClick:Ue=>$(Ue,we),className:`w-full truncate text-[11px] font-bold px-2 py-1.5 rounded border shadow-sm transition-all hover:-translate-y-[1px] hover:shadow-md cursor-pointer ${Qm(we.color,Ke)}`,children:we.title},we.id)}),me.length>3&&e.jsxs("div",{className:"text-[10px] font-bold text-[#64748b] pl-1 pt-0.5",children:["+",me.length-3," more"]})]})]},V)})})]})]})}),e.jsx(zt,{children:d&&e.jsx(Re.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:"lg:w-[35%] xl:w-[30%] h-full shrink-0",children:e.jsxs("div",{className:"bg-white/90 backdrop-blur-[12px] rounded-[24px] border border-white shadow-[0_8px_32px_rgba(0,0,0,0.04)] overflow-hidden flex flex-col h-full",children:[e.jsxs("div",{className:"p-6 border-b border-[#f1f5f9] bg-white shrink-0 flex justify-between items-center relative overflow-hidden group",children:[e.jsx("div",{className:"absolute top-[-30px] right-[-30px] w-24 h-24 bg-purple-50 rounded-full mix-blend-multiply filter blur-2xl opacity-50 transition-transform duration-700 group-hover:scale-150"}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h2",{className:"text-[20px] font-bold text-[#1e293b]",children:v.toLocaleDateString(void 0,{weekday:"long"})}),e.jsx("p",{className:"text-[13px] font-medium text-[#64748b]",children:v.toLocaleDateString(void 0,{day:"numeric",month:"long",year:"numeric"})})]}),e.jsx("button",{onClick:()=>Q(v),title:"Add Event",className:"w-10 h-10 flex items-center justify-center rounded-full bg-[#a855f7] text-white hover:bg-[#9333ea] shadow-md shadow-purple-200 transition-all hover:scale-105 active:scale-95 relative z-10",children:e.jsx(ua,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar pb-12",children:M.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center opacity-40",children:[e.jsx(Er,{className:"w-12 h-12 text-slate-300 mb-4"}),e.jsx("p",{className:"text-[14px] font-bold text-[#1e293b]",children:"No events today"}),e.jsx("p",{className:"text-[12px] text-[#64748b]",children:"Schedule a meeting or add a class."})]}):M.map(_=>{const V=_.id.startsWith("schedule-"),me=Vm(_.color,V);return e.jsxs("div",{className:"relative pl-6 before:absolute before:left-2 before:top-2 before:bottom-[-24px] before:w-[2px] before:bg-slate-100 last:before:hidden",children:[e.jsx("div",{className:`absolute left-0 top-1.5 w-4 h-4 rounded-full border-[3px] border-white shadow-sm z-10 ${me.dot}`}),e.jsxs("div",{onClick:oe=>$(oe,_),className:`group relative bg-white border border-[#e2e8f0] rounded-[20px] p-5 shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all border-l-[6px] cursor-pointer ${me.border}`,children:[e.jsx("div",{className:"flex justify-between items-start mb-2",children:e.jsx("h4",{className:"text-[15px] font-bold text-[#1e293b] group-hover:text-[#9333ea] transition-colors break-words line-clamp-2 w-full pr-2",children:_.title})}),e.jsxs("div",{className:`flex items-center gap-2 text-[11px] font-bold bg-slate-50 w-max px-2.5 py-1 rounded-lg border mb-3 ${me.time}`,children:[e.jsx(Ls,{className:"w-3.5 h-3.5"})," ",e.jsxs("span",{children:[qa(_.startTime),_.endTime?` - ${qa(_.endTime)}`:""]})]}),_.description&&e.jsx("p",{className:"text-[13px] font-medium text-[#64748b] bg-slate-50/50 px-3 py-2 rounded-xl border border-slate-100/30 break-words whitespace-normal w-full overflow-hidden",children:_.description})]})]},_.id)})})]})})})]}),e.jsx(Wn,{open:w,onOpenChange:g,children:e.jsx(qn,{className:"sm:max-w-[500px] p-0 overflow-hidden rounded-[28px] border-none shadow-2xl [&>button]:hidden",children:e.jsxs("div",{className:"p-8 bg-white",children:[e.jsxs(Mc,{className:"mb-6",children:[e.jsx(Ac,{className:"text-[24px] font-bold text-[#1e293b] tracking-tight",children:I?"Edit Event":"Add New Event"}),e.jsx(zc,{className:"text-[14px] text-[#64748b]",children:"Schedule a classroom activity or reminder."})]}),l&&e.jsx("p",{className:"text-rose-500 text-sm font-semibold mb-4",children:l}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] ml-1",children:"Event Title"}),e.jsx(_s,{value:f,onChange:_=>C(_.target.value),placeholder:"e.g., Mathematics Quiz - Grade 11",className:"bg-white border-slate-200 focus:border-[#a855f7] focus:ring-4 focus:ring-purple-50 rounded-xl h-12 px-4 transition-all text-[14px]"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] ml-1",children:"Date"}),e.jsx(_s,{type:"date",value:U,onChange:_=>k(_.target.value),className:"bg-white border-slate-200 focus:border-[#a855f7] rounded-xl h-12 px-4 text-[14px]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] ml-1",children:"Start Time"}),e.jsx(_s,{type:"time",value:D,onChange:_=>J(_.target.value),className:"bg-white border-slate-200 focus:border-[#a855f7] rounded-xl h-12 px-4 text-[14px]"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] ml-1",children:"Notes (Optional)"}),e.jsx(Om,{value:b,onChange:_=>F(_.target.value),placeholder:"Additional details about this event...",className:"bg-white border-slate-200 focus:border-[#a855f7] rounded-xl min-h-[100px] p-4 transition-all text-[14px] break-all"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("label",{className:"text-[13px] font-bold text-[#1e293b] ml-1",children:"Color Theme"}),e.jsx("div",{className:"flex gap-3 ml-1",children:Gm.map(_=>e.jsx("button",{onClick:()=>fe(_),className:`w-8 h-8 rounded-full flex items-center justify-center transition-all ${ie===_?"ring-2 ring-offset-2 ring-slate-800 scale-110 shadow-sm":"hover:scale-110 opacity-80 hover:opacity-100"}`,style:{backgroundColor:Or(_)},title:_,children:ie===_&&e.jsx(Gt,{className:"w-4 h-4 text-white"})},_))})]})]}),e.jsxs("div",{className:"flex gap-3 mt-8",children:[e.jsx(wt,{variant:"outline",onClick:()=>g(!1),className:"flex-1 h-12 rounded-xl font-bold border-slate-200 hover:bg-slate-100 transition-all text-[14px]",children:"Cancel"}),e.jsx(wt,{onClick:j,disabled:A,className:"flex-[1.5] h-12 rounded-xl font-bold bg-[#a855f7] hover:bg-[#9333ea] text-white shadow-lg shadow-purple-200 transition-all hover:scale-[1.02] text-[14px]",children:A?e.jsx(gt,{className:"w-5 h-5 animate-spin"}):"Save Event"})]})]})})}),e.jsx(Wn,{open:Ce,onOpenChange:ue,children:e.jsx(qn,{className:"sm:max-w-[400px] p-0 overflow-hidden rounded-[24px] border-none shadow-2xl [&>button]:hidden",children:ge&&e.jsxs("div",{className:"p-8 bg-white relative",children:[e.jsx("button",{onClick:()=>ue(!1),"aria-label":"Close event details",className:"absolute top-4 right-4 p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(qt,{size:18})}),e.jsxs("div",{className:"flex items-start gap-4 mb-6",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl flex items-center justify-center shrink-0",style:{backgroundColor:Or(ge.color||"purple")+"20",color:Or(ge.color||"purple")},children:ge.id.startsWith("schedule-")?e.jsx(nr,{size:24}):e.jsx(Er,{size:24})}),e.jsxs("div",{className:"pr-6",children:[e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] leading-tight mb-2",children:ge.title}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 text-[12px] font-semibold border border-slate-200",children:[e.jsx(Er,{size:12}),ge.startTime.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 text-[12px] font-semibold border border-slate-200",children:[e.jsx(Ls,{size:12}),qa(ge.startTime),ge.endTime?` - ${qa(ge.endTime)}`:""]})]})]})]}),ge.description&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Uc,{size:16,className:"text-slate-400"}),e.jsx("h4",{className:"text-[13px] font-bold text-slate-700",children:"Details"})]}),e.jsx("p",{className:"text-[14px] text-slate-600 leading-relaxed bg-slate-50/50 p-4 rounded-xl border border-slate-100/50 break-words",children:ge.description})]}),e.jsxs("div",{className:"flex gap-3 pt-2 border-t border-slate-100",children:[e.jsxs(wt,{variant:"outline",onClick:()=>T(ge.id),className:"flex-1 h-11 rounded-xl font-bold border-rose-200 text-rose-600 hover:bg-rose-50 hover:text-rose-700 transition-all text-[13px]",children:[e.jsx(ji,{className:"w-4 h-4 mr-2"})," Delete"]}),e.jsxs(wt,{onClick:()=>pe(ge),className:"flex-1 h-11 rounded-xl font-bold bg-[#1e293b] hover:bg-slate-800 text-white shadow-lg shadow-slate-200 transition-all hover:scale-[1.02] text-[13px]",children:[e.jsx(Ci,{className:"w-4 h-4 mr-2"})," Edit Event"]})]})]})})})]})},hr=[{hex:"#9956DE",bg:"bg-[#9956DE]/10",border:"border-[#9956DE]/20",borderLeft:"border-l-[#9956DE]",text:"text-[#9956DE]",groupHover:"group-hover:text-[#9956DE]"},{hex:"#7274ED",bg:"bg-[#7274ED]/10",border:"border-[#7274ED]/20",borderLeft:"border-l-[#7274ED]",text:"text-[#7274ED]",groupHover:"group-hover:text-[#7274ED]"},{hex:"#1FA7E1",bg:"bg-[#1FA7E1]/10",border:"border-[#1FA7E1]/20",borderLeft:"border-l-[#1FA7E1]",text:"text-[#1FA7E1]",groupHover:"group-hover:text-[#1FA7E1]"},{hex:"#6ED1CF",bg:"bg-[#6ED1CF]/10",border:"border-[#6ED1CF]/20",borderLeft:"border-l-[#6ED1CF]",text:"text-[#6ED1CF]",groupHover:"group-hover:text-[#6ED1CF]"},{hex:"#FFB356",bg:"bg-[#FFB356]/10",border:"border-[#FFB356]/20",borderLeft:"border-l-[#FFB356]",text:"text-[#FFB356]",groupHover:"group-hover:text-[#FFB356]"}],Yo=({classes:t,onSelectClass:s,onOpenNotifications:a,onOpenProfile:r,insightDismissed:o,onOpenInsightModal:n,viewType:i="analytics",onCreateClass:l})=>{const{currentUser:c,userProfile:d}=vs(),[m,p]=u.useState(""),h=i==="competency",v=t.reduce((g,I)=>g+(I.studentCount||0),0),y=t.reduce((g,I)=>g+(I.atRiskCount||0),0),S=t.length>0?(t.reduce((g,I)=>g+(I.avgScore||0),0)/t.length).toFixed(1):0,N=u.useMemo(()=>{const g=[],I=t.filter(A=>A.atRiskCount>0);if(I.length>0){const A=[...I].sort((W,f)=>f.atRiskCount-W.atRiskCount)[0];g.push({icon:Kr,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-bold text-white",children:A.name})," has ",A.atRiskCount," at-risk student",A.atRiskCount>1?"s":""," needing intervention."]})})}const L=t.filter(A=>A.avgScore>0&&A.avgScore<60);return L.length>0&&g.push({icon:Kr,text:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-bold text-white",children:[L.length," class",L.length>1?"es":""]})," below 60% average — consider review sessions."]})}),y===0&&v>0&&g.push({icon:bs,text:e.jsxs(e.Fragment,{children:["All ",e.jsxs("span",{className:"font-bold text-white",children:[v," students"]})," are on track. Great work!"]})}),t.length>0&&Number(S)===0&&g.push({icon:Vt,text:e.jsxs(e.Fragment,{children:["No quiz data yet. ",e.jsx("span",{className:"font-bold text-white",children:"Assign assessments"})," to start tracking progress."]})}),g.length===0&&g.push({icon:bs,text:e.jsx(e.Fragment,{children:"No action items right now. Check back after students complete activities."})}),g},[t,y,v,S]),w=t.filter(g=>g.name.toLowerCase().includes(m.toLowerCase())||(g.gradeLevel||"").toLowerCase().includes(m.toLowerCase()));return e.jsx("div",{className:"h-full overflow-y-auto w-full block",children:e.jsxs("div",{className:"max-w-[1400px] mx-auto p-3 sm:p-[24px] xl:p-[32px] space-y-3 sm:space-y-[24px]",children:[e.jsx("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:e.jsx("div",{className:"flex-1 max-w-xl",children:e.jsxs("div",{className:"flex items-center bg-white/80 px-4 py-2.5 rounded-[16px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white backdrop-blur-[12px] group focus-within:ring-2 focus-within:ring-indigo-500/20 transition-all",children:[e.jsx(Xs,{className:"w-4 h-4 text-[#64748b] shrink-0 group-focus-within:text-[#4f46e5] transition-colors"}),e.jsx("input",{type:"text",placeholder:"Global search for a student across all classes...",value:m,onChange:g=>p(g.target.value),className:"bg-transparent border-none focus:outline-none ml-3 text-[13px] w-full text-[#475569] placeholder:text-[#94a3b8]"})]})})}),h?e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-[16px]",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(168,85,247,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Total Students Evaluated"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(hs,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none mb-6",children:v}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3",children:e.jsx("span",{className:"text-[12px] font-medium text-white/90",children:"Active across all classes"})})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#0ea5e9] to-[#0284c7] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(14,165,233,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Global Avg Competency"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(fs,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[32px] font-bold relative z-10 leading-none mb-6",children:[S,"%"]}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3",children:e.jsxs("span",{className:"text-[12px] font-medium text-white/90",children:["Across ",t.length," ",t.length===1?"class":"classes"]})})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f97316] to-[#ea580c] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(249,115,22,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-4",children:[e.jsx("span",{className:"text-[13px] font-medium text-white/90",children:"Universal Weakness"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(fs,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[20px] font-bold relative z-10 leading-tight mb-2 truncate",children:"Foundational Skills"}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3 mt-auto",children:e.jsxs("span",{className:"text-[12px] font-medium text-white/90",children:["Identified in ",t.length," classes"]})})]})]}):e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-2 sm:gap-[16px]",children:[e.jsxs("div",{className:"lg:col-span-8 grid grid-cols-3 sm:grid-cols-3 gap-2 sm:gap-[16px]",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#10b981] to-[#059669] rounded-[14px] sm:rounded-[16px] p-[14px] sm:p-[20px] shadow-[0_4px_12px_rgba(16,185,129,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-2 sm:mb-4",children:[e.jsx("span",{className:"text-[11px] sm:text-[13px] font-medium text-white/90",children:"Total Students"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(hs,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[24px] sm:text-[32px] font-bold relative z-10 leading-none mb-3 sm:mb-6",children:v}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3",children:e.jsxs("span",{className:"text-[12px] font-medium text-white/90",children:["Across ",t.length," ",t.length===1?"class":"classes"]})})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#0ea5e9] to-[#0284c7] rounded-[14px] sm:rounded-[16px] p-[14px] sm:p-[20px] shadow-[0_4px_12px_rgba(14,165,233,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-2 sm:mb-4",children:[e.jsx("span",{className:"text-[11px] sm:text-[13px] font-medium text-white/90",children:"Class average"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(fs,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[24px] sm:text-[32px] font-bold relative z-10 leading-none mb-3 sm:mb-6",children:[S,"%"]}),e.jsx("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3",children:e.jsxs("span",{className:"text-[12px] font-medium text-white/90",children:["Across ",t.length," ",t.length===1?"class":"classes"]})})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f97316] to-[#ea580c] rounded-[14px] sm:rounded-[16px] p-[14px] sm:p-[20px] shadow-[0_4px_12px_rgba(249,115,22,0.2)] flex flex-col justify-between h-full group text-white",children:[e.jsx("div",{className:"absolute -right-12 -bottom-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex items-start justify-between relative z-10 mb-2 sm:mb-4",children:[e.jsx("span",{className:"text-[11px] sm:text-[13px] font-medium text-white/90",children:"At risk"}),e.jsx("div",{className:"w-8 h-8 rounded-full border border-white/30 flex items-center justify-center bg-white/10",children:e.jsx(br,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[24px] sm:text-[32px] font-bold relative z-10 leading-none mb-3 sm:mb-6",children:y}),e.jsxs("div",{className:"flex items-center justify-between relative z-10 border-t border-white/20 pt-3",children:[e.jsx("span",{className:"text-[12px] font-medium text-white/90",children:"Requires attention"}),e.jsxs("span",{className:"text-[11px] font-bold bg-white/20 px-2 py-0.5 rounded-[4px] backdrop-blur-sm",children:[v>0?Math.round(y/v*100):0,"%"]})]})]})]}),e.jsxs("div",{className:"lg:col-span-4 relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(168,85,247,0.2)] flex flex-col text-white",children:[e.jsx("div",{className:"absolute -right-12 -top-12 w-40 h-40 bg-white/10 rounded-full"}),e.jsxs("div",{className:"flex justify-between items-center mb-4 relative z-10 border-b border-white/20 pb-3",children:[e.jsxs("h3",{className:"text-[14px] font-semibold text-white flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-white animate-pulse shadow-[0_0_8px_rgba(255,255,255,0.8)]"}),"AI Action Items"]}),e.jsxs("span",{className:"text-[10px] font-bold text-[#9333ea] bg-white px-2 py-0.5 rounded-[4px]",children:[N.length," Pending"]})]}),e.jsx("div",{className:"space-y-[8px] flex-1 overflow-y-auto no-scrollbar relative z-10",children:N.map((g,I)=>e.jsxs("div",{className:"bg-white/10 hover:bg-white/20 rounded-[8px] p-3 text-[12px] border border-white/10 transition-colors backdrop-blur-sm group cursor-pointer flex gap-3 items-start",children:[e.jsx("div",{className:"mt-0.5 shrink-0 text-white/80 group-hover:text-white transition-colors",children:e.jsx(g.icon,{className:"w-4 h-4"})}),e.jsx("div",{className:"leading-snug text-white/90",children:g.text})]},I))})]})]}),e.jsxs("div",{className:"bg-white/60 backdrop-blur-[12px] rounded-[24px] p-3 sm:p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white mt-3 sm:mt-[24px]",children:[e.jsxs("div",{className:"mb-6 border-b border-[#f1f5f9] pb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-[18px] font-semibold text-[#1e293b]",children:h?"Select a Class":"My Classes"}),l&&!h&&e.jsxs("button",{onClick:l,className:"flex items-center gap-1.5 px-3 py-1.5 text-[12px] font-semibold text-[#9956DE] bg-[#9956DE]/10 rounded-lg hover:bg-[#9956DE]/20 transition-colors",children:[e.jsx(ua,{size:14}),"Create Class"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-[16px]",children:[w.map((g,I)=>{const L=hr[I%hr.length];let A=null;return g.riskLevel==="high"?A=e.jsx("span",{className:"inline-flex px-2 py-1 bg-rose-50 text-rose-600 text-[10px] font-bold rounded-md border border-rose-100/50 uppercase",children:"High Risk"}):g.riskLevel==="medium"?A=e.jsx("span",{className:"inline-flex px-2 py-1 bg-amber-50 text-amber-600 text-[10px] font-bold rounded-md border border-amber-100/50 uppercase",children:"Medium Risk"}):A=e.jsx("span",{className:"inline-flex px-2 py-1 bg-emerald-50 text-emerald-600 text-[10px] font-bold rounded-md border border-emerald-100/50 uppercase",children:"On Track"}),e.jsxs("div",{onClick:()=>s(g),className:`flex flex-col p-[16px] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.04)] hover:shadow-md hover:-translate-y-0.5 rounded-[18px] transition-all cursor-pointer group border border-[#f1f5f9] border-l-[6px] ${L.borderLeft}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-[12px] ${L.bg} flex items-center justify-center border ${L.border}`,children:e.jsx(Vt,{className:`w-5 h-5 ${L.text}`})}),e.jsxs("div",{children:[e.jsx("h4",{className:`font-bold text-[14px] text-[#1e293b] mb-0.5 transition-colors ${L.groupHover}`,children:g.name}),e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider",children:g.gradeLevel||"Senior High"})]})]}),A]}),e.jsxs("div",{className:"flex items-center justify-between text-[13px] text-[#475569] bg-[#f8fafc] rounded-[12px] p-3 border border-[#f1f5f9]",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Students"}),e.jsx("span",{className:"font-semibold text-[#1e293b]",children:g.studentCount})]}),e.jsx("div",{className:"w-[1px] h-8 bg-[#e2e8f0]"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:h?"Avg Competency":"Average"}),e.jsxs("span",{className:"font-semibold text-[#1e293b]",children:[g.avgScore,"%"]})]}),!h&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-[1px] h-8 bg-[#e2e8f0]"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Schedule"}),e.jsx("span",{className:"font-semibold text-[#1e293b]",children:g.schedule||"Mon-Fri"})]})]})]})]},g.id)}),w.length===0&&e.jsx("div",{className:"col-span-full py-8 text-center text-[#64748b] text-[13px] bg-[#f8fafc] rounded-[18px] border border-[#e2e8f0]",children:"No classes match your search."})]})]})]})})},jl="PH_SHS_OFFICIAL_CLASS_RECORD",Ym=.85,on=.85,Km="2026.04.24",yl=4,sr=["INPUT DATA","SENIOR HIGH SCHOOL CLASS RECORD","LEARNERS NAMES","WRITTEN WORK","PERFORMANCE TASKS","QUARTERLY ASSESSMENT","REMARK","FINAL SEMESTRAL GRADES"],Xm=[...sr,"Pursuant to DepEd Order 8 series of 2015","INITIAL GRADE","QUARTERLY GRADE","ADDITIONAL REMARKS","MALE","FEMALE","SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY","WEIGHT OF COMPONENTS","LOOK UP","HELPER","ATTACHMENTS"],Jm=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],Oa=["WITH ATTACHMENTS","OFFICIALLY DROPPED","WITHDRAWN","UNOFFICIALLY DROPPED","TRANSFEREE","SHIFTER"],Zm=["TOTAL","SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY","WEIGHT OF COMPONENTS"],ex={SECOND:["SECOND QUARTER","2ND QUARTER","Q2"]},aa={inputData:["input data"],firstQuarter:["first quarter","1st quarter","q1"],secondQuarter:["second quarter","2nd quarter","q2"],finalSemestral:["final semestral","final grades","semestral"],helper:["helper","weight","attachments"],lookup:["look up","lookup","reference"]},Jt={region:["REGION"],division:["DIVISION"],schoolName:["SCHOOL NAME"],schoolId:["SCHOOL ID"],schoolYear:["SCHOOL YEAR"],gradeSection:["GRADE / SECTION","GRADE/SECTION"],semester:["SEMESTER"],track:["TRACK"],subjectCode:["SUBJECT CODE"],subjectName:["SUBJECT NAME","SUBJECT"],teacherName:["TEACHER","NAME OF TEACHER"]},He={learnerNo:["NO","NO.","#"],learnerName:["LEARNERS NAMES","LEARNER NAME","NAME"],writtenWork:["WRITTEN WORK","WW"],performanceTasks:["PERFORMANCE TASKS","PT"],quarterlyAssessment:["QUARTERLY ASSESSMENT","QA"],total:["TOTAL"],ps:["PS"],ws:["WS"],initialGrade:["INITIAL GRADE"],quarterlyGrade:["QUARTERLY GRADE"],firstQuarter:["FIRST QUARTER","1ST QUARTER"],secondQuarter:["SECOND QUARTER","2ND QUARTER"],firstSemester:["FIRST SEMESTER"],finalGrades:["FINAL GRADES","FINAL GRADE"],remark:["REMARK","REMARKS"],additionalRemarks:["ADDITIONAL REMARKS","ADDITIONAL REMARK"]};function tx(t){return t==null?null:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:String(t)}function Ct(t){return String(t??"").replace(/[\u00a0\t\r\n]+/g," ").replace(/[|]+/g," ").replace(/\s+/g," ").trim().toUpperCase()}function Ko(t){return Ct(t).replace(/[^A-Z0-9]+/g,"")}function Te(t,s){const a=Ct(t),r=Ct(s);if(!a||!r)return!1;if(a.includes(r))return!0;const o=Ko(t),n=Ko(s);return!o||!n?!1:o.includes(n)}function ar(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=t.replace(/,/g,"").trim();if(!s)return;const a=Number(s);if(Number.isFinite(a))return a}}function Br(t){return Ct(t).toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,80)}function Sl(t){const s={};return t.forEach(a=>{const r=ts.encode_cell(a.s);for(let o=a.s.r;o<=a.e.r;o+=1)for(let n=a.s.c;n<=a.e.c;n+=1){const i=ts.encode_cell({r:o,c:n});s[i]=r}}),s}function sx(t,s,a){const o=(a||Sl(t.merges))[s]||s;return t.cells[o]||t.cells[s]}const kl="A1:A1",Xo=1200,Jo=200,Zo=2e5;function ax(t){const s=Math.max(0,t.s.r),a=Math.max(0,t.s.c);let r=Math.max(s,t.e.r),o=Math.max(a,t.e.c);r-s+1>Xo&&(r=s+Xo-1),o-a+1>Jo&&(o=a+Jo-1);const n=r-s+1,i=o-a+1;if(n*i>Zo){const c=Math.max(1,Math.floor(Zo/i));r=s+Math.min(n,c)-1}return{s:{r:s,c:a},e:{r,c:o}}}function rx(t){try{return ts.decode_range(t)}catch{return ts.decode_range(kl)}}function nx(t){let s=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY;return Object.keys(t.cells).forEach(n=>{try{const i=ts.decode_cell(n);s=Math.min(s,i.r),a=Math.min(a,i.c),r=Math.max(r,i.r),o=Math.max(o,i.c)}catch{}}),t.merges.forEach(n=>{s=Math.min(s,n.s.r,n.e.r),a=Math.min(a,n.s.c,n.e.c),r=Math.max(r,n.s.r,n.e.r),o=Math.max(o,n.s.c,n.e.c)}),!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(r)||!Number.isFinite(o)?null:{s:{r:Math.max(0,Math.trunc(s)),c:Math.max(0,Math.trunc(a))},e:{r:Math.max(0,Math.trunc(r)),c:Math.max(0,Math.trunc(o))}}}function ox(t){const s=rx(t.ref||kl),a=nx(t);return ax(a||s)}function ix(t,s){const a=ox(s),r=`${ts.encode_cell(a.s)}:${ts.encode_cell(a.e)}`,o=Sl(s.merges),n=a.e.r-a.s.r+1,i=a.e.c-a.s.c+1,l=[];for(let c=0;ct.endRow||at.endCol?null:t.cells[s-t.startRow]?.[a-t.startCol]??null}function Hs(t,s){return st.endRow?"":(t.cells[s-t.startRow]||[]).map(r=>r?.normalizedText||"").filter(Boolean).join(" ").trim()}function ja(t){return ts.encode_col(t)}function Ya(t){const s=String(t||"").trim().toUpperCase();if(!s||!/^[A-Z]+$/.test(s))return-1;try{return ts.decode_col(s)}catch{return-1}}function lx(t){return`${ts.encode_cell(t.s)}:${ts.encode_cell(t.e)}`}function cx(t,s){const a=[];for(let r=s.s.r;r<=s.e.r;r+=1){const o=[];for(let n=s.s.c;n<=s.e.c;n+=1){const i=Ve(t,r,n);o.push(i?.displayValue??null)}a.push(o)}return a}function dx(t,s){const a=Ct(t),r=Ct(s);return!a||!r?0:a===r?1:a.includes(r)?.9:.75}function kn(t,s){const a=[];for(let r=0;r{Te(l.normalizedText,c)&&a.push({sheetName:t.sheetName,anchor:c,row:l.row,col:l.col,address:l.address,value:String(l.displayValue??""),confidence:dx(l.displayValue,c)})})}const o=t.startRow+r,n=Hs(t,o);n&&s.forEach(i=>{if(!Te(n,i))return;const l=t.cells[r].find(c=>c?.normalizedText);l&&a.push({sheetName:t.sheetName,anchor:i,row:o,col:l.col,address:l.address,value:n,confidence:.8})})}return a}function ux(t,s){return Object.values(t).flatMap(a=>kn(a,s))}function Tt(t,s){return kn(t,[s]).sort((a,r)=>a.row-r.row||a.col-r.col)}function Cl(t,s,a,r=6){for(let o=1;o<=r;o+=1){const i=Ve(t,s,a+o)?.displayValue;if(i!=null&&String(i).trim())return String(i).trim()}for(let o=1;o<=r;o+=1){const i=Ve(t,s+o,a)?.displayValue;if(i!=null&&String(i).trim())return String(i).trim()}}function Il(t,s,a=5){let r=s,o=-1;for(let n=Math.max(t.startRow,s-a);n<=Math.min(t.endRow,s+a);n+=1){const i=Hs(t,n),l=["LEARNERS NAMES","WRITTEN WORK","PERFORMANCE TASKS","QUARTERLY ASSESSMENT","REMARK"].reduce((c,d)=>i.includes(d)?c+1:c,0);l>o&&(o=l,r=n)}return r}function mx(t,s){const a=Ct(t).toLowerCase(),r=o=>[...s].some(n=>Te(n,o));return aa.inputData.some(o=>a.includes(o))||r("INPUT DATA")?"inputData":aa.finalSemestral.some(o=>a.includes(o))||r("FINAL SEMESTRAL GRADES")||r("FINAL GRADES")?"finalSemestral":aa.firstQuarter.some(o=>a.includes(o))||r("FIRST QUARTER")?"firstQuarter":aa.secondQuarter.some(o=>a.includes(o))||r("SECOND QUARTER")?"secondQuarter":r("SENIOR HIGH SCHOOL CLASS RECORD")||r("WRITTEN WORK")&&r("PERFORMANCE TASKS")?"firstQuarter":aa.helper.some(o=>a.includes(o))||r("WEIGHT OF COMPONENTS")||r("ATTACHMENTS")||r("HELPER")?"helper":aa.lookup.some(o=>a.includes(o))||r("LOOK UP")?"lookup":"other"}function xx(t){const s=t.criticalTotal>0?t.criticalFound/t.criticalTotal:0,a=t.totalSheets>0?t.recognizedSheets/t.totalSheets:0,r=t.hasDepedAnchor?1:0,o=.65*s+.2*a+.15*r;return Number(Math.max(0,Math.min(1,o)).toFixed(4))}function px(t){const s=ux(t.matrices,Xm),a=new Set,r=[];sr.forEach(v=>{s.some(S=>Te(S.anchor,v))&&(a.add(v),r.push(`Found critical anchor: ${v}`))});const o=sr.filter(v=>!a.has(v)),n=new Map;s.forEach(v=>{n.has(v.sheetName)||n.set(v.sheetName,new Set),n.get(v.sheetName)?.add(v.anchor)});const i=t.sheetNames.map(v=>{const y=n.get(v)||new Set,S=mx(v,y),N=Math.min(1,.35+Math.min(.55,y.size*.08)),w=[`sheet:${v}`,`signals:${y.size}`,...[...y].slice(0,5)];return{sheetName:v,role:S,confidence:Number(N.toFixed(3)),evidence:w}}),l={firstQuarter:[],secondQuarter:[],finalSemestral:[],helper:[],lookup:[],other:[]};i.forEach(v=>{switch(v.role){case"inputData":l.inputData?l.other.push(v.sheetName):l.inputData=v.sheetName;break;case"firstQuarter":l.firstQuarter.push(v.sheetName);break;case"secondQuarter":l.secondQuarter.push(v.sheetName);break;case"finalSemestral":l.finalSemestral.push(v.sheetName);break;case"helper":l.helper.push(v.sheetName);break;case"lookup":l.lookup.push(v.sheetName);break;case"other":default:l.other.push(v.sheetName);break}});const c=(l.inputData?1:0)+l.firstQuarter.length+l.secondQuarter.length+l.finalSemestral.length+l.helper.length+l.lookup.length,d=xx({criticalFound:a.size,criticalTotal:sr.length,recognizedSheets:c,totalSheets:t.sheetNames.length,hasDepedAnchor:s.some(v=>Te(v.anchor,"Pursuant to DepEd Order 8 series of 2015"))}),m=l.firstQuarter.length>0||l.secondQuarter.length>0,p=!!l.inputData&&m&&l.finalSemestral.length>0,h=d>=.55&&p;return l.inputData||r.push("Input Data sheet not confidently detected."),m||r.push("No quarter class record sheet detected."),l.finalSemestral.length===0&&r.push("No Final Semestral Grades sheet detected."),{format:jl,isOfficialFormatLikely:h,confidence:d,evidence:r,missingCriticalAnchors:o,detectedSheets:l,anchorMatches:s}}function fr(t){if(typeof t=="number"&&Number.isFinite(t))return t;const s=String(t??"").trim();if(!s)return;const a=Number(s.replace(/[^0-9]/g,""));if(!(!Number.isFinite(a)||a<=0))return a}function Cn(t){const s=Ct(t);if(s.includes("FEMALE"))return"FEMALE";if(s.includes("MALE"))return"MALE"}function In(t){const s=Ct(t.rowText);return s?s==="MALE"||s==="FEMALE"?"sex-header":Jm.some(a=>s.includes(a))?"signature":Zm.some(a=>s.includes(a))?"helper":s.includes("LEARNERS NAMES")||s.includes("WRITTEN WORK")||s.includes("PERFORMANCE TASKS")||s.includes("QUARTERLY ASSESSMENT")||s.includes("INITIAL GRADE")||s.includes("QUARTERLY GRADE")?"header":t.hasLearnerName||t.hasLearnerNumber?"learner":s.includes("ATTACHMENTS")||s.includes("LOOK UP")?"helper":"unknown":"blank"}function hx(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{Tt(t,r).forEach(o=>{a.push({role:r,name:String(Ve(t,o.row,o.col+1)?.displayValue||"").trim()||void 0,sourceSheet:t.sheetName,sourceRow:o.row+1})})}),a}function fx(t){const s=[],a=Tt(t,"LEARNERS NAMES")[0],r=a?Il(t,a.row,5):t.startRow,o=(N,w)=>Tt(t,N).find(I=>Math.abs(I.row-r)<=2)?.col??w,n=o(He.learnerNo[0],t.startCol),i=o(He.learnerName[0],t.startCol+1),l=o(He.firstQuarter[0],i+1),c=o(He.secondQuarter[0],l+1),d=o(He.firstSemester[0],c+1),m=o(He.finalGrades[0],d+1),p=o(He.remark[0],m+1),h=o(He.additionalRemarks[0],p+1),v=[];let y="UNKNOWN",S=0;for(let N=r+1;N<=t.endRow;N+=1){const w=Hs(t,N),g=In({rowText:w,hasLearnerNumber:/\b\d{1,2}\b/.test(w),hasLearnerName:/[A-Z]{2,}/.test(w)});if(g==="sex-header"){y=Cn(w)||y;continue}if(g==="signature"||g==="helper")break;if(g==="blank"){if(S+=1,S>=yl)break;continue}if(g!=="learner")continue;S=0;const I=fr(Ve(t,N,n)?.displayValue),L=String(Ve(t,N,i)?.displayValue||"").trim();if(!L&&I===void 0)continue;const A=Ve(t,N,l)?.displayValue??null,W=Ve(t,N,c)?.displayValue??null,f=Ve(t,N,d)?.displayValue??null,C=Ve(t,N,m)?.displayValue??null,b=Ve(t,N,p)?.displayValue??null;let F=Ve(t,N,h)?.displayValue??null;const U=Oa.filter(k=>Te(w,k));U.length>0&&(F=[F,U.join("; ")].filter(Boolean).join("; ")||null),!L&&I!==void 0&&s.push(`Row ${N+1} has learner number ${I} but empty learner name.`),v.push({learnerNo:I,fullName:L||`Unnamed Learner ${I||N+1}`,sex:y,firstQuarter:A,secondQuarter:W,firstSemester:f,finalGrades:C,remark:b,additionalRemarks:F,sourceRow:N+1})}return{sheetName:t.sheetName,learnerGrades:v,signatures:hx(t),warnings:s}}function rs(t,s){for(const a of s){const r=Tt(t,a);for(const o of r){const n=Cl(t,o.row,o.col,8);if(n&&n.trim())return n.trim()}}}function gx(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{Tt(t,r).forEach(n=>{const i=Cl(t,n.row,n.col,10);a.push({role:r,name:i,sourceSheet:t.sheetName,sourceRow:n.row+1})})}),a}function bx(t){const s=Tt(t,"LEARNERS NAMES")[0];if(!s)return[];const a=s.row+1,r=s.col,o=Math.max(t.startCol,r-1),n=Math.min(t.endCol,r+1),i=Math.min(t.endCol,r+2),l=[];let c="UNKNOWN",d=0;for(let m=a;m<=t.endRow;m+=1){const p=Hs(t,m),h=In({rowText:p,hasLearnerNumber:!!fr(Ve(t,m,o)?.displayValue),hasLearnerName:!!String(Ve(t,m,r)?.displayValue||"").trim()});if(h==="sex-header"){c=Cn(p)||c,d=0;continue}if(h==="signature"||h==="helper")break;if(h!=="learner"){if(h==="blank"&&(d+=1),d>=5)break;continue}d=0;const v=fr(Ve(t,m,o)?.displayValue),y=String(Ve(t,m,r)?.displayValue||"").trim(),S=String(Ve(t,m,n)?.displayValue||"").trim()||void 0,N=String(Ve(t,m,i)?.displayValue||"").trim()||void 0,w=Oa.filter(g=>Te(p,g));!y&&v===void 0||l.push({learnerNo:v,sex:c,fullName:y||`Unnamed Learner ${v||m}`,sourceSheet:t.sheetName,sourceRow:m+1,remarks:S,additionalRemarks:N,statuses:w.length>0?w:void 0})}return l}function vx(t){const s=[],a=[];for(let r=t.startRow;r<=t.endRow;r+=1){const o=Hs(t,r);if(o){if(Oa.some(n=>Te(o,n))){s.push(o);continue}(Te(o,"IMPORTANT")||Te(o,"NOTE")||Te(o,"ATTACHMENT")||Te(o,"LOOK UP"))&&a.push(o)}}return{attachmentRules:Array.from(new Set(s)),helperNotes:Array.from(new Set(a))}}function wx(t){const s=[],a={region:rs(t,Jt.region),division:rs(t,Jt.division),schoolName:rs(t,Jt.schoolName),schoolId:rs(t,Jt.schoolId),schoolYear:rs(t,Jt.schoolYear),gradeSection:rs(t,Jt.gradeSection),semester:rs(t,Jt.semester),track:rs(t,Jt.track),subjectCode:rs(t,Jt.subjectCode),subjectName:rs(t,Jt.subjectName),teacherName:rs(t,Jt.teacherName)},r=bx(t),o=gx(t),{attachmentRules:n,helperNotes:i}=vx(t);return a.schoolName||s.push("Input Data metadata is missing School Name."),a.schoolYear||s.push("Input Data metadata is missing School Year."),r.length===0&&s.push("No learners detected in Input Data sheet."),kn(t,Object.values(Jt).flat()).length<4&&s.push("Input Data sheet contains limited metadata anchors; layout may have drifted."),{sheetName:t.sheetName,schoolContext:a,learners:r,signatures:o,attachmentRules:n,helperNotes:i,warnings:s}}function Nx(t){const s=Ct(t.sheetName);return ex.SECOND.some(a=>Te(s,a))?"SECOND":"FIRST"}function jx(t,s){const a=[],r=[],o=[];let n,i="NONE";for(let l=t.startCol;l<=t.endCol;l+=1){const c=Ve(t,s,l),d=Ct(c?.displayValue||""),m=Ve(t,s+1,l),p=String(m?.displayValue||c?.displayValue||"").trim();if(!d&&!p)continue;if(Te(d,He.writtenWork[0])){i="WW";continue}if(Te(d,He.performanceTasks[0])){i="PT";continue}if(Te(d,He.quarterlyAssessment[0])){n={key:Br(p||"quarterly_assessment"),label:p||"Quarterly Assessment",column:ja(l)},i="DERIVED";continue}if(Te(d,He.initialGrade[0])||Te(d,He.quarterlyGrade[0])||Te(d,He.remark[0])||Te(d,He.additionalRemarks[0])||Te(d,He.firstQuarter[0])||Te(d,He.secondQuarter[0])||Te(d,He.firstSemester[0])||Te(d,He.finalGrades[0])||Te(d,He.ps[0])||Te(d,He.ws[0])||Te(d,He.total[0])){i="DERIVED",o.push({key:Br(p||d),label:p||d,column:ja(l)});continue}const h={key:Br(p||d||ja(l)),label:p||d||ja(l),maxScore:ar(m?.displayValue),column:ja(l)};i==="WW"?a.push(h):i==="PT"?r.push(h):i==="DERIVED"&&o.push(h)}return{writtenWorks:a,performanceTasks:r,quarterlyAssessment:n,derived:o}}function yx(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{Tt(t,r).forEach(o=>{const n=Ve(t,o.row,o.col+1),i=String(n?.displayValue||"").trim()||void 0;a.push({role:r,name:i,sourceSheet:t.sheetName,sourceRow:o.row+1})})}),a}function ei(t,s,a){for(let r=t.startCol;r<=t.endCol;r+=1){const o=Ct(Ve(t,s,r)?.displayValue||""),n=Ct(Ve(t,s+1,r)?.displayValue||"");if(a.some(i=>Te(o,i)||Te(n,i)))return r}}function Sx(t,s,a,r){const o={learnerNo:fr(Ve(t,s,r.numberCol)?.displayValue),fullName:String(Ve(t,s,r.nameCol)?.displayValue||"").trim(),sourceRow:s+1},n={};a.writtenWorks.forEach(d=>{const m=d.column?Ya(d.column):-1;if(m<0)return;const p=Ve(t,s,m)?.displayValue;n[d.key]=p??null}),Object.keys(n).length>0&&(o.writtenWorks=n);const i={};if(a.performanceTasks.forEach(d=>{const m=d.column?Ya(d.column):-1;if(m<0)return;const p=Ve(t,s,m)?.displayValue;i[d.key]=p??null}),Object.keys(i).length>0&&(o.performanceTasks=i),a.quarterlyAssessment?.column){const d=Ya(a.quarterlyAssessment.column);o.quarterlyAssessment=Ve(t,s,d)?.displayValue??null}const l=a.derived||[],c={};return l.forEach(d=>{if(!d.column)return;const m=Ya(d.column);if(m<0)return;const p=Ve(t,s,m)?.displayValue??null;c[d.key]=p,Te(d.label,He.initialGrade[0])&&(o.initialGrade=p),Te(d.label,He.quarterlyGrade[0])&&(o.quarterlyGrade=p),Te(d.label,He.firstQuarter[0])&&(o.firstQuarter=p),Te(d.label,He.secondQuarter[0])&&(o.secondQuarter=p),Te(d.label,He.firstSemester[0])&&(o.firstSemester=p),Te(d.label,He.finalGrades[0])&&(o.finalGrades=p),Te(d.label,He.remark[0])&&(o.remark=p!==null?String(p):null),Te(d.label,He.additionalRemarks[0])&&(o.additionalRemarks=p!==null?String(p):null)}),Object.keys(c).length>0&&(o.totals=c),o}function kx(t){const s=Nx(t),a=[],r=Tt(t,He.learnerName[0])[0]||Tt(t,He.learnerName[1])[0],o=r?Il(t,r.row,4):t.startRow,n=jx(t,o),i=ei(t,o,He.learnerNo)??t.startCol,l=ei(t,o,He.learnerName)??Math.min(t.endCol,i+1),c=[];let d="UNKNOWN",m=0;for(let y=o+1;y<=t.endRow;y+=1){const S=Hs(t,y),N=In({rowText:S,hasLearnerNumber:/\b\d{1,2}\b/.test(S),hasLearnerName:/[A-Z]{2,}/.test(S)});if(N==="sex-header"){d=Cn(S)||d;continue}if(N==="signature"||N==="helper")break;if(N==="blank"){if(m+=1,m>=yl)break;continue}if(N!=="learner")continue;m=0;const w=Sx(t,y,n,{numberCol:i,nameCol:l});if(w.sex=d,!w.fullName&&w.learnerNo===void 0)continue;const g=Oa.filter(I=>Te(S,I));g.length>0&&!w.additionalRemarks&&(w.additionalRemarks=g.join("; ")),!w.fullName&&w.learnerNo!==void 0&&(a.push(`Row ${y+1} has learner number ${w.learnerNo} but empty name.`),w.fullName=`Unnamed Learner ${w.learnerNo}`),c.push(w)}n.writtenWorks.length===0&&n.performanceTasks.length===0&&a.push(`No detailed assessment columns detected in ${t.sheetName}.`);const p=ar(Tt(t,"WRITTEN WORK %")[0]?.value||Tt(t,"WRITTEN WORK")[0]?.value),h=ar(Tt(t,"PERFORMANCE TASKS %")[0]?.value||Tt(t,"PERFORMANCE TASKS")[0]?.value),v=ar(Tt(t,"QUARTERLY ASSESSMENT %")[0]?.value||Tt(t,"QUARTERLY ASSESSMENT")[0]?.value);return{sheetName:t.sheetName,quarter:s,gradingWeights:{writtenWork:p,performanceTasks:h,quarterlyAssessment:v},assessmentColumns:n,learnerGrades:c,signatures:yx(t),warnings:a}}function Cx(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{Tt(t,r).forEach(o=>{a.push({role:r,name:String(Ve(t,o.row,o.col+1)?.displayValue||"").trim()||void 0,sourceSheet:t.sheetName,sourceRow:o.row+1})})}),a}function Ix(t){const s=[];let a=!1;for(let r=t.startRow;r<=t.endRow;r+=1){const o=Hs(t,r);if(!o){if(a&&s.length>0)break;continue}if(Te(o,"WEIGHT OF COMPONENTS")){a=!0;continue}if(!a)continue;const n={sourceRow:r+1,raw:o};for(let i=t.startCol;i<=t.endCol;i+=1){const l=Ve(t,r,i)?.displayValue;l==null||String(l).trim()===""||(n[`c${i}`]=l)}Object.keys(n).length>2&&s.push(n)}return s}function Tx(t){const s=[],a=[],r=[],o=[],n=[];return t.forEach(i=>{Cx(i).forEach(l=>a.push(l)),Ix(i).forEach(l=>r.push({...l,sourceSheet:i.sheetName}));for(let l=i.startRow;l<=i.endRow;l+=1){const c=Hs(i,l);if(c){if(Oa.some(d=>Te(c,d))){o.push(`${i.sheetName}: ${c}`);continue}(Te(c,"HELPER")||Te(c,"LOOK UP")||Te(c,"IMPORTANT")||Te(c,"REFERENCE")||Te(c,"ATTACHMENT"))&&n.push(`${i.sheetName}: ${c}`)}}}),r.length===0&&s.push("No component weight rows were parsed from reference sheets."),{sheetName:t.map(i=>i.sheetName).join(", "),componentWeights:r,attachmentRules:Array.from(new Set(o)),helperNotes:Array.from(new Set(n)),signatures:a,warnings:s}}function _x(t,s,a){const r=new Map,o=n=>{const i=`${Ct(n.fullName)}|${n.learnerNo||""}|${n.sourceSheet}`,l=r.get(i);if(!l){r.set(i,n);return}const c=Array.from(new Set([...l.statuses||[],...n.statuses||[]]));r.set(i,{...l,...n,remarks:n.remarks||l.remarks,additionalRemarks:n.additionalRemarks||l.additionalRemarks,statuses:c.length>0?c:void 0})};return t.forEach(o),s.forEach(n=>{n.learnerGrades.forEach(i=>{o({learnerNo:i.learnerNo,sex:i.sex,fullName:i.fullName,sourceSheet:n.sheetName,sourceRow:i.sourceRow,remarks:i.remark||void 0,additionalRemarks:i.additionalRemarks||void 0})})}),a.forEach(n=>{n.learnerGrades.forEach(i=>{o({learnerNo:i.learnerNo,sex:i.sex,fullName:i.fullName,sourceSheet:n.sheetName,sourceRow:i.sourceRow,remarks:i.remark||void 0,additionalRemarks:i.additionalRemarks||void 0})})}),Array.from(r.values())}function Ex(t,s,a,r){const o=[...t.signatures,...s.flatMap(i=>i.signatures),...a.flatMap(i=>i.signatures),...r.signatures],n=new Map;return o.forEach(i=>{const l=`${Ct(i.role)}|${Ct(i.name||"")}|${i.sourceSheet}`;n.set(l,i)}),Array.from(n.values())}function Rx(t){const s=_x(t.inputData.learners,t.quarterSheets,t.finalSheets);return{format:jl,version:Km,workbookMeta:{fileName:t.workbook.fileName,sheetNames:t.workbook.sheetNames,detectedSheets:{inputData:t.detection.detectedSheets.inputData,firstQuarter:t.detection.detectedSheets.firstQuarter,secondQuarter:t.detection.detectedSheets.secondQuarter,finalSemestral:t.detection.detectedSheets.finalSemestral,helper:t.detection.detectedSheets.helper,lookup:t.detection.detectedSheets.lookup,other:t.detection.detectedSheets.other}},schoolContext:{...t.inputData.schoolContext},learners:s,quarterlyRecords:t.quarterSheets.map(a=>({sheetName:a.sheetName,quarter:a.quarter,gradingWeights:a.gradingWeights,assessmentColumns:a.assessmentColumns,learnerGrades:a.learnerGrades})),finalSemestralRecords:t.finalSheets.map(a=>({sheetName:a.sheetName,learnerGrades:a.learnerGrades})),references:{componentWeights:t.references.componentWeights,attachmentRules:Array.from(new Set([...t.inputData.attachmentRules||[],...t.references.attachmentRules||[]])),helperNotes:Array.from(new Set([...t.inputData.helperNotes||[],...t.references.helperNotes||[]])),signatures:Ex(t.inputData,t.quarterSheets,t.finalSheets,t.references),unclassifiedBlocks:t.unclassifiedBlocks},validation:t.validation,raw:t.workbook.raw}}function Mx(t){return!t||t.length===0?[]:t.map(s=>({s:{r:s.s.r,c:s.s.c},e:{r:s.e.r,c:s.e.c}}))}function Ax(t){const s={ref:t["!ref"],merges:Mx(t["!merges"]),cells:{}};return Object.keys(t).filter(a=>!a.startsWith("!")).forEach(a=>{const r=t[a];!r||!(r.v!==void 0||typeof r.w=="string"&&r.w.trim().length>0||typeof r.f=="string"&&r.f.trim().length>0)||(s.cells[a]={v:r.v,w:r.w,t:r.t,f:r.f})}),s}function zx(t,s){const a=Dc(s,{type:"array",cellFormula:!0,cellNF:!0,cellText:!0,cellDates:!0,raw:!1}),r={},o={};return a.SheetNames.forEach(n=>{const i=a.Sheets[n];if(!i)return;const l=Ax(i);o[n]=l,r[n]=ix(n,l)}),{fileName:t,sheetNames:a.SheetNames,raw:{sheets:o},matrices:r}}async function Lx(t){const s=await t.arrayBuffer();return zx(t.name,s)}class Dx{state={};markRange(s,a,r){const o=s;this.state[o]||(this.state[o]={mappedAddresses:new Set,mappings:[]});for(let n=a.s.r;n<=a.e.r;n+=1)for(let i=a.s.c;i<=a.e.c;i+=1)this.state[o].mappedAddresses.add(`${n}:${i}`);this.state[o].mappings.push({sheetName:s,range:a,reason:r})}getMappings(){return Object.values(this.state).flatMap(s=>s.mappings)}getMappedRegionCount(){return this.getMappings().length}getUnmappedBlocks(s,a="unclassified"){const r=[];return Object.values(s).forEach(o=>{const n=new Set,i=this.state[o.sheetName]?.mappedAddresses??new Set;for(let l=o.startRow;l<=o.endRow;l+=1)for(let c=o.startCol;c<=o.endCol;c+=1){const d=`${l}:${c}`;if(n.has(d)||i.has(d))continue;const m=Ve(o,l,c);if(!(m&&m.displayValue!==null&&m.displayValue!==void 0&&String(m.displayValue).trim())){n.add(d);continue}const h=this.collectComponent(o,l,c,i,n);h&&r.push({sheetName:o.sheetName,range:lx(h),purposeGuess:a,raw2D:cx(o,h)})}}),r}collectComponent(s,a,r,o,n){const i=[{row:a,col:r}];let l=a,c=a,d=r,m=r,p=!1;for(;i.length>0;){const h=i.shift();if(!h)break;const v=`${h.row}:${h.col}`;if(n.has(v)||o.has(v))continue;n.add(v);const y=Ve(s,h.row,h.col);y&&y.displayValue!==null&&y.displayValue!==void 0&&String(y.displayValue).trim()&&(p=!0,l=Math.min(l,h.row),c=Math.max(c,h.row),d=Math.min(d,h.col),m=Math.max(m,h.col),[{row:h.row-1,col:h.col},{row:h.row+1,col:h.col},{row:h.row,col:h.col-1},{row:h.row,col:h.col+1}].forEach(N=>{N.rows.endRow||N.cols.endCol||i.push(N)}))}return p?{s:{r:l,c:d},e:{r:c,c:m}}:null}}function $x(t){const s=t.detection.detectedSheets,a=[s.inputData?1:0,s.firstQuarter.length,s.secondQuarter.length,s.finalSemestral.length,s.helper.length,s.lookup.length].reduce((r,o)=>r+o,0);return{totalSheets:t.totalSheets,recognizedSheets:a,unclassifiedSheets:s.other.length,mappedCellRegions:t.mappedCellRegions,unmappedCellRegions:t.unmappedCellRegions}}function Fx(t){const s=new Map;t.forEach(r=>{const o=`${r.learnerNo||""}|${r.fullName.trim().toUpperCase()}`;s.has(o)||s.set(o,[]),s.get(o)?.push(r.sourceRow)});const a=[];return s.forEach((r,o)=>{r.length>1&&a.push(`Duplicate learner entry detected for ${o} at rows ${r.join(", ")}.`)}),a}function Ox(t){const s=[];return t.forEach(a=>{a.learnerGrades.forEach(r=>{r.fullName.trim()||s.push(`${a.sheetName} row ${r.sourceRow}: learner name is blank.`);const o=r.writtenWorks&&Object.values(r.writtenWorks).some(i=>i!==null&&i!==""),n=r.performanceTasks&&Object.values(r.performanceTasks).some(i=>i!==null&&i!=="");!o&&!n&&r.quarterlyAssessment==null&&s.push(`${a.sheetName} row ${r.sourceRow}: all grade blocks are empty.`)})}),s}function Px(t){const s=[];return t.forEach(a=>{a.learnerGrades.forEach(r=>{r.fullName.trim()||s.push(`${a.sheetName} row ${r.sourceRow}: learner name is blank.`),r.finalGrades==null&&r.firstSemester==null&&r.firstQuarter==null&&r.secondQuarter==null&&s.push(`${a.sheetName} row ${r.sourceRow}: no semestral/final values detected.`)})}),s}function Bx(t){const s=[],a=[];t.detection.detectedSheets.inputData||a.push("Missing Input Data sheet."),t.quarterSheets.length===0&&a.push("No quarter class record sheets were extracted."),t.finalSheets.length===0&&a.push("No Final Semestral sheet was extracted."),t.detection.missingCriticalAnchors.length>0&&s.push(`Missing critical anchors: ${t.detection.missingCriticalAnchors.join(", ")}.`),Fx(t.inputData.learners).forEach(n=>s.push(n)),Ox(t.quarterSheets).forEach(n=>s.push(n)),Px(t.finalSheets).forEach(n=>s.push(n)),s.push(...t.inputData.warnings),t.quarterSheets.forEach(n=>s.push(...n.warnings)),t.finalSheets.forEach(n=>s.push(...n.warnings)),t.unmappedCellRegions>t.mappedCellRegions&&s.push("A significant portion of workbook regions are unclassified; review diagnostics before confirming import.");const r=t.detection.confidence,o=t.detection.isOfficialFormatLikely&&a.length===0;return r({fullName:i.fullName,learnerNo:i.learnerNo,sex:i.sex,remarks:i.remarks,additionalRemarks:i.additionalRemarks,statuses:i.statuses,sourceSheet:i.sourceSheet,sourceRow:i.sourceRow})),r=t.quarterlyRecords.flatMap(i=>i.learnerGrades.map(l=>({fullName:l.fullName,sourceSheet:i.sheetName,sourceRow:l.sourceRow,quarter:i.quarter,firstQuarter:l.firstQuarter,secondQuarter:l.secondQuarter,firstSemester:l.firstSemester,finalGrades:l.finalGrades,quarterlyGrade:l.quarterlyGrade,initialGrade:l.initialGrade,remark:l.remark,additionalRemarks:l.additionalRemarks}))),o=t.finalSemestralRecords.flatMap(i=>i.learnerGrades.map(l=>({fullName:l.fullName,sourceSheet:i.sheetName,sourceRow:l.sourceRow,firstQuarter:l.firstQuarter,secondQuarter:l.secondQuarter,firstSemester:l.firstSemester,finalGrades:l.finalGrades,remark:l.remark,additionalRemarks:l.additionalRemarks}))),n=[...t.learners,...t.quarterlyRecords.flatMap(i=>i.learnerGrades.map(l=>({learnerNo:l.learnerNo,sex:l.sex,fullName:l.fullName,sourceSheet:i.sheetName,sourceRow:l.sourceRow,remarks:l.remark||void 0,additionalRemarks:l.additionalRemarks||void 0})))].map(i=>({fullName:i.fullName,remark:i.remarks||null,additionalRemarks:i.additionalRemarks||null,statuses:"statuses"in i?i.statuses:void 0,sourceSheet:i.sourceSheet,sourceRow:i.sourceRow}));return{classEntity:s,studentEntities:a,gradeEntities:[...r,...o],remarksEntities:n}}const ti=1500;function si(t){return t?Object.values(t.matrices).reduce((s,a)=>s+a.rowCount*a.colCount,0):0}function ai(t){const s=`[shs-import] parse ${t.stage} file=${t.fileName} duration=${t.durationMs}ms sheets=${t.sheetCount} matrixCells=${t.matrixCellCount}`;if(t.stage==="failed"){console.error(`${s}${t.errorMessage?` error=${t.errorMessage}`:""}`);return}if(t.durationMs>=ti){console.warn(`${s} slow=true threshold=${ti}ms`);return}}function qs(t,s){t?.onProgress?.(s)}function Ux(t,s){return Array.from(new Set(t.filter(a=>Number.isFinite(a)).map(a=>Math.max(s.startRow,Math.min(s.endRow,Math.trunc(a))))))}function ya(t,s,a,r){Ux(a,s).forEach(o=>{t.markRange(s.sheetName,{s:{r:o,c:s.startCol},e:{r:o,c:s.endCol}},r)})}async function Gx(t,s){const a=s?.confidenceThreshold??Ym,r=Date.now();let o=null;try{if(qs(s,{stage:"reading",message:"Reading workbook structure and raw sheets..."}),o=await Lx(t),!o)throw new Error("Workbook read returned null");qs(s,{stage:"detecting-format",message:"Detecting DepEd SHS workbook format..."});const n=px(o);qs(s,{stage:"extracting",message:"Extracting metadata, learners, grades, and references..."});const i=n.detectedSheets.inputData||o.sheetNames[0],l=o.matrices[i],c=l?wx(l):{sheetName:i,schoolContext:{},learners:[],signatures:[],attachmentRules:[],helperNotes:[],warnings:["Input data sheet was not available in matrix map."]},m=[...n.detectedSheets.firstQuarter||[],...n.detectedSheets.secondQuarter||[]].map(I=>o.matrices[I]).filter(I=>!!I).map(I=>kx(I)),p=(n.detectedSheets.finalSemestral||[]).map(I=>o.matrices[I]).filter(I=>!!I).map(I=>fx(I)),h=[...n.detectedSheets.helper||[],...n.detectedSheets.lookup||[]].map(I=>o.matrices[I]).filter(I=>!!I),v=Tx(h),y=new Dx;n.anchorMatches.forEach(I=>{const L=o.matrices[I.sheetName];L&&ya(y,L,[I.row],`Anchor match: ${I.anchor}`)}),[c.sheetName].forEach(I=>{const L=o.matrices[I];if(!L)return;const A=Array.from({length:Math.min(14,L.rowCount)},(C,b)=>L.startRow+b),W=c.learners.map(C=>C.sourceRow-1),f=c.signatures.map(C=>C.sourceRow).filter(C=>typeof C=="number").map(C=>C-1);ya(y,L,[...A,...W,...f],"Input Data parsed rows")}),m.forEach(I=>{const L=o.matrices[I.sheetName];if(!L)return;const A=I.learnerGrades.map(C=>C.sourceRow-1),W=I.signatures.map(C=>C.sourceRow).filter(C=>typeof C=="number").map(C=>C-1),f=A.length>0?Math.max(L.startRow,Math.min(...A)-2):L.startRow;ya(y,L,[f,f+1,...A,...W],"Quarter sheet parsed rows")}),p.forEach(I=>{const L=o.matrices[I.sheetName];if(!L)return;const A=I.learnerGrades.map(C=>C.sourceRow-1),W=I.signatures.map(C=>C.sourceRow).filter(C=>typeof C=="number").map(C=>C-1),f=A.length>0?Math.max(L.startRow,Math.min(...A)-2):L.startRow;ya(y,L,[f,f+1,...A,...W],"Final semestral parsed rows")}),h.forEach(I=>{const L=v.componentWeights.filter(f=>f.sourceSheet===I.sheetName).map(f=>f.sourceRow).filter(f=>typeof f=="number").map(f=>f-1),A=v.signatures?.filter(f=>f.sourceSheet===I.sheetName).map(f=>f.sourceRow).filter(f=>typeof f=="number").map(f=>f-1)||[],W=L.length===0&&A.length===0?[I.startRow,I.startRow+1,I.startRow+2]:[];ya(y,I,[...L,...A,...W],"Reference/helper parsed rows")});const S=y.getUnmappedBlocks(o.matrices);qs(s,{stage:"validating",message:"Validating completeness and structural integrity..."});const N=Bx({detection:n,inputData:c,quarterSheets:m,finalSheets:p,mappedCellRegions:y.getMappedRegionCount(),unmappedCellRegions:S.length,totalSheets:o.sheetNames.length});qs(s,{stage:"normalizing",message:"Normalizing parsed workbook and creating entity mapping..."});const w=Rx({workbook:o,detection:n,inputData:c,quarterSheets:m,finalSheets:p,references:v,validation:N,unclassifiedBlocks:S});w.validation.confidence$.trim().toLowerCase().replace(/\s+/g," "),fe=$=>{if(typeof $=="number"&&Number.isFinite($))return $;const j=Number(String($??"").replace(/[^0-9.-]+/g,""));return Number.isFinite(j)?j:null},Ce=($,j)=>{const T=Number.isFinite($)?$:j;return Math.max(0,Math.min(100,T))},ue=$=>{const j=String($??"");return/[",\n]/.test(j)?`"${j.replace(/"/g,'""')}"`:j},ge=($,j)=>{const T=new Map,_=["quarterlyGrade","finalGrades","firstSemester","firstQuarter","secondQuarter","initialGrade"];$.mapping.gradeEntities.forEach(Ue=>{const Je=ie(Ue.fullName||"");if(!Je)return;const ht=_.map(rt=>fe(Ue[rt])).filter(rt=>rt!==null);if(ht.length===0)return;const dt=T.get(Je)||[];T.set(Je,dt.concat(ht))});const V=$.mapping.studentEntities||[];if(V.length===0)return null;const me=($.imported.schoolContext.semester||$.imported.schoolContext.schoolYear||"First Semester").trim(),oe=($.imported.schoolContext.subjectName||"Class Record Import").trim(),ae=(t||s||"import").replace(/[^a-zA-Z0-9]+/g,"").toUpperCase().slice(0,12)||"IMPORT",we=[["name","lrn","email","engagementScore","avgQuizScore","attendance","assignmentCompletion","term","assessmentName"].join(",")];if(V.forEach((Ue,Je)=>{const ht=ie(Ue.fullName||""),dt=T.get(ht)||[],rt=dt.length>0?dt.reduce((js,Kt)=>js+Kt,0)/dt.length:75,Mt=Ce(rt,75),At=Ce(Mt+5,85),It=Ce(Mt*.7+At*.3,80),cs=Ce(At*.6+Mt*.4,82),Us=Ue.learnerNo||Je+1,Yt=`IMP-${ae}-${String(Us).padStart(4,"0")}`,ds=Ue.fullName||`Learner ${Je+1}`;we.push([ue(ds),ue(Yt),ue(""),ue(Number(It.toFixed(1))),ue(Number(Mt.toFixed(1))),ue(Number(At.toFixed(1))),ue(Number(cs.toFixed(1))),ue(me),ue(oe)].join(","))}),we.length<=1)return null;const Ke=j.replace(/\.(xlsx|xls)$/i,"");return new File([we.join(` -`)],`${Ke}-normalized.csv`,{type:"text/csv"})},B=async $=>{C(!0),k(""),J(null);let j=$;if(/\.(xlsx|xls)$/i.test($.name))try{const T=await Gx($,{confidenceThreshold:on});g(T);const _=ge(T,$.name);_&&(j=_)}catch{g(null)}else g(null);try{const T=await xt.uploadClassRecords(j,{classSectionId:t,className:s,datasetIntent:"synthetic_student_records"}),_=T.students.length,me=((oe,ae,je,we)=>({classSectionId:oe.classSectionId||ae||"imported_class",className:oe.className||je||"Imported Class",classMetadata:oe.classMetadata||we}))(T,t,s,a);_>0&&l?.({students:T.students,classSectionId:me.classSectionId,className:me.className,classMetadata:me.classMetadata}),T.success?(le.success(`Successfully imported ${_} student records.`),J({datasetIntent:T.datasetIntent,summary:T.interpretationSummary,columns:T.columnInterpretations?.map(oe=>({columnName:oe.columnName,mappedField:oe.mappedField,usagePolicy:oe.usagePolicy,confidenceBand:oe.confidenceBand,domainSignals:oe.domainSignals}))||[]}),c?.()):le.error("Import completed but no usable student rows were detected. Check required columns and retry.")}catch(T){le.error(T instanceof Error?T.message:"Upload failed")}finally{C(!1)}},te=async $=>{F(!0);try{const j=await xt.uploadCourseMaterials($,{classSectionId:t,className:s});if(j.success){const T=j.topics?.length??0;le.success(`Course material imported (${T} topics extracted).`),c?.()}}catch(j){le.error(j instanceof Error?j.message:"Course material upload failed")}finally{F(!1)}},[ne,ze]=u.useState(r),[Fe,Pe]=u.useState(!1),[G,se]=u.useState(null),M=u.useMemo(()=>{let $=ne;if(o.length>0){const j=new Set(o.map(T=>Ss(T.classSectionId||T.id)));$=$.filter(T=>j.has(Ss(T.classSectionId))||j.has(Ss(T.classroomId)))}else return[];return t&&($=$.filter(j=>Ss(j.classSectionId)===Ss(t)||Ss(j.classroomId)===Ss(t))),$},[ne,t,o]);u.useEffect(()=>{ze(r),Q(Object.fromEntries(r.map($=>[Ka($),{grade:$.grade||"",section:$.section||""}])))},[r]);const[q,Q]=u.useState({}),pe=async()=>{Pe(!0);let $=0,j=0;try{for(const _ of M){const V=q[Ka(_)],me=V?.grade||_.grade,oe=V?.section||_.section;try{n&&(me!==_.grade||oe!==_.section)&&(await yr(_.id,me,oe,n,new Date().getFullYear().toString(),i),await ll(_.id,me,oe),$++)}catch(ae){console.warn(`[EditRecords] Failed to save ${_.name}:`,ae),j++}}const T=ne.map(_=>{const V=q[Ka(_)];if(!V)return _;const me=yt({metadata:_.classMetadata,classSectionId:_.classSectionId,className:[V.grade,V.section].filter(Boolean).join(" - "),grade:V.grade,section:V.section});return{..._,grade:V.grade,section:V.section,className:me.className||[V.grade,V.section].filter(Boolean).join(" - "),classSectionId:me.classSectionId||_.classSectionId,classMetadata:me}});ze(T),m?.(T),j>0?le.warning(`Saved ${$} records, ${j} failed`):le.success("Records saved successfully")}catch{le.error("Failed to save changes")}finally{Pe(!1)}};return e.jsx("div",{className:"h-full overflow-y-auto w-full block",children:e.jsxs("div",{className:"w-full p-[24px] xl:p-[32px] space-y-[24px]",children:[S==="main"&&e.jsxs("div",{className:"block space-y-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[16px] p-4 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-slate-200 flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-indigo-50 flex items-center justify-center border border-indigo-100/50",children:e.jsx(lr,{className:"w-5 h-5 text-indigo-500"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[14px] font-bold text-[#1e293b]",children:"Upload Context"}),e.jsx("p",{className:"text-[12px] text-[#64748b]",children:"Select where the imported data should be applied"})]})]}),e.jsxs("div",{className:"relative w-full md:w-[300px]",children:[e.jsxs("select",{className:"appearance-none bg-[#f8fafc] border border-[#e2e8f0] text-[#1e293b] font-bold text-[13px] rounded-lg pl-4 pr-10 py-2.5 outline-none focus:border-[#4f46e5] focus:ring-2 focus:ring-[#4f46e5]/20 shadow-[0_1px_4px_rgba(0,0,0,0.02)] cursor-pointer w-full transition-colors",value:s||t||"All Classes",onChange:()=>{},children:[e.jsx("option",{value:"All Classes",children:"All Classes"}),o.map($=>e.jsx("option",{value:$.classSectionId||$.id,children:$.name},$.id))]}),e.jsx(Ot,{className:"w-4 h-4 text-[#64748b] absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{onDragOver:$=>{$.preventDefault(),L(!0)},onDragLeave:()=>L(!1),onDrop:$=>{$.preventDefault(),L(!1);const j=$.dataTransfer.files[0];j&&B(j)},onClick:()=>re.current?.click(),className:`border-2 border-dashed transition-all rounded-[24px] p-8 flex flex-col items-center justify-center text-center cursor-pointer group shadow-[0_4px_20px_rgba(0,0,0,0.02)] relative overflow-hidden h-[280px] ${I?"border-[#1FA7E1] bg-[#1FA7E1]/10":"border-[#1FA7E1]/30 hover:border-[#1FA7E1] bg-white hover:bg-[#1FA7E1]/5"}`,children:[e.jsx("input",{ref:re,type:"file",accept:".csv,.xlsx,.xls",onChange:$=>{const j=$.target.files?.[0];j&&B(j)},className:"hidden"}),e.jsx("div",{className:"w-16 h-16 rounded-full bg-[#1FA7E1]/10 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300 shadow-sm border border-[#1FA7E1]/20",children:f?e.jsx("span",{className:"animate-spin text-[#1FA7E1]",children:"..."}):e.jsx(cd,{className:"w-8 h-8 text-[#1FA7E1]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:f?"Uploading...":"Class Records"}),e.jsx("p",{className:"text-[13px] text-[#64748b] max-w-sm mb-6",children:"Upload student grades, attendance logs, and quiz scores to power predictive analytics."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".csv"}),e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".xlsx"})]})]}),e.jsxs("div",{onDragOver:$=>{$.preventDefault(),W(!0)},onDragLeave:()=>W(!1),onDrop:$=>{$.preventDefault(),W(!1);const j=$.dataTransfer.files[0];j&&te(j)},onClick:()=>ce.current?.click(),className:`border-2 border-dashed transition-all rounded-[24px] p-8 flex flex-col items-center justify-center text-center cursor-pointer group shadow-[0_4px_20px_rgba(0,0,0,0.02)] relative overflow-hidden h-[280px] ${A?"border-[#9956DE] bg-[#9956DE]/10":"border-[#9956DE]/30 hover:border-[#9956DE] bg-white hover:bg-[#9956DE]/5"}`,children:[e.jsx("input",{ref:ce,type:"file",accept:".pdf,.docx,.txt",onChange:$=>{const j=$.target.files?.[0];j&&te(j)},className:"hidden"}),e.jsx("div",{className:"w-16 h-16 rounded-full bg-[#9956DE]/10 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300 shadow-sm border border-[#9956DE]/20",children:b?e.jsx("span",{className:"animate-spin text-[#9956DE]",children:"..."}):e.jsx(As,{className:"w-8 h-8 text-[#9956DE]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:b?"Uploading...":"Course Materials"}),e.jsx("p",{className:"text-[13px] text-[#64748b] max-w-sm mb-6",children:"Upload syllabus, lesson plans, and curriculum docs to ground AI lesson generation."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".pdf"}),e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".docx"}),e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".txt"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-[16px]",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#0ea5e9] to-[#0284c7] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(14,165,233,0.2)] flex flex-col text-white group transition-all duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-sky-500/30",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full"}),e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center shrink-0 mb-3 relative z-10 transition-transform group-hover:scale-110",children:e.jsx(id,{className:"w-5 h-5 text-white"})}),e.jsx("h4",{className:"font-bold text-[14px] mb-1.5 relative z-10",children:"Smart Parsing"}),e.jsx("p",{className:"text-[12px] text-white/90 leading-relaxed relative z-10",children:"AI automatically understands varied spreadsheet formats and maps column names securely."})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f97316] to-[#ea580c] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(249,115,22,0.2)] flex flex-col text-white group transition-all duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-orange-500/30",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full"}),e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center shrink-0 mb-3 relative z-10 transition-transform group-hover:scale-110",children:e.jsx(Kr,{className:"w-5 h-5 text-white"})}),e.jsx("h4",{className:"font-bold text-[14px] mb-1.5 relative z-10",children:"Risk Prediction"}),e.jsx("p",{className:"text-[12px] text-white/90 leading-relaxed relative z-10",children:"Analyzes historical performance patterns across your data to predict at-risk students."})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(168,85,247,0.2)] flex flex-col text-white group transition-all duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-purple-500/30",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full"}),e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center shrink-0 mb-3 relative z-10 transition-transform group-hover:scale-110",children:e.jsx(bs,{className:"w-5 h-5 text-white"})}),e.jsx("h4",{className:"font-bold text-[14px] mb-1.5 relative z-10",children:"Contextual AI"}),e.jsx("p",{className:"text-[12px] text-white/90 leading-relaxed relative z-10",children:"Maps curriculum topics to generate highly personalized remedial lesson paths."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white flex flex-col justify-between h-full",children:[e.jsx("h2",{className:"text-[16px] font-semibold text-[#1e293b] mb-4",children:"Data Health"}),e.jsxs("div",{className:"flex-1 bg-emerald-50/50 border border-emerald-100 rounded-[16px] p-6 flex flex-col items-center justify-center text-center transition-all duration-300 hover:bg-emerald-50 hover:shadow-md hover:border-emerald-200",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-emerald-100 flex items-center justify-center mb-3 text-emerald-600 transition-transform duration-300 hover:scale-110 hover:-translate-y-1",children:e.jsx(Sa,{className:"w-6 h-6"})}),e.jsx("h3",{className:"text-emerald-700 font-bold text-[15px] mb-1",children:"All Records Synced"}),e.jsx("p",{className:"text-emerald-600/80 text-[12px] max-w-[200px]",children:"AI parsing completed successfully with no anomalies detected."})]}),e.jsxs("div",{className:"flex flex-col gap-2 mt-4",children:[e.jsxs("button",{onClick:()=>N("edit-records"),className:"w-full flex items-center justify-center gap-2 bg-[#1e293b] hover:bg-black text-white text-[13px] font-semibold rounded-full px-4 py-3 shadow-[0_1px_4px_rgba(0,0,0,0.04)] transition-transform hover:scale-[1.02]",children:[e.jsx(ad,{className:"w-4 h-4"})," Edit Class Records"]}),e.jsx("button",{onClick:()=>N("mapping-logs"),className:"w-full flex items-center justify-center gap-2 bg-white text-[#475569] border border-slate-300 hover:bg-slate-50 text-[13px] font-semibold rounded-full px-4 py-3 shadow-[0_1px_4px_rgba(0,0,0,0.04)] transition-colors",children:"View Mapping Logs"})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white flex flex-col h-full",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-[16px] font-semibold text-[#1e293b]",children:"Recent Uploads"}),e.jsx("button",{onClick:()=>N("mapping-logs"),className:"text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors",children:"View All"})]}),e.jsxs("div",{className:"flex-1 space-y-[12px] overflow-y-auto no-scrollbar flex flex-col justify-center items-center h-[120px]",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-slate-50 flex items-center justify-center mb-2 border border-slate-100",children:e.jsx(Xc,{className:"w-5 h-5 text-slate-300"})}),e.jsx("p",{className:"text-[13px] font-medium text-slate-500",children:"There are no recent uploads yet."})]})]})]})]}),S==="mapping-logs"&&e.jsxs("div",{className:"space-y-[16px]",children:[e.jsx("div",{className:"shrink-0 mb-2",children:e.jsxs("button",{onClick:()=>N("main"),className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors w-max bg-white px-[18px] py-2 rounded-full shadow-sm border border-slate-200",children:[e.jsx(cr,{className:"w-4 h-4"})," Back to Uploads"]})}),e.jsxs("div",{className:"bg-white rounded-[18px] border border-[#f1f5f9] overflow-hidden shadow-sm",children:[e.jsx("div",{className:"p-5 border-b border-[#f1f5f9] bg-slate-50 flex justify-between items-center",children:e.jsx("h2",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Latest Import Mapping"})}),e.jsx("div",{className:"p-5",children:D?e.jsx("div",{className:"space-y-3",children:D.columns.map(($,j)=>e.jsxs("div",{className:"flex justify-between p-3 border rounded bg-slate-50",children:[e.jsx("span",{className:"font-semibold text-sm",children:$.columnName}),e.jsx("span",{className:"text-sm text-indigo-600",children:$.mappedField||"Unmapped"})]},j))}):e.jsx("p",{className:"text-slate-500 text-sm",children:"No recent mapping logs to display."})})]})]}),S==="edit-records"&&e.jsxs("div",{className:"space-y-[16px] h-full flex flex-col",children:[e.jsx("div",{className:"shrink-0 mb-2",children:e.jsxs("button",{onClick:()=>N("main"),className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors w-max bg-white px-[18px] py-2 rounded-full shadow-sm border border-slate-200",children:[e.jsx(cr,{className:"w-4 h-4"})," Back to Uploads"]})}),e.jsxs("div",{className:"bg-white rounded-[18px] border border-slate-200 shadow-sm overflow-hidden flex flex-col flex-1",children:[e.jsxs("div",{className:"p-5 border-b border-slate-200 flex justify-between items-center bg-white",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-[18px] font-bold text-[#1e293b]",children:"Edit Class Records"}),e.jsx("p",{className:"text-[13px] text-[#64748b]",children:"Review and modify student data manually"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>N("main"),className:"px-5 py-2 rounded-full border border-slate-300 text-slate-700 font-semibold text-[13px] hover:bg-slate-50",children:"Cancel"}),e.jsx("button",{onClick:pe,disabled:Fe,className:"px-5 py-2 rounded-full bg-emerald-500 text-white font-semibold text-[13px] hover:bg-emerald-600 flex items-center gap-2 disabled:opacity-50",children:Fe?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(yi,{className:"w-4 h-4"})," Save Changes"]})})]})]}),e.jsxs("div",{className:"px-5 py-3 border-b border-slate-200 flex justify-between items-center bg-slate-50/50 shrink-0 text-slate-500 text-[13px]",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(oa,{className:"w-4 h-4"})," Click on any field to edit"]}),e.jsxs("span",{children:["Showing ",M.length," records"]})]}),e.jsx("div",{className:"overflow-auto flex-1 table-scrollbar bg-white relative",children:e.jsxs("div",{className:"min-w-[1100px] w-full flex flex-col min-h-full",children:[e.jsxs("div",{className:"flex items-center w-full bg-slate-100/90 border-b border-slate-200 text-[12px] font-semibold text-slate-500 tracking-wide sticky top-0 z-20 shadow-[0_1px_2px_rgba(0,0,0,0.02)] h-12",children:[e.jsx("div",{className:"flex-[1.5] min-w-[240px] px-6 sticky left-0 z-30 bg-slate-100/90 backdrop-blur-sm border-r border-slate-200 h-full flex items-center shadow-[2px_0_4px_rgba(0,0,0,0.02)]",children:"Student Name"}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 h-full flex items-center justify-center",children:"LRN"}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 h-full flex items-center justify-center",children:"Grade"}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 h-full flex items-center justify-center",children:"Section"}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 h-full flex items-center justify-center",children:"Avg Score"}),e.jsx("div",{className:"w-[120px] shrink-0 px-4 h-full flex items-center justify-center",children:"Risk Level"}),e.jsx("div",{className:"flex-1 min-w-[180px] px-4 h-full flex items-center justify-center",children:"Weakest Topic"}),e.jsx("div",{className:"w-[80px] shrink-0 px-4 h-full flex items-center justify-center border-r border-transparent",children:"Action"})]}),e.jsx("div",{className:"flex flex-col w-full pb-4",children:M.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4",children:e.jsx(oa,{className:"w-7 h-7 text-slate-400"})}),e.jsx("h3",{className:"text-[16px] font-bold text-slate-700 mb-2",children:"No managed classes found"}),e.jsx("p",{className:"text-[13px] text-slate-500 max-w-sm",children:"You don't currently manage any classes. Ask your administrator to assign you as a section manager, or create a new class from the Dashboard."})]}):M.map(($,j)=>{const T=Ka($),_=$.name.split(" "),V=_.length>1?`${_[0][0]}${_[_.length-1][0]}`.toUpperCase():$.name.substring(0,2).toUpperCase(),me=["bg-[#be185d]","bg-[#3b82f6]","bg-[#f43f5e]","bg-[#2563eb]","bg-[#059669]","bg-[#d946ef]"],oe=me[j%me.length],ae=($.avgScore??0)>=75?"text-emerald-500":($.avgScore??0)>=60?"text-orange-500":"text-rose-500";let je="bg-slate-50 text-slate-600 border-slate-200";const we=($.riskLevel||"").toLowerCase();return we==="low"?je="bg-emerald-50 text-emerald-600 border-emerald-200":we==="high"?je="bg-rose-50 text-rose-600 border-rose-200":we==="medium"&&(je="bg-orange-50 text-orange-600 border-orange-200"),e.jsxs("div",{className:"flex items-center w-full border-b border-slate-100 hover:bg-slate-50 transition-colors group min-h-[64px]",children:[e.jsxs("div",{className:"flex-[1.5] min-w-[240px] px-6 sticky left-0 z-10 bg-white group-hover:bg-slate-50 border-r border-slate-100 h-full flex items-center gap-4 shadow-[2px_0_4px_rgba(0,0,0,0.01)]",children:[e.jsx("div",{className:`w-8 h-8 rounded-full ${oe} text-white flex items-center justify-center font-bold text-[12px] shrink-0`,children:V}),e.jsx("span",{className:"font-semibold text-slate-800 text-[14px] truncate",children:$.name})]}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 flex justify-center text-[13px] text-slate-500",children:$.lrn||"—"}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 flex justify-center",children:e.jsx("input",{type:"text",value:q[T]?.grade||$.grade||"",onChange:Ke=>Q(Ue=>({...Ue,[T]:{...Ue[T],grade:Ke.target.value}})),readOnly:G!==T,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${G===T?"bg-white border border-purple-500 ring-2 ring-purple-500/20":"bg-slate-100 border border-transparent cursor-default"}`})}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 flex justify-center",children:e.jsx("input",{type:"text",value:q[T]?.section||$.section||"",onChange:Ke=>Q(Ue=>({...Ue,[T]:{...Ue[T],section:Ke.target.value}})),readOnly:G!==T,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${G===T?"bg-white border border-purple-500 ring-2 ring-purple-500/20":"bg-slate-100 border border-transparent cursor-default"}`})}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 flex justify-center",children:e.jsxs("span",{className:`${ae} font-bold text-[14px]`,children:[$.avgScore,"%"]})}),e.jsx("div",{className:"w-[120px] shrink-0 px-4 flex justify-center",children:e.jsx("span",{className:`px-3 py-1 text-[10px] font-bold rounded uppercase border ${je}`,children:$.riskLevel||"Unknown"})}),e.jsx("div",{className:"flex-1 min-w-[180px] px-4 flex justify-center text-[13px] text-slate-600 truncate",children:$.weakestTopic||"Foundational Skills"}),e.jsx("div",{className:"w-[80px] shrink-0 px-4 flex justify-center border-r border-transparent",children:e.jsx("button",{onClick:()=>se(G===T?null:T),className:`w-8 h-8 rounded-full flex items-center justify-center transition-colors ${G===T?"bg-purple-100 text-purple-600":"hover:bg-slate-200 text-slate-400"}`,children:e.jsx(Ci,{className:"w-4 h-4"})})})]},T)})})]})})]})]})]})})}const Vx=[{value:"available",label:"Available",icon:e.jsx(La,{size:14}),color:"text-emerald-600"},{value:"teacher_uploaded",label:"Teacher Material",icon:e.jsx(Wr,{size:14}),color:"text-blue-600"},{value:"coming_soon",label:"Coming Soon",icon:e.jsx(Ls,{size:14}),color:"text-amber-600"},{value:"unavailable",label:"Unavailable",icon:e.jsx(yc,{size:14}),color:"text-slate-400"}],Wx=({teacherId:t})=>{const[s,a]=u.useState(""),[r,o]=u.useState("teacher_uploaded"),[n,i]=u.useState(!1),[l,c]=u.useState(null),d=async()=>{if(!s){le.error("Select a module first.");return}i(!0);try{let m;if(l&&r==="teacher_uploaded"){const p=Fc(Ql,`teacher_modules/${t}/${s}/${l.name}`);await Oc(p,l),m=await Pc(p)}await $c(s,r,t,m),le.success(`Module status updated to "${r}".`),c(null)}catch(m){le.error(m.message||"Failed to update module status.")}finally{i(!1)}};return e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-white p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-slate-800",children:"Module Availability Control"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"Set module status or upload alternative PDF when DepEd content is unavailable."})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-600 mb-1 block",children:"Module"}),e.jsxs("select",{value:s,onChange:m=>a(m.target.value),className:"w-full rounded-lg border border-slate-200 px-3 py-2 text-sm",children:[e.jsx("option",{value:"",children:"Select module..."}),Gl.map(m=>e.jsxs("option",{value:m.id,children:[m.moduleTitle," (",m.quarter,")"]},m.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-600 mb-1 block",children:"Status"}),e.jsx("select",{value:r,onChange:m=>o(m.target.value),className:"w-full rounded-lg border border-slate-200 px-3 py-2 text-sm",children:Vx.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))})]})]}),r==="teacher_uploaded"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-600 mb-1 block",children:"Upload Alternative PDF (optional)"}),e.jsx("input",{type:"file",accept:".pdf",onChange:m=>c(m.target.files?.[0]||null),className:"text-sm text-slate-600"})]}),e.jsx("button",{type:"button",onClick:d,disabled:!s||n,className:"px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-bold disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:n?"Updating...":"Update Status"})]})},Xa="ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789",ri="school.mathpulse.local";function ni(t=10){const s=typeof globalThis<"u"&&typeof globalThis.crypto<"u"?globalThis.crypto:void 0;if(s&&typeof s.getRandomValues=="function"){const r=new Uint32Array(t);s.getRandomValues(r);let o="";for(let n=0;n{const[l,c]=u.useState(""),[d,m]=u.useState(""),[p,h]=u.useState(!1),[v,y]=u.useState(null),[S,N]=u.useState(null),[w,g]=u.useState(!1);u.useEffect(()=>{t&&(y(null),g(!1),h(!1),N(null),c((a?.email||qx(a)).trim()),m(ni()))},[t,a]);const I=u.useMemo(()=>a?[a.grade,a.section].filter(Boolean).join(" · ")||"Unassigned section":null,[a]),L=()=>{m(ni()),g(!1)},A=async()=>{try{const C=S?.temporaryPassword||d;if(!C)return;typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(C),g(!0),le.success("Temporary password copied. Share it with the student now — it will not be shown again."),window.setTimeout(()=>g(!1),2500)}catch(C){console.warn("Clipboard write failed:",C),le.error("Unable to copy password. Please copy it manually.")}},W=async()=>{if(!a)return;const C=l.trim();if(!Yx(C)){y("Enter a valid email address before creating the account.");return}if(!d||d.length<8){y("Temporary password must be at least 8 characters.");return}if(!r){y("Missing teacher context. Please refresh and try again.");return}h(!0),y(null);try{const b=await Yu({name:a.name,lrn:a.lrn,email:C,grade:a.grade,section:a.section,classSectionId:a.classSectionId,adviserTeacherId:r,adviserTeacherName:o,schoolYear:n,temporaryPassword:d});N(b),i?.({...b,rosterId:a.rosterId}),le.success(`Account created for ${a.name}.`)}catch(b){const F=b instanceof Error?b.message:"Failed to create account.";y(F)}finally{h(!1)}},f=S?.temporaryPassword||d;return e.jsx(zt,{children:t&&a&&e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4",onClick:()=>{p||s()},children:e.jsxs(Re.div,{initial:{opacity:0,scale:.95,y:12},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:12},transition:{type:"spring",damping:28,stiffness:320},onClick:C=>C.stopPropagation(),className:"bg-[#f7f9fc] rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden border border-[#dde3eb]",role:"dialog","aria-modal":"true","aria-labelledby":"create-student-account-modal-title",children:[e.jsxs("div",{className:"flex items-start justify-between px-6 pt-6",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0",children:e.jsx(ui,{size:22})}),e.jsxs("div",{children:[e.jsx("h2",{id:"create-student-account-modal-title",className:"text-[16px] font-bold text-[#0a1628]",children:S?"Account Created":"Create Student Account"}),e.jsx("p",{className:"text-[12px] text-[#5a6578] mt-0.5",children:S?"Share these credentials with the student. The password will not be shown again.":`Provision a system account for ${a.name}.`})]})]}),e.jsx("button",{type:"button",onClick:()=>{p||s()},className:"p-1.5 rounded-lg hover:bg-[#dde3eb] transition-colors","aria-label":"Close",children:e.jsx(qt,{className:"w-4 h-4 text-[#5a6578]"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-4",children:[e.jsxs("div",{className:"bg-white border border-[#e2e8f0] rounded-2xl p-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-[#64748b]",children:"Roster Row"}),e.jsx("p",{className:"text-[14px] font-semibold text-[#0a1628] mt-1",children:a.name}),e.jsxs("p",{className:"text-[12px] text-[#475569] mt-0.5",children:[a.lrn?`LRN ${a.lrn} · `:"",I]})]}),!S&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-[12px] font-semibold text-[#0a1628]",children:"Email address"}),e.jsx("input",{type:"email",value:l,onChange:C=>c(C.target.value),disabled:p,className:"mt-1 w-full rounded-xl border border-[#dde3eb] bg-white px-3 py-2 text-[13px] text-[#0a1628] focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-200",placeholder:"student@school.example",autoComplete:"off",spellCheck:!1}),e.jsx("span",{className:"text-[11px] text-[#64748b] mt-1 block",children:"Auto-generated from LRN if available. The student will sign in with this address."})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[12px] font-semibold text-[#0a1628] block",children:"Temporary password"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("input",{type:"text",value:d,readOnly:!0,className:"flex-1 rounded-xl border border-[#dde3eb] bg-white px-3 py-2 text-[13px] font-mono tracking-wide text-[#0a1628] focus:outline-none"}),e.jsx("button",{type:"button",onClick:L,disabled:p,className:"p-2 rounded-xl border border-[#dde3eb] bg-white hover:bg-[#f1f5f9] transition-colors disabled:opacity-60","aria-label":"Regenerate temporary password",children:e.jsx(xs,{className:"w-4 h-4 text-[#475569]"})}),e.jsx("button",{type:"button",onClick:A,className:"p-2 rounded-xl border border-[#dde3eb] bg-white hover:bg-[#f1f5f9] transition-colors","aria-label":"Copy temporary password",children:w?e.jsx(Gt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Vr,{className:"w-4 h-4 text-[#475569]"})})]}),e.jsx("span",{className:"text-[11px] text-[#64748b] mt-1 block",children:"The student should change this on first sign-in. Share it once — it will not be persisted."})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 rounded-xl bg-rose-50 border border-rose-200 px-3 py-2 text-[12px] text-rose-700",children:[e.jsx(Lc,{className:"w-4 h-4 mt-0.5 shrink-0"}),e.jsx("span",{children:v})]})]}),S&&e.jsxs("div",{className:"rounded-2xl border border-emerald-200 bg-emerald-50 p-4 space-y-2",children:[e.jsx("p",{className:"text-[12px] font-semibold text-emerald-800",children:"Credentials"}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl bg-white border border-emerald-100 px-3 py-2",children:[e.jsx("span",{className:"text-[12px] text-[#475569]",children:"Email"}),e.jsx("span",{className:"text-[13px] font-semibold text-[#0a1628]",children:S.email})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl bg-white border border-emerald-100 px-3 py-2",children:[e.jsx("span",{className:"text-[12px] text-[#475569]",children:"Temporary password"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[13px] font-semibold font-mono text-[#0a1628]",children:f}),e.jsx("button",{type:"button",onClick:A,className:"p-1.5 rounded-lg border border-emerald-200 bg-white hover:bg-emerald-100 transition-colors","aria-label":"Copy temporary password",children:w?e.jsx(Gt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Vr,{className:"w-4 h-4 text-emerald-700"})})]})]}),e.jsx("p",{className:"text-[11px] text-emerald-800",children:"This password is not stored anywhere. If you close this dialog without copying, you will need to reset it from the admin tools."})]})]}),e.jsx("div",{className:"flex items-center justify-end gap-2 px-6 pb-6",children:S?e.jsx(wt,{type:"button",onClick:s,className:"bg-indigo-600 hover:bg-indigo-700 text-white text-[13px] font-semibold rounded-xl px-5 py-2",children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{type:"button",variant:"ghost",onClick:s,disabled:p,className:"text-[13px] font-semibold text-[#475569] rounded-xl px-4 py-2 hover:bg-[#dde3eb]",children:"Cancel"}),e.jsx(wt,{type:"button",onClick:W,disabled:p,className:"bg-indigo-600 hover:bg-indigo-700 text-white text-[13px] font-semibold rounded-xl px-5 py-2 disabled:opacity-60",children:p?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(gt,{className:"w-4 h-4 animate-spin"}),"Creating…"]}):"Create account"})]})})]})})})};function Xx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=yt({metadata:t.classMetadata,classSectionId:t.classSectionId,className:t.name,grade:t.grade,gradeLevel:t.gradeLevel,classification:t.classification,strand:t.strand,section:t.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId||t.teacherId,ownerTeacherName:t.ownerTeacherName,adviserTeacherId:t.adviserTeacherId||t.teacherId,adviserTeacherName:t.adviserTeacherName||t.ownerTeacherName,managerId:t.managerId,managerName:t.managerName});return{id:t.id,name:a.className||t.name,classSectionId:a.classSectionId||t.classSectionId,classMetadata:a,gradeLevel:a.gradeLevel||void 0,classification:a.classification||void 0,strand:a.strand||void 0,managerId:a.managerId||void 0,managerName:a.managerName||void 0,schedule:t.schedule,studentCount:t.studentCount,avgScore:t.avgScore,atRiskCount:t.atRiskCount,riskLevel:s}}function Hr(t,s){const a=t.riskStatus?["intervene","critical","at_risk"].includes(t.riskStatus)?"high":t.riskStatus==="watch"?"medium":"low":(t.riskLevel||"Low").toLowerCase(),r=t.lastActive?Tl(t.lastActive.toDate()):"Unknown",o=t.className||s||"Imported Class",n=gs(o),i=t.grade||n.grade,l=t.section||n.section,c=yt({metadata:t.classMetadata,classSectionId:t.classSectionId||t.classroomId,className:[i,l].filter(Boolean).join(" - ")||o,grade:i,gradeLevel:t.gradeLevel,classification:t.classification,strand:t.strand,section:l,adviserTeacherId:t.teacherId,ownerTeacherId:t.teacherId,managerId:t.classMetadata?.managerId||t.managerId,managerName:t.classMetadata?.managerName||t.managerName});return{id:t.id,lrn:t.lrn,name:t.name,avatar:t.avatar||`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:t.avgQuizScore,riskLevel:a,riskStatus:t.riskStatus||null,wri:t.wri??null,weakestTopic:t.weakestTopic||"N/A",classroomId:t.classroomId||c.classSectionId||o,className:c.className||[i,l].filter(Boolean).join(" - ")||o,grade:i,gradeLevel:c.gradeLevel||Ns(i)||void 0,classification:c.classification||pa(c.gradeLevel||i)||void 0,strand:c.strand||ha(c.className,l)||void 0,section:l,classSectionId:c.classSectionId||t.classSectionId,classMetadata:c,managerId:c.managerId||void 0,managerName:c.managerName||void 0,lastActive:r,struggles:t.struggles||[],engagementScore:t.engagementScore,attendance:t.attendance,assignmentCompletion:t.assignmentCompletion,hasRegisteredAccount:t.hasRegisteredAccount,source:t.source,accountUid:t.accountUid,email:t.email}}function Jx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=yt({metadata:t.classMetadata,classSectionId:t.classSectionId,className:t.name,grade:t.grade,gradeLevel:t.gradeLevel||t.classMetadata?.gradeLevel,classification:t.classification||t.classMetadata?.classification,strand:t.strand||t.classMetadata?.strand,section:t.section,managerId:t.managerId||t.classMetadata?.managerId,managerName:t.managerName||t.classMetadata?.managerName});return{id:t.id,name:a.className||t.name,classSectionId:a.classSectionId||t.classSectionId||void 0,classMetadata:a,gradeLevel:a.gradeLevel||void 0,classification:a.classification||void 0,strand:a.strand||void 0,managerId:a.managerId||void 0,managerName:a.managerName||void 0,schedule:t.schedule||"Mon-Fri",studentCount:t.studentCount,avgScore:t.avgScore,atRiskCount:t.atRiskCount,riskLevel:s}}function Zx(t){const s=(t.riskLevel||"Low").toLowerCase(),a=yt({metadata:t.classMetadata,classSectionId:t.classSectionId,className:t.className||[t.grade,t.section].filter(Boolean).join(" - ")||"Imported Class",grade:t.grade,gradeLevel:t.gradeLevel||t.classMetadata?.gradeLevel,classification:t.classification||t.classMetadata?.classification,strand:t.strand||t.classMetadata?.strand,section:t.section,managerId:t.managerId||t.classMetadata?.managerId,managerName:t.managerName||t.classMetadata?.managerName}),r=a.className||"Imported Class";return{id:t.id,lrn:t.lrn||void 0,name:t.name,avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:t.avgQuizScore,riskLevel:s,weakestTopic:t.weakestTopic||"Foundational Skills",classroomId:a.classSectionId||t.classSectionId||r,className:r,grade:a.grade||gs(r).grade,gradeLevel:a.gradeLevel||Ns(a.grade||gs(r).grade)||void 0,classification:a.classification||pa(a.gradeLevel||a.grade)||void 0,strand:a.strand||ha(r,a.section||t.section)||void 0,section:a.section||gs(r).section,classSectionId:a.classSectionId||t.classSectionId||void 0,classMetadata:a,managerId:a.managerId||void 0,managerName:a.managerName||void 0,lastActive:"Recently imported",struggles:[t.weakestTopic||"Foundational Skills"],engagementScore:t.engagementScore,attendance:t.attendance,assignmentCompletion:t.assignmentCompletion}}function ep(t,s,a){return t<60||s<75||a<55?"high":t<75||s<85||a<70?"medium":"low"}function tp(t,s,a,r){const o=yt({metadata:r,classSectionId:s,className:a}),n=o.className||"Imported Class",i=o.classSectionId||"imported_class",l=Number(t.avgQuizScore||0),c=Number(t.attendance||0),d=Number(t.engagementScore||0),m=Number(t.assignmentCompletion||0),p=t.unknownFields?.weakestTopic||t.unknownFields?.topic||"Foundational Skills",h=ep(l,c,d),v=t.studentId||t.lrn||t.email||t.name||Math.random().toString(36).slice(2);return{id:`upload-${i}-${v}`,lrn:t.lrn,name:t.name,avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:l,riskLevel:h,weakestTopic:p,classroomId:i,className:n,grade:o.grade||gs(n).grade,gradeLevel:o.gradeLevel||Ns(o.grade||gs(n).grade)||void 0,classification:o.classification||pa(o.gradeLevel||o.grade)||void 0,strand:o.strand||ha(n,o.section)||void 0,section:o.section||gs(n).section,classSectionId:i,classMetadata:o,managerId:o.managerId||void 0,managerName:o.managerName||void 0,lastActive:"Recently imported",struggles:[p],engagementScore:d,attendance:c,assignmentCompletion:m}}function Tl(t){const s=Date.now()-t.getTime(),a=Math.floor(s/6e4);if(a<1)return"Just now";if(a<60)return`${a} min${a>1?"s":""} ago`;const r=Math.floor(a/60);if(r<24)return`${r} hour${r>1?"s":""} ago`;const o=Math.floor(r/24);return`${o} day${o>1?"s":""} ago`}function lt(t){return(t||"").trim().toLowerCase()}function oi(t){const s=lt(t.classSectionId);if(s)return`section:${s}`;const a=(t.id||"").trim().toLowerCase();return a?`id:${a}`:`name:${(t.name||"").trim().toLowerCase()}`}function ii(t,s){const a=new Map;return t.forEach(r=>{a.set(oi(r),r)}),s.forEach(r=>{const o=oi(r),n=a.get(o);if(!n){a.set(o,r);return}const i=Math.max(n.atRiskCount||0,r.atRiskCount||0),l=Math.max(n.studentCount||0,r.studentCount||0),c=r.avgScore>0?r.avgScore:n.avgScore,d=i>=5?"high":i>=2?"medium":"low",m=yt({metadata:n.classMetadata,classSectionId:n.classSectionId||r.classSectionId,className:n.name||r.name,grade:n.classMetadata?.grade||r.classMetadata?.grade,gradeLevel:n.classMetadata?.gradeLevel||r.classMetadata?.gradeLevel,classification:n.classMetadata?.classification||r.classMetadata?.classification,strand:n.classMetadata?.strand||r.classMetadata?.strand,section:n.classMetadata?.section||r.classMetadata?.section,schoolYear:n.classMetadata?.schoolYear||r.classMetadata?.schoolYear,ownerTeacherId:n.classMetadata?.ownerTeacherId||r.classMetadata?.ownerTeacherId,ownerTeacherName:n.classMetadata?.ownerTeacherName||r.classMetadata?.ownerTeacherName,adviserTeacherId:n.classMetadata?.adviserTeacherId||r.classMetadata?.adviserTeacherId,adviserTeacherName:n.classMetadata?.adviserTeacherName||r.classMetadata?.adviserTeacherName,managerId:n.classMetadata?.managerId||r.classMetadata?.managerId,managerName:n.classMetadata?.managerName||r.classMetadata?.managerName});a.set(o,{...n,classSectionId:m.classSectionId||n.classSectionId||r.classSectionId,name:m.className||n.name||r.name,classMetadata:m,gradeLevel:m.gradeLevel||void 0,classification:m.classification||void 0,strand:m.strand||void 0,managerId:m.managerId||void 0,managerName:m.managerName||void 0,schedule:n.schedule||r.schedule,studentCount:l,atRiskCount:i,avgScore:c,riskLevel:d})}),Array.from(a.values())}function gr(t){const s=(t.lrn||"").trim().toLowerCase();if(s)return`lrn:${s}`;const a=t.name.trim().toLowerCase();if(a)return`name:${a}`;const r=lt(t.classSectionId)||lt(t.classroomId),o=(t.id||"").trim().toLowerCase();return r&&o?`${r}|id:${o}`:`${r}|anonymous`}function ln(t){const s=lt(t.classSectionId)||lt(t.classroomId),a=(t.lrn||"").trim().toLowerCase(),r=(t.id||"").trim().toLowerCase(),o=t.name.trim().toLowerCase().replace(/\s+/g,"_");return s&&a?`${s}|lrn:${a}`:s&&r?`${s}|id:${r}`:a?`lrn:${a}`:r&&o?`id:${r}|name:${o}`:r?`id:${r}`:s&&o?`${s}|name:${o}`:`name:${o||"unknown"}`}function li(t,s){const a=new Map;return t.forEach(r=>{a.set(gr(r),r)}),s.forEach(r=>{const o=gr(r),n=a.get(o);if(!n){a.set(o,r);return}const i=[n.riskLevel,r.riskLevel].includes("high")?"high":[n.riskLevel,r.riskLevel].includes("medium")?"medium":"low",l=yt({metadata:n.classMetadata,classSectionId:n.classSectionId||r.classSectionId,className:n.className||r.className,grade:n.grade||r.grade,gradeLevel:n.gradeLevel||r.gradeLevel,classification:n.classification||r.classification,strand:n.strand||r.strand,section:n.section||r.section,managerId:n.managerId||r.managerId,managerName:n.managerName||r.managerName});a.set(o,{...n,lrn:n.lrn||r.lrn,classSectionId:l.classSectionId||n.classSectionId||r.classSectionId,classroomId:n.classroomId||r.classroomId,className:l.className||n.className||r.className,grade:l.grade||n.grade||r.grade,gradeLevel:l.gradeLevel||n.gradeLevel||r.gradeLevel,classification:l.classification||n.classification||r.classification,strand:l.strand||n.strand||r.strand,section:l.section||n.section||r.section,managerId:l.managerId||n.managerId||r.managerId,managerName:l.managerName||n.managerName||r.managerName,classMetadata:l,avgScore:r.avgScore>0?r.avgScore:n.avgScore,attendance:r.attendance>0?r.attendance:n.attendance,engagementScore:r.engagementScore>0?r.engagementScore:n.engagementScore,assignmentCompletion:r.assignmentCompletion>0?r.assignmentCompletion:n.assignmentCompletion,weakestTopic:n.weakestTopic&&n.weakestTopic!=="N/A"?n.weakestTopic:r.weakestTopic,riskLevel:i,struggles:n.struggles.length>0?n.struggles:r.struggles,hasRegisteredAccount:n.hasRegisteredAccount===!0||r.hasRegisteredAccount===!0?!0:n.hasRegisteredAccount??r.hasRegisteredAccount,source:n.source==="registered"&&r.source==="import"||n.source==="import"&&r.source==="registered"||n.source==="both"||r.source==="both"?"both":n.source||r.source,accountUid:n.accountUid||r.accountUid,email:n.email||r.email})}),Array.from(a.values())}const lh=({onLogout:t,onOpenProfile:s,onOpenSettings:a})=>{const{currentUser:r,userProfile:o}=vs(),[n,i]=u.useState("dashboard"),[l,c]=u.useState(!1),[d,m]=u.useState(!1),[p,h]=u.useState(!1),[v,y]=u.useState(!1),[S,N]=u.useState(!1),[w,g]=u.useState(!1),[I,L]=u.useState(!1),A=["streak_reminder","daily_checkin","streak_milestone","achievement_unlocked","level_up","xp_earned","quiz_result"],{notifications:W}=fi(),f=W.filter(E=>!E.isRead&&!A.includes(E.type)).length,[C,b]=u.useState(null),[F,U]=u.useState(null),[k,D]=u.useState(!1),[J,re]=u.useState(!1),[ce,ie]=u.useState(!1),[fe,Ce]=u.useState(!1),[ue,ge]=u.useState([]),[B,te]=u.useState([]),ne=u.useMemo(()=>r?.uid?ue.filter(E=>E.managerId===r.uid||E.classMetadata?.managerId===r.uid):ue,[ue,r?.uid]),[ze,Fe]=u.useState([]),[Pe,G]=u.useState(""),[se,M]=u.useState(!0),[q,Q]=u.useState(!1),[pe,$]=u.useState(0),[j,T]=u.useState([]),[_,V]=u.useState(!1),[me,oe]=u.useState(null),[ae,je]=u.useState(null),we=o?.name||"Teacher",Ke=u.useRef(new Map);u.useEffect(()=>{const E=()=>y(window.innerWidth<1024);return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),u.useEffect(()=>{if(!r)return;const E=r.uid;let R=!0,ve;return(async()=>{M(!0);try{const Me=await cl(E);let K=Me.map(Xx);const Xe=await Ju(E).catch(()=>[]),nt=new Map;Xe.forEach(P=>{const X=lt(P.classSectionId);X&&nt.set(X,P)}),K=K.map(P=>{const X=nt.get(lt(P.classSectionId));if(!X)return P;const _e=yt({metadata:P.classMetadata,classSectionId:X.classSectionId||P.classSectionId,className:X.className||P.name,grade:X.grade||P.classMetadata?.grade,gradeLevel:X.gradeLevel||P.classMetadata?.gradeLevel,classification:X.classification||P.classMetadata?.classification,strand:X.strand||P.classMetadata?.strand,section:X.section||P.classMetadata?.section,schoolYear:X.schoolYear||P.classMetadata?.schoolYear,ownerTeacherId:X.ownerTeacherId||P.classMetadata?.ownerTeacherId,ownerTeacherName:X.ownerTeacherName||P.classMetadata?.ownerTeacherName,managerId:X.managerId||P.classMetadata?.managerId,managerName:X.managerName||P.classMetadata?.managerName});return{...P,name:_e.className||P.name,classSectionId:_e.classSectionId||P.classSectionId,classMetadata:_e,gradeLevel:_e.gradeLevel||P.gradeLevel,classification:_e.classification||P.classification,strand:_e.strand||P.strand,managerId:_e.managerId||P.managerId,managerName:_e.managerName||P.managerName}});const ke=new Map,jt=new Map;Me.forEach(P=>{const X=yt({metadata:P.classMetadata,classSectionId:P.classSectionId,className:P.name,grade:P.grade,gradeLevel:P.gradeLevel,classification:P.classification,strand:P.strand,section:P.section,schoolYear:P.schoolYear,ownerTeacherId:P.ownerTeacherId||P.teacherId,ownerTeacherName:P.ownerTeacherName,adviserTeacherId:P.adviserTeacherId||P.teacherId,adviserTeacherName:P.adviserTeacherName,managerId:P.managerId,managerName:P.managerName});ke.set(P.id,X.className||P.name),jt.set(P.id,X);const _e=lt(P.classSectionId);if(_e){const Oe=nt.get(_e),Ht=yt({metadata:X,classSectionId:Oe?.classSectionId||_e,className:Oe?.className||X.className,grade:Oe?.grade||X.grade,gradeLevel:Oe?.gradeLevel||X.gradeLevel,classification:Oe?.classification||X.classification,strand:Oe?.strand||X.strand,section:Oe?.section||X.section,schoolYear:Oe?.schoolYear||X.schoolYear,ownerTeacherId:Oe?.ownerTeacherId||X.ownerTeacherId,ownerTeacherName:Oe?.ownerTeacherName||X.ownerTeacherName,managerId:Oe?.managerId||X.managerId,managerName:Oe?.managerName||X.managerName});ke.set(_e,Ht.className||P.name),jt.set(_e,Ht)}});const Bt=P=>{const X=lt(P.classSectionId||P.classroomId);if(!X)return P;const _e=jt.get(X);if(!_e)return P;const Oe=yt({metadata:_e,classSectionId:P.classSectionId||_e.classSectionId,className:P.className||_e.className,grade:P.grade||_e.grade,gradeLevel:P.gradeLevel||_e.gradeLevel,classification:P.classification||_e.classification,strand:P.strand||_e.strand,section:P.section||_e.section,managerId:P.managerId||_e.managerId,managerName:P.managerName||_e.managerName});return{...P,className:Oe.className||P.className,grade:Oe.grade||P.grade,gradeLevel:Oe.gradeLevel||P.gradeLevel,classification:Oe.classification||P.classification,strand:Oe.strand||P.strand,section:Oe.section||P.section,classSectionId:Oe.classSectionId||P.classSectionId,classMetadata:Oe,managerId:Oe.managerId||P.managerId,managerName:Oe.managerName||P.managerName}},$t=(P,X,_e)=>ke.get(P)||(X?ke.get(X):void 0)||_e||"Unknown",Le=Array.from(new Set([...Xe.map(P=>P.classSectionId),...Me.map(P=>P.classSectionId).filter(Boolean),...K.map(P=>P.classSectionId).filter(Boolean)].map(P=>(P||"").trim()).filter(P=>!!P))),[ft,ut]=await Promise.all([yn(E).catch(P=>(console.warn("[TeacherDashboard] managed-student fetch failed:",P),[])),Vu(E,Le).catch(P=>(console.warn("[TeacherDashboard] registered-student fetch failed:",P),[]))]);let Ft=ut;if(ut.length===0&&ft.length===0)try{const{collection:P,query:X,where:_e,getDocs:Oe}=await Cs(async()=>{const{collection:Ut,query:We,where:ga,getDocs:ba}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{collection:Ut,query:We,where:ga,getDocs:ba}},__vite__mapDeps([2,3])),{db:Ht}=await Cs(async()=>{const{db:Ut}=await import("./index-BvEKrMkD.js").then(We=>We.b7);return{db:Ut}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),De=X(P(Ht,"users"),_e("role","==","student"));Ft=(await Oe(De)).docs.map(Ut=>{const We=Ut.data();return{uid:Ut.id,name:String(We.name||We.displayName||"").trim()||"Student",email:String(We.email||"").trim(),lrn:We.lrn?String(We.lrn).trim():void 0,photo:We.photo?String(We.photo).trim():We.photoURL?String(We.photoURL).trim():void 0,grade:We.grade?String(We.grade).trim():void 0,section:We.section?String(We.section).trim():void 0,classSectionId:We.classSectionId?String(We.classSectionId).trim():void 0,adviserTeacherId:We.adviserTeacherId?String(We.adviserTeacherId).trim():void 0,role:"student",createdAt:We.createdAt||void 0}}).filter(Ut=>Ut.name!=="Student"||Ut.email)}catch(P){console.warn("[TeacherDashboard] fallback all-students fetch failed:",P)}const ss=new Map,Qs=new Map,Pa=new Map;ft.forEach(P=>{ss.set(P.id,P),P.lrn&&Qs.set(P.lrn.trim().toLowerCase(),P);const X=Ao(P.name),_e=lt(P.classSectionId||P.classroomId);X&&Pa.set(`${X}|${_e}`,P)});const Ba=new Set,Ha=Ft.map(P=>{const X=Wu(P),_e=(P.lrn||"").trim().toLowerCase(),Oe=Ao(P.name),Ht=lt(P.classSectionId);let De;if(ss.has(P.uid))De=ss.get(P.uid);else if(_e&&Qs.has(_e))De=Qs.get(_e);else if(Oe){const We=`${Oe}|${Ht}`;De=Pa.get(We)}if(De){Ba.add(De.id);const We={...X,id:P.uid,accountUid:P.uid,email:X.email||De.email,lrn:X.lrn||De.lrn,name:X.name||De.name,avatar:X.avatar||De.avatar,riskLevel:De.riskLevel||X.riskLevel,avgQuizScore:De.avgQuizScore||X.avgQuizScore,engagementScore:De.engagementScore||X.engagementScore,attendance:De.attendance||X.attendance,assignmentCompletion:De.assignmentCompletion||X.assignmentCompletion,weakestTopic:De.weakestTopic||X.weakestTopic,struggles:De.struggles||X.struggles,lastActive:De.lastActive||X.lastActive,wri:De.wri??null,riskStatus:De.riskStatus??null,riskUpdatedAt:De.riskUpdatedAt??null,diagnosticScore:De.diagnosticScore??null,externalGradesAvg:De.externalGradesAvg??null,systemPerformanceAvg:De.systemPerformanceAvg??null,riskHistory:De.riskHistory,grade:X.grade||De.grade,gradeLevel:X.gradeLevel||De.gradeLevel,section:X.section||De.section,classSectionId:X.classSectionId||De.classSectionId,classroomId:X.classroomId||De.classroomId,classMetadata:De.classMetadata||X.classMetadata,hasRegisteredAccount:!0,source:"both"},ga=lt(We.classSectionId||We.classroomId),ba=$t(We.classroomId||"",ga,We.className);return Bt(Hr(We,ba))}const Ga=lt(X.classSectionId||X.classroomId),Ut=$t(X.classroomId||"",Ga,X.className);return Bt(Hr(X,Ut))}),Ua=ft.filter(P=>!Ba.has(P.id)).map(P=>{const X={...P,hasRegisteredAccount:!1,source:"import"},_e=lt(X.classSectionId||X.classroomId),Oe=$t(X.classroomId,_e,X.className);return Bt(Hr(X,Oe))}),Vs=[...Ha,...Ua];if(!R)return;ge(P=>K.length===0&&P.length>0?P:K),te(P=>Vs.length===0&&P.length>0?P:Vs),xt.getImportedClassOverview({limit:3e3,forceRefresh:pe>0}).then(P=>{R&&(P.warnings.length>0&&console.warn("Imported class overview warnings:",P.warnings.join(" ")),ge(X=>ii(X,P.classrooms.map(Jx))),te(X=>{if(X.length===0)return X;const _e=P.students.map(Zx),Oe=new Set;X.forEach(De=>Oe.add(gr(De)));const Ht=_e.filter(De=>Oe.has(gr(De)));return Ht.length===0?X:li(X,Ht)}))}).catch(P=>{console.warn("Imported class overview merge unavailable:",P)});const fa=Me.map(P=>P.id);fa.length>0&&(ve=em(fa,P=>{R&&Fe(P.map(X=>({id:X.id,student:X.studentName,action:X.action,topic:X.topic,time:Tl(X.timestamp.toDate()),type:X.type})))}))}catch(Me){console.error("Failed to load teacher data:",Me),le.error("Failed to load dashboard data")}finally{M(!1)}})(),()=>{R=!1,ve&&ve()}},[r,pe]),u.useEffect(()=>{if(!r)return;let E=!0;return Zu("",80).then(R=>{E&&T(R)}).catch(R=>{console.warn("Failed to load teacher directory options:",R)}),()=>{E=!1}},[r]),u.useEffect(()=>{if(B.length===0)return;(async()=>{if(B.length===0){G("");return}Q(!0);try{const R=B.map(ee=>({name:ee.name,engagementScore:ee.engagementScore,avgQuizScore:ee.avgScore,attendance:ee.attendance,riskLevel:ee.riskLevel})),ve=await xt.getDailyInsight({students:R});G(ve.insight)}catch{G(`${B.filter(R=>R.riskLevel==="high").length} students are at high risk of falling behind. Review their progress in the analytics view.`)}finally{Q(!1)}})()},[B]);const Ue=ue.reduce((E,R)=>E+R.studentCount,0),Je=B.filter(E=>E.riskLevel==="high").length,ht=(()=>{const E=B.map(R=>R.avgScore).filter(R=>R>0);return E.length>0?Math.round(E.reduce((R,ve)=>R+ve,0)/E.length):0})(),dt=[{name:"High Risk",value:B.filter(E=>E.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:B.filter(E=>E.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:B.filter(E=>E.riskLevel==="low").length,color:"#75D06A"}],rt={};B.forEach(E=>{E.weakestTopic&&E.weakestTopic!=="N/A"&&(rt[E.weakestTopic]||(rt[E.weakestTopic]={total:0,sum:0}),rt[E.weakestTopic].total+=1,rt[E.weakestTopic].sum+=E.avgScore)});const Mt=Object.entries(rt).map(([E,R])=>({topic:E,score:Math.round(R.sum/R.total)})).sort((E,R)=>E.score-R.score).slice(0,6),At=E=>{b(E),i("analytics")},It=E=>{U(E),i("intervention")},cs=()=>{U(null),i("analytics")},Us=()=>{b(null),U(null),i("dashboard")},Yt=async(E,R)=>{if(!r){le.error("Unable to assign manager: teacher context is missing.");return}const ve=gs(E.classMetadata?.className||E.name),ee=yt({metadata:E.classMetadata,classSectionId:E.classSectionId,className:E.name,grade:E.classMetadata?.grade||ve.grade,gradeLevel:E.classMetadata?.gradeLevel,classification:E.classMetadata?.classification,strand:E.classMetadata?.strand,section:E.classMetadata?.section||ve.section,schoolYear:E.classMetadata?.schoolYear||String(new Date().getFullYear()),ownerTeacherId:E.classMetadata?.ownerTeacherId||r.uid,ownerTeacherName:E.classMetadata?.ownerTeacherName||we,adviserTeacherId:E.classMetadata?.adviserTeacherId||r.uid,adviserTeacherName:E.classMetadata?.adviserTeacherName||we,managerId:R.uid,managerName:R.name}),Me=ee.classSectionId||Pt(ee.grade||ve.grade,ee.section||ve.section);if(!Me){le.error("Unable to assign manager: missing class section ID.");return}V(!0);try{await dl({classSectionId:Me,className:ee.className||E.name,grade:ee.grade||ve.grade,gradeLevel:ee.gradeLevel||Ns(ee.grade||ve.grade)||ee.grade||ve.grade,classification:ee.classification||pa(ee.gradeLevel||ee.grade)||void 0,strand:ee.strand||ha(ee.className,ee.section)||void 0,section:ee.section||ve.section,schoolYear:ee.schoolYear||String(new Date().getFullYear()),ownerTeacherId:ee.ownerTeacherId||r.uid,ownerTeacherName:ee.ownerTeacherName||we,managerId:R.uid,managerName:R.name});const K=yt({metadata:ee,classSectionId:Me,managerId:R.uid,managerName:R.name}),Xe=lt(Me);ge(nt=>nt.map(ke=>lt(ke.classSectionId)!==Xe?ke:{...ke,name:K.className||ke.name,classSectionId:K.classSectionId||ke.classSectionId,classMetadata:K,gradeLevel:K.gradeLevel||ke.gradeLevel,classification:K.classification||ke.classification,strand:K.strand||ke.strand,managerId:R.uid,managerName:R.name})),te(nt=>nt.map(ke=>{if(lt(ke.classSectionId||ke.classroomId)!==Xe)return ke;const Bt=yt({metadata:ke.classMetadata,classSectionId:K.classSectionId||ke.classSectionId,className:ke.className||K.className,grade:ke.grade||K.grade,gradeLevel:ke.gradeLevel||K.gradeLevel,classification:ke.classification||K.classification,strand:ke.strand||K.strand,section:ke.section||K.section,managerId:R.uid,managerName:R.name});return{...ke,classMetadata:Bt,gradeLevel:Bt.gradeLevel||ke.gradeLevel,classification:Bt.classification||ke.classification,strand:Bt.strand||ke.strand,managerId:R.uid,managerName:R.name}})),b(nt=>!nt||lt(nt.classSectionId)!==Xe?nt:{...nt,classMetadata:K,managerId:R.uid,managerName:R.name,gradeLevel:K.gradeLevel||nt.gradeLevel,classification:K.classification||nt.classification,strand:K.strand||nt.strand}),le.success(`Assigned ${R.name} as section manager.`)}catch(K){console.error("Failed to assign class manager:",K),le.error(K instanceof Error?K.message:"Failed to assign class manager")}finally{V(!1)}},ds=u.useCallback(E=>{oe({rosterId:E.id,name:E.name,lrn:E.lrn,email:E.email,grade:E.grade,section:E.section,classSectionId:E.classSectionId})},[]),js=u.useCallback(E=>{te(R=>R.map(ve=>ve.id===E.rosterId?{...ve,hasRegisteredAccount:!0,source:"both",accountUid:E.uid,email:E.email||ve.email}:ve)),$(R=>R+1)},[]),Kt=u.useCallback(async(E,R)=>{if(!r){le.error("Cannot reassign section without an authenticated teacher.");return}const ve=r.uid,ee=(R.classSectionId||"").trim();if(!ee){le.error("Pick a target section first.");return}je(E.id);try{await qu({studentId:E.accountUid||E.id,isRegisteredAccount:!!E.hasRegisteredAccount,newClassSectionId:ee,newGrade:R.grade,newSection:R.section,previousClassSectionId:E.classSectionId,teacherId:ve,teacherName:we,schoolYear:E.classMetadata?.schoolYear||String(new Date().getFullYear())}),te(Me=>Me.map(K=>{if(K.id!==E.id)return K;const Xe=yt({metadata:K.classMetadata,classSectionId:ee,className:K.className,grade:R.grade,section:R.section});return{...K,grade:R.grade,section:R.section,classSectionId:ee,classroomId:ee,classMetadata:Xe}})),le.success(`Moved ${E.name} to ${R.grade} - ${R.section}.`)}catch(Me){console.error("Section reassignment failed:",Me),le.error(Me instanceof Error?Me.message:"Failed to reassign section.")}finally{je(null)}},[r,we]),Gs=u.useCallback(async E=>{if(!r||!window.confirm(`Remove ${E.name} from this class? This cannot be undone.`))return;const R=E.classSectionId||E.classroomId||"";if(!R){le.error("Cannot determine class section for this student.");return}try{await Ku(E.accountUid||E.id,R),te(ve=>ve.filter(ee=>ee.id!==E.id)),le.success(`Removed ${E.name} from class.`)}catch(ve){console.error("Remove student failed:",ve),le.error("Failed to remove student.")}},[r]);u.useEffect(()=>{const E=()=>{const R=window.innerWidth<1024;y(R),R?c(!1):h(!1)};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),u.useEffect(()=>{v&&h(!1)},[n,v]);const Es=E=>{i(E),b(null),U(null)},Rs=u.useMemo(()=>{if(!C)return;if(C.classMetadata?.classSectionId)return C.classMetadata.classSectionId||void 0;if(C.classSectionId)return C.classSectionId;const E=gs(C.classMetadata?.className||C.name);return Pt(E.grade,E.section)||void 0},[C]),Ge=u.useMemo(()=>C||null,[C]),z=u.useMemo(()=>{if(!Ge)return;const E=ue.findIndex(R=>R.id===Ge.id);return hr[Math.max(0,E)%hr.length]},[Ge,ue]),de=u.useMemo(()=>{if(!Ge)return B;const E=(Ge.id||"").trim().toLowerCase(),R=lt(Ge.classSectionId),ve=(Ge.name||"").trim().toLowerCase();return B.filter(ee=>{const Me=lt(ee.classroomId),K=lt(ee.classSectionId),Xe=(ee.className||"").trim().toLowerCase();return R&&(K===R||Me===R)||E&&(Me===E||K===E)||ve&&Xe===ve})},[Ge,B]);return se?e.jsx(Vl,{message:"Loading dashboard..."}):e.jsxs("div",{className:"relative flex h-screen w-full bg-background overflow-hidden",children:[v&&p&&e.jsx("button",{"aria-label":"Close navigation",className:"fixed inset-0 z-30 bg-slate-900/40 backdrop-blur-[1px]",onClick:()=>h(!1)}),e.jsxs(Re.aside,{initial:!1,animate:{width:v?280:l&&!d?80:280,x:v?p?0:-300:0},transition:{type:"spring",stiffness:360,damping:34},onMouseEnter:()=>!v&&l&&m(!0),onMouseLeave:()=>m(!1),className:"fixed inset-y-0 left-0 z-40 bg-[#f7f9fc] rounded-3xl border border-[#dde3eb] flex flex-col shadow-sm lg:static lg:z-auto p-5",children:[e.jsxs("div",{className:`mb-8 flex items-center ${l&&!d?"justify-center":"justify-between"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 bg-gradient-to-r from-[#7274ED] to-[#9956DE] rounded-2xl flex items-center justify-center shadow-md flex-shrink-0",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"MathPulse AI",className:"w-10 h-10 object-contain drop-shadow-md"})}),(!l||d)&&e.jsx("div",{children:e.jsx("h1",{className:"text-base font-semibold font-display text-[#0a1628] whitespace-nowrap",children:"MathPulse AI"})})]}),!v&&(!l||d)&&e.jsx(Re.button,{whileHover:{scale:1.1},whileTap:{scale:.95},onClick:()=>c(!l),className:"p-2 hover:bg-[#dde3eb] rounded-lg transition-colors text-[#5a6578]","aria-label":l?"Expand sidebar":"Collapse sidebar",children:l?e.jsx(zs,{size:20}):e.jsx($s,{size:20})}),v&&e.jsx("button",{onClick:()=>h(!1),className:"p-2 hover:bg-[#dde3eb] rounded-lg transition-colors text-[#5a6578]","aria-label":"Close navigation",children:e.jsx(qt,{size:20})})]}),e.jsxs("nav",{className:"flex-1 space-y-5",children:[e.jsxs("div",{children:[l&&!d?e.jsx("div",{className:"px-4 mb-2 flex items-center gap-2",children:e.jsx("div",{className:"flex-1 h-[1px] bg-[#dde3eb]"})}):e.jsx("p",{className:"px-4 mb-2 text-[10px] font-semibold text-[#5a6578] uppercase tracking-widest",children:"Overview"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ms,{icon:ac,label:"Dashboard",active:n==="dashboard",collapsed:l&&!d,onClick:Us,forceExpanded:v}),e.jsx(Ms,{icon:Ds,label:"Class Analytics",active:n==="analytics"||n==="intervention",collapsed:l&&!d,onClick:()=>Es("analytics"),forceExpanded:v})]})]}),e.jsxs("div",{children:[l&&!d?e.jsx("div",{className:"px-4 mb-2 flex items-center gap-2",children:e.jsx("div",{className:"flex-1 h-[1px] bg-[#dde3eb]"})}):e.jsx("p",{className:"px-4 mb-2 text-[10px] font-semibold text-[#5a6578] uppercase tracking-widest",children:"Students"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ms,{icon:fs,label:"Topic Mastery",active:n==="topic_mastery",collapsed:l&&!d,onClick:()=>Es("topic_mastery"),forceExpanded:v}),e.jsx(Ms,{icon:hs,label:"Competency",active:n==="competency",collapsed:l&&!d,onClick:()=>Es("competency"),forceExpanded:v})]})]}),e.jsxs("div",{children:[l&&!d?e.jsx("div",{className:"px-4 mb-2 flex items-center gap-2",children:e.jsx("div",{className:"flex-1 h-[1px] bg-[#dde3eb]"})}):e.jsx("p",{className:"px-4 mb-2 text-[10px] font-semibold text-[#5a6578] uppercase tracking-widest",children:"Tools"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ms,{icon:rc,label:"Data Import",active:n==="import",collapsed:l&&!d,onClick:()=>i("import"),forceExpanded:v}),e.jsx(Ms,{icon:qr,label:"AI Quiz Maker",active:n==="quiz_maker",collapsed:l&&!d,onClick:()=>i("quiz_maker"),forceExpanded:v}),e.jsx(Ms,{icon:Vt,label:"Question Bank",active:n==="question_bank",collapsed:l&&!d,onClick:()=>i("question_bank"),forceExpanded:v}),e.jsx(Ms,{icon:nr,label:"Calendar",active:n==="calendar",collapsed:l&&!d,onClick:()=>i("calendar"),forceExpanded:v})]})]})]}),e.jsxs("div",{className:"space-y-2 border-t border-[#dde3eb] pt-4",children:[e.jsxs(Re.button,{whileHover:{x:2},whileTap:{scale:.98},className:`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-[#5a6578] font-semibold border border-transparent hover:bg-[#dde3eb] hover:border-[#dde3eb] hover:text-[#0a1628] transition-all duration-200 whitespace-nowrap ${l&&!d?"justify-center":""}`,onClick:a,title:l&&!d?"Settings":"",children:[e.jsx(nc,{size:18,strokeWidth:2,className:"flex-shrink-0"}),(!l||d)&&e.jsx("span",{className:"font-body text-xs",children:"Settings"})]}),e.jsx("div",{className:"text-[#5a6578]",children:e.jsx(oc,{onClick:()=>N(!0),collapsed:l&&!d})})]})]}),e.jsxs("div",{className:"flex-1 flex overflow-hidden bg-gradient-to-br from-[#eef2ff] via-[#f5f3ff] to-[#fff7ed]",children:[e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[["dashboard","analytics","intervention","competency","topic_mastery","calendar","notifications","question_bank","import","quiz_maker"].includes(n)&&e.jsx("header",{className:"bg-transparent border-b border-[#e2e8f0]/40 px-[24px] xl:px-[32px] pt-[24px] pb-[16px] flex-shrink-0 z-30",children:e.jsxs("div",{className:"flex flex-row items-center justify-between gap-2 mb-0",children:[e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[v&&e.jsx("button",{onClick:()=>h(!0),className:"mt-1 p-2 rounded-lg border border-border text-muted-foreground hover:text-[#9956DE] hover:border-[#9956DE]/30 hover:bg-[#9956DE]/12 transition-colors","aria-label":"Open navigation",children:e.jsx(Wl,{size:18})}),e.jsxs("div",{children:[e.jsxs("h1",{className:"text-lg sm:text-[26px] font-bold text-[#1e293b] tracking-tight leading-tight truncate",children:[n==="dashboard"&&"Teacher Dashboard",n==="analytics"&&"Class Analytics",n==="intervention"&&"Intervention Center",n==="competency"&&"Student Competency",n==="topic_mastery"&&"Topic Mastery",n==="calendar"&&"Academic Calendar",n==="notifications"&&"Notifications",n==="question_bank"&&"Question Bank",n==="import"&&"Data Import",n==="quiz_maker"&&"AI Quiz Maker"]}),e.jsxs("p",{className:"text-[13px] text-[#64748b] mt-1",children:[n==="dashboard"&&`Welcome back, ${we}`,n==="analytics"&&"Analyze performance and risk across your classes.",n==="intervention"&&"Identify and support students who need immediate help.",n==="competency"&&"Track individual student progress against learning goals.",n==="topic_mastery"&&"Overview of student mastery levels across different math topics.",n==="calendar"&&"Manage your schedules and academic events.",n==="notifications"&&"Stay updated with student activity and system alerts.",n==="question_bank"&&"Manage and create math questions for your quizzes.",n==="import"&&"Upload class records and materials to power AI analytics.",n==="quiz_maker"&&"Create AI-powered quizzes based on your curriculum."]})]}),n==="dashboard"&&e.jsxs("div",{className:"hidden xl:flex items-center gap-2 ml-4 mt-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-[#9956DE]/12 border border-[#9956DE]/30 rounded-lg",children:[e.jsx(hs,{size:13,className:"text-[#9956DE]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#9956DE]",children:[Ue," students"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-[#F08386]/12 border border-[#F08386]/30 rounded-lg",children:[e.jsx(da,{size:13,className:"text-[#F08386]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#C65E63]",children:[Je," at risk"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-[#75D06A]/14 border border-[#75D06A]/35 rounded-lg",children:[e.jsx(ca,{size:13,className:"text-[#75D06A]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#4D9F46]",children:[ht,"% avg"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:()=>{re(!0),D(!0)},className:"relative w-10 h-10 flex items-center justify-center bg-[#eef2ff]/80 hover:bg-[#e0e7ff] rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#a5b4fc]/60 text-[#4f46e5] hover:border-[#818cf8] transition-colors cursor-pointer hover:scale-[1.02]","aria-label":"View AI Insight",children:[e.jsx(bs,{size:18}),!k&&Pe&&e.jsx("div",{className:"absolute top-2.5 right-2.5 w-2 h-2 bg-rose-500 rounded-full border border-white animate-pulse"})]}),e.jsx("span",{className:"absolute -bottom-8 left-1/2 -translate-x-1/2 text-[10px] bg-[#1e293b] text-white px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 pointer-events-none",children:"AI Insight"})]}),v&&n==="dashboard"&&e.jsx("button",{onClick:()=>Ce(E=>!E),className:`relative w-10 h-10 flex items-center justify-center rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border transition-colors cursor-pointer hover:scale-[1.02] ${fe?"bg-[#818cf8] border-[#6366f1] text-white":"bg-white/60 hover:bg-white/80 border-white/50 text-[#64748b] hover:text-[#1e293b]"}`,"aria-label":fe?"Close calendar panel":"Open calendar panel",title:fe?"Close calendar":"View calendar",children:e.jsx(nr,{size:18})}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>ie(!ce),className:"relative w-10 h-10 flex items-center justify-center bg-white/60 hover:bg-white/80 rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50 text-[#64748b] hover:text-[#1e293b] transition-colors cursor-pointer hover:scale-[1.02]","aria-label":"View notifications",title:"Notifications",children:[e.jsx(dr,{size:18}),f>0&&e.jsx("span",{className:"absolute top-2.5 right-2.5 w-2 h-2 bg-rose-500 rounded-full border border-white"})]}),e.jsx(tc,{isOpen:ce,onClose:()=>ie(!1),onViewAll:()=>i("notifications")})]}),n!=="dashboard"&&e.jsxs("div",{onClick:s,className:"flex items-center gap-2 bg-white/60 px-4 py-2 rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50 cursor-pointer hover:bg-white/80 transition-colors h-10 hover:scale-[1.02]",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-indigo-100 overflow-hidden shrink-0",children:e.jsx("img",{src:o?.photo||`https://ui-avatars.com/api/?name=${encodeURIComponent(we)}&background=e0e7ff&color=4f46e5`,alt:"Profile",className:"w-full h-full object-cover"})}),e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:we})]})]})]})}),e.jsx("main",{className:`flex-1 flex flex-col ${n==="intervention"||n==="analytics"?"overflow-hidden":"overflow-y-auto"}`,children:e.jsxs(zt,{mode:"wait",children:[n==="dashboard"&&e.jsx(ap,{classes:ne,liveActivity:ze,onViewClass:At,onViewAllClasses:()=>i("analytics"),onViewActivityStudent:E=>{const R=B.find(ve=>ve.name===E);R&&It(R)},dailyInsight:Pe,insightLoading:q,isInsightDismissed:k,onDismissInsight:()=>D(!0),onOpenInsightModal:()=>{re(!0),D(!0)},totalStudents:Ue,totalAtRisk:Je,avgPerformance:ht,onCreateClass:()=>g(!0)}),n==="analytics"&&Ge&&e.jsx(op,{selectedClass:Ge,students:de,allClasses:ue,riskDistribution:dt,topicPerformance:Mt,onViewStudent:It,onCreateAccount:ds,onReassignSection:Kt,reassignBusyId:ae,onBack:()=>b(null),teacherOptions:j,managerUpdating:_,onAssignManager:E=>Yt(Ge,E),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,classColor:z,insightDismissed:k,onOpenInsightModal:()=>re(!0),onAddStudents:()=>L(!0),onRemoveStudent:Gs}),n==="analytics"&&!Ge&&ne.length>0&&e.jsx(Yo,{classes:ne,onSelectClass:At,onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:k,onOpenInsightModal:()=>re(!0),onCreateClass:()=>g(!0)}),n==="analytics"&&!Ge&&ne.length===0&&e.jsx(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-6",children:e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-8 shadow-sm max-w-2xl",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-[#9956DE]/20 text-[#9956DE] flex items-center justify-center mb-4",children:e.jsx(Ds,{size:24})}),e.jsx("h2",{className:"text-2xl font-display font-semibold text-foreground mb-2",children:"Class Analytics"}),e.jsx("p",{className:"text-sm text-muted-foreground font-body leading-relaxed mb-4",children:"No classes available yet. Create a class or import class records to unlock analytics views."}),e.jsxs(wt,{onClick:()=>g(!0),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(ua,{size:16,className:"mr-1.5"}),"Create Class"]})]})}),n==="intervention"&&F&&e.jsx(ip,{student:F,teacherId:r?.uid||"",teacherName:we,initialCache:Ke.current.get(F.id),onCacheUpdate:(E,R)=>Ke.current.set(E,R),onStudentUpdated:E=>{const R=F?ln(F):null;U(E),te(ve=>ve.map(ee=>{const Me=ln(ee),K=R?Me===R:!1,Xe=ee.id===E.id&<(ee.classSectionId)===lt(E.classSectionId);return K||Xe?E:ee}))},onBack:cs,onNavigateToQuizMaker:E=>{i("quiz_maker"),E&&sessionStorage.setItem("quizMakerInitialTab",E)}}),n==="topic_mastery"&&e.jsx(Tm,{classSectionId:Rs,onOpenNotifications:()=>i("notifications"),onOpenProfile:s}),n==="competency"&&Ge&&e.jsx(Mm,{classSectionId:Rs,className:C?.name,fallbackStudents:B,onBack:()=>b(null),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:k,onOpenInsightModal:()=>re(!0)}),n==="competency"&&!Ge&&ue.length>0&&e.jsx(Yo,{classes:ne,onSelectClass:E=>b(E),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:k,onOpenInsightModal:()=>re(!0),viewType:"competency"}),n==="competency"&&!Ge&&ue.length===0&&e.jsx(sp,{icon:hs,title:"Student Competency",description:"No classes available yet. Import class records to view competency breakdowns."}),n==="import"&&e.jsxs(e.Fragment,{children:[e.jsx(Qx,{classSectionId:Rs,className:C?.name,classMetadata:C?.classMetadata,students:B,classes:ne.map(E=>({id:E.id,name:E.name,classSectionId:E.classSectionId})),teacherId:r?.uid||"",teacherName:we,onStudentsUpdated:E=>te(E),onBackToClasses:()=>i("dashboard"),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,onImportedClassRecords:E=>{const R=E.students.map(ke=>tp(ke,E.classSectionId,E.className,E.classMetadata)),ve=yt({metadata:E.classMetadata,classSectionId:E.classSectionId,className:E.className}),ee=ve.classSectionId||"imported_class",Me=ve.className||"Imported Class",K=R.filter(ke=>ke.riskLevel==="high").length,Xe=R.length>0?Math.round(R.reduce((ke,jt)=>ke+jt.avgScore,0)/R.length):0,nt={id:ee,name:Me,classSectionId:ee,classMetadata:{...ve,classSectionId:ee,className:Me},schedule:"Mon-Fri",studentCount:R.length,avgScore:Xe,atRiskCount:K,riskLevel:K>=5?"high":K>=2?"medium":"low"};te(ke=>li(ke,R)),ge(ke=>ii(ke,[nt]))},onDataChanged:()=>$(E=>E+1)}),e.jsx("div",{className:"mt-6",children:e.jsx(Wx,{teacherId:r?.uid||""})})]}),n==="notifications"&&e.jsx(zm,{liveActivity:ze,atRiskStudents:B.filter(E=>E.riskLevel==="high").map(E=>({name:E.name,riskLevel:E.riskLevel,weakestTopic:E.weakestTopic})),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,teacherName:we}),n==="calendar"&&e.jsx(qm,{classes:ue,teacherId:r?.uid}),n==="quiz_maker"&&e.jsx(bl,{onBack:()=>{const E=sessionStorage.getItem("quizMakerReturnTo");sessionStorage.removeItem("quizMakerReturnTo"),sessionStorage.removeItem("quizMakerInitialTab"),i(E==="intervention"?"intervention":"dashboard")},onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,teacherName:we}),n==="question_bank"&&e.jsx(Cm,{onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,teacherName:we})]})})]}),n==="dashboard"&&!v&&e.jsx(di,{onViewCalendar:()=>i("calendar"),onOpenProfile:s,userProfile:o,teacherName:we,liveActivity:ze})]}),e.jsx(zt,{children:v&&n==="dashboard"&&fe&&e.jsxs(e.Fragment,{children:[e.jsx(Re.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-[2px]","aria-label":"Close calendar panel",onClick:()=>Ce(!1)},"cal-backdrop"),e.jsx(Re.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:320,damping:32},className:"fixed top-0 right-0 bottom-0 z-50 w-[300px] max-w-[85vw] shadow-2xl",children:e.jsx(di,{onViewCalendar:()=>{i("calendar"),Ce(!1)},onOpenProfile:()=>{s?.(),Ce(!1)},userProfile:o,teacherName:we,liveActivity:ze})},"cal-drawer")]})}),e.jsx(zt,{children:J&&e.jsx("div",{className:"fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4",children:e.jsxs(Re.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white rounded-2xl shadow-xl w-full max-w-lg overflow-hidden border border-slate-200",children:[e.jsxs("div",{className:"p-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600",children:e.jsx(bs,{size:16})}),e.jsx("h3",{className:"font-semibold text-slate-800",children:"Detailed AI Insight"})]}),e.jsx("button",{onClick:()=>{re(!1)},className:"p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(qt,{size:18})})]}),e.jsx("div",{className:"p-6",children:e.jsx("div",{className:"text-sm text-slate-600 leading-relaxed",children:e.jsx(Tc,{children:Pe?.replace(/[*_]*\s*\(?Word\s*count\s*:\s*[*_]*\s*\d+\)?\s*[*_]*/gi,"").trim()||`**${Je} students (${Ue>0?Math.round(Je/Ue*100):0}%)** are currently at high risk of falling behind in recent topics. Review their progress in the analytics view to plan interventions.`})})}),e.jsx("div",{className:"p-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2",children:e.jsx("button",{onClick:()=>{re(!1)},className:"px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-800 hover:bg-slate-200 rounded-lg transition-colors",children:"Minimize to Menu"})})]})})}),e.jsx(Xl,{isOpen:S,onClose:()=>N(!1),onConfirm:t,title:"Logout",message:"Are you sure you want to logout?",confirmText:"Logout",cancelText:"Cancel"}),e.jsx(tm,{open:w,onClose:()=>g(!1),onCreated:()=>$(E=>E+1),teacherName:we}),e.jsx(sm,{open:I,onClose:()=>L(!1),onAdded:()=>$(E=>E+1),grade:Ge?.gradeLevel||Ge?.classMetadata?.grade||"Grade 11",section:Ge?.classMetadata?.section||Ge?.name?.split(" - ")[1]||"",teacherName:we,existingStudentUids:de.map(E=>E.id)}),e.jsx(Kx,{isOpen:!!me,onClose:()=>oe(null),seed:me,adviserTeacherId:r?.uid||"",adviserTeacherName:we,schoolYear:me?B.find(E=>E.id===me.rosterId)?.classMetadata?.schoolYear||String(new Date().getFullYear()):void 0,onCreated:js})]})},Ms=({icon:t,label:s,active:a,collapsed:r,forceExpanded:o=!1,onClick:n})=>e.jsxs(Re.button,{onClick:n,whileHover:{x:2},whileTap:{scale:.98},className:`w-full flex items-center gap-3 px-4 py-3 rounded-2xl cursor-pointer transition-all duration-200 border whitespace-nowrap ${r&&!o?"justify-center":""} ${a?"bg-[#9956DE]/12 border-[#9956DE]/30 shadow-sm text-[#9956DE]":"bg-transparent border-transparent text-[#5a6578] hover:bg-[#dde3eb] hover:border-[#dde3eb] hover:text-[#0a1628]"}`,children:[e.jsx(t,{size:18,strokeWidth:a?2.5:2,className:"flex-shrink-0"}),(!r||o)&&e.jsx("span",{className:"font-body font-semibold text-xs",children:s}),a&&!r&&e.jsx(Re.div,{layoutId:"sidebar-active-indicator",className:"ml-auto w-2 h-2 rounded-full bg-[#9956DE]",transition:{type:"spring",duration:.4}})]}),sp=({icon:t,title:s,description:a})=>e.jsx(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-6",children:e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-8 shadow-sm max-w-2xl",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-[#9956DE]/20 text-[#9956DE] flex items-center justify-center mb-4",children:e.jsx(t,{size:24})}),e.jsx("h2",{className:"text-2xl font-display font-semibold text-foreground mb-2",children:s}),e.jsx("p",{className:"text-sm text-muted-foreground font-body leading-relaxed",children:a})]})}),ap=({classes:t,liveActivity:s,onViewClass:a,onViewAllClasses:r,onViewActivityStudent:o,dailyInsight:n,insightLoading:i,isInsightDismissed:l,onDismissInsight:c,onOpenInsightModal:d,totalStudents:m,totalAtRisk:p,avgPerformance:h,onCreateClass:v})=>{const y=m>0?Math.round(p/m*100):0,S=m>0?Math.round((m-p)/m*100):0;return e.jsxs(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-3 sm:p-6 space-y-4",children:[!l&&n&&e.jsxs("div",{onClick:d,className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] border border-white p-[14px_16px] sm:p-[18px_20px] flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4 shadow-[0_1px_4px_rgba(0,0,0,0.04)] cursor-pointer hover:shadow-md transition-shadow group",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx("div",{className:"absolute -inset-[5px] rounded-full border-2 border-[#a5b4fc] opacity-50 animate-pulse"}),e.jsx("div",{className:"w-[46px] h-[46px] rounded-full bg-[#eef2ff] border-2 border-[#c7d2fe] flex items-center justify-center text-[#4f46e5] text-xl relative overflow-hidden group-hover:scale-[1.05] transition-transform",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Mascot",className:"w-[85%] h-[85%] object-contain"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-[#1e1b4b] flex flex-wrap items-center gap-2 mb-1",children:[e.jsx(bs,{size:14,className:"text-[#818cf8]"}),"MathPulse AI insight",e.jsx("span",{className:"bg-[#fee2e2] text-[#b91c1c] text-[10px] font-semibold px-2 py-0.5 rounded-full border border-[#fca5a5]",children:"Attention needed"})]}),e.jsx("div",{className:"text-[12.5px] text-[#475569] leading-[1.55]",children:"Some students may be at risk of falling behind. Click to view detailed analysis."})]}),e.jsxs("div",{className:"flex gap-2 flex-shrink-0 self-end sm:self-auto",children:[e.jsx("button",{onClick:N=>{N.stopPropagation(),c()},className:"px-[15px] py-[7px] rounded-[10px] text-xs font-medium cursor-pointer border border-[#e2e8f0] bg-white text-[#475569] hover:bg-[#f8fafc] transition-colors",children:"Dismiss"}),e.jsx("button",{onClick:N=>{N.stopPropagation(),r()},className:"px-[15px] py-[7px] rounded-[10px] text-xs font-medium cursor-pointer border border-[#4f46e5] bg-[#4f46e5] text-white shadow-[0_2px_8px_rgba(79,70,229,0.13)] hover:bg-[#4338ca] transition-colors",children:"Review students"})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-1.5 sm:gap-3",children:[e.jsxs("div",{className:"group relative overflow-hidden bg-[#10b981] shadow-[0_4px_16px_rgba(16,185,129,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"Total students"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(hs,{size:15})})]}),e.jsx("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:m}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Added this year"}),e.jsx("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:m>0?"+1":"0"})]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#0ea5e9] shadow-[0_4px_16px_rgba(14,165,233,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"Class average"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(fs,{size:15})})]}),e.jsxs("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:[h,"%"]}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Vs. last month"}),e.jsx("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:"+2.5%"})]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#a855f7] shadow-[0_4px_16px_rgba(168,85,247,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"Engage­ment"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(vi,{size:15})})]}),e.jsxs("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:[S,"%"]}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Active participants"}),e.jsx("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:Math.round(S/100*m)})]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#f97316] shadow-[0_4px_16px_rgba(249,115,22,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"At risk"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(br,{size:15})})]}),e.jsx("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:p}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Requires attention"}),e.jsxs("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:[y,"%"]})]})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] border border-white p-[18px_20px] shadow-[0_1px_4px_rgba(0,0,0,0.04)]",children:[e.jsxs("div",{className:"flex justify-between items-center mb-[14px]",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-[#1e293b]",children:"My classes"}),e.jsx("span",{onClick:r,className:"text-[12px] text-[#10b981] font-semibold cursor-pointer hover:underline",children:"View all"})]}),e.jsxs("div",{className:"space-y-[9px]",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-slate-500 mb-3",children:"No classes imported yet."}),v&&e.jsx("button",{onClick:v,className:"text-sm text-[#9956DE] font-semibold hover:underline",children:"+ Create a class"})]}),t.map((N,w)=>{const g=[{bg:"bg-[#f3e8ff]",text:"text-[#a855f7]",borderHover:"hover:border-[#d8b4fe]",stripe:"bg-[#a855f7]"},{bg:"bg-[#eff6ff]",text:"text-[#3b82f6]",borderHover:"hover:border-[#bfdbfe]",stripe:"bg-[#3b82f6]"},{bg:"bg-[#f0fdf4]",text:"text-[#22c55e]",borderHover:"hover:border-[#bbf7d0]",stripe:"bg-[#22c55e]"},{bg:"bg-[#fff7ed]",text:"text-[#f97316]",borderHover:"hover:border-[#fed7aa]",stripe:"bg-[#f97316]"},{bg:"bg-[#fff1f2]",text:"text-[#f43f5e]",borderHover:"hover:border-[#fecdd3]",stripe:"bg-[#f43f5e]"}],I=g[w%g.length];return e.jsxs("div",{onClick:()=>a(N),className:`relative overflow-hidden flex items-center gap-3 p-[12px_13px] pl-[16px] border border-[#f1f5f9] rounded-[14px] cursor-pointer ${I.borderHover} hover:shadow-[0_2px_10px_rgba(0,0,0,0.04)] hover:bg-[#fafbff] transition-all group`,children:[e.jsx("div",{className:`absolute left-0 top-0 bottom-0 w-[5px] ${I.stripe}`}),e.jsx("div",{className:`w-[38px] h-[38px] rounded-[10px] flex items-center justify-center flex-shrink-0 text-[17px] ${I.bg} ${I.text} group-hover:scale-110 transition-transform duration-300`,children:e.jsx(Vt,{size:18})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[12.5px] font-medium text-[#1e293b]",children:N.name}),e.jsx("div",{className:"text-[11px] text-[#94a3b8] mt-[1px]",children:N.classification||"High School"})]}),e.jsx("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[65px]",children:N.schedule||"Mon-Fri"}),e.jsxs("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[85px]",children:[N.studentCount," students"]}),e.jsx("span",{className:`text-[10px] font-semibold px-[9px] py-[3px] rounded-[6px] ${N.riskLevel==="high"?"bg-[#fee2e2] text-[#b91c1c] border border-[#fca5a5]":N.riskLevel==="medium"?"bg-[#fffbeb] text-[#b45309] border border-[#fcd34d]":"bg-[#ecfdf5] text-[#065f46] border border-[#6ee7b7]"}`,children:N.riskLevel==="high"?"High risk":N.riskLevel==="medium"?"Medium risk":"On track"}),e.jsx(Yr,{size:16,className:"text-[#cbd5e1] ml-auto hover:text-[#64748b]"})]},N.id)})]})]})]})},rp=he.memo(({student:t,onViewStudent:s,onCreateAccount:a,onRemoveStudent:r})=>{const n=t.riskLevel==="high"?{borderLeft:"border-l-rose-500",bgAvatar:"bg-rose-50 text-rose-600 border-rose-100/50",badge:"text-rose-600 bg-rose-50",progress:"bg-rose-500"}:t.riskLevel==="medium"?{borderLeft:"border-l-amber-500",bgAvatar:"bg-amber-50 text-amber-600 border-amber-100/50",badge:"text-amber-600 bg-amber-50",progress:"bg-amber-500"}:{borderLeft:"border-l-emerald-500",bgAvatar:"bg-emerald-50 text-emerald-600 border-emerald-100/50",badge:"text-emerald-600 bg-emerald-50",progress:"bg-emerald-500"},i=t.hasRegisteredAccount===!1&&t.source==="import",l=t.hasRegisteredAccount===!0;return e.jsxs("div",{onClick:()=>s(t),className:`p-[12px] bg-white rounded-[14px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#f1f5f9] border-l-[4px] ${n.borderLeft} hover:scale-[1.02] transition-transform cursor-pointer group flex flex-col justify-between`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-[10px]",children:[e.jsxs("div",{className:"flex gap-[8px] items-center min-w-0 pr-2",children:[t.avatar?e.jsx("img",{src:t.avatar,alt:t.name,className:`w-8 h-8 rounded-full border ${n.bgAvatar.split(" ")[2]} object-cover shrink-0`}):e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center font-semibold text-[11px] shrink-0 border ${n.bgAvatar}`,children:t.name.substring(0,2).toUpperCase()}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("p",{className:"text-[13px] font-semibold text-[#1e293b] leading-tight truncate",children:t.name}),l&&e.jsx("span",{title:"Registered student account",className:"w-1.5 h-1.5 rounded-full bg-emerald-500 shrink-0"})]}),e.jsxs("p",{className:"text-[10px] text-[#64748b] flex items-center gap-[4px] mt-0.5 truncate",children:[e.jsx(Ls,{className:"w-[10px] h-[10px] shrink-0"})," ",t.lastActive||"recently"]})]})]}),e.jsxs("span",{className:`font-semibold text-[11px] px-[6px] py-[2px] rounded-[14px] shrink-0 ${n.badge}`,children:[t.avgScore,"%"]}),r&&e.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),r(t)},className:"opacity-0 group-hover:opacity-100 transition-opacity text-slate-400 hover:text-red-500 p-1 rounded shrink-0","aria-label":`Remove ${t.name} from class`,title:"Remove from class",children:e.jsx(qt,{size:14})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2 px-2 py-1 rounded-[10px] bg-amber-50 border border-amber-100/80",children:[e.jsx("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"No Account"}),a&&e.jsxs("button",{type:"button",onClick:c=>{c.stopPropagation(),a(t)},className:"flex items-center gap-1 px-2 py-0.5 rounded-full bg-white text-amber-700 border border-amber-200 hover:bg-amber-100 text-[10px] font-semibold transition-colors","aria-label":`Create system account for ${t.name}`,children:[e.jsx("span",{"aria-hidden":!0,children:"+"}),"Create"]})]}),e.jsx("div",{className:"w-full bg-[#f1f5f9] h-1.5 rounded-full overflow-hidden mt-auto",children:e.jsx("div",{className:`h-full rounded-full ${n.progress}`,style:{width:`${t.avgScore}%`}})})]})}),np=({students:t,allClasses:s,currentClass:a,onReassignSection:r,reassignBusyId:o})=>{const[n,i]=u.useState(!1),l=u.useMemo(()=>{const d=new Map;return s.forEach(m=>{const p=(m.classSectionId||m.id||"").trim();if(!p)return;const h=(m.classMetadata?.grade||"").trim(),v=(m.classMetadata?.section||"").trim();if(!h||!v)return;const y=m.name||`${h} - ${v}`;d.set(p,{classSectionId:p,grade:h,section:v,label:y})}),Array.from(d.values()).sort((m,p)=>m.label.localeCompare(p.label))},[s]),c=u.useMemo(()=>{const d=new Map,m=[];return t.forEach(p=>{const h=(p.classSectionId||"").trim();if(!h){m.push(p);return}const v=p.section||p.className||h,y=d.get(h)||{label:v,students:[]};y.students=[...y.students,p],d.set(h,y)}),{assigned:Array.from(d.entries()).map(([p,h])=>({sectionId:p,...h})).sort((p,h)=>p.label.localeCompare(h.label)),unassigned:m}},[t]);return e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] border border-white shadow-[0_1px_4px_rgba(0,0,0,0.04)] overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>i(d=>!d),className:"w-full flex items-center justify-between px-6 py-4 text-left","aria-expanded":n,children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Section Management"}),e.jsxs("p",{className:"text-[12px] text-[#64748b] mt-0.5",children:["Move students between sections. Showing ",t.length," students across ",c.assigned.length," section",c.assigned.length===1?"":"s",c.unassigned.length>0?` · ${c.unassigned.length} unassigned`:"","."]})]}),e.jsx(Ot,{className:`w-4 h-4 text-[#64748b] transition-transform ${n?"rotate-180":""}`})]}),n&&e.jsxs("div",{className:"border-t border-[#f1f5f9] divide-y divide-[#f1f5f9]",children:[c.assigned.length===0&&c.unassigned.length===0&&e.jsx("p",{className:"text-[12px] text-[#64748b] px-6 py-5",children:"No students yet. Add students to this teacher to manage section assignments."}),c.assigned.map(d=>e.jsxs("div",{className:"px-6 py-4",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-[#64748b] mb-2",children:[d.label," ",e.jsxs("span",{className:"text-[10px] font-normal text-[#94a3b8]",children:["(",d.students.length,")"]})]}),e.jsx("div",{className:"space-y-1.5",children:d.students.map(m=>e.jsx(ci,{student:m,sectionTargets:l,currentSectionId:a.classSectionId,onReassign:r,isBusy:o===m.id},`section-row-${m.id}`))})]},d.sectionId)),c.unassigned.length>0&&e.jsxs("div",{className:"px-6 py-4 bg-amber-50/40",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-amber-700 mb-2",children:["Unassigned ",e.jsxs("span",{className:"text-[10px] font-normal text-amber-600/80",children:["(",c.unassigned.length,")"]})]}),e.jsx("div",{className:"space-y-1.5",children:c.unassigned.map(d=>e.jsx(ci,{student:d,sectionTargets:l,currentSectionId:a.classSectionId,onReassign:r,isBusy:o===d.id},`section-row-${d.id}`))})]})]})]})},ci=({student:t,sectionTargets:s,currentSectionId:a,onReassign:r,isBusy:o})=>{const[n,i]=u.useState(t.classSectionId||"");u.useEffect(()=>{i(t.classSectionId||"")},[t.classSectionId]);const l=()=>{const d=s.find(m=>m.classSectionId===n);d&&d.classSectionId!==t.classSectionId&&r(t,d)},c=n===(t.classSectionId||"");return e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-2 md:gap-3 px-3 py-2 rounded-[12px] bg-white border border-[#f1f5f9]",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[13px] font-semibold text-[#1e293b] truncate",children:t.name}),e.jsxs("p",{className:"text-[11px] text-[#64748b] truncate",children:[t.lrn?`LRN ${t.lrn} · `:"",t.classMetadata?.className||t.className||"Unassigned section",a&&t.classSectionId===a?" · current":""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("select",{value:n,onChange:d=>i(d.target.value),disabled:o||s.length===0,className:"text-[12px] rounded-xl border border-[#dde3eb] bg-white px-3 py-1.5 text-[#0a1628] focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-200 disabled:opacity-60",children:[e.jsx("option",{value:"",children:"Select section…"}),s.map(d=>e.jsx("option",{value:d.classSectionId,children:d.label},d.classSectionId))]}),e.jsx("button",{type:"button",onClick:l,disabled:o||c||!n,className:"text-[12px] font-semibold rounded-xl px-3 py-1.5 bg-indigo-600 text-white hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:hover:bg-indigo-600",children:o?"Saving…":"Move"})]})]})},op=({selectedClass:t,students:s,allClasses:a,riskDistribution:r,topicPerformance:o,onViewStudent:n,onCreateAccount:i,onReassignSection:l,reassignBusyId:c,onBack:d,teacherOptions:m,managerUpdating:p,onAssignManager:h,onOpenNotifications:v,onOpenProfile:y,classColor:S,insightDismissed:N,onOpenInsightModal:w,onAddStudents:g,onRemoveStudent:I})=>{const{currentUser:L,userProfile:A}=vs(),[W,f]=u.useState(""),[C,b]=u.useState(""),[F,U]=u.useState("All"),[k,D]=u.useState(null),[J,re]=u.useState(!0),[ce,ie]=u.useState(!1),[fe,Ce]=u.useState(!0);u.useEffect(()=>{let j=!1;return re(!0),zo(t.id).then(T=>{j||D(T)}).catch(T=>console.warn("[AnalyticsView] Backend fetch failed, using local data:",T)).finally(()=>{j||re(!1)}),()=>{j=!0}},[t.id]),u.useEffect(()=>{let j,T;return(async()=>{try{const{collection:_,onSnapshot:V}=await Cs(async()=>{const{collection:je,onSnapshot:we}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{collection:je,onSnapshot:we}},__vite__mapDeps([2,3])),{db:me}=await Cs(async()=>{const{db:je}=await import("./index-BvEKrMkD.js").then(we=>we.b7);return{db:je}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),oe=_(me,"classes",t.id,"student_summaries");let ae=!0;j=V(oe,()=>{if(ae){ae=!1;return}T&&clearTimeout(T),T=setTimeout(()=>{zo(t.id).then(D).catch(()=>{})},2e3)})}catch{}})(),()=>{j?.(),T&&clearTimeout(T)}},[t.id]);const[ue,ge]=u.useState(new Map);u.useEffect(()=>{let j=!1;const T=s.filter(_=>_.accountUid||_.hasRegisteredAccount);if(T.length!==0)return(async()=>{try{const{doc:_,getDoc:V}=await Cs(async()=>{const{doc:je,getDoc:we}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{doc:je,getDoc:we}},__vite__mapDeps([2,3])),{db:me}=await Cs(async()=>{const{db:je}=await import("./index-BvEKrMkD.js").then(we=>we.b7);return{db:je}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),oe=new Map,ae=T.slice(0,50);await Promise.all(ae.map(async je=>{const we=je.accountUid||je.id;try{const Ke=await V(_(me,"progress",we));if(Ke.exists()){const Je=Ke.data().averageScore||0;Je>0&&oe.set(je.id,Je)}}catch{}})),j||ge(oe)}catch{}})(),()=>{j=!0}},[s]);const B=k!=null&&k.students.some(j=>j.quiz_attempt_count>0),te=(()=>{if(B)return k.class_average;if(t.avgScore>0)return t.avgScore;if(s.length===0)return 0;const j=s.map(T=>ue.get(T.id)||T.avgScore).filter(T=>T>0);return j.length>0?Math.round(j.reduce((T,_)=>T+_,0)/j.length):0})(),ne=(()=>{if(B)return k.completion_rate;if(s.length===0)return 0;const j=s.filter(T=>ue.has(T.id)||T.assignmentCompletion>0).length;return Math.round(j/s.length*100)})(),ze=(()=>{if(B)return k.participation_rate;if(s.length===0)return 0;const j=s.filter(T=>ue.has(T.id)||T.engagementScore>0||T.avgScore>0).length;return s.length>0?Math.round(j/s.length*100):0})(),Fe=k?.insights?.risk_distribution?[{name:"Critical",value:k.insights.risk_distribution.Critical||0,color:"#dc2626"},{name:"High Risk",value:k.insights.risk_distribution["High Risk"]||0,color:"#f43f5e"},{name:"Medium Risk",value:k.insights.risk_distribution["Medium Risk"]||0,color:"#f59e0b"},{name:"Low Risk",value:k.insights.risk_distribution["Low Risk"]||0,color:"#10b981"},{name:"Unassessed",value:k.insights.risk_distribution.Unassessed||0,color:"#94a3b8"}].filter(j=>j.value>0):[{name:"High Risk",value:s.filter(j=>j.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:s.filter(j=>j.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:s.filter(j=>j.riskLevel==="low").length,color:"#75D06A"}];u.useEffect(()=>{b(t.classMetadata?.managerId||t.managerId||"")},[t]);const Pe=u.useMemo(()=>{const j=W.trim().toLowerCase();let T=s;if(j&&(T=T.filter(_=>_.name.toLowerCase().includes(j)||(_.lrn||"").toLowerCase().includes(j)||(_.weakestTopic||"").toLowerCase().includes(j))),F==="Good")if(k){const _=new Set(k.students.filter(V=>V.quiz_attempt_count>0&&V.avg_score>=75).map(V=>V.student_id));T=T.filter(V=>_.has(V.id))}else T=T.filter(_=>_.avgScore>=85&&_.riskLevel!=="high");else if(F==="Risk")if(k){const _=new Set(k.students.filter(V=>["High Risk","Critical","Unassessed"].includes(V.risk_level)).map(V=>V.student_id));T=T.filter(V=>_.has(V.id))}else T=T.filter(_=>_.riskLevel==="high"||_.avgScore<75);return T},[W,s,F,k]),G=u.useMemo(()=>B?k.students.filter(j=>j.quiz_attempt_count>0).sort((j,T)=>T.avg_score-j.avg_score).slice(0,5).map(j=>{const T=s.find(_=>_.id===j.student_id);return T?{...T,avgScore:j.avg_score}:null}).filter(Boolean):[...s].map(j=>({...j,avgScore:ue.get(j.id)||j.avgScore})).sort((j,T)=>T.avgScore-j.avgScore).slice(0,5),[s,k,B,ue]),se=u.useMemo(()=>B?k.students.filter(j=>["High Risk","Critical"].includes(j.risk_level)).sort((j,T)=>j.avg_score-T.avg_score).map(j=>{const T=s.find(_=>_.id===j.student_id);return T?{...T,avgScore:j.avg_score,_backendRisk:j.risk_level}:null}).filter(Boolean):[...s].filter(j=>j.riskLevel==="high"||(ue.get(j.id)||j.avgScore)<70||j.assignmentCompletion<65),[s,k,B,ue]),M=u.useMemo(()=>k?.insights?.topic_performance?.length?k.insights.topic_performance.map(j=>({topic:j.topic,score:j.class_accuracy})):o,[k,o]),q=j=>{if(B){const T=k.students.find(_=>_.student_id===j);if(T&&T.avg_score>0)return T.avg_score}return ue.has(j)?ue.get(j):null},Q=j=>{if(!k)return null;const T=k.students.find(_=>_.student_id===j);return T?T.risk_level:null},pe=async()=>{ie(!0);try{const j=await am(t.id);D(T=>T&&{...T,insights:j})}catch(j){console.warn("[AnalyticsView] Refresh insights failed:",j?.message)}finally{ie(!1)}};u.useMemo(()=>m.find(j=>j.uid===C),[m,C]);const $=[t.classMetadata?.gradeLevel||t.gradeLevel,t.classMetadata?.classification||t.classification,t.classMetadata?.strand||t.strand].filter(Boolean);return e.jsxs(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-3 sm:p-[24px] xl:p-[32px] space-y-3 sm:space-y-[24px] h-full overflow-y-auto",children:[e.jsx("div",{className:"flex items-center justify-between mb-3 sm:mb-6",children:e.jsxs("button",{onClick:d,className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors bg-white/60 hover:bg-white/80 px-[18px] py-2 rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50",children:[e.jsx($s,{className:"w-4 h-4"}),"Back to Classes"]})}),e.jsxs("header",{style:{backgroundColor:S?.hex||"#6366f1"},className:"rounded-[24px] p-4 sm:p-[24px] lg:p-[32px] shadow-[0_8px_32px_rgba(0,0,0,0.08)] flex flex-col lg:flex-row lg:items-center justify-between gap-4 sm:gap-6 relative overflow-hidden group text-white",children:[e.jsx("div",{className:"absolute -right-10 -bottom-10 w-48 h-48 rounded-full bg-white/10 group-hover:scale-[1.3] transition-transform duration-700 ease-out pointer-events-none"}),e.jsx("div",{className:"absolute -left-10 -top-10 w-32 h-32 rounded-full bg-white/10 group-hover:scale-[1.2] transition-transform duration-700 delay-75 ease-out pointer-events-none"}),e.jsxs("div",{className:"shrink-0 relative z-10",children:[e.jsx("h1",{className:"text-xl sm:text-[28px] font-bold mb-2 sm:mb-3 tracking-tight",children:t.name}),e.jsx("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:$.map((j,T)=>e.jsx("span",{className:"px-3 py-1 bg-white/20 backdrop-blur-md text-white text-[12px] font-semibold rounded-full shadow-sm border border-white/20",children:j},j))}),e.jsxs("p",{className:"text-[13px] text-white/80 font-medium",children:["Manager: ",t.classMetadata?.managerName||t.managerName||"Not assigned"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-[18px] w-full",children:[e.jsxs("div",{className:"group relative overflow-hidden bg-[#0ea5e9] shadow-[0_4px_16px_rgba(14,165,233,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Class Average"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(fs,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Math.round(te),"%"]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#10b981] shadow-[0_4px_16px_rgba(16,185,129,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Completion"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(La,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Math.round(ne),"%"]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#a855f7] shadow-[0_4px_16px_rgba(168,85,247,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Participation"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(hs,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Math.round(ze),"%"]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#f97316] shadow-[0_4px_16px_rgba(249,115,22,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Attention"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(da,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[se.length," ",e.jsx("span",{className:"text-[12px] opacity-90 font-medium",children:"students"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-3 sm:gap-[24px] h-auto xl:h-[600px]",children:[e.jsxs("div",{className:"xl:col-span-1 bg-white/80 backdrop-blur-[12px] rounded-[18px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white flex flex-col overflow-hidden h-[500px] xl:h-full",children:[e.jsxs("div",{className:"p-5 border-b border-[#f1f5f9] shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h2",{className:"text-[15px] font-semibold text-[#1e293b]",children:["Students ",e.jsxs("span",{className:"text-[#64748b] text-[13px]",children:["(",Pe.length,")"]})]}),e.jsx("button",{onClick:()=>g?.(),className:"text-[11px] font-semibold text-[#9956DE] hover:text-[#7c3aed] bg-[#9956DE]/10 hover:bg-[#9956DE]/20 px-3 py-1.5 rounded-lg transition-colors",children:"+ Add"})]}),e.jsxs("div",{className:"flex items-center bg-white px-4 py-2 rounded-[14px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#f1f5f9] group",children:[e.jsx(Xs,{className:"w-4 h-4 text-[#64748b] shrink-0 group-focus-within:text-[#4f46e5] transition-colors"}),e.jsx("input",{type:"text",placeholder:"Search students...",value:W,onChange:j=>f(j.target.value),className:"bg-transparent border-none focus:outline-none ml-2 text-[13px] w-full text-[#475569] placeholder:text-[#64748b]"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-4 overflow-x-auto no-scrollbar pb-1",children:[e.jsx("button",{onClick:()=>U("All"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${F==="All"?"bg-[#4f46e5] text-white shadow-[0_1px_4px_rgba(0,0,0,0.04)]":"bg-[#f8fafc] text-[#64748b] hover:bg-[#f1f5f9]"}`,children:"All Students"}),e.jsx("button",{onClick:()=>U("Good"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${F==="Good"?"bg-emerald-50 text-emerald-600 border border-emerald-100/50 shadow-[0_1px_4px_rgba(0,0,0,0.04)]":"bg-emerald-50/40 text-emerald-600 border border-emerald-50 hover:bg-emerald-50"}`,children:"Top Performers"}),e.jsx("button",{onClick:()=>U("Risk"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${F==="Risk"?"bg-rose-50 text-rose-600 border border-rose-100/50 shadow-[0_1px_4px_rgba(0,0,0,0.04)]":"bg-rose-50/40 text-rose-600 border border-rose-50 hover:bg-rose-50"}`,children:"Needs Attention"})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-4 flex flex-col no-scrollbar",children:e.jsx(yu,{style:{height:"100%"},data:Pe,className:"no-scrollbar",itemContent:(j,T)=>{const _=q(T.id),V=_!==null?{...T,avgScore:_}:T;return e.jsx("div",{className:"py-[6px] px-[8px]",children:e.jsx(rp,{student:V,onViewStudent:n,onCreateAccount:i,onRemoveStudent:I})})},computeItemKey:(j,T)=>ln(T)})})]}),e.jsxs("div",{className:"xl:col-span-2 flex flex-col gap-[24px] h-full overflow-y-auto no-scrollbar pb-10 xl:pb-0",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white flex flex-col group h-[280px]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h3",{className:"font-semibold text-[15px] text-[#1e293b]",children:"Risk Distribution"}),e.jsx(Yr,{className:"w-4 h-4 text-[#64748b] cursor-pointer group-hover:scale-110 transition-transform"})]}),e.jsx("div",{className:"relative w-full flex-1 min-h-[180px]",children:e.jsx(Yn,{width:"100%",height:"100%",children:e.jsxs(Kn,{data:Fe,children:[e.jsx(Xn,{strokeDasharray:"4 4",stroke:"#f1f5f9",vertical:!1}),e.jsx(Jn,{dataKey:"name",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#475569",fontSize:11,fontWeight:600},dy:10}),e.jsx(Zn,{axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600}}),e.jsx(eo,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(to,{dataKey:"value",radius:[6,6,0,0],barSize:80,children:Fe.map((j,T)=>{const _={Critical:"#dc2626","High Risk":"#f43f5e","Medium Risk":"#f59e0b","Low Risk":"#10b981",Unassessed:"#94a3b8"};return e.jsx(so,{fill:_[j.name]||j.color},`cell-${T}`)})})]})})})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white flex flex-col group h-[280px]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h3",{className:"font-semibold text-[15px] text-[#1e293b]",children:"Topic Performance"}),e.jsx(Yr,{className:"w-4 h-4 text-[#64748b] cursor-pointer group-hover:scale-110 transition-transform"})]}),e.jsx("div",{className:"relative w-full flex-1 min-h-[180px] -ml-8",children:e.jsx(Yn,{width:"100%",height:"100%",children:e.jsxs(Kn,{data:M,layout:"vertical",margin:{top:0,right:10,left:40,bottom:0},children:[e.jsx(Xn,{strokeDasharray:"4 4",stroke:"#f1f5f9",horizontal:!1}),e.jsx(Jn,{type:"number",domain:[0,100],axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600},tickFormatter:j=>`${j}%`}),e.jsx(Zn,{dataKey:"topic",type:"category",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#1e293b",fontSize:11,fontWeight:600},dx:-10}),e.jsx(eo,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(to,{dataKey:"score",radius:[0,6,6,0],barSize:28,children:M.map((j,T)=>{const _=j.score>=75?"#10b981":j.score>=60?"#f59e0b":"#f43f5e";return e.jsx(so,{fill:_},`cell-${T}`)})})]})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("h3",{className:"font-semibold text-[15px] text-[#1e293b] flex items-center gap-2",children:[e.jsx(ca,{className:"w-4 h-4 text-emerald-500"}),"Top Performers"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[G.map(j=>e.jsxs("div",{onClick:()=>n(j),className:"flex justify-between items-center p-3 bg-emerald-50/40 rounded-[14px] border border-emerald-50 group hover:scale-[1.02] transition-transform cursor-pointer",children:[e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:j.name}),e.jsxs("span",{className:"text-[13px] font-semibold text-emerald-600",children:[q(j.id)??j.avgScore,"%"]})]},`top-${j.id}`)),G.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No students available yet."})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("h3",{className:"font-semibold text-[15px] text-[#1e293b] flex items-center gap-2",children:[e.jsx(da,{className:"w-4 h-4 text-rose-500"}),"Needs Attention"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[se.slice(0,4).map(j=>{const T=Q(j.id),_=T||(j.riskLevel==="high"?"HIGH RISK":"MEDIUM RISK"),V=T==="Critical"||j.avgScore===0&&j.riskLevel==="high",me=T==="High Risk"||j.riskLevel==="high",oe=V?"bg-red-50/60 border-red-100":me?"bg-rose-50/40 border-rose-50":"bg-amber-50/40 border-amber-50",ae=V?"text-red-700":me?"text-rose-600":"text-amber-600";return e.jsxs("div",{onClick:()=>n(j),className:`flex justify-between items-center p-3 rounded-[14px] border group hover:scale-[1.02] transition-transform cursor-pointer ${oe}`,children:[e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:j.name}),e.jsx("span",{className:`text-[11px] font-semibold bg-white px-2 py-0.5 rounded-[14px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#f1f5f9] ${ae}`,children:_.toUpperCase()})]},`attn-${j.id}`)}),se.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No urgent students."})]})]})]})]})]}),k?.insights&&e.jsxs("div",{className:"bg-gradient-to-br from-indigo-50/80 to-purple-50/60 backdrop-blur-[12px] rounded-[18px] p-5 sm:p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-indigo-100/50",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("button",{onClick:()=>Ce(!fe),className:"flex items-center gap-2 text-[15px] font-semibold text-[#1e293b]",children:[e.jsx(bs,{className:"w-4 h-4 text-indigo-500"}),"AI Class Insights",e.jsx(Ot,{className:`w-4 h-4 text-[#64748b] transition-transform ${fe?"":"-rotate-90"}`})]}),e.jsxs("button",{onClick:pe,disabled:ce,className:"flex items-center gap-1.5 text-[11px] font-semibold text-indigo-600 hover:text-indigo-700 bg-white/70 hover:bg-white px-3 py-1.5 rounded-lg transition-colors disabled:opacity-50",children:[e.jsx(xs,{className:`w-3 h-3 ${ce?"animate-spin":""}`}),ce?"Refreshing...":"Refresh AI Analysis"]})]}),fe&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/70 rounded-[14px] p-4 border border-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ds,{size:18,className:"text-indigo-600"}),e.jsx("h4",{className:"text-[13px] font-semibold text-[#1e293b]",children:"Class Overview"})]}),e.jsx("p",{className:"text-[12px] text-[#475569] leading-relaxed",children:k.insights.class_summary})]}),e.jsxs("div",{className:"bg-white/70 rounded-[14px] p-4 border border-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ca,{size:18,className:"text-emerald-600"}),e.jsx("h4",{className:"text-[13px] font-semibold text-[#1e293b]",children:"What's Working"})]}),e.jsx("p",{className:"text-[12px] text-[#475569] leading-relaxed",children:k.insights.class_strengths})]}),e.jsxs("div",{className:"bg-white/70 rounded-[14px] p-4 border border-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(fs,{size:18,className:"text-amber-600"}),e.jsx("h4",{className:"text-[13px] font-semibold text-[#1e293b]",children:"Recommended Actions"})]}),e.jsx("ul",{className:"space-y-1.5",children:k.insights.recommended_actions.map((j,T)=>e.jsxs("li",{className:"text-[12px] text-[#475569] leading-relaxed flex items-start gap-1.5",children:[e.jsx("span",{className:"text-indigo-500 mt-0.5 shrink-0",children:"•"}),j]},T))})]})]})]}),e.jsx(np,{students:s,allClasses:a,currentClass:t,onReassignSection:l,reassignBusyId:c})]})},ip=({student:t,teacherId:s,teacherName:a,onStudentUpdated:r,onBack:o,onNavigateToQuizMaker:n,initialCache:i,onCacheUpdate:l})=>{const c=(t.riskLevel||"low").toLowerCase(),d=c==="high"||c==="medium",m=u.useMemo(()=>xt.getImportGroundedRolloutFlags(),[]),[p,h]=u.useState(null),[v,y]=u.useState(!0),[S,N]=u.useState(!1),[w,g]=u.useState(null),[I,L]=u.useState(i?.learningPath||""),[A,W]=u.useState(!0),[f,C]=u.useState(i?.gradeDraft||t.grade||"Grade 11"),[b,F]=u.useState(i?.sectionDraft||t.section||"Section A"),[U,k]=u.useState(!1),[D,J]=u.useState(i?.lessonPlan??null),[re,ce]=u.useState([]),[ie,fe]=u.useState(""),[Ce,ue]=u.useState(!1),[ge,B]=u.useState(""),[te,ne]=u.useState("all"),[ze,Fe]=u.useState("all"),[Pe,G]=u.useState(!1),[se,M]=u.useState(!1),[q,Q]=u.useState(null),[pe,$]=u.useState(!1),[j,T]=u.useState(!1),[_,V]=u.useState(0),[me,oe]=u.useState(!1),[ae,je]=u.useState("choose"),[we,Ke]=u.useState([]),[Ue,Je]=u.useState(!1),[ht,dt]=u.useState(!1),[rt,Mt]=u.useState(!1),[At,It]=u.useState(!1);u.useEffect(()=>{C(t.grade||"Grade 11"),F(t.section||"Section A")},[t.grade,t.section]),u.useEffect(()=>{let z=!1;return y(!0),rn(t.id).then(de=>{z||h(de)}).catch(de=>console.warn("[InterventionView] Backend fetch failed:",de)).finally(()=>{z||y(!1)}),Sn(t.id).then(de=>{z||N(de.length>0)}).catch(()=>{}),()=>{z=!0}},[t.id]);const[cs,Us]=u.useState(null),[Yt,ds]=u.useState(null);u.useEffect(()=>{let z=!1;const de=t.accountUid||t.id;return Gr(de).then(E=>{if(!z&&(E?.averageScore&&Us(Math.round(E.averageScore)),E?.subjects)){let R=0,ve=0;for(const ee of Object.values(E.subjects))for(const Me of Object.values(ee.modulesProgress||{}))ve++,Me.progress>=100&&R++;ds({completed:R,total:ve})}}).catch(()=>{}),()=>{z=!0}},[t.id,t.accountUid]),u.useEffect(()=>{const z=de=>{if(de.key==="Escape"){if(At){It(!1);return}if(ht){rt?It(!0):dt(!1);return}me&&oe(!1)}};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[ht,me,rt,At]),u.useEffect(()=>{if(ht){const z=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=z}}},[ht]),u.useEffect(()=>{l?.(t.id,{lessonPlan:D,learningPath:I,gradeDraft:f,sectionDraft:b})},[D,I,f,b,t.id,l]),u.useEffect(()=>{(async()=>{W(!0);try{let de="";try{de=await Yl(t.struggles.length>0?t.struggles:[t.weakestTopic],"general_math"),fe(de)}catch{fe("")}const E=await xt.getLearningPath({weaknesses:t.struggles.length>0?t.struggles:[t.weakestTopic],gradeLevel:"High School",subject:"general_math"}),R=de?`${E.learningPath} +`)],`${Ke}-normalized.csv`,{type:"text/csv"})},B=async $=>{C(!0),k(""),J(null);let j=$;if(/\.(xlsx|xls)$/i.test($.name))try{const T=await Gx($,{confidenceThreshold:on});g(T);const _=ge(T,$.name);_&&(j=_)}catch{g(null)}else g(null);try{const T=await xt.uploadClassRecords(j,{classSectionId:t,className:s,datasetIntent:"synthetic_student_records"}),_=T.students.length,me=((oe,ae,je,we)=>({classSectionId:oe.classSectionId||ae||"imported_class",className:oe.className||je||"Imported Class",classMetadata:oe.classMetadata||we}))(T,t,s,a);_>0&&l?.({students:T.students,classSectionId:me.classSectionId,className:me.className,classMetadata:me.classMetadata}),T.success?(le.success(`Successfully imported ${_} student records.`),J({datasetIntent:T.datasetIntent,summary:T.interpretationSummary,columns:T.columnInterpretations?.map(oe=>({columnName:oe.columnName,mappedField:oe.mappedField,usagePolicy:oe.usagePolicy,confidenceBand:oe.confidenceBand,domainSignals:oe.domainSignals}))||[]}),c?.()):le.error("Import completed but no usable student rows were detected. Check required columns and retry.")}catch(T){le.error(T instanceof Error?T.message:"Upload failed")}finally{C(!1)}},te=async $=>{F(!0);try{const j=await xt.uploadCourseMaterials($,{classSectionId:t,className:s});if(j.success){const T=j.topics?.length??0;le.success(`Course material imported (${T} topics extracted).`),c?.()}}catch(j){le.error(j instanceof Error?j.message:"Course material upload failed")}finally{F(!1)}},[ne,ze]=u.useState(r),[Fe,Pe]=u.useState(!1),[G,se]=u.useState(null),M=u.useMemo(()=>{let $=ne;if(o.length>0){const j=new Set(o.map(T=>Ss(T.classSectionId||T.id)));$=$.filter(T=>j.has(Ss(T.classSectionId))||j.has(Ss(T.classroomId)))}else return[];return t&&($=$.filter(j=>Ss(j.classSectionId)===Ss(t)||Ss(j.classroomId)===Ss(t))),$},[ne,t,o]);u.useEffect(()=>{ze(r),Q(Object.fromEntries(r.map($=>[Ka($),{grade:$.grade||"",section:$.section||""}])))},[r]);const[q,Q]=u.useState({}),pe=async()=>{Pe(!0);let $=0,j=0;try{for(const _ of M){const V=q[Ka(_)],me=V?.grade||_.grade,oe=V?.section||_.section;try{n&&(me!==_.grade||oe!==_.section)&&(await yr(_.id,me,oe,n,new Date().getFullYear().toString(),i),await ll(_.id,me,oe),$++)}catch(ae){console.warn(`[EditRecords] Failed to save ${_.name}:`,ae),j++}}const T=ne.map(_=>{const V=q[Ka(_)];if(!V)return _;const me=yt({metadata:_.classMetadata,classSectionId:_.classSectionId,className:[V.grade,V.section].filter(Boolean).join(" - "),grade:V.grade,section:V.section});return{..._,grade:V.grade,section:V.section,className:me.className||[V.grade,V.section].filter(Boolean).join(" - "),classSectionId:me.classSectionId||_.classSectionId,classMetadata:me}});ze(T),m?.(T),j>0?le.warning(`Saved ${$} records, ${j} failed`):le.success("Records saved successfully")}catch{le.error("Failed to save changes")}finally{Pe(!1)}};return e.jsx("div",{className:"h-full overflow-y-auto w-full block",children:e.jsxs("div",{className:"w-full p-[24px] xl:p-[32px] space-y-[24px]",children:[S==="main"&&e.jsxs("div",{className:"block space-y-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[16px] p-4 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-slate-200 flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-indigo-50 flex items-center justify-center border border-indigo-100/50",children:e.jsx(lr,{className:"w-5 h-5 text-indigo-500"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[14px] font-bold text-[#1e293b]",children:"Upload Context"}),e.jsx("p",{className:"text-[12px] text-[#64748b]",children:"Select where the imported data should be applied"})]})]}),e.jsxs("div",{className:"relative w-full md:w-[300px]",children:[e.jsxs("select",{className:"appearance-none bg-[#f8fafc] border border-[#e2e8f0] text-[#1e293b] font-bold text-[13px] rounded-lg pl-4 pr-10 py-2.5 outline-none focus:border-[#4f46e5] focus:ring-2 focus:ring-[#4f46e5]/20 shadow-[0_1px_4px_rgba(0,0,0,0.02)] cursor-pointer w-full transition-colors",value:s||t||"All Classes",onChange:()=>{},children:[e.jsx("option",{value:"All Classes",children:"All Classes"}),o.map($=>e.jsx("option",{value:$.classSectionId||$.id,children:$.name},$.id))]}),e.jsx(Ot,{className:"w-4 h-4 text-[#64748b] absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{onDragOver:$=>{$.preventDefault(),L(!0)},onDragLeave:()=>L(!1),onDrop:$=>{$.preventDefault(),L(!1);const j=$.dataTransfer.files[0];j&&B(j)},onClick:()=>re.current?.click(),className:`border-2 border-dashed transition-all rounded-[24px] p-8 flex flex-col items-center justify-center text-center cursor-pointer group shadow-[0_4px_20px_rgba(0,0,0,0.02)] relative overflow-hidden h-[280px] ${I?"border-[#1FA7E1] bg-[#1FA7E1]/10":"border-[#1FA7E1]/30 hover:border-[#1FA7E1] bg-white hover:bg-[#1FA7E1]/5"}`,children:[e.jsx("input",{ref:re,type:"file",accept:".csv,.xlsx,.xls",onChange:$=>{const j=$.target.files?.[0];j&&B(j)},className:"hidden"}),e.jsx("div",{className:"w-16 h-16 rounded-full bg-[#1FA7E1]/10 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300 shadow-sm border border-[#1FA7E1]/20",children:f?e.jsx("span",{className:"animate-spin text-[#1FA7E1]",children:"..."}):e.jsx(cd,{className:"w-8 h-8 text-[#1FA7E1]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:f?"Uploading...":"Class Records"}),e.jsx("p",{className:"text-[13px] text-[#64748b] max-w-sm mb-6",children:"Upload student grades, attendance logs, and quiz scores to power predictive analytics."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".csv"}),e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".xlsx"})]})]}),e.jsxs("div",{onDragOver:$=>{$.preventDefault(),W(!0)},onDragLeave:()=>W(!1),onDrop:$=>{$.preventDefault(),W(!1);const j=$.dataTransfer.files[0];j&&te(j)},onClick:()=>ce.current?.click(),className:`border-2 border-dashed transition-all rounded-[24px] p-8 flex flex-col items-center justify-center text-center cursor-pointer group shadow-[0_4px_20px_rgba(0,0,0,0.02)] relative overflow-hidden h-[280px] ${A?"border-[#9956DE] bg-[#9956DE]/10":"border-[#9956DE]/30 hover:border-[#9956DE] bg-white hover:bg-[#9956DE]/5"}`,children:[e.jsx("input",{ref:ce,type:"file",accept:".pdf,.docx,.txt",onChange:$=>{const j=$.target.files?.[0];j&&te(j)},className:"hidden"}),e.jsx("div",{className:"w-16 h-16 rounded-full bg-[#9956DE]/10 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300 shadow-sm border border-[#9956DE]/20",children:b?e.jsx("span",{className:"animate-spin text-[#9956DE]",children:"..."}):e.jsx(As,{className:"w-8 h-8 text-[#9956DE]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:b?"Uploading...":"Course Materials"}),e.jsx("p",{className:"text-[13px] text-[#64748b] max-w-sm mb-6",children:"Upload syllabus, lesson plans, and curriculum docs to ground AI lesson generation."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".pdf"}),e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".docx"}),e.jsx("span",{className:"px-3 py-1 bg-slate-100 text-slate-500 text-[11px] font-semibold rounded-full border border-slate-200",children:".txt"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-[16px]",children:[e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#0ea5e9] to-[#0284c7] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(14,165,233,0.2)] flex flex-col text-white group transition-all duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-sky-500/30",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full"}),e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center shrink-0 mb-3 relative z-10 transition-transform group-hover:scale-110",children:e.jsx(id,{className:"w-5 h-5 text-white"})}),e.jsx("h4",{className:"font-bold text-[14px] mb-1.5 relative z-10",children:"Smart Parsing"}),e.jsx("p",{className:"text-[12px] text-white/90 leading-relaxed relative z-10",children:"AI automatically understands varied spreadsheet formats and maps column names securely."})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#f97316] to-[#ea580c] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(249,115,22,0.2)] flex flex-col text-white group transition-all duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-orange-500/30",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full"}),e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center shrink-0 mb-3 relative z-10 transition-transform group-hover:scale-110",children:e.jsx(Kr,{className:"w-5 h-5 text-white"})}),e.jsx("h4",{className:"font-bold text-[14px] mb-1.5 relative z-10",children:"Risk Prediction"}),e.jsx("p",{className:"text-[12px] text-white/90 leading-relaxed relative z-10",children:"Analyzes historical performance patterns across your data to predict at-risk students."})]}),e.jsxs("div",{className:"relative overflow-hidden bg-gradient-to-br from-[#a855f7] to-[#9333ea] rounded-[16px] p-[20px] shadow-[0_4px_12px_rgba(168,85,247,0.2)] flex flex-col text-white group transition-all duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-purple-500/30",children:[e.jsx("div",{className:"absolute -right-8 -bottom-8 w-24 h-24 bg-white/10 rounded-full"}),e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center shrink-0 mb-3 relative z-10 transition-transform group-hover:scale-110",children:e.jsx(bs,{className:"w-5 h-5 text-white"})}),e.jsx("h4",{className:"font-bold text-[14px] mb-1.5 relative z-10",children:"Contextual AI"}),e.jsx("p",{className:"text-[12px] text-white/90 leading-relaxed relative z-10",children:"Maps curriculum topics to generate highly personalized remedial lesson paths."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white flex flex-col justify-between h-full",children:[e.jsx("h2",{className:"text-[16px] font-semibold text-[#1e293b] mb-4",children:"Data Health"}),e.jsxs("div",{className:"flex-1 bg-emerald-50/50 border border-emerald-100 rounded-[16px] p-6 flex flex-col items-center justify-center text-center transition-all duration-300 hover:bg-emerald-50 hover:shadow-md hover:border-emerald-200",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-emerald-100 flex items-center justify-center mb-3 text-emerald-600 transition-transform duration-300 hover:scale-110 hover:-translate-y-1",children:e.jsx(Sa,{className:"w-6 h-6"})}),e.jsx("h3",{className:"text-emerald-700 font-bold text-[15px] mb-1",children:"All Records Synced"}),e.jsx("p",{className:"text-emerald-600/80 text-[12px] max-w-[200px]",children:"AI parsing completed successfully with no anomalies detected."})]}),e.jsxs("div",{className:"flex flex-col gap-2 mt-4",children:[e.jsxs("button",{onClick:()=>N("edit-records"),className:"w-full flex items-center justify-center gap-2 bg-[#1e293b] hover:bg-black text-white text-[13px] font-semibold rounded-full px-4 py-3 shadow-[0_1px_4px_rgba(0,0,0,0.04)] transition-transform hover:scale-[1.02]",children:[e.jsx(ad,{className:"w-4 h-4"})," Edit Class Records"]}),e.jsx("button",{onClick:()=>N("mapping-logs"),className:"w-full flex items-center justify-center gap-2 bg-white text-[#475569] border border-slate-300 hover:bg-slate-50 text-[13px] font-semibold rounded-full px-4 py-3 shadow-[0_1px_4px_rgba(0,0,0,0.04)] transition-colors",children:"View Mapping Logs"})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[24px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white flex flex-col h-full",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-[16px] font-semibold text-[#1e293b]",children:"Recent Uploads"}),e.jsx("button",{onClick:()=>N("mapping-logs"),className:"text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors",children:"View All"})]}),e.jsxs("div",{className:"flex-1 space-y-[12px] overflow-y-auto no-scrollbar flex flex-col justify-center items-center h-[120px]",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-slate-50 flex items-center justify-center mb-2 border border-slate-100",children:e.jsx(Xc,{className:"w-5 h-5 text-slate-300"})}),e.jsx("p",{className:"text-[13px] font-medium text-slate-500",children:"There are no recent uploads yet."})]})]})]})]}),S==="mapping-logs"&&e.jsxs("div",{className:"space-y-[16px]",children:[e.jsx("div",{className:"shrink-0 mb-2",children:e.jsxs("button",{onClick:()=>N("main"),className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors w-max bg-white px-[18px] py-2 rounded-full shadow-sm border border-slate-200",children:[e.jsx(cr,{className:"w-4 h-4"})," Back to Uploads"]})}),e.jsxs("div",{className:"bg-white rounded-[18px] border border-[#f1f5f9] overflow-hidden shadow-sm",children:[e.jsx("div",{className:"p-5 border-b border-[#f1f5f9] bg-slate-50 flex justify-between items-center",children:e.jsx("h2",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Latest Import Mapping"})}),e.jsx("div",{className:"p-5",children:D?e.jsx("div",{className:"space-y-3",children:D.columns.map(($,j)=>e.jsxs("div",{className:"flex justify-between p-3 border rounded bg-slate-50",children:[e.jsx("span",{className:"font-semibold text-sm",children:$.columnName}),e.jsx("span",{className:"text-sm text-indigo-600",children:$.mappedField||"Unmapped"})]},j))}):e.jsx("p",{className:"text-slate-500 text-sm",children:"No recent mapping logs to display."})})]})]}),S==="edit-records"&&e.jsxs("div",{className:"space-y-[16px] h-full flex flex-col",children:[e.jsx("div",{className:"shrink-0 mb-2",children:e.jsxs("button",{onClick:()=>N("main"),className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors w-max bg-white px-[18px] py-2 rounded-full shadow-sm border border-slate-200",children:[e.jsx(cr,{className:"w-4 h-4"})," Back to Uploads"]})}),e.jsxs("div",{className:"bg-white rounded-[18px] border border-slate-200 shadow-sm overflow-hidden flex flex-col flex-1",children:[e.jsxs("div",{className:"p-5 border-b border-slate-200 flex justify-between items-center bg-white",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-[18px] font-bold text-[#1e293b]",children:"Edit Class Records"}),e.jsx("p",{className:"text-[13px] text-[#64748b]",children:"Review and modify student data manually"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>N("main"),className:"px-5 py-2 rounded-full border border-slate-300 text-slate-700 font-semibold text-[13px] hover:bg-slate-50",children:"Cancel"}),e.jsx("button",{onClick:pe,disabled:Fe,className:"px-5 py-2 rounded-full bg-emerald-500 text-white font-semibold text-[13px] hover:bg-emerald-600 flex items-center gap-2 disabled:opacity-50",children:Fe?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(yi,{className:"w-4 h-4"})," Save Changes"]})})]})]}),e.jsxs("div",{className:"px-5 py-3 border-b border-slate-200 flex justify-between items-center bg-slate-50/50 shrink-0 text-slate-500 text-[13px]",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(oa,{className:"w-4 h-4"})," Click on any field to edit"]}),e.jsxs("span",{children:["Showing ",M.length," records"]})]}),e.jsx("div",{className:"overflow-auto flex-1 table-scrollbar bg-white relative",children:e.jsxs("div",{className:"min-w-[1100px] w-full flex flex-col min-h-full",children:[e.jsxs("div",{className:"flex items-center w-full bg-slate-100/90 border-b border-slate-200 text-[12px] font-semibold text-slate-500 tracking-wide sticky top-0 z-20 shadow-[0_1px_2px_rgba(0,0,0,0.02)] h-12",children:[e.jsx("div",{className:"flex-[1.5] min-w-[240px] px-6 sticky left-0 z-30 bg-slate-100/90 backdrop-blur-sm border-r border-slate-200 h-full flex items-center shadow-[2px_0_4px_rgba(0,0,0,0.02)]",children:"Student Name"}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 h-full flex items-center justify-center",children:"LRN"}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 h-full flex items-center justify-center",children:"Grade"}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 h-full flex items-center justify-center",children:"Section"}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 h-full flex items-center justify-center",children:"Avg Score"}),e.jsx("div",{className:"w-[120px] shrink-0 px-4 h-full flex items-center justify-center",children:"Risk Level"}),e.jsx("div",{className:"flex-1 min-w-[180px] px-4 h-full flex items-center justify-center",children:"Weakest Topic"}),e.jsx("div",{className:"w-[80px] shrink-0 px-4 h-full flex items-center justify-center border-r border-transparent",children:"Action"})]}),e.jsx("div",{className:"flex flex-col w-full pb-4",children:M.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4",children:e.jsx(oa,{className:"w-7 h-7 text-slate-400"})}),e.jsx("h3",{className:"text-[16px] font-bold text-slate-700 mb-2",children:"No managed classes found"}),e.jsx("p",{className:"text-[13px] text-slate-500 max-w-sm",children:"You don't currently manage any classes. Ask your administrator to assign you as a section manager, or create a new class from the Dashboard."})]}):M.map(($,j)=>{const T=Ka($),_=$.name.split(" "),V=_.length>1?`${_[0][0]}${_[_.length-1][0]}`.toUpperCase():$.name.substring(0,2).toUpperCase(),me=["bg-[#be185d]","bg-[#3b82f6]","bg-[#f43f5e]","bg-[#2563eb]","bg-[#059669]","bg-[#d946ef]"],oe=me[j%me.length],ae=($.avgScore??0)>=75?"text-emerald-500":($.avgScore??0)>=60?"text-orange-500":"text-rose-500";let je="bg-slate-50 text-slate-600 border-slate-200";const we=($.riskLevel||"").toLowerCase();return we==="low"?je="bg-emerald-50 text-emerald-600 border-emerald-200":we==="high"?je="bg-rose-50 text-rose-600 border-rose-200":we==="medium"&&(je="bg-orange-50 text-orange-600 border-orange-200"),e.jsxs("div",{className:"flex items-center w-full border-b border-slate-100 hover:bg-slate-50 transition-colors group min-h-[64px]",children:[e.jsxs("div",{className:"flex-[1.5] min-w-[240px] px-6 sticky left-0 z-10 bg-white group-hover:bg-slate-50 border-r border-slate-100 h-full flex items-center gap-4 shadow-[2px_0_4px_rgba(0,0,0,0.01)]",children:[e.jsx("div",{className:`w-8 h-8 rounded-full ${oe} text-white flex items-center justify-center font-bold text-[12px] shrink-0`,children:V}),e.jsx("span",{className:"font-semibold text-slate-800 text-[14px] truncate",children:$.name})]}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 flex justify-center text-[13px] text-slate-500",children:$.lrn||"—"}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 flex justify-center",children:e.jsx("input",{type:"text",value:q[T]?.grade||$.grade||"",onChange:Ke=>Q(Ue=>({...Ue,[T]:{...Ue[T],grade:Ke.target.value}})),readOnly:G!==T,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${G===T?"bg-white border border-purple-500 ring-2 ring-purple-500/20":"bg-slate-100 border border-transparent cursor-default"}`})}),e.jsx("div",{className:"w-[140px] shrink-0 px-4 flex justify-center",children:e.jsx("input",{type:"text",value:q[T]?.section||$.section||"",onChange:Ke=>Q(Ue=>({...Ue,[T]:{...Ue[T],section:Ke.target.value}})),readOnly:G!==T,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${G===T?"bg-white border border-purple-500 ring-2 ring-purple-500/20":"bg-slate-100 border border-transparent cursor-default"}`})}),e.jsx("div",{className:"w-[100px] shrink-0 px-4 flex justify-center",children:e.jsxs("span",{className:`${ae} font-bold text-[14px]`,children:[$.avgScore,"%"]})}),e.jsx("div",{className:"w-[120px] shrink-0 px-4 flex justify-center",children:e.jsx("span",{className:`px-3 py-1 text-[10px] font-bold rounded uppercase border ${je}`,children:$.riskLevel||"Unknown"})}),e.jsx("div",{className:"flex-1 min-w-[180px] px-4 flex justify-center text-[13px] text-slate-600 truncate",children:$.weakestTopic||"Foundational Skills"}),e.jsx("div",{className:"w-[80px] shrink-0 px-4 flex justify-center border-r border-transparent",children:e.jsx("button",{onClick:()=>se(G===T?null:T),className:`w-8 h-8 rounded-full flex items-center justify-center transition-colors ${G===T?"bg-purple-100 text-purple-600":"hover:bg-slate-200 text-slate-400"}`,children:e.jsx(Ci,{className:"w-4 h-4"})})})]},T)})})]})})]})]})]})})}const Vx=[{value:"available",label:"Available",icon:e.jsx(La,{size:14}),color:"text-emerald-600"},{value:"teacher_uploaded",label:"Teacher Material",icon:e.jsx(Wr,{size:14}),color:"text-blue-600"},{value:"coming_soon",label:"Coming Soon",icon:e.jsx(Ls,{size:14}),color:"text-amber-600"},{value:"unavailable",label:"Unavailable",icon:e.jsx(yc,{size:14}),color:"text-slate-400"}],Wx=({teacherId:t})=>{const[s,a]=u.useState(""),[r,o]=u.useState("teacher_uploaded"),[n,i]=u.useState(!1),[l,c]=u.useState(null),d=async()=>{if(!s){le.error("Select a module first.");return}i(!0);try{let m;if(l&&r==="teacher_uploaded"){const p=Fc(Ql,`teacher_modules/${t}/${s}/${l.name}`);await Oc(p,l),m=await Pc(p)}await $c(s,r,t,m),le.success(`Module status updated to "${r}".`),c(null)}catch(m){le.error(m.message||"Failed to update module status.")}finally{i(!1)}};return e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-white p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-slate-800",children:"Module Availability Control"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"Set module status or upload alternative PDF when DepEd content is unavailable."})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-600 mb-1 block",children:"Module"}),e.jsxs("select",{value:s,onChange:m=>a(m.target.value),className:"w-full rounded-lg border border-slate-200 px-3 py-2 text-sm",children:[e.jsx("option",{value:"",children:"Select module..."}),Gl.map(m=>e.jsxs("option",{value:m.id,children:[m.moduleTitle," (",m.quarter,")"]},m.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-600 mb-1 block",children:"Status"}),e.jsx("select",{value:r,onChange:m=>o(m.target.value),className:"w-full rounded-lg border border-slate-200 px-3 py-2 text-sm",children:Vx.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))})]})]}),r==="teacher_uploaded"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-600 mb-1 block",children:"Upload Alternative PDF (optional)"}),e.jsx("input",{type:"file",accept:".pdf",onChange:m=>c(m.target.files?.[0]||null),className:"text-sm text-slate-600"})]}),e.jsx("button",{type:"button",onClick:d,disabled:!s||n,className:"px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-bold disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:n?"Updating...":"Update Status"})]})},Xa="ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789",ri="school.mathpulse.local";function ni(t=10){const s=typeof globalThis<"u"&&typeof globalThis.crypto<"u"?globalThis.crypto:void 0;if(s&&typeof s.getRandomValues=="function"){const r=new Uint32Array(t);s.getRandomValues(r);let o="";for(let n=0;n{const[l,c]=u.useState(""),[d,m]=u.useState(""),[p,h]=u.useState(!1),[v,y]=u.useState(null),[S,N]=u.useState(null),[w,g]=u.useState(!1);u.useEffect(()=>{t&&(y(null),g(!1),h(!1),N(null),c((a?.email||qx(a)).trim()),m(ni()))},[t,a]);const I=u.useMemo(()=>a?[a.grade,a.section].filter(Boolean).join(" · ")||"Unassigned section":null,[a]),L=()=>{m(ni()),g(!1)},A=async()=>{try{const C=S?.temporaryPassword||d;if(!C)return;typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(C),g(!0),le.success("Temporary password copied. Share it with the student now — it will not be shown again."),window.setTimeout(()=>g(!1),2500)}catch(C){console.warn("Clipboard write failed:",C),le.error("Unable to copy password. Please copy it manually.")}},W=async()=>{if(!a)return;const C=l.trim();if(!Yx(C)){y("Enter a valid email address before creating the account.");return}if(!d||d.length<8){y("Temporary password must be at least 8 characters.");return}if(!r){y("Missing teacher context. Please refresh and try again.");return}h(!0),y(null);try{const b=await Yu({name:a.name,lrn:a.lrn,email:C,grade:a.grade,section:a.section,classSectionId:a.classSectionId,adviserTeacherId:r,adviserTeacherName:o,schoolYear:n,temporaryPassword:d});N(b),i?.({...b,rosterId:a.rosterId}),le.success(`Account created for ${a.name}.`)}catch(b){const F=b instanceof Error?b.message:"Failed to create account.";y(F)}finally{h(!1)}},f=S?.temporaryPassword||d;return e.jsx(zt,{children:t&&a&&e.jsx(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4",onClick:()=>{p||s()},children:e.jsxs(Re.div,{initial:{opacity:0,scale:.95,y:12},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:12},transition:{type:"spring",damping:28,stiffness:320},onClick:C=>C.stopPropagation(),className:"bg-[#f7f9fc] rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden border border-[#dde3eb]",role:"dialog","aria-modal":"true","aria-labelledby":"create-student-account-modal-title",children:[e.jsxs("div",{className:"flex items-start justify-between px-6 pt-6",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0",children:e.jsx(ui,{size:22})}),e.jsxs("div",{children:[e.jsx("h2",{id:"create-student-account-modal-title",className:"text-[16px] font-bold text-[#0a1628]",children:S?"Account Created":"Create Student Account"}),e.jsx("p",{className:"text-[12px] text-[#5a6578] mt-0.5",children:S?"Share these credentials with the student. The password will not be shown again.":`Provision a system account for ${a.name}.`})]})]}),e.jsx("button",{type:"button",onClick:()=>{p||s()},className:"p-1.5 rounded-lg hover:bg-[#dde3eb] transition-colors","aria-label":"Close",children:e.jsx(qt,{className:"w-4 h-4 text-[#5a6578]"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-4",children:[e.jsxs("div",{className:"bg-white border border-[#e2e8f0] rounded-2xl p-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-[#64748b]",children:"Roster Row"}),e.jsx("p",{className:"text-[14px] font-semibold text-[#0a1628] mt-1",children:a.name}),e.jsxs("p",{className:"text-[12px] text-[#475569] mt-0.5",children:[a.lrn?`LRN ${a.lrn} · `:"",I]})]}),!S&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-[12px] font-semibold text-[#0a1628]",children:"Email address"}),e.jsx("input",{type:"email",value:l,onChange:C=>c(C.target.value),disabled:p,className:"mt-1 w-full rounded-xl border border-[#dde3eb] bg-white px-3 py-2 text-[13px] text-[#0a1628] focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-200",placeholder:"student@school.example",autoComplete:"off",spellCheck:!1}),e.jsx("span",{className:"text-[11px] text-[#64748b] mt-1 block",children:"Auto-generated from LRN if available. The student will sign in with this address."})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[12px] font-semibold text-[#0a1628] block",children:"Temporary password"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("input",{type:"text",value:d,readOnly:!0,className:"flex-1 rounded-xl border border-[#dde3eb] bg-white px-3 py-2 text-[13px] font-mono tracking-wide text-[#0a1628] focus:outline-none"}),e.jsx("button",{type:"button",onClick:L,disabled:p,className:"p-2 rounded-xl border border-[#dde3eb] bg-white hover:bg-[#f1f5f9] transition-colors disabled:opacity-60","aria-label":"Regenerate temporary password",children:e.jsx(xs,{className:"w-4 h-4 text-[#475569]"})}),e.jsx("button",{type:"button",onClick:A,className:"p-2 rounded-xl border border-[#dde3eb] bg-white hover:bg-[#f1f5f9] transition-colors","aria-label":"Copy temporary password",children:w?e.jsx(Gt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Vr,{className:"w-4 h-4 text-[#475569]"})})]}),e.jsx("span",{className:"text-[11px] text-[#64748b] mt-1 block",children:"The student should change this on first sign-in. Share it once — it will not be persisted."})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 rounded-xl bg-rose-50 border border-rose-200 px-3 py-2 text-[12px] text-rose-700",children:[e.jsx(Lc,{className:"w-4 h-4 mt-0.5 shrink-0"}),e.jsx("span",{children:v})]})]}),S&&e.jsxs("div",{className:"rounded-2xl border border-emerald-200 bg-emerald-50 p-4 space-y-2",children:[e.jsx("p",{className:"text-[12px] font-semibold text-emerald-800",children:"Credentials"}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl bg-white border border-emerald-100 px-3 py-2",children:[e.jsx("span",{className:"text-[12px] text-[#475569]",children:"Email"}),e.jsx("span",{className:"text-[13px] font-semibold text-[#0a1628]",children:S.email})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl bg-white border border-emerald-100 px-3 py-2",children:[e.jsx("span",{className:"text-[12px] text-[#475569]",children:"Temporary password"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[13px] font-semibold font-mono text-[#0a1628]",children:f}),e.jsx("button",{type:"button",onClick:A,className:"p-1.5 rounded-lg border border-emerald-200 bg-white hover:bg-emerald-100 transition-colors","aria-label":"Copy temporary password",children:w?e.jsx(Gt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Vr,{className:"w-4 h-4 text-emerald-700"})})]})]}),e.jsx("p",{className:"text-[11px] text-emerald-800",children:"This password is not stored anywhere. If you close this dialog without copying, you will need to reset it from the admin tools."})]})]}),e.jsx("div",{className:"flex items-center justify-end gap-2 px-6 pb-6",children:S?e.jsx(wt,{type:"button",onClick:s,className:"bg-indigo-600 hover:bg-indigo-700 text-white text-[13px] font-semibold rounded-xl px-5 py-2",children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{type:"button",variant:"ghost",onClick:s,disabled:p,className:"text-[13px] font-semibold text-[#475569] rounded-xl px-4 py-2 hover:bg-[#dde3eb]",children:"Cancel"}),e.jsx(wt,{type:"button",onClick:W,disabled:p,className:"bg-indigo-600 hover:bg-indigo-700 text-white text-[13px] font-semibold rounded-xl px-5 py-2 disabled:opacity-60",children:p?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(gt,{className:"w-4 h-4 animate-spin"}),"Creating…"]}):"Create account"})]})})]})})})};function Xx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=yt({metadata:t.classMetadata,classSectionId:t.classSectionId,className:t.name,grade:t.grade,gradeLevel:t.gradeLevel,classification:t.classification,strand:t.strand,section:t.section,schoolYear:t.schoolYear,ownerTeacherId:t.ownerTeacherId||t.teacherId,ownerTeacherName:t.ownerTeacherName,adviserTeacherId:t.adviserTeacherId||t.teacherId,adviserTeacherName:t.adviserTeacherName||t.ownerTeacherName,managerId:t.managerId,managerName:t.managerName});return{id:t.id,name:a.className||t.name,classSectionId:a.classSectionId||t.classSectionId,classMetadata:a,gradeLevel:a.gradeLevel||void 0,classification:a.classification||void 0,strand:a.strand||void 0,managerId:a.managerId||void 0,managerName:a.managerName||void 0,schedule:t.schedule,studentCount:t.studentCount,avgScore:t.avgScore,atRiskCount:t.atRiskCount,riskLevel:s}}function Hr(t,s){const a=t.riskStatus?["intervene","critical","at_risk"].includes(t.riskStatus)?"high":t.riskStatus==="watch"?"medium":"low":(t.riskLevel||"Low").toLowerCase(),r=t.lastActive?Tl(t.lastActive.toDate()):"Unknown",o=t.className||s||"Imported Class",n=gs(o),i=t.grade||n.grade,l=t.section||n.section,c=yt({metadata:t.classMetadata,classSectionId:t.classSectionId||t.classroomId,className:[i,l].filter(Boolean).join(" - ")||o,grade:i,gradeLevel:t.gradeLevel,classification:t.classification,strand:t.strand,section:l,adviserTeacherId:t.teacherId,ownerTeacherId:t.teacherId,managerId:t.classMetadata?.managerId||t.managerId,managerName:t.classMetadata?.managerName||t.managerName});return{id:t.id,lrn:t.lrn,name:t.name,avatar:t.avatar||`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:t.avgQuizScore,riskLevel:a,riskStatus:t.riskStatus||null,wri:t.wri??null,weakestTopic:t.weakestTopic||"N/A",classroomId:t.classroomId||c.classSectionId||o,className:c.className||[i,l].filter(Boolean).join(" - ")||o,grade:i,gradeLevel:c.gradeLevel||Ns(i)||void 0,classification:c.classification||pa(c.gradeLevel||i)||void 0,strand:c.strand||ha(c.className,l)||void 0,section:l,classSectionId:c.classSectionId||t.classSectionId,classMetadata:c,managerId:c.managerId||void 0,managerName:c.managerName||void 0,lastActive:r,struggles:t.struggles||[],engagementScore:t.engagementScore,attendance:t.attendance,assignmentCompletion:t.assignmentCompletion,hasRegisteredAccount:t.hasRegisteredAccount,source:t.source,accountUid:t.accountUid,email:t.email}}function Jx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=yt({metadata:t.classMetadata,classSectionId:t.classSectionId,className:t.name,grade:t.grade,gradeLevel:t.gradeLevel||t.classMetadata?.gradeLevel,classification:t.classification||t.classMetadata?.classification,strand:t.strand||t.classMetadata?.strand,section:t.section,managerId:t.managerId||t.classMetadata?.managerId,managerName:t.managerName||t.classMetadata?.managerName});return{id:t.id,name:a.className||t.name,classSectionId:a.classSectionId||t.classSectionId||void 0,classMetadata:a,gradeLevel:a.gradeLevel||void 0,classification:a.classification||void 0,strand:a.strand||void 0,managerId:a.managerId||void 0,managerName:a.managerName||void 0,schedule:t.schedule||"Mon-Fri",studentCount:t.studentCount,avgScore:t.avgScore,atRiskCount:t.atRiskCount,riskLevel:s}}function Zx(t){const s=(t.riskLevel||"Low").toLowerCase(),a=yt({metadata:t.classMetadata,classSectionId:t.classSectionId,className:t.className||[t.grade,t.section].filter(Boolean).join(" - ")||"Imported Class",grade:t.grade,gradeLevel:t.gradeLevel||t.classMetadata?.gradeLevel,classification:t.classification||t.classMetadata?.classification,strand:t.strand||t.classMetadata?.strand,section:t.section,managerId:t.managerId||t.classMetadata?.managerId,managerName:t.managerName||t.classMetadata?.managerName}),r=a.className||"Imported Class";return{id:t.id,lrn:t.lrn||void 0,name:t.name,avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:t.avgQuizScore,riskLevel:s,weakestTopic:t.weakestTopic||"Foundational Skills",classroomId:a.classSectionId||t.classSectionId||r,className:r,grade:a.grade||gs(r).grade,gradeLevel:a.gradeLevel||Ns(a.grade||gs(r).grade)||void 0,classification:a.classification||pa(a.gradeLevel||a.grade)||void 0,strand:a.strand||ha(r,a.section||t.section)||void 0,section:a.section||gs(r).section,classSectionId:a.classSectionId||t.classSectionId||void 0,classMetadata:a,managerId:a.managerId||void 0,managerName:a.managerName||void 0,lastActive:"Recently imported",struggles:[t.weakestTopic||"Foundational Skills"],engagementScore:t.engagementScore,attendance:t.attendance,assignmentCompletion:t.assignmentCompletion}}function ep(t,s,a){return t<60||s<75||a<55?"high":t<75||s<85||a<70?"medium":"low"}function tp(t,s,a,r){const o=yt({metadata:r,classSectionId:s,className:a}),n=o.className||"Imported Class",i=o.classSectionId||"imported_class",l=Number(t.avgQuizScore||0),c=Number(t.attendance||0),d=Number(t.engagementScore||0),m=Number(t.assignmentCompletion||0),p=t.unknownFields?.weakestTopic||t.unknownFields?.topic||"Foundational Skills",h=ep(l,c,d),v=t.studentId||t.lrn||t.email||t.name||Math.random().toString(36).slice(2);return{id:`upload-${i}-${v}`,lrn:t.lrn,name:t.name,avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:l,riskLevel:h,weakestTopic:p,classroomId:i,className:n,grade:o.grade||gs(n).grade,gradeLevel:o.gradeLevel||Ns(o.grade||gs(n).grade)||void 0,classification:o.classification||pa(o.gradeLevel||o.grade)||void 0,strand:o.strand||ha(n,o.section)||void 0,section:o.section||gs(n).section,classSectionId:i,classMetadata:o,managerId:o.managerId||void 0,managerName:o.managerName||void 0,lastActive:"Recently imported",struggles:[p],engagementScore:d,attendance:c,assignmentCompletion:m}}function Tl(t){const s=Date.now()-t.getTime(),a=Math.floor(s/6e4);if(a<1)return"Just now";if(a<60)return`${a} min${a>1?"s":""} ago`;const r=Math.floor(a/60);if(r<24)return`${r} hour${r>1?"s":""} ago`;const o=Math.floor(r/24);return`${o} day${o>1?"s":""} ago`}function lt(t){return(t||"").trim().toLowerCase()}function oi(t){const s=lt(t.classSectionId);if(s)return`section:${s}`;const a=(t.id||"").trim().toLowerCase();return a?`id:${a}`:`name:${(t.name||"").trim().toLowerCase()}`}function ii(t,s){const a=new Map;return t.forEach(r=>{a.set(oi(r),r)}),s.forEach(r=>{const o=oi(r),n=a.get(o);if(!n){a.set(o,r);return}const i=Math.max(n.atRiskCount||0,r.atRiskCount||0),l=Math.max(n.studentCount||0,r.studentCount||0),c=r.avgScore>0?r.avgScore:n.avgScore,d=i>=5?"high":i>=2?"medium":"low",m=yt({metadata:n.classMetadata,classSectionId:n.classSectionId||r.classSectionId,className:n.name||r.name,grade:n.classMetadata?.grade||r.classMetadata?.grade,gradeLevel:n.classMetadata?.gradeLevel||r.classMetadata?.gradeLevel,classification:n.classMetadata?.classification||r.classMetadata?.classification,strand:n.classMetadata?.strand||r.classMetadata?.strand,section:n.classMetadata?.section||r.classMetadata?.section,schoolYear:n.classMetadata?.schoolYear||r.classMetadata?.schoolYear,ownerTeacherId:n.classMetadata?.ownerTeacherId||r.classMetadata?.ownerTeacherId,ownerTeacherName:n.classMetadata?.ownerTeacherName||r.classMetadata?.ownerTeacherName,adviserTeacherId:n.classMetadata?.adviserTeacherId||r.classMetadata?.adviserTeacherId,adviserTeacherName:n.classMetadata?.adviserTeacherName||r.classMetadata?.adviserTeacherName,managerId:n.classMetadata?.managerId||r.classMetadata?.managerId,managerName:n.classMetadata?.managerName||r.classMetadata?.managerName});a.set(o,{...n,classSectionId:m.classSectionId||n.classSectionId||r.classSectionId,name:m.className||n.name||r.name,classMetadata:m,gradeLevel:m.gradeLevel||void 0,classification:m.classification||void 0,strand:m.strand||void 0,managerId:m.managerId||void 0,managerName:m.managerName||void 0,schedule:n.schedule||r.schedule,studentCount:l,atRiskCount:i,avgScore:c,riskLevel:d})}),Array.from(a.values())}function gr(t){const s=(t.lrn||"").trim().toLowerCase();if(s)return`lrn:${s}`;const a=t.name.trim().toLowerCase();if(a)return`name:${a}`;const r=lt(t.classSectionId)||lt(t.classroomId),o=(t.id||"").trim().toLowerCase();return r&&o?`${r}|id:${o}`:`${r}|anonymous`}function ln(t){const s=lt(t.classSectionId)||lt(t.classroomId),a=(t.lrn||"").trim().toLowerCase(),r=(t.id||"").trim().toLowerCase(),o=t.name.trim().toLowerCase().replace(/\s+/g,"_");return s&&a?`${s}|lrn:${a}`:s&&r?`${s}|id:${r}`:a?`lrn:${a}`:r&&o?`id:${r}|name:${o}`:r?`id:${r}`:s&&o?`${s}|name:${o}`:`name:${o||"unknown"}`}function li(t,s){const a=new Map;return t.forEach(r=>{a.set(gr(r),r)}),s.forEach(r=>{const o=gr(r),n=a.get(o);if(!n){a.set(o,r);return}const i=[n.riskLevel,r.riskLevel].includes("high")?"high":[n.riskLevel,r.riskLevel].includes("medium")?"medium":"low",l=yt({metadata:n.classMetadata,classSectionId:n.classSectionId||r.classSectionId,className:n.className||r.className,grade:n.grade||r.grade,gradeLevel:n.gradeLevel||r.gradeLevel,classification:n.classification||r.classification,strand:n.strand||r.strand,section:n.section||r.section,managerId:n.managerId||r.managerId,managerName:n.managerName||r.managerName});a.set(o,{...n,lrn:n.lrn||r.lrn,classSectionId:l.classSectionId||n.classSectionId||r.classSectionId,classroomId:n.classroomId||r.classroomId,className:l.className||n.className||r.className,grade:l.grade||n.grade||r.grade,gradeLevel:l.gradeLevel||n.gradeLevel||r.gradeLevel,classification:l.classification||n.classification||r.classification,strand:l.strand||n.strand||r.strand,section:l.section||n.section||r.section,managerId:l.managerId||n.managerId||r.managerId,managerName:l.managerName||n.managerName||r.managerName,classMetadata:l,avgScore:r.avgScore>0?r.avgScore:n.avgScore,attendance:r.attendance>0?r.attendance:n.attendance,engagementScore:r.engagementScore>0?r.engagementScore:n.engagementScore,assignmentCompletion:r.assignmentCompletion>0?r.assignmentCompletion:n.assignmentCompletion,weakestTopic:n.weakestTopic&&n.weakestTopic!=="N/A"?n.weakestTopic:r.weakestTopic,riskLevel:i,struggles:n.struggles.length>0?n.struggles:r.struggles,hasRegisteredAccount:n.hasRegisteredAccount===!0||r.hasRegisteredAccount===!0?!0:n.hasRegisteredAccount??r.hasRegisteredAccount,source:n.source==="registered"&&r.source==="import"||n.source==="import"&&r.source==="registered"||n.source==="both"||r.source==="both"?"both":n.source||r.source,accountUid:n.accountUid||r.accountUid,email:n.email||r.email})}),Array.from(a.values())}const lh=({onLogout:t,onOpenProfile:s,onOpenSettings:a})=>{const{currentUser:r,userProfile:o}=vs(),[n,i]=u.useState("dashboard"),[l,c]=u.useState(!1),[d,m]=u.useState(!1),[p,h]=u.useState(!1),[v,y]=u.useState(!1),[S,N]=u.useState(!1),[w,g]=u.useState(!1),[I,L]=u.useState(!1),A=["streak_reminder","daily_checkin","streak_milestone","achievement_unlocked","level_up","xp_earned","quiz_result"],{notifications:W}=fi(),f=W.filter(E=>!E.isRead&&!A.includes(E.type)).length,[C,b]=u.useState(null),[F,U]=u.useState(null),[k,D]=u.useState(!1),[J,re]=u.useState(!1),[ce,ie]=u.useState(!1),[fe,Ce]=u.useState(!1),[ue,ge]=u.useState([]),[B,te]=u.useState([]),ne=u.useMemo(()=>r?.uid?ue.filter(E=>E.managerId===r.uid||E.classMetadata?.managerId===r.uid):ue,[ue,r?.uid]),[ze,Fe]=u.useState([]),[Pe,G]=u.useState(""),[se,M]=u.useState(!0),[q,Q]=u.useState(!1),[pe,$]=u.useState(0),[j,T]=u.useState([]),[_,V]=u.useState(!1),[me,oe]=u.useState(null),[ae,je]=u.useState(null),we=o?.name||"Teacher",Ke=u.useRef(new Map);u.useEffect(()=>{const E=()=>y(window.innerWidth<1024);return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),u.useEffect(()=>{if(!r)return;const E=r.uid;let R=!0,ve;return(async()=>{M(!0);try{const Me=await cl(E);let K=Me.map(Xx);const Xe=await Ju(E).catch(()=>[]),nt=new Map;Xe.forEach(P=>{const X=lt(P.classSectionId);X&&nt.set(X,P)}),K=K.map(P=>{const X=nt.get(lt(P.classSectionId));if(!X)return P;const _e=yt({metadata:P.classMetadata,classSectionId:X.classSectionId||P.classSectionId,className:X.className||P.name,grade:X.grade||P.classMetadata?.grade,gradeLevel:X.gradeLevel||P.classMetadata?.gradeLevel,classification:X.classification||P.classMetadata?.classification,strand:X.strand||P.classMetadata?.strand,section:X.section||P.classMetadata?.section,schoolYear:X.schoolYear||P.classMetadata?.schoolYear,ownerTeacherId:X.ownerTeacherId||P.classMetadata?.ownerTeacherId,ownerTeacherName:X.ownerTeacherName||P.classMetadata?.ownerTeacherName,managerId:X.managerId||P.classMetadata?.managerId,managerName:X.managerName||P.classMetadata?.managerName});return{...P,name:_e.className||P.name,classSectionId:_e.classSectionId||P.classSectionId,classMetadata:_e,gradeLevel:_e.gradeLevel||P.gradeLevel,classification:_e.classification||P.classification,strand:_e.strand||P.strand,managerId:_e.managerId||P.managerId,managerName:_e.managerName||P.managerName}});const ke=new Map,jt=new Map;Me.forEach(P=>{const X=yt({metadata:P.classMetadata,classSectionId:P.classSectionId,className:P.name,grade:P.grade,gradeLevel:P.gradeLevel,classification:P.classification,strand:P.strand,section:P.section,schoolYear:P.schoolYear,ownerTeacherId:P.ownerTeacherId||P.teacherId,ownerTeacherName:P.ownerTeacherName,adviserTeacherId:P.adviserTeacherId||P.teacherId,adviserTeacherName:P.adviserTeacherName,managerId:P.managerId,managerName:P.managerName});ke.set(P.id,X.className||P.name),jt.set(P.id,X);const _e=lt(P.classSectionId);if(_e){const Oe=nt.get(_e),Ht=yt({metadata:X,classSectionId:Oe?.classSectionId||_e,className:Oe?.className||X.className,grade:Oe?.grade||X.grade,gradeLevel:Oe?.gradeLevel||X.gradeLevel,classification:Oe?.classification||X.classification,strand:Oe?.strand||X.strand,section:Oe?.section||X.section,schoolYear:Oe?.schoolYear||X.schoolYear,ownerTeacherId:Oe?.ownerTeacherId||X.ownerTeacherId,ownerTeacherName:Oe?.ownerTeacherName||X.ownerTeacherName,managerId:Oe?.managerId||X.managerId,managerName:Oe?.managerName||X.managerName});ke.set(_e,Ht.className||P.name),jt.set(_e,Ht)}});const Bt=P=>{const X=lt(P.classSectionId||P.classroomId);if(!X)return P;const _e=jt.get(X);if(!_e)return P;const Oe=yt({metadata:_e,classSectionId:P.classSectionId||_e.classSectionId,className:P.className||_e.className,grade:P.grade||_e.grade,gradeLevel:P.gradeLevel||_e.gradeLevel,classification:P.classification||_e.classification,strand:P.strand||_e.strand,section:P.section||_e.section,managerId:P.managerId||_e.managerId,managerName:P.managerName||_e.managerName});return{...P,className:Oe.className||P.className,grade:Oe.grade||P.grade,gradeLevel:Oe.gradeLevel||P.gradeLevel,classification:Oe.classification||P.classification,strand:Oe.strand||P.strand,section:Oe.section||P.section,classSectionId:Oe.classSectionId||P.classSectionId,classMetadata:Oe,managerId:Oe.managerId||P.managerId,managerName:Oe.managerName||P.managerName}},$t=(P,X,_e)=>ke.get(P)||(X?ke.get(X):void 0)||_e||"Unknown",Le=Array.from(new Set([...Xe.map(P=>P.classSectionId),...Me.map(P=>P.classSectionId).filter(Boolean),...K.map(P=>P.classSectionId).filter(Boolean)].map(P=>(P||"").trim()).filter(P=>!!P))),[ft,ut]=await Promise.all([yn(E).catch(P=>(console.warn("[TeacherDashboard] managed-student fetch failed:",P),[])),Vu(E,Le).catch(P=>(console.warn("[TeacherDashboard] registered-student fetch failed:",P),[]))]);let Ft=ut;if(ut.length===0&&ft.length===0)try{const{collection:P,query:X,where:_e,getDocs:Oe}=await Cs(async()=>{const{collection:Ut,query:We,where:ga,getDocs:ba}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{collection:Ut,query:We,where:ga,getDocs:ba}},__vite__mapDeps([2,3])),{db:Ht}=await Cs(async()=>{const{db:Ut}=await import("./index-BdLfAeGL.js").then(We=>We.b7);return{db:Ut}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),De=X(P(Ht,"users"),_e("role","==","student"));Ft=(await Oe(De)).docs.map(Ut=>{const We=Ut.data();return{uid:Ut.id,name:String(We.name||We.displayName||"").trim()||"Student",email:String(We.email||"").trim(),lrn:We.lrn?String(We.lrn).trim():void 0,photo:We.photo?String(We.photo).trim():We.photoURL?String(We.photoURL).trim():void 0,grade:We.grade?String(We.grade).trim():void 0,section:We.section?String(We.section).trim():void 0,classSectionId:We.classSectionId?String(We.classSectionId).trim():void 0,adviserTeacherId:We.adviserTeacherId?String(We.adviserTeacherId).trim():void 0,role:"student",createdAt:We.createdAt||void 0}}).filter(Ut=>Ut.name!=="Student"||Ut.email)}catch(P){console.warn("[TeacherDashboard] fallback all-students fetch failed:",P)}const ss=new Map,Qs=new Map,Pa=new Map;ft.forEach(P=>{ss.set(P.id,P),P.lrn&&Qs.set(P.lrn.trim().toLowerCase(),P);const X=Ao(P.name),_e=lt(P.classSectionId||P.classroomId);X&&Pa.set(`${X}|${_e}`,P)});const Ba=new Set,Ha=Ft.map(P=>{const X=Wu(P),_e=(P.lrn||"").trim().toLowerCase(),Oe=Ao(P.name),Ht=lt(P.classSectionId);let De;if(ss.has(P.uid))De=ss.get(P.uid);else if(_e&&Qs.has(_e))De=Qs.get(_e);else if(Oe){const We=`${Oe}|${Ht}`;De=Pa.get(We)}if(De){Ba.add(De.id);const We={...X,id:P.uid,accountUid:P.uid,email:X.email||De.email,lrn:X.lrn||De.lrn,name:X.name||De.name,avatar:X.avatar||De.avatar,riskLevel:De.riskLevel||X.riskLevel,avgQuizScore:De.avgQuizScore||X.avgQuizScore,engagementScore:De.engagementScore||X.engagementScore,attendance:De.attendance||X.attendance,assignmentCompletion:De.assignmentCompletion||X.assignmentCompletion,weakestTopic:De.weakestTopic||X.weakestTopic,struggles:De.struggles||X.struggles,lastActive:De.lastActive||X.lastActive,wri:De.wri??null,riskStatus:De.riskStatus??null,riskUpdatedAt:De.riskUpdatedAt??null,diagnosticScore:De.diagnosticScore??null,externalGradesAvg:De.externalGradesAvg??null,systemPerformanceAvg:De.systemPerformanceAvg??null,riskHistory:De.riskHistory,grade:X.grade||De.grade,gradeLevel:X.gradeLevel||De.gradeLevel,section:X.section||De.section,classSectionId:X.classSectionId||De.classSectionId,classroomId:X.classroomId||De.classroomId,classMetadata:De.classMetadata||X.classMetadata,hasRegisteredAccount:!0,source:"both"},ga=lt(We.classSectionId||We.classroomId),ba=$t(We.classroomId||"",ga,We.className);return Bt(Hr(We,ba))}const Ga=lt(X.classSectionId||X.classroomId),Ut=$t(X.classroomId||"",Ga,X.className);return Bt(Hr(X,Ut))}),Ua=ft.filter(P=>!Ba.has(P.id)).map(P=>{const X={...P,hasRegisteredAccount:!1,source:"import"},_e=lt(X.classSectionId||X.classroomId),Oe=$t(X.classroomId,_e,X.className);return Bt(Hr(X,Oe))}),Vs=[...Ha,...Ua];if(!R)return;ge(P=>K.length===0&&P.length>0?P:K),te(P=>Vs.length===0&&P.length>0?P:Vs),xt.getImportedClassOverview({limit:3e3,forceRefresh:pe>0}).then(P=>{R&&(P.warnings.length>0&&console.warn("Imported class overview warnings:",P.warnings.join(" ")),ge(X=>ii(X,P.classrooms.map(Jx))),te(X=>{if(X.length===0)return X;const _e=P.students.map(Zx),Oe=new Set;X.forEach(De=>Oe.add(gr(De)));const Ht=_e.filter(De=>Oe.has(gr(De)));return Ht.length===0?X:li(X,Ht)}))}).catch(P=>{console.warn("Imported class overview merge unavailable:",P)});const fa=Me.map(P=>P.id);fa.length>0&&(ve=em(fa,P=>{R&&Fe(P.map(X=>({id:X.id,student:X.studentName,action:X.action,topic:X.topic,time:Tl(X.timestamp.toDate()),type:X.type})))}))}catch(Me){console.error("Failed to load teacher data:",Me),le.error("Failed to load dashboard data")}finally{M(!1)}})(),()=>{R=!1,ve&&ve()}},[r,pe]),u.useEffect(()=>{if(!r)return;let E=!0;return Zu("",80).then(R=>{E&&T(R)}).catch(R=>{console.warn("Failed to load teacher directory options:",R)}),()=>{E=!1}},[r]),u.useEffect(()=>{if(B.length===0)return;(async()=>{if(B.length===0){G("");return}Q(!0);try{const R=B.map(ee=>({name:ee.name,engagementScore:ee.engagementScore,avgQuizScore:ee.avgScore,attendance:ee.attendance,riskLevel:ee.riskLevel})),ve=await xt.getDailyInsight({students:R});G(ve.insight)}catch{G(`${B.filter(R=>R.riskLevel==="high").length} students are at high risk of falling behind. Review their progress in the analytics view.`)}finally{Q(!1)}})()},[B]);const Ue=ue.reduce((E,R)=>E+R.studentCount,0),Je=B.filter(E=>E.riskLevel==="high").length,ht=(()=>{const E=B.map(R=>R.avgScore).filter(R=>R>0);return E.length>0?Math.round(E.reduce((R,ve)=>R+ve,0)/E.length):0})(),dt=[{name:"High Risk",value:B.filter(E=>E.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:B.filter(E=>E.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:B.filter(E=>E.riskLevel==="low").length,color:"#75D06A"}],rt={};B.forEach(E=>{E.weakestTopic&&E.weakestTopic!=="N/A"&&(rt[E.weakestTopic]||(rt[E.weakestTopic]={total:0,sum:0}),rt[E.weakestTopic].total+=1,rt[E.weakestTopic].sum+=E.avgScore)});const Mt=Object.entries(rt).map(([E,R])=>({topic:E,score:Math.round(R.sum/R.total)})).sort((E,R)=>E.score-R.score).slice(0,6),At=E=>{b(E),i("analytics")},It=E=>{U(E),i("intervention")},cs=()=>{U(null),i("analytics")},Us=()=>{b(null),U(null),i("dashboard")},Yt=async(E,R)=>{if(!r){le.error("Unable to assign manager: teacher context is missing.");return}const ve=gs(E.classMetadata?.className||E.name),ee=yt({metadata:E.classMetadata,classSectionId:E.classSectionId,className:E.name,grade:E.classMetadata?.grade||ve.grade,gradeLevel:E.classMetadata?.gradeLevel,classification:E.classMetadata?.classification,strand:E.classMetadata?.strand,section:E.classMetadata?.section||ve.section,schoolYear:E.classMetadata?.schoolYear||String(new Date().getFullYear()),ownerTeacherId:E.classMetadata?.ownerTeacherId||r.uid,ownerTeacherName:E.classMetadata?.ownerTeacherName||we,adviserTeacherId:E.classMetadata?.adviserTeacherId||r.uid,adviserTeacherName:E.classMetadata?.adviserTeacherName||we,managerId:R.uid,managerName:R.name}),Me=ee.classSectionId||Pt(ee.grade||ve.grade,ee.section||ve.section);if(!Me){le.error("Unable to assign manager: missing class section ID.");return}V(!0);try{await dl({classSectionId:Me,className:ee.className||E.name,grade:ee.grade||ve.grade,gradeLevel:ee.gradeLevel||Ns(ee.grade||ve.grade)||ee.grade||ve.grade,classification:ee.classification||pa(ee.gradeLevel||ee.grade)||void 0,strand:ee.strand||ha(ee.className,ee.section)||void 0,section:ee.section||ve.section,schoolYear:ee.schoolYear||String(new Date().getFullYear()),ownerTeacherId:ee.ownerTeacherId||r.uid,ownerTeacherName:ee.ownerTeacherName||we,managerId:R.uid,managerName:R.name});const K=yt({metadata:ee,classSectionId:Me,managerId:R.uid,managerName:R.name}),Xe=lt(Me);ge(nt=>nt.map(ke=>lt(ke.classSectionId)!==Xe?ke:{...ke,name:K.className||ke.name,classSectionId:K.classSectionId||ke.classSectionId,classMetadata:K,gradeLevel:K.gradeLevel||ke.gradeLevel,classification:K.classification||ke.classification,strand:K.strand||ke.strand,managerId:R.uid,managerName:R.name})),te(nt=>nt.map(ke=>{if(lt(ke.classSectionId||ke.classroomId)!==Xe)return ke;const Bt=yt({metadata:ke.classMetadata,classSectionId:K.classSectionId||ke.classSectionId,className:ke.className||K.className,grade:ke.grade||K.grade,gradeLevel:ke.gradeLevel||K.gradeLevel,classification:ke.classification||K.classification,strand:ke.strand||K.strand,section:ke.section||K.section,managerId:R.uid,managerName:R.name});return{...ke,classMetadata:Bt,gradeLevel:Bt.gradeLevel||ke.gradeLevel,classification:Bt.classification||ke.classification,strand:Bt.strand||ke.strand,managerId:R.uid,managerName:R.name}})),b(nt=>!nt||lt(nt.classSectionId)!==Xe?nt:{...nt,classMetadata:K,managerId:R.uid,managerName:R.name,gradeLevel:K.gradeLevel||nt.gradeLevel,classification:K.classification||nt.classification,strand:K.strand||nt.strand}),le.success(`Assigned ${R.name} as section manager.`)}catch(K){console.error("Failed to assign class manager:",K),le.error(K instanceof Error?K.message:"Failed to assign class manager")}finally{V(!1)}},ds=u.useCallback(E=>{oe({rosterId:E.id,name:E.name,lrn:E.lrn,email:E.email,grade:E.grade,section:E.section,classSectionId:E.classSectionId})},[]),js=u.useCallback(E=>{te(R=>R.map(ve=>ve.id===E.rosterId?{...ve,hasRegisteredAccount:!0,source:"both",accountUid:E.uid,email:E.email||ve.email}:ve)),$(R=>R+1)},[]),Kt=u.useCallback(async(E,R)=>{if(!r){le.error("Cannot reassign section without an authenticated teacher.");return}const ve=r.uid,ee=(R.classSectionId||"").trim();if(!ee){le.error("Pick a target section first.");return}je(E.id);try{await qu({studentId:E.accountUid||E.id,isRegisteredAccount:!!E.hasRegisteredAccount,newClassSectionId:ee,newGrade:R.grade,newSection:R.section,previousClassSectionId:E.classSectionId,teacherId:ve,teacherName:we,schoolYear:E.classMetadata?.schoolYear||String(new Date().getFullYear())}),te(Me=>Me.map(K=>{if(K.id!==E.id)return K;const Xe=yt({metadata:K.classMetadata,classSectionId:ee,className:K.className,grade:R.grade,section:R.section});return{...K,grade:R.grade,section:R.section,classSectionId:ee,classroomId:ee,classMetadata:Xe}})),le.success(`Moved ${E.name} to ${R.grade} - ${R.section}.`)}catch(Me){console.error("Section reassignment failed:",Me),le.error(Me instanceof Error?Me.message:"Failed to reassign section.")}finally{je(null)}},[r,we]),Gs=u.useCallback(async E=>{if(!r||!window.confirm(`Remove ${E.name} from this class? This cannot be undone.`))return;const R=E.classSectionId||E.classroomId||"";if(!R){le.error("Cannot determine class section for this student.");return}try{await Ku(E.accountUid||E.id,R),te(ve=>ve.filter(ee=>ee.id!==E.id)),le.success(`Removed ${E.name} from class.`)}catch(ve){console.error("Remove student failed:",ve),le.error("Failed to remove student.")}},[r]);u.useEffect(()=>{const E=()=>{const R=window.innerWidth<1024;y(R),R?c(!1):h(!1)};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),u.useEffect(()=>{v&&h(!1)},[n,v]);const Es=E=>{i(E),b(null),U(null)},Rs=u.useMemo(()=>{if(!C)return;if(C.classMetadata?.classSectionId)return C.classMetadata.classSectionId||void 0;if(C.classSectionId)return C.classSectionId;const E=gs(C.classMetadata?.className||C.name);return Pt(E.grade,E.section)||void 0},[C]),Ge=u.useMemo(()=>C||null,[C]),z=u.useMemo(()=>{if(!Ge)return;const E=ue.findIndex(R=>R.id===Ge.id);return hr[Math.max(0,E)%hr.length]},[Ge,ue]),de=u.useMemo(()=>{if(!Ge)return B;const E=(Ge.id||"").trim().toLowerCase(),R=lt(Ge.classSectionId),ve=(Ge.name||"").trim().toLowerCase();return B.filter(ee=>{const Me=lt(ee.classroomId),K=lt(ee.classSectionId),Xe=(ee.className||"").trim().toLowerCase();return R&&(K===R||Me===R)||E&&(Me===E||K===E)||ve&&Xe===ve})},[Ge,B]);return se?e.jsx(Vl,{message:"Loading dashboard..."}):e.jsxs("div",{className:"relative flex h-screen w-full bg-background overflow-hidden",children:[v&&p&&e.jsx("button",{"aria-label":"Close navigation",className:"fixed inset-0 z-30 bg-slate-900/40 backdrop-blur-[1px]",onClick:()=>h(!1)}),e.jsxs(Re.aside,{initial:!1,animate:{width:v?280:l&&!d?80:280,x:v?p?0:-300:0},transition:{type:"spring",stiffness:360,damping:34},onMouseEnter:()=>!v&&l&&m(!0),onMouseLeave:()=>m(!1),className:"fixed inset-y-0 left-0 z-40 bg-[#f7f9fc] rounded-3xl border border-[#dde3eb] flex flex-col shadow-sm lg:static lg:z-auto p-5",children:[e.jsxs("div",{className:`mb-8 flex items-center ${l&&!d?"justify-center":"justify-between"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 bg-gradient-to-r from-[#7274ED] to-[#9956DE] rounded-2xl flex items-center justify-center shadow-md flex-shrink-0",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"MathPulse AI",className:"w-10 h-10 object-contain drop-shadow-md"})}),(!l||d)&&e.jsx("div",{children:e.jsx("h1",{className:"text-base font-semibold font-display text-[#0a1628] whitespace-nowrap",children:"MathPulse AI"})})]}),!v&&(!l||d)&&e.jsx(Re.button,{whileHover:{scale:1.1},whileTap:{scale:.95},onClick:()=>c(!l),className:"p-2 hover:bg-[#dde3eb] rounded-lg transition-colors text-[#5a6578]","aria-label":l?"Expand sidebar":"Collapse sidebar",children:l?e.jsx(zs,{size:20}):e.jsx($s,{size:20})}),v&&e.jsx("button",{onClick:()=>h(!1),className:"p-2 hover:bg-[#dde3eb] rounded-lg transition-colors text-[#5a6578]","aria-label":"Close navigation",children:e.jsx(qt,{size:20})})]}),e.jsxs("nav",{className:"flex-1 space-y-5",children:[e.jsxs("div",{children:[l&&!d?e.jsx("div",{className:"px-4 mb-2 flex items-center gap-2",children:e.jsx("div",{className:"flex-1 h-[1px] bg-[#dde3eb]"})}):e.jsx("p",{className:"px-4 mb-2 text-[10px] font-semibold text-[#5a6578] uppercase tracking-widest",children:"Overview"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ms,{icon:ac,label:"Dashboard",active:n==="dashboard",collapsed:l&&!d,onClick:Us,forceExpanded:v}),e.jsx(Ms,{icon:Ds,label:"Class Analytics",active:n==="analytics"||n==="intervention",collapsed:l&&!d,onClick:()=>Es("analytics"),forceExpanded:v})]})]}),e.jsxs("div",{children:[l&&!d?e.jsx("div",{className:"px-4 mb-2 flex items-center gap-2",children:e.jsx("div",{className:"flex-1 h-[1px] bg-[#dde3eb]"})}):e.jsx("p",{className:"px-4 mb-2 text-[10px] font-semibold text-[#5a6578] uppercase tracking-widest",children:"Students"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ms,{icon:fs,label:"Topic Mastery",active:n==="topic_mastery",collapsed:l&&!d,onClick:()=>Es("topic_mastery"),forceExpanded:v}),e.jsx(Ms,{icon:hs,label:"Competency",active:n==="competency",collapsed:l&&!d,onClick:()=>Es("competency"),forceExpanded:v})]})]}),e.jsxs("div",{children:[l&&!d?e.jsx("div",{className:"px-4 mb-2 flex items-center gap-2",children:e.jsx("div",{className:"flex-1 h-[1px] bg-[#dde3eb]"})}):e.jsx("p",{className:"px-4 mb-2 text-[10px] font-semibold text-[#5a6578] uppercase tracking-widest",children:"Tools"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ms,{icon:rc,label:"Data Import",active:n==="import",collapsed:l&&!d,onClick:()=>i("import"),forceExpanded:v}),e.jsx(Ms,{icon:qr,label:"AI Quiz Maker",active:n==="quiz_maker",collapsed:l&&!d,onClick:()=>i("quiz_maker"),forceExpanded:v}),e.jsx(Ms,{icon:Vt,label:"Question Bank",active:n==="question_bank",collapsed:l&&!d,onClick:()=>i("question_bank"),forceExpanded:v}),e.jsx(Ms,{icon:nr,label:"Calendar",active:n==="calendar",collapsed:l&&!d,onClick:()=>i("calendar"),forceExpanded:v})]})]})]}),e.jsxs("div",{className:"space-y-2 border-t border-[#dde3eb] pt-4",children:[e.jsxs(Re.button,{whileHover:{x:2},whileTap:{scale:.98},className:`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-[#5a6578] font-semibold border border-transparent hover:bg-[#dde3eb] hover:border-[#dde3eb] hover:text-[#0a1628] transition-all duration-200 whitespace-nowrap ${l&&!d?"justify-center":""}`,onClick:a,title:l&&!d?"Settings":"",children:[e.jsx(nc,{size:18,strokeWidth:2,className:"flex-shrink-0"}),(!l||d)&&e.jsx("span",{className:"font-body text-xs",children:"Settings"})]}),e.jsx("div",{className:"text-[#5a6578]",children:e.jsx(oc,{onClick:()=>N(!0),collapsed:l&&!d})})]})]}),e.jsxs("div",{className:"flex-1 flex overflow-hidden bg-gradient-to-br from-[#eef2ff] via-[#f5f3ff] to-[#fff7ed]",children:[e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[["dashboard","analytics","intervention","competency","topic_mastery","calendar","notifications","question_bank","import","quiz_maker"].includes(n)&&e.jsx("header",{className:"bg-transparent border-b border-[#e2e8f0]/40 px-[24px] xl:px-[32px] pt-[24px] pb-[16px] flex-shrink-0 z-30",children:e.jsxs("div",{className:"flex flex-row items-center justify-between gap-2 mb-0",children:[e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[v&&e.jsx("button",{onClick:()=>h(!0),className:"mt-1 p-2 rounded-lg border border-border text-muted-foreground hover:text-[#9956DE] hover:border-[#9956DE]/30 hover:bg-[#9956DE]/12 transition-colors","aria-label":"Open navigation",children:e.jsx(Wl,{size:18})}),e.jsxs("div",{children:[e.jsxs("h1",{className:"text-lg sm:text-[26px] font-bold text-[#1e293b] tracking-tight leading-tight truncate",children:[n==="dashboard"&&"Teacher Dashboard",n==="analytics"&&"Class Analytics",n==="intervention"&&"Intervention Center",n==="competency"&&"Student Competency",n==="topic_mastery"&&"Topic Mastery",n==="calendar"&&"Academic Calendar",n==="notifications"&&"Notifications",n==="question_bank"&&"Question Bank",n==="import"&&"Data Import",n==="quiz_maker"&&"AI Quiz Maker"]}),e.jsxs("p",{className:"text-[13px] text-[#64748b] mt-1",children:[n==="dashboard"&&`Welcome back, ${we}`,n==="analytics"&&"Analyze performance and risk across your classes.",n==="intervention"&&"Identify and support students who need immediate help.",n==="competency"&&"Track individual student progress against learning goals.",n==="topic_mastery"&&"Overview of student mastery levels across different math topics.",n==="calendar"&&"Manage your schedules and academic events.",n==="notifications"&&"Stay updated with student activity and system alerts.",n==="question_bank"&&"Manage and create math questions for your quizzes.",n==="import"&&"Upload class records and materials to power AI analytics.",n==="quiz_maker"&&"Create AI-powered quizzes based on your curriculum."]})]}),n==="dashboard"&&e.jsxs("div",{className:"hidden xl:flex items-center gap-2 ml-4 mt-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-[#9956DE]/12 border border-[#9956DE]/30 rounded-lg",children:[e.jsx(hs,{size:13,className:"text-[#9956DE]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#9956DE]",children:[Ue," students"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-[#F08386]/12 border border-[#F08386]/30 rounded-lg",children:[e.jsx(da,{size:13,className:"text-[#F08386]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#C65E63]",children:[Je," at risk"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-[#75D06A]/14 border border-[#75D06A]/35 rounded-lg",children:[e.jsx(ca,{size:13,className:"text-[#75D06A]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#4D9F46]",children:[ht,"% avg"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:()=>{re(!0),D(!0)},className:"relative w-10 h-10 flex items-center justify-center bg-[#eef2ff]/80 hover:bg-[#e0e7ff] rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#a5b4fc]/60 text-[#4f46e5] hover:border-[#818cf8] transition-colors cursor-pointer hover:scale-[1.02]","aria-label":"View AI Insight",children:[e.jsx(bs,{size:18}),!k&&Pe&&e.jsx("div",{className:"absolute top-2.5 right-2.5 w-2 h-2 bg-rose-500 rounded-full border border-white animate-pulse"})]}),e.jsx("span",{className:"absolute -bottom-8 left-1/2 -translate-x-1/2 text-[10px] bg-[#1e293b] text-white px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 pointer-events-none",children:"AI Insight"})]}),v&&n==="dashboard"&&e.jsx("button",{onClick:()=>Ce(E=>!E),className:`relative w-10 h-10 flex items-center justify-center rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border transition-colors cursor-pointer hover:scale-[1.02] ${fe?"bg-[#818cf8] border-[#6366f1] text-white":"bg-white/60 hover:bg-white/80 border-white/50 text-[#64748b] hover:text-[#1e293b]"}`,"aria-label":fe?"Close calendar panel":"Open calendar panel",title:fe?"Close calendar":"View calendar",children:e.jsx(nr,{size:18})}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>ie(!ce),className:"relative w-10 h-10 flex items-center justify-center bg-white/60 hover:bg-white/80 rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50 text-[#64748b] hover:text-[#1e293b] transition-colors cursor-pointer hover:scale-[1.02]","aria-label":"View notifications",title:"Notifications",children:[e.jsx(dr,{size:18}),f>0&&e.jsx("span",{className:"absolute top-2.5 right-2.5 w-2 h-2 bg-rose-500 rounded-full border border-white"})]}),e.jsx(tc,{isOpen:ce,onClose:()=>ie(!1),onViewAll:()=>i("notifications")})]}),n!=="dashboard"&&e.jsxs("div",{onClick:s,className:"flex items-center gap-2 bg-white/60 px-4 py-2 rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50 cursor-pointer hover:bg-white/80 transition-colors h-10 hover:scale-[1.02]",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-indigo-100 overflow-hidden shrink-0",children:e.jsx("img",{src:o?.photo||`https://ui-avatars.com/api/?name=${encodeURIComponent(we)}&background=e0e7ff&color=4f46e5`,alt:"Profile",className:"w-full h-full object-cover"})}),e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:we})]})]})]})}),e.jsx("main",{className:`flex-1 flex flex-col ${n==="intervention"||n==="analytics"?"overflow-hidden":"overflow-y-auto"}`,children:e.jsxs(zt,{mode:"wait",children:[n==="dashboard"&&e.jsx(ap,{classes:ne,liveActivity:ze,onViewClass:At,onViewAllClasses:()=>i("analytics"),onViewActivityStudent:E=>{const R=B.find(ve=>ve.name===E);R&&It(R)},dailyInsight:Pe,insightLoading:q,isInsightDismissed:k,onDismissInsight:()=>D(!0),onOpenInsightModal:()=>{re(!0),D(!0)},totalStudents:Ue,totalAtRisk:Je,avgPerformance:ht,onCreateClass:()=>g(!0)}),n==="analytics"&&Ge&&e.jsx(op,{selectedClass:Ge,students:de,allClasses:ue,riskDistribution:dt,topicPerformance:Mt,onViewStudent:It,onCreateAccount:ds,onReassignSection:Kt,reassignBusyId:ae,onBack:()=>b(null),teacherOptions:j,managerUpdating:_,onAssignManager:E=>Yt(Ge,E),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,classColor:z,insightDismissed:k,onOpenInsightModal:()=>re(!0),onAddStudents:()=>L(!0),onRemoveStudent:Gs}),n==="analytics"&&!Ge&&ne.length>0&&e.jsx(Yo,{classes:ne,onSelectClass:At,onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:k,onOpenInsightModal:()=>re(!0),onCreateClass:()=>g(!0)}),n==="analytics"&&!Ge&&ne.length===0&&e.jsx(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-6",children:e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-8 shadow-sm max-w-2xl",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-[#9956DE]/20 text-[#9956DE] flex items-center justify-center mb-4",children:e.jsx(Ds,{size:24})}),e.jsx("h2",{className:"text-2xl font-display font-semibold text-foreground mb-2",children:"Class Analytics"}),e.jsx("p",{className:"text-sm text-muted-foreground font-body leading-relaxed mb-4",children:"No classes available yet. Create a class or import class records to unlock analytics views."}),e.jsxs(wt,{onClick:()=>g(!0),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(ua,{size:16,className:"mr-1.5"}),"Create Class"]})]})}),n==="intervention"&&F&&e.jsx(ip,{student:F,teacherId:r?.uid||"",teacherName:we,initialCache:Ke.current.get(F.id),onCacheUpdate:(E,R)=>Ke.current.set(E,R),onStudentUpdated:E=>{const R=F?ln(F):null;U(E),te(ve=>ve.map(ee=>{const Me=ln(ee),K=R?Me===R:!1,Xe=ee.id===E.id&<(ee.classSectionId)===lt(E.classSectionId);return K||Xe?E:ee}))},onBack:cs,onNavigateToQuizMaker:E=>{i("quiz_maker"),E&&sessionStorage.setItem("quizMakerInitialTab",E)}}),n==="topic_mastery"&&e.jsx(Tm,{classSectionId:Rs,onOpenNotifications:()=>i("notifications"),onOpenProfile:s}),n==="competency"&&Ge&&e.jsx(Mm,{classSectionId:Rs,className:C?.name,fallbackStudents:B,onBack:()=>b(null),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:k,onOpenInsightModal:()=>re(!0)}),n==="competency"&&!Ge&&ue.length>0&&e.jsx(Yo,{classes:ne,onSelectClass:E=>b(E),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:k,onOpenInsightModal:()=>re(!0),viewType:"competency"}),n==="competency"&&!Ge&&ue.length===0&&e.jsx(sp,{icon:hs,title:"Student Competency",description:"No classes available yet. Import class records to view competency breakdowns."}),n==="import"&&e.jsxs(e.Fragment,{children:[e.jsx(Qx,{classSectionId:Rs,className:C?.name,classMetadata:C?.classMetadata,students:B,classes:ne.map(E=>({id:E.id,name:E.name,classSectionId:E.classSectionId})),teacherId:r?.uid||"",teacherName:we,onStudentsUpdated:E=>te(E),onBackToClasses:()=>i("dashboard"),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,onImportedClassRecords:E=>{const R=E.students.map(ke=>tp(ke,E.classSectionId,E.className,E.classMetadata)),ve=yt({metadata:E.classMetadata,classSectionId:E.classSectionId,className:E.className}),ee=ve.classSectionId||"imported_class",Me=ve.className||"Imported Class",K=R.filter(ke=>ke.riskLevel==="high").length,Xe=R.length>0?Math.round(R.reduce((ke,jt)=>ke+jt.avgScore,0)/R.length):0,nt={id:ee,name:Me,classSectionId:ee,classMetadata:{...ve,classSectionId:ee,className:Me},schedule:"Mon-Fri",studentCount:R.length,avgScore:Xe,atRiskCount:K,riskLevel:K>=5?"high":K>=2?"medium":"low"};te(ke=>li(ke,R)),ge(ke=>ii(ke,[nt]))},onDataChanged:()=>$(E=>E+1)}),e.jsx("div",{className:"mt-6",children:e.jsx(Wx,{teacherId:r?.uid||""})})]}),n==="notifications"&&e.jsx(zm,{liveActivity:ze,atRiskStudents:B.filter(E=>E.riskLevel==="high").map(E=>({name:E.name,riskLevel:E.riskLevel,weakestTopic:E.weakestTopic})),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,teacherName:we}),n==="calendar"&&e.jsx(qm,{classes:ue,teacherId:r?.uid}),n==="quiz_maker"&&e.jsx(bl,{onBack:()=>{const E=sessionStorage.getItem("quizMakerReturnTo");sessionStorage.removeItem("quizMakerReturnTo"),sessionStorage.removeItem("quizMakerInitialTab"),i(E==="intervention"?"intervention":"dashboard")},onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,teacherName:we}),n==="question_bank"&&e.jsx(Cm,{onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{re(!0),D(!0)},userPhoto:o?.photo,teacherName:we})]})})]}),n==="dashboard"&&!v&&e.jsx(di,{onViewCalendar:()=>i("calendar"),onOpenProfile:s,userProfile:o,teacherName:we,liveActivity:ze})]}),e.jsx(zt,{children:v&&n==="dashboard"&&fe&&e.jsxs(e.Fragment,{children:[e.jsx(Re.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-[2px]","aria-label":"Close calendar panel",onClick:()=>Ce(!1)},"cal-backdrop"),e.jsx(Re.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:320,damping:32},className:"fixed top-0 right-0 bottom-0 z-50 w-[300px] max-w-[85vw] shadow-2xl",children:e.jsx(di,{onViewCalendar:()=>{i("calendar"),Ce(!1)},onOpenProfile:()=>{s?.(),Ce(!1)},userProfile:o,teacherName:we,liveActivity:ze})},"cal-drawer")]})}),e.jsx(zt,{children:J&&e.jsx("div",{className:"fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4",children:e.jsxs(Re.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white rounded-2xl shadow-xl w-full max-w-lg overflow-hidden border border-slate-200",children:[e.jsxs("div",{className:"p-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600",children:e.jsx(bs,{size:16})}),e.jsx("h3",{className:"font-semibold text-slate-800",children:"Detailed AI Insight"})]}),e.jsx("button",{onClick:()=>{re(!1)},className:"p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(qt,{size:18})})]}),e.jsx("div",{className:"p-6",children:e.jsx("div",{className:"text-sm text-slate-600 leading-relaxed",children:e.jsx(Tc,{children:Pe?.replace(/[*_]*\s*\(?Word\s*count\s*:\s*[*_]*\s*\d+\)?\s*[*_]*/gi,"").trim()||`**${Je} students (${Ue>0?Math.round(Je/Ue*100):0}%)** are currently at high risk of falling behind in recent topics. Review their progress in the analytics view to plan interventions.`})})}),e.jsx("div",{className:"p-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2",children:e.jsx("button",{onClick:()=>{re(!1)},className:"px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-800 hover:bg-slate-200 rounded-lg transition-colors",children:"Minimize to Menu"})})]})})}),e.jsx(Xl,{isOpen:S,onClose:()=>N(!1),onConfirm:t,title:"Logout",message:"Are you sure you want to logout?",confirmText:"Logout",cancelText:"Cancel"}),e.jsx(tm,{open:w,onClose:()=>g(!1),onCreated:()=>$(E=>E+1),teacherName:we}),e.jsx(sm,{open:I,onClose:()=>L(!1),onAdded:()=>$(E=>E+1),grade:Ge?.gradeLevel||Ge?.classMetadata?.grade||"Grade 11",section:Ge?.classMetadata?.section||Ge?.name?.split(" - ")[1]||"",teacherName:we,existingStudentUids:de.map(E=>E.id)}),e.jsx(Kx,{isOpen:!!me,onClose:()=>oe(null),seed:me,adviserTeacherId:r?.uid||"",adviserTeacherName:we,schoolYear:me?B.find(E=>E.id===me.rosterId)?.classMetadata?.schoolYear||String(new Date().getFullYear()):void 0,onCreated:js})]})},Ms=({icon:t,label:s,active:a,collapsed:r,forceExpanded:o=!1,onClick:n})=>e.jsxs(Re.button,{onClick:n,whileHover:{x:2},whileTap:{scale:.98},className:`w-full flex items-center gap-3 px-4 py-3 rounded-2xl cursor-pointer transition-all duration-200 border whitespace-nowrap ${r&&!o?"justify-center":""} ${a?"bg-[#9956DE]/12 border-[#9956DE]/30 shadow-sm text-[#9956DE]":"bg-transparent border-transparent text-[#5a6578] hover:bg-[#dde3eb] hover:border-[#dde3eb] hover:text-[#0a1628]"}`,children:[e.jsx(t,{size:18,strokeWidth:a?2.5:2,className:"flex-shrink-0"}),(!r||o)&&e.jsx("span",{className:"font-body font-semibold text-xs",children:s}),a&&!r&&e.jsx(Re.div,{layoutId:"sidebar-active-indicator",className:"ml-auto w-2 h-2 rounded-full bg-[#9956DE]",transition:{type:"spring",duration:.4}})]}),sp=({icon:t,title:s,description:a})=>e.jsx(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-6",children:e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-8 shadow-sm max-w-2xl",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-[#9956DE]/20 text-[#9956DE] flex items-center justify-center mb-4",children:e.jsx(t,{size:24})}),e.jsx("h2",{className:"text-2xl font-display font-semibold text-foreground mb-2",children:s}),e.jsx("p",{className:"text-sm text-muted-foreground font-body leading-relaxed",children:a})]})}),ap=({classes:t,liveActivity:s,onViewClass:a,onViewAllClasses:r,onViewActivityStudent:o,dailyInsight:n,insightLoading:i,isInsightDismissed:l,onDismissInsight:c,onOpenInsightModal:d,totalStudents:m,totalAtRisk:p,avgPerformance:h,onCreateClass:v})=>{const y=m>0?Math.round(p/m*100):0,S=m>0?Math.round((m-p)/m*100):0;return e.jsxs(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-3 sm:p-6 space-y-4",children:[!l&&n&&e.jsxs("div",{onClick:d,className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] border border-white p-[14px_16px] sm:p-[18px_20px] flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4 shadow-[0_1px_4px_rgba(0,0,0,0.04)] cursor-pointer hover:shadow-md transition-shadow group",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx("div",{className:"absolute -inset-[5px] rounded-full border-2 border-[#a5b4fc] opacity-50 animate-pulse"}),e.jsx("div",{className:"w-[46px] h-[46px] rounded-full bg-[#eef2ff] border-2 border-[#c7d2fe] flex items-center justify-center text-[#4f46e5] text-xl relative overflow-hidden group-hover:scale-[1.05] transition-transform",children:e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Mascot",className:"w-[85%] h-[85%] object-contain"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-[#1e1b4b] flex flex-wrap items-center gap-2 mb-1",children:[e.jsx(bs,{size:14,className:"text-[#818cf8]"}),"MathPulse AI insight",e.jsx("span",{className:"bg-[#fee2e2] text-[#b91c1c] text-[10px] font-semibold px-2 py-0.5 rounded-full border border-[#fca5a5]",children:"Attention needed"})]}),e.jsx("div",{className:"text-[12.5px] text-[#475569] leading-[1.55]",children:"Some students may be at risk of falling behind. Click to view detailed analysis."})]}),e.jsxs("div",{className:"flex gap-2 flex-shrink-0 self-end sm:self-auto",children:[e.jsx("button",{onClick:N=>{N.stopPropagation(),c()},className:"px-[15px] py-[7px] rounded-[10px] text-xs font-medium cursor-pointer border border-[#e2e8f0] bg-white text-[#475569] hover:bg-[#f8fafc] transition-colors",children:"Dismiss"}),e.jsx("button",{onClick:N=>{N.stopPropagation(),r()},className:"px-[15px] py-[7px] rounded-[10px] text-xs font-medium cursor-pointer border border-[#4f46e5] bg-[#4f46e5] text-white shadow-[0_2px_8px_rgba(79,70,229,0.13)] hover:bg-[#4338ca] transition-colors",children:"Review students"})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-1.5 sm:gap-3",children:[e.jsxs("div",{className:"group relative overflow-hidden bg-[#10b981] shadow-[0_4px_16px_rgba(16,185,129,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"Total students"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(hs,{size:15})})]}),e.jsx("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:m}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Added this year"}),e.jsx("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:m>0?"+1":"0"})]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#0ea5e9] shadow-[0_4px_16px_rgba(14,165,233,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"Class average"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(fs,{size:15})})]}),e.jsxs("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:[h,"%"]}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Vs. last month"}),e.jsx("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:"+2.5%"})]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#a855f7] shadow-[0_4px_16px_rgba(168,85,247,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"Engage­ment"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(vi,{size:15})})]}),e.jsxs("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:[S,"%"]}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Active participants"}),e.jsx("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:Math.round(S/100*m)})]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#f97316] shadow-[0_4px_16px_rgba(249,115,22,0.13)] rounded-sm sm:rounded-lg p-[10px] sm:p-[15px] text-white flex flex-col gap-[6px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[9px] sm:text-[11px] opacity-90 leading-tight",children:"At risk"}),e.jsx("div",{className:"hidden sm:flex bg-white/20 p-1.5 rounded-lg",children:e.jsx(br,{size:15})})]}),e.jsx("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:p}),e.jsxs("div",{className:"relative z-10 border-t border-white/30 pt-1.5 sm:pt-2 flex justify-between items-center text-[9px] sm:text-[10px] opacity-90",children:[e.jsx("span",{className:"hidden sm:block",children:"Requires attention"}),e.jsxs("span",{className:"bg-black/15 px-[5px] sm:px-[7px] py-[2px] rounded font-semibold",children:[y,"%"]})]})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] border border-white p-[18px_20px] shadow-[0_1px_4px_rgba(0,0,0,0.04)]",children:[e.jsxs("div",{className:"flex justify-between items-center mb-[14px]",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-[#1e293b]",children:"My classes"}),e.jsx("span",{onClick:r,className:"text-[12px] text-[#10b981] font-semibold cursor-pointer hover:underline",children:"View all"})]}),e.jsxs("div",{className:"space-y-[9px]",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-slate-500 mb-3",children:"No classes imported yet."}),v&&e.jsx("button",{onClick:v,className:"text-sm text-[#9956DE] font-semibold hover:underline",children:"+ Create a class"})]}),t.map((N,w)=>{const g=[{bg:"bg-[#f3e8ff]",text:"text-[#a855f7]",borderHover:"hover:border-[#d8b4fe]",stripe:"bg-[#a855f7]"},{bg:"bg-[#eff6ff]",text:"text-[#3b82f6]",borderHover:"hover:border-[#bfdbfe]",stripe:"bg-[#3b82f6]"},{bg:"bg-[#f0fdf4]",text:"text-[#22c55e]",borderHover:"hover:border-[#bbf7d0]",stripe:"bg-[#22c55e]"},{bg:"bg-[#fff7ed]",text:"text-[#f97316]",borderHover:"hover:border-[#fed7aa]",stripe:"bg-[#f97316]"},{bg:"bg-[#fff1f2]",text:"text-[#f43f5e]",borderHover:"hover:border-[#fecdd3]",stripe:"bg-[#f43f5e]"}],I=g[w%g.length];return e.jsxs("div",{onClick:()=>a(N),className:`relative overflow-hidden flex items-center gap-3 p-[12px_13px] pl-[16px] border border-[#f1f5f9] rounded-[14px] cursor-pointer ${I.borderHover} hover:shadow-[0_2px_10px_rgba(0,0,0,0.04)] hover:bg-[#fafbff] transition-all group`,children:[e.jsx("div",{className:`absolute left-0 top-0 bottom-0 w-[5px] ${I.stripe}`}),e.jsx("div",{className:`w-[38px] h-[38px] rounded-[10px] flex items-center justify-center flex-shrink-0 text-[17px] ${I.bg} ${I.text} group-hover:scale-110 transition-transform duration-300`,children:e.jsx(Vt,{size:18})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[12.5px] font-medium text-[#1e293b]",children:N.name}),e.jsx("div",{className:"text-[11px] text-[#94a3b8] mt-[1px]",children:N.classification||"High School"})]}),e.jsx("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[65px]",children:N.schedule||"Mon-Fri"}),e.jsxs("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[85px]",children:[N.studentCount," students"]}),e.jsx("span",{className:`text-[10px] font-semibold px-[9px] py-[3px] rounded-[6px] ${N.riskLevel==="high"?"bg-[#fee2e2] text-[#b91c1c] border border-[#fca5a5]":N.riskLevel==="medium"?"bg-[#fffbeb] text-[#b45309] border border-[#fcd34d]":"bg-[#ecfdf5] text-[#065f46] border border-[#6ee7b7]"}`,children:N.riskLevel==="high"?"High risk":N.riskLevel==="medium"?"Medium risk":"On track"}),e.jsx(Yr,{size:16,className:"text-[#cbd5e1] ml-auto hover:text-[#64748b]"})]},N.id)})]})]})]})},rp=he.memo(({student:t,onViewStudent:s,onCreateAccount:a,onRemoveStudent:r})=>{const n=t.riskLevel==="high"?{borderLeft:"border-l-rose-500",bgAvatar:"bg-rose-50 text-rose-600 border-rose-100/50",badge:"text-rose-600 bg-rose-50",progress:"bg-rose-500"}:t.riskLevel==="medium"?{borderLeft:"border-l-amber-500",bgAvatar:"bg-amber-50 text-amber-600 border-amber-100/50",badge:"text-amber-600 bg-amber-50",progress:"bg-amber-500"}:{borderLeft:"border-l-emerald-500",bgAvatar:"bg-emerald-50 text-emerald-600 border-emerald-100/50",badge:"text-emerald-600 bg-emerald-50",progress:"bg-emerald-500"},i=t.hasRegisteredAccount===!1&&t.source==="import",l=t.hasRegisteredAccount===!0;return e.jsxs("div",{onClick:()=>s(t),className:`p-[12px] bg-white rounded-[14px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#f1f5f9] border-l-[4px] ${n.borderLeft} hover:scale-[1.02] transition-transform cursor-pointer group flex flex-col justify-between`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-[10px]",children:[e.jsxs("div",{className:"flex gap-[8px] items-center min-w-0 pr-2",children:[t.avatar?e.jsx("img",{src:t.avatar,alt:t.name,className:`w-8 h-8 rounded-full border ${n.bgAvatar.split(" ")[2]} object-cover shrink-0`}):e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center font-semibold text-[11px] shrink-0 border ${n.bgAvatar}`,children:t.name.substring(0,2).toUpperCase()}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("p",{className:"text-[13px] font-semibold text-[#1e293b] leading-tight truncate",children:t.name}),l&&e.jsx("span",{title:"Registered student account",className:"w-1.5 h-1.5 rounded-full bg-emerald-500 shrink-0"})]}),e.jsxs("p",{className:"text-[10px] text-[#64748b] flex items-center gap-[4px] mt-0.5 truncate",children:[e.jsx(Ls,{className:"w-[10px] h-[10px] shrink-0"})," ",t.lastActive||"recently"]})]})]}),e.jsxs("span",{className:`font-semibold text-[11px] px-[6px] py-[2px] rounded-[14px] shrink-0 ${n.badge}`,children:[t.avgScore,"%"]}),r&&e.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),r(t)},className:"opacity-0 group-hover:opacity-100 transition-opacity text-slate-400 hover:text-red-500 p-1 rounded shrink-0","aria-label":`Remove ${t.name} from class`,title:"Remove from class",children:e.jsx(qt,{size:14})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2 px-2 py-1 rounded-[10px] bg-amber-50 border border-amber-100/80",children:[e.jsx("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"No Account"}),a&&e.jsxs("button",{type:"button",onClick:c=>{c.stopPropagation(),a(t)},className:"flex items-center gap-1 px-2 py-0.5 rounded-full bg-white text-amber-700 border border-amber-200 hover:bg-amber-100 text-[10px] font-semibold transition-colors","aria-label":`Create system account for ${t.name}`,children:[e.jsx("span",{"aria-hidden":!0,children:"+"}),"Create"]})]}),e.jsx("div",{className:"w-full bg-[#f1f5f9] h-1.5 rounded-full overflow-hidden mt-auto",children:e.jsx("div",{className:`h-full rounded-full ${n.progress}`,style:{width:`${t.avgScore}%`}})})]})}),np=({students:t,allClasses:s,currentClass:a,onReassignSection:r,reassignBusyId:o})=>{const[n,i]=u.useState(!1),l=u.useMemo(()=>{const d=new Map;return s.forEach(m=>{const p=(m.classSectionId||m.id||"").trim();if(!p)return;const h=(m.classMetadata?.grade||"").trim(),v=(m.classMetadata?.section||"").trim();if(!h||!v)return;const y=m.name||`${h} - ${v}`;d.set(p,{classSectionId:p,grade:h,section:v,label:y})}),Array.from(d.values()).sort((m,p)=>m.label.localeCompare(p.label))},[s]),c=u.useMemo(()=>{const d=new Map,m=[];return t.forEach(p=>{const h=(p.classSectionId||"").trim();if(!h){m.push(p);return}const v=p.section||p.className||h,y=d.get(h)||{label:v,students:[]};y.students=[...y.students,p],d.set(h,y)}),{assigned:Array.from(d.entries()).map(([p,h])=>({sectionId:p,...h})).sort((p,h)=>p.label.localeCompare(h.label)),unassigned:m}},[t]);return e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] border border-white shadow-[0_1px_4px_rgba(0,0,0,0.04)] overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>i(d=>!d),className:"w-full flex items-center justify-between px-6 py-4 text-left","aria-expanded":n,children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Section Management"}),e.jsxs("p",{className:"text-[12px] text-[#64748b] mt-0.5",children:["Move students between sections. Showing ",t.length," students across ",c.assigned.length," section",c.assigned.length===1?"":"s",c.unassigned.length>0?` · ${c.unassigned.length} unassigned`:"","."]})]}),e.jsx(Ot,{className:`w-4 h-4 text-[#64748b] transition-transform ${n?"rotate-180":""}`})]}),n&&e.jsxs("div",{className:"border-t border-[#f1f5f9] divide-y divide-[#f1f5f9]",children:[c.assigned.length===0&&c.unassigned.length===0&&e.jsx("p",{className:"text-[12px] text-[#64748b] px-6 py-5",children:"No students yet. Add students to this teacher to manage section assignments."}),c.assigned.map(d=>e.jsxs("div",{className:"px-6 py-4",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-[#64748b] mb-2",children:[d.label," ",e.jsxs("span",{className:"text-[10px] font-normal text-[#94a3b8]",children:["(",d.students.length,")"]})]}),e.jsx("div",{className:"space-y-1.5",children:d.students.map(m=>e.jsx(ci,{student:m,sectionTargets:l,currentSectionId:a.classSectionId,onReassign:r,isBusy:o===m.id},`section-row-${m.id}`))})]},d.sectionId)),c.unassigned.length>0&&e.jsxs("div",{className:"px-6 py-4 bg-amber-50/40",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-amber-700 mb-2",children:["Unassigned ",e.jsxs("span",{className:"text-[10px] font-normal text-amber-600/80",children:["(",c.unassigned.length,")"]})]}),e.jsx("div",{className:"space-y-1.5",children:c.unassigned.map(d=>e.jsx(ci,{student:d,sectionTargets:l,currentSectionId:a.classSectionId,onReassign:r,isBusy:o===d.id},`section-row-${d.id}`))})]})]})]})},ci=({student:t,sectionTargets:s,currentSectionId:a,onReassign:r,isBusy:o})=>{const[n,i]=u.useState(t.classSectionId||"");u.useEffect(()=>{i(t.classSectionId||"")},[t.classSectionId]);const l=()=>{const d=s.find(m=>m.classSectionId===n);d&&d.classSectionId!==t.classSectionId&&r(t,d)},c=n===(t.classSectionId||"");return e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-2 md:gap-3 px-3 py-2 rounded-[12px] bg-white border border-[#f1f5f9]",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[13px] font-semibold text-[#1e293b] truncate",children:t.name}),e.jsxs("p",{className:"text-[11px] text-[#64748b] truncate",children:[t.lrn?`LRN ${t.lrn} · `:"",t.classMetadata?.className||t.className||"Unassigned section",a&&t.classSectionId===a?" · current":""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("select",{value:n,onChange:d=>i(d.target.value),disabled:o||s.length===0,className:"text-[12px] rounded-xl border border-[#dde3eb] bg-white px-3 py-1.5 text-[#0a1628] focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-200 disabled:opacity-60",children:[e.jsx("option",{value:"",children:"Select section…"}),s.map(d=>e.jsx("option",{value:d.classSectionId,children:d.label},d.classSectionId))]}),e.jsx("button",{type:"button",onClick:l,disabled:o||c||!n,className:"text-[12px] font-semibold rounded-xl px-3 py-1.5 bg-indigo-600 text-white hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:hover:bg-indigo-600",children:o?"Saving…":"Move"})]})]})},op=({selectedClass:t,students:s,allClasses:a,riskDistribution:r,topicPerformance:o,onViewStudent:n,onCreateAccount:i,onReassignSection:l,reassignBusyId:c,onBack:d,teacherOptions:m,managerUpdating:p,onAssignManager:h,onOpenNotifications:v,onOpenProfile:y,classColor:S,insightDismissed:N,onOpenInsightModal:w,onAddStudents:g,onRemoveStudent:I})=>{const{currentUser:L,userProfile:A}=vs(),[W,f]=u.useState(""),[C,b]=u.useState(""),[F,U]=u.useState("All"),[k,D]=u.useState(null),[J,re]=u.useState(!0),[ce,ie]=u.useState(!1),[fe,Ce]=u.useState(!0);u.useEffect(()=>{let j=!1;return re(!0),zo(t.id).then(T=>{j||D(T)}).catch(T=>console.warn("[AnalyticsView] Backend fetch failed, using local data:",T)).finally(()=>{j||re(!1)}),()=>{j=!0}},[t.id]),u.useEffect(()=>{let j,T;return(async()=>{try{const{collection:_,onSnapshot:V}=await Cs(async()=>{const{collection:je,onSnapshot:we}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{collection:je,onSnapshot:we}},__vite__mapDeps([2,3])),{db:me}=await Cs(async()=>{const{db:je}=await import("./index-BdLfAeGL.js").then(we=>we.b7);return{db:je}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),oe=_(me,"classes",t.id,"student_summaries");let ae=!0;j=V(oe,()=>{if(ae){ae=!1;return}T&&clearTimeout(T),T=setTimeout(()=>{zo(t.id).then(D).catch(()=>{})},2e3)})}catch{}})(),()=>{j?.(),T&&clearTimeout(T)}},[t.id]);const[ue,ge]=u.useState(new Map);u.useEffect(()=>{let j=!1;const T=s.filter(_=>_.accountUid||_.hasRegisteredAccount);if(T.length!==0)return(async()=>{try{const{doc:_,getDoc:V}=await Cs(async()=>{const{doc:je,getDoc:we}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{doc:je,getDoc:we}},__vite__mapDeps([2,3])),{db:me}=await Cs(async()=>{const{db:je}=await import("./index-BdLfAeGL.js").then(we=>we.b7);return{db:je}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),oe=new Map,ae=T.slice(0,50);await Promise.all(ae.map(async je=>{const we=je.accountUid||je.id;try{const Ke=await V(_(me,"progress",we));if(Ke.exists()){const Je=Ke.data().averageScore||0;Je>0&&oe.set(je.id,Je)}}catch{}})),j||ge(oe)}catch{}})(),()=>{j=!0}},[s]);const B=k!=null&&k.students.some(j=>j.quiz_attempt_count>0),te=(()=>{if(B)return k.class_average;if(t.avgScore>0)return t.avgScore;if(s.length===0)return 0;const j=s.map(T=>ue.get(T.id)||T.avgScore).filter(T=>T>0);return j.length>0?Math.round(j.reduce((T,_)=>T+_,0)/j.length):0})(),ne=(()=>{if(B)return k.completion_rate;if(s.length===0)return 0;const j=s.filter(T=>ue.has(T.id)||T.assignmentCompletion>0).length;return Math.round(j/s.length*100)})(),ze=(()=>{if(B)return k.participation_rate;if(s.length===0)return 0;const j=s.filter(T=>ue.has(T.id)||T.engagementScore>0||T.avgScore>0).length;return s.length>0?Math.round(j/s.length*100):0})(),Fe=k?.insights?.risk_distribution?[{name:"Critical",value:k.insights.risk_distribution.Critical||0,color:"#dc2626"},{name:"High Risk",value:k.insights.risk_distribution["High Risk"]||0,color:"#f43f5e"},{name:"Medium Risk",value:k.insights.risk_distribution["Medium Risk"]||0,color:"#f59e0b"},{name:"Low Risk",value:k.insights.risk_distribution["Low Risk"]||0,color:"#10b981"},{name:"Unassessed",value:k.insights.risk_distribution.Unassessed||0,color:"#94a3b8"}].filter(j=>j.value>0):[{name:"High Risk",value:s.filter(j=>j.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:s.filter(j=>j.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:s.filter(j=>j.riskLevel==="low").length,color:"#75D06A"}];u.useEffect(()=>{b(t.classMetadata?.managerId||t.managerId||"")},[t]);const Pe=u.useMemo(()=>{const j=W.trim().toLowerCase();let T=s;if(j&&(T=T.filter(_=>_.name.toLowerCase().includes(j)||(_.lrn||"").toLowerCase().includes(j)||(_.weakestTopic||"").toLowerCase().includes(j))),F==="Good")if(k){const _=new Set(k.students.filter(V=>V.quiz_attempt_count>0&&V.avg_score>=75).map(V=>V.student_id));T=T.filter(V=>_.has(V.id))}else T=T.filter(_=>_.avgScore>=85&&_.riskLevel!=="high");else if(F==="Risk")if(k){const _=new Set(k.students.filter(V=>["High Risk","Critical","Unassessed"].includes(V.risk_level)).map(V=>V.student_id));T=T.filter(V=>_.has(V.id))}else T=T.filter(_=>_.riskLevel==="high"||_.avgScore<75);return T},[W,s,F,k]),G=u.useMemo(()=>B?k.students.filter(j=>j.quiz_attempt_count>0).sort((j,T)=>T.avg_score-j.avg_score).slice(0,5).map(j=>{const T=s.find(_=>_.id===j.student_id);return T?{...T,avgScore:j.avg_score}:null}).filter(Boolean):[...s].map(j=>({...j,avgScore:ue.get(j.id)||j.avgScore})).sort((j,T)=>T.avgScore-j.avgScore).slice(0,5),[s,k,B,ue]),se=u.useMemo(()=>B?k.students.filter(j=>["High Risk","Critical"].includes(j.risk_level)).sort((j,T)=>j.avg_score-T.avg_score).map(j=>{const T=s.find(_=>_.id===j.student_id);return T?{...T,avgScore:j.avg_score,_backendRisk:j.risk_level}:null}).filter(Boolean):[...s].filter(j=>j.riskLevel==="high"||(ue.get(j.id)||j.avgScore)<70||j.assignmentCompletion<65),[s,k,B,ue]),M=u.useMemo(()=>k?.insights?.topic_performance?.length?k.insights.topic_performance.map(j=>({topic:j.topic,score:j.class_accuracy})):o,[k,o]),q=j=>{if(B){const T=k.students.find(_=>_.student_id===j);if(T&&T.avg_score>0)return T.avg_score}return ue.has(j)?ue.get(j):null},Q=j=>{if(!k)return null;const T=k.students.find(_=>_.student_id===j);return T?T.risk_level:null},pe=async()=>{ie(!0);try{const j=await am(t.id);D(T=>T&&{...T,insights:j})}catch(j){console.warn("[AnalyticsView] Refresh insights failed:",j?.message)}finally{ie(!1)}};u.useMemo(()=>m.find(j=>j.uid===C),[m,C]);const $=[t.classMetadata?.gradeLevel||t.gradeLevel,t.classMetadata?.classification||t.classification,t.classMetadata?.strand||t.strand].filter(Boolean);return e.jsxs(Re.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"p-3 sm:p-[24px] xl:p-[32px] space-y-3 sm:space-y-[24px] h-full overflow-y-auto",children:[e.jsx("div",{className:"flex items-center justify-between mb-3 sm:mb-6",children:e.jsxs("button",{onClick:d,className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors bg-white/60 hover:bg-white/80 px-[18px] py-2 rounded-full backdrop-blur-[12px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50",children:[e.jsx($s,{className:"w-4 h-4"}),"Back to Classes"]})}),e.jsxs("header",{style:{backgroundColor:S?.hex||"#6366f1"},className:"rounded-[24px] p-4 sm:p-[24px] lg:p-[32px] shadow-[0_8px_32px_rgba(0,0,0,0.08)] flex flex-col lg:flex-row lg:items-center justify-between gap-4 sm:gap-6 relative overflow-hidden group text-white",children:[e.jsx("div",{className:"absolute -right-10 -bottom-10 w-48 h-48 rounded-full bg-white/10 group-hover:scale-[1.3] transition-transform duration-700 ease-out pointer-events-none"}),e.jsx("div",{className:"absolute -left-10 -top-10 w-32 h-32 rounded-full bg-white/10 group-hover:scale-[1.2] transition-transform duration-700 delay-75 ease-out pointer-events-none"}),e.jsxs("div",{className:"shrink-0 relative z-10",children:[e.jsx("h1",{className:"text-xl sm:text-[28px] font-bold mb-2 sm:mb-3 tracking-tight",children:t.name}),e.jsx("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:$.map((j,T)=>e.jsx("span",{className:"px-3 py-1 bg-white/20 backdrop-blur-md text-white text-[12px] font-semibold rounded-full shadow-sm border border-white/20",children:j},j))}),e.jsxs("p",{className:"text-[13px] text-white/80 font-medium",children:["Manager: ",t.classMetadata?.managerName||t.managerName||"Not assigned"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-[18px] w-full",children:[e.jsxs("div",{className:"group relative overflow-hidden bg-[#0ea5e9] shadow-[0_4px_16px_rgba(14,165,233,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Class Average"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(fs,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Math.round(te),"%"]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#10b981] shadow-[0_4px_16px_rgba(16,185,129,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Completion"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(La,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Math.round(ne),"%"]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#a855f7] shadow-[0_4px_16px_rgba(168,85,247,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Participation"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(hs,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Math.round(ze),"%"]})]}),e.jsxs("div",{className:"group relative overflow-hidden bg-[#f97316] shadow-[0_4px_16px_rgba(249,115,22,0.13)] rounded-lg sm:rounded-2xl p-[12px] sm:p-[15px] text-white flex flex-col gap-[8px] sm:gap-[10px]",children:[e.jsx("div",{className:"absolute -right-4 -bottom-4 w-24 h-24 rounded-full bg-white/10 group-hover:scale-[1.6] transition-transform duration-500 ease-out"}),e.jsx("div",{className:"absolute -left-4 -top-4 w-12 h-12 rounded-full bg-white/10 group-hover:scale-[1.4] transition-transform duration-500 delay-75 ease-out"}),e.jsxs("div",{className:"relative z-10 flex justify-between items-start",children:[e.jsx("span",{className:"text-[10px] sm:text-[11px] opacity-90 uppercase tracking-wider font-semibold",children:"Attention"}),e.jsx("div",{className:"bg-white/20 p-1.5 rounded-lg flex",children:e.jsx(da,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[se.length," ",e.jsx("span",{className:"text-[12px] opacity-90 font-medium",children:"students"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-3 sm:gap-[24px] h-auto xl:h-[600px]",children:[e.jsxs("div",{className:"xl:col-span-1 bg-white/80 backdrop-blur-[12px] rounded-[18px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white flex flex-col overflow-hidden h-[500px] xl:h-full",children:[e.jsxs("div",{className:"p-5 border-b border-[#f1f5f9] shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h2",{className:"text-[15px] font-semibold text-[#1e293b]",children:["Students ",e.jsxs("span",{className:"text-[#64748b] text-[13px]",children:["(",Pe.length,")"]})]}),e.jsx("button",{onClick:()=>g?.(),className:"text-[11px] font-semibold text-[#9956DE] hover:text-[#7c3aed] bg-[#9956DE]/10 hover:bg-[#9956DE]/20 px-3 py-1.5 rounded-lg transition-colors",children:"+ Add"})]}),e.jsxs("div",{className:"flex items-center bg-white px-4 py-2 rounded-[14px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#f1f5f9] group",children:[e.jsx(Xs,{className:"w-4 h-4 text-[#64748b] shrink-0 group-focus-within:text-[#4f46e5] transition-colors"}),e.jsx("input",{type:"text",placeholder:"Search students...",value:W,onChange:j=>f(j.target.value),className:"bg-transparent border-none focus:outline-none ml-2 text-[13px] w-full text-[#475569] placeholder:text-[#64748b]"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-4 overflow-x-auto no-scrollbar pb-1",children:[e.jsx("button",{onClick:()=>U("All"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${F==="All"?"bg-[#4f46e5] text-white shadow-[0_1px_4px_rgba(0,0,0,0.04)]":"bg-[#f8fafc] text-[#64748b] hover:bg-[#f1f5f9]"}`,children:"All Students"}),e.jsx("button",{onClick:()=>U("Good"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${F==="Good"?"bg-emerald-50 text-emerald-600 border border-emerald-100/50 shadow-[0_1px_4px_rgba(0,0,0,0.04)]":"bg-emerald-50/40 text-emerald-600 border border-emerald-50 hover:bg-emerald-50"}`,children:"Top Performers"}),e.jsx("button",{onClick:()=>U("Risk"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${F==="Risk"?"bg-rose-50 text-rose-600 border border-rose-100/50 shadow-[0_1px_4px_rgba(0,0,0,0.04)]":"bg-rose-50/40 text-rose-600 border border-rose-50 hover:bg-rose-50"}`,children:"Needs Attention"})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-4 flex flex-col no-scrollbar",children:e.jsx(yu,{style:{height:"100%"},data:Pe,className:"no-scrollbar",itemContent:(j,T)=>{const _=q(T.id),V=_!==null?{...T,avgScore:_}:T;return e.jsx("div",{className:"py-[6px] px-[8px]",children:e.jsx(rp,{student:V,onViewStudent:n,onCreateAccount:i,onRemoveStudent:I})})},computeItemKey:(j,T)=>ln(T)})})]}),e.jsxs("div",{className:"xl:col-span-2 flex flex-col gap-[24px] h-full overflow-y-auto no-scrollbar pb-10 xl:pb-0",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white flex flex-col group h-[280px]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h3",{className:"font-semibold text-[15px] text-[#1e293b]",children:"Risk Distribution"}),e.jsx(Yr,{className:"w-4 h-4 text-[#64748b] cursor-pointer group-hover:scale-110 transition-transform"})]}),e.jsx("div",{className:"relative w-full flex-1 min-h-[180px]",children:e.jsx(Yn,{width:"100%",height:"100%",children:e.jsxs(Kn,{data:Fe,children:[e.jsx(Xn,{strokeDasharray:"4 4",stroke:"#f1f5f9",vertical:!1}),e.jsx(Jn,{dataKey:"name",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#475569",fontSize:11,fontWeight:600},dy:10}),e.jsx(Zn,{axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600}}),e.jsx(eo,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(to,{dataKey:"value",radius:[6,6,0,0],barSize:80,children:Fe.map((j,T)=>{const _={Critical:"#dc2626","High Risk":"#f43f5e","Medium Risk":"#f59e0b","Low Risk":"#10b981",Unassessed:"#94a3b8"};return e.jsx(so,{fill:_[j.name]||j.color},`cell-${T}`)})})]})})})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white flex flex-col group h-[280px]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h3",{className:"font-semibold text-[15px] text-[#1e293b]",children:"Topic Performance"}),e.jsx(Yr,{className:"w-4 h-4 text-[#64748b] cursor-pointer group-hover:scale-110 transition-transform"})]}),e.jsx("div",{className:"relative w-full flex-1 min-h-[180px] -ml-8",children:e.jsx(Yn,{width:"100%",height:"100%",children:e.jsxs(Kn,{data:M,layout:"vertical",margin:{top:0,right:10,left:40,bottom:0},children:[e.jsx(Xn,{strokeDasharray:"4 4",stroke:"#f1f5f9",horizontal:!1}),e.jsx(Jn,{type:"number",domain:[0,100],axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600},tickFormatter:j=>`${j}%`}),e.jsx(Zn,{dataKey:"topic",type:"category",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#1e293b",fontSize:11,fontWeight:600},dx:-10}),e.jsx(eo,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(to,{dataKey:"score",radius:[0,6,6,0],barSize:28,children:M.map((j,T)=>{const _=j.score>=75?"#10b981":j.score>=60?"#f59e0b":"#f43f5e";return e.jsx(so,{fill:_},`cell-${T}`)})})]})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-[24px]",children:[e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("h3",{className:"font-semibold text-[15px] text-[#1e293b] flex items-center gap-2",children:[e.jsx(ca,{className:"w-4 h-4 text-emerald-500"}),"Top Performers"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[G.map(j=>e.jsxs("div",{onClick:()=>n(j),className:"flex justify-between items-center p-3 bg-emerald-50/40 rounded-[14px] border border-emerald-50 group hover:scale-[1.02] transition-transform cursor-pointer",children:[e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:j.name}),e.jsxs("span",{className:"text-[13px] font-semibold text-emerald-600",children:[q(j.id)??j.avgScore,"%"]})]},`top-${j.id}`)),G.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No students available yet."})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("h3",{className:"font-semibold text-[15px] text-[#1e293b] flex items-center gap-2",children:[e.jsx(da,{className:"w-4 h-4 text-rose-500"}),"Needs Attention"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[se.slice(0,4).map(j=>{const T=Q(j.id),_=T||(j.riskLevel==="high"?"HIGH RISK":"MEDIUM RISK"),V=T==="Critical"||j.avgScore===0&&j.riskLevel==="high",me=T==="High Risk"||j.riskLevel==="high",oe=V?"bg-red-50/60 border-red-100":me?"bg-rose-50/40 border-rose-50":"bg-amber-50/40 border-amber-50",ae=V?"text-red-700":me?"text-rose-600":"text-amber-600";return e.jsxs("div",{onClick:()=>n(j),className:`flex justify-between items-center p-3 rounded-[14px] border group hover:scale-[1.02] transition-transform cursor-pointer ${oe}`,children:[e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:j.name}),e.jsx("span",{className:`text-[11px] font-semibold bg-white px-2 py-0.5 rounded-[14px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-[#f1f5f9] ${ae}`,children:_.toUpperCase()})]},`attn-${j.id}`)}),se.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No urgent students."})]})]})]})]})]}),k?.insights&&e.jsxs("div",{className:"bg-gradient-to-br from-indigo-50/80 to-purple-50/60 backdrop-blur-[12px] rounded-[18px] p-5 sm:p-6 shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-indigo-100/50",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("button",{onClick:()=>Ce(!fe),className:"flex items-center gap-2 text-[15px] font-semibold text-[#1e293b]",children:[e.jsx(bs,{className:"w-4 h-4 text-indigo-500"}),"AI Class Insights",e.jsx(Ot,{className:`w-4 h-4 text-[#64748b] transition-transform ${fe?"":"-rotate-90"}`})]}),e.jsxs("button",{onClick:pe,disabled:ce,className:"flex items-center gap-1.5 text-[11px] font-semibold text-indigo-600 hover:text-indigo-700 bg-white/70 hover:bg-white px-3 py-1.5 rounded-lg transition-colors disabled:opacity-50",children:[e.jsx(xs,{className:`w-3 h-3 ${ce?"animate-spin":""}`}),ce?"Refreshing...":"Refresh AI Analysis"]})]}),fe&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/70 rounded-[14px] p-4 border border-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ds,{size:18,className:"text-indigo-600"}),e.jsx("h4",{className:"text-[13px] font-semibold text-[#1e293b]",children:"Class Overview"})]}),e.jsx("p",{className:"text-[12px] text-[#475569] leading-relaxed",children:k.insights.class_summary})]}),e.jsxs("div",{className:"bg-white/70 rounded-[14px] p-4 border border-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ca,{size:18,className:"text-emerald-600"}),e.jsx("h4",{className:"text-[13px] font-semibold text-[#1e293b]",children:"What's Working"})]}),e.jsx("p",{className:"text-[12px] text-[#475569] leading-relaxed",children:k.insights.class_strengths})]}),e.jsxs("div",{className:"bg-white/70 rounded-[14px] p-4 border border-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(fs,{size:18,className:"text-amber-600"}),e.jsx("h4",{className:"text-[13px] font-semibold text-[#1e293b]",children:"Recommended Actions"})]}),e.jsx("ul",{className:"space-y-1.5",children:k.insights.recommended_actions.map((j,T)=>e.jsxs("li",{className:"text-[12px] text-[#475569] leading-relaxed flex items-start gap-1.5",children:[e.jsx("span",{className:"text-indigo-500 mt-0.5 shrink-0",children:"•"}),j]},T))})]})]})]}),e.jsx(np,{students:s,allClasses:a,currentClass:t,onReassignSection:l,reassignBusyId:c})]})},ip=({student:t,teacherId:s,teacherName:a,onStudentUpdated:r,onBack:o,onNavigateToQuizMaker:n,initialCache:i,onCacheUpdate:l})=>{const c=(t.riskLevel||"low").toLowerCase(),d=c==="high"||c==="medium",m=u.useMemo(()=>xt.getImportGroundedRolloutFlags(),[]),[p,h]=u.useState(null),[v,y]=u.useState(!0),[S,N]=u.useState(!1),[w,g]=u.useState(null),[I,L]=u.useState(i?.learningPath||""),[A,W]=u.useState(!0),[f,C]=u.useState(i?.gradeDraft||t.grade||"Grade 11"),[b,F]=u.useState(i?.sectionDraft||t.section||"Section A"),[U,k]=u.useState(!1),[D,J]=u.useState(i?.lessonPlan??null),[re,ce]=u.useState([]),[ie,fe]=u.useState(""),[Ce,ue]=u.useState(!1),[ge,B]=u.useState(""),[te,ne]=u.useState("all"),[ze,Fe]=u.useState("all"),[Pe,G]=u.useState(!1),[se,M]=u.useState(!1),[q,Q]=u.useState(null),[pe,$]=u.useState(!1),[j,T]=u.useState(!1),[_,V]=u.useState(0),[me,oe]=u.useState(!1),[ae,je]=u.useState("choose"),[we,Ke]=u.useState([]),[Ue,Je]=u.useState(!1),[ht,dt]=u.useState(!1),[rt,Mt]=u.useState(!1),[At,It]=u.useState(!1);u.useEffect(()=>{C(t.grade||"Grade 11"),F(t.section||"Section A")},[t.grade,t.section]),u.useEffect(()=>{let z=!1;return y(!0),rn(t.id).then(de=>{z||h(de)}).catch(de=>console.warn("[InterventionView] Backend fetch failed:",de)).finally(()=>{z||y(!1)}),Sn(t.id).then(de=>{z||N(de.length>0)}).catch(()=>{}),()=>{z=!0}},[t.id]);const[cs,Us]=u.useState(null),[Yt,ds]=u.useState(null);u.useEffect(()=>{let z=!1;const de=t.accountUid||t.id;return Gr(de).then(E=>{if(!z&&(E?.averageScore&&Us(Math.round(E.averageScore)),E?.subjects)){let R=0,ve=0;for(const ee of Object.values(E.subjects))for(const Me of Object.values(ee.modulesProgress||{}))ve++,Me.progress>=100&&R++;ds({completed:R,total:ve})}}).catch(()=>{}),()=>{z=!0}},[t.id,t.accountUid]),u.useEffect(()=>{const z=de=>{if(de.key==="Escape"){if(At){It(!1);return}if(ht){rt?It(!0):dt(!1);return}me&&oe(!1)}};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[ht,me,rt,At]),u.useEffect(()=>{if(ht){const z=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=z}}},[ht]),u.useEffect(()=>{l?.(t.id,{lessonPlan:D,learningPath:I,gradeDraft:f,sectionDraft:b})},[D,I,f,b,t.id,l]),u.useEffect(()=>{(async()=>{W(!0);try{let de="";try{de=await Yl(t.struggles.length>0?t.struggles:[t.weakestTopic],"general_math"),fe(de)}catch{fe("")}const E=await xt.getLearningPath({weaknesses:t.struggles.length>0?t.struggles:[t.weakestTopic],gradeLevel:"High School",subject:"general_math"}),R=de?`${E.learningPath} -${de}`:E.learningPath;L(R)}catch{L("Unable to generate learning path. Please try again later."),fe("")}finally{W(!1)}})()},[t]);const js=u.useCallback(async()=>{ue(!0),B("");try{const z=t.classSectionId||Pt(f||"Grade 11",b||"Section A"),de=t.struggles.length>0?t.struggles[0]:t.weakestTopic,E=await Do({gradeLevel:f||t.grade||"Grade 11",subject:"general_math",quarter:1,moduleUnit:[f,b].filter(Boolean).join(" - ")||t.className,lessonTitle:`Grounded Lesson: ${de}`,learningCompetency:de,learnerLevel:t.avgScore<60?"support":t.avgScore<80?"developing":"advanced",classSectionId:z,className:[f,b].filter(Boolean).join(" - ")||t.className,focusTopics:t.struggles.length>0?t.struggles:[t.weakestTopic],topicCount:5,preferImportedTopics:m.lessonEnabled,allowReviewSources:Pe,allowUnverifiedLesson:se},!0);J(E),ce(E.curriculumSources||[]),Q(null),xt.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:z,className:[f,b].filter(Boolean).join(" - ")||t.className,metadata:{usedImportedTopics:E.usedImportedTopics,importedTopicCount:E.importedTopicCount,blockCount:E.blocks.length,publishReady:E.publishReady,sourceLegitimacyStatus:E.sourceLegitimacy.status,selfValidationPassed:E.selfValidation.passed,importGroundingEnabled:m.lessonEnabled}})}catch(z){let de=z instanceof Error?z.message:"Unable to generate lesson plan at this time.";if(z instanceof rr&&z.status===422)try{const R=JSON.parse(z.responseBody)?.detail;if(R?.selfValidation&&!se)try{const K=t.classSectionId||Pt(f||"Grade 11",b||"Section A"),Xe=t.struggles.length>0?t.struggles[0]:t.weakestTopic,nt=await Do({gradeLevel:f||t.grade||"Grade 11",subject:"general_math",quarter:1,moduleUnit:[f,b].filter(Boolean).join(" - ")||t.className,lessonTitle:`Grounded Lesson: ${Xe}`,learningCompetency:Xe,learnerLevel:t.avgScore<60?"support":t.avgScore<80?"developing":"advanced",classSectionId:K,className:[f,b].filter(Boolean).join(" - ")||t.className,focusTopics:t.struggles.length>0?t.struggles:[t.weakestTopic],topicCount:5,preferImportedTopics:m.lessonEnabled,allowReviewSources:Pe,allowUnverifiedLesson:!0},!0);J(nt),ce(nt.curriculumSources||[]),Q(null),B("");return}catch{}R?.message&&(de=R.message);const ve=R?.sourceLegitimacy?.issues||[],ee=R?.selfValidation?.issues||[],Me=[...ve,...ee].filter(Boolean).slice(0,3);Me.length>0&&(de=`${de} ${Me.join(" ")}`)}catch{}B(de),J(null),ce([]),xt.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:t.classSectionId||Pt(f||"Grade 11",b||"Section A"),className:[f,b].filter(Boolean).join(" - ")||t.className,metadata:{error:de,allowReviewSources:Pe,allowUnverifiedLesson:se,importGroundingEnabled:m.lessonEnabled}})}finally{ue(!1)}},[t,f,b,m.lessonEnabled,Pe,se]),Kt=u.useCallback(async()=>{if(!D)return le.error("Generate a lesson plan first."),null;$(!0);try{const z=await pm(D,s,{teacherName:a,studentId:t.id,studentName:t.name});return Q(z),le.success("Lesson plan saved as draft."),z}catch(z){return console.error("Failed to save lesson draft:",z),le.error(z instanceof Error?z.message:"Failed to save lesson draft."),null}finally{$(!1)}},[D,s,a,t.id,t.name]),Gs=u.useCallback(async()=>{if(!D){le.error("Generate a lesson plan first.");return}if(!D.publishReady){const z=[...D.sourceLegitimacy.issues,...D.selfValidation.issues].filter(Boolean).slice(0,2).join(" ");le.error(z||"Lesson is not publish-ready. Resolve legitimacy and validation checks first.");return}T(!0);try{let z=q;if(z||(z=await Kt()),!z)return;await hm(z),le.success("Lesson plan published to class content."),xt.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:D.classSectionId||t.classSectionId,className:D.className||t.className,metadata:{action:"publish_lesson_plan",lessonPlanId:z,publishReady:D.publishReady,sourceLegitimacyStatus:D.sourceLegitimacy.status,selfValidationPassed:D.selfValidation.passed}})}catch(z){console.error("Failed to publish lesson plan:",z),le.error(z instanceof Error?z.message:"Failed to publish lesson plan."),xt.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:D.classSectionId||t.classSectionId,className:D.className||t.className,metadata:{action:"publish_lesson_plan",error:z instanceof Error?z.message:"Failed to publish lesson plan."}})}finally{T(!1)}},[D,q,Kt,t.className,t.classSectionId]);u.useEffect(()=>{js()},[_]),u.useEffect(()=>{V(z=>z+1)},[t.id]),u.useEffect(()=>{ne("all"),Fe("all")},[D]),u.useMemo(()=>D?Array.from(new Set(D.blocks.map(z=>z.provenance?.sourceFile?.trim()).filter(z=>!!z))).sort((z,de)=>z.localeCompare(de)):[],[D]),u.useMemo(()=>D?Array.from(new Set(D.blocks.map(z=>z.provenance?.materialId?.trim()).filter(z=>!!z))).sort((z,de)=>z.localeCompare(de)):[],[D]);const Es=u.useMemo(()=>D?D.blocks.filter(z=>{const de=te==="all"||(z.provenance?.sourceFile||"").trim()===te,E=ze==="all"||(z.provenance?.materialId||"").trim()===ze;return de&&E}):[],[D,te,ze]),Rs=u.useMemo(()=>p?.learning_path?.steps?.length?p.learning_path.steps.map(z=>({id:z.step_number,type:z.type==="video_lesson"?"video":z.type==="assessment"?"assessment":"quiz",title:z.title,duration:`${z.duration_minutes} mins`,questions:z.num_items||void 0,icon:z.type==="video_lesson"?Za:z.type==="assessment"?Sa:z.type==="review"?xs:qr,competency:z.competency_tag,difficulty:z.difficulty,is_completed:z.is_completed})):[{id:1,type:"video",title:`${t.weakestTopic} Fundamentals`,duration:"8 mins",questions:void 0,icon:Za,competency:"",difficulty:"easy",is_completed:!1},{id:2,type:"quiz",title:`${t.weakestTopic} Practice`,duration:"12 mins",questions:10,icon:qr,competency:"",difficulty:"easy",is_completed:!1},{id:3,type:"assessment",title:"Final Check",duration:"10 mins",questions:5,icon:Sa,competency:"",difficulty:"medium",is_completed:!1}],[p,t.weakestTopic]),Ge=async()=>{if(!s){le.error("Unable to update section: teacher context missing");return}k(!0);try{await yr(t.id,f,b,s,new Date().getFullYear().toString(),a),await ll(t.id,f,b);const z={...t,grade:f,section:b,className:[f,b].filter(Boolean).join(" - "),classSectionId:Pt(f,b)};r(z),le.success("Student section assignment updated")}catch(z){console.error("Failed to update student section assignment:",z),le.error("Failed to update section assignment")}finally{k(!1)}};return e.jsxs(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"w-full h-full flex overflow-hidden relative",children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-[24px] xl:p-[32px] no-scrollbar",children:e.jsxs("div",{className:"max-w-[1000px] mx-auto space-y-[24px]",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-[8px]",children:e.jsx("div",{children:e.jsxs("button",{onClick:o,className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors bg-white/60 hover:bg-white/80 px-[18px] py-2 rounded-full backdrop-blur-[12px] mb-[16px] w-max shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50",children:[e.jsx(cr,{className:"w-4 h-4"}),"Back to Analytics"]})})}),e.jsxs("div",{className:"bg-gradient-to-br from-[#ecfdf5] via-[#f0fdf4] to-[#f7fdf9] backdrop-blur-[12px] rounded-[20px] p-[24px] border border-emerald-100 shadow-[0_4px_16px_rgba(16,185,129,0.08)] relative overflow-hidden",children:[e.jsx("div",{className:"absolute right-[-20px] bottom-[-20px] opacity-[0.06] pointer-events-none",children:e.jsx(Pn,{className:"w-48 h-48 text-emerald-600"})}),e.jsxs("div",{className:"flex items-center gap-3 mb-5 relative z-10",children:[e.jsx("div",{className:"w-10 h-10 rounded-[12px] bg-gradient-to-br from-[#059669] to-[#10b981] flex items-center justify-center shrink-0 shadow-[0_4px_10px_rgba(5,150,105,0.3)]",children:e.jsx(Pn,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-[15px] font-bold text-[#1e293b]",children:"AI Analysis"}),e.jsxs("span",{className:"flex items-center gap-1 px-2.5 py-0.5 bg-emerald-500 text-white text-[10px] font-bold rounded-full uppercase tracking-wider shadow-sm",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse"}),"Insights Active"]})]})]}),ie&&e.jsx($o,{sources:re,className:"mb-4 relative z-10"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 w-full relative z-10",children:[e.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-[14px] p-4 border border-emerald-100/60 shadow-[0_1px_4px_rgba(0,0,0,0.04)] relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 w-1 h-full bg-emerald-400 rounded-l-[14px]"}),e.jsxs("h4",{className:"text-[11px] font-bold text-emerald-600 uppercase tracking-wider mb-2.5 flex items-center gap-1.5 pl-2",children:[e.jsx(ca,{className:"w-3.5 h-3.5"})," Learning Strengths"]}),e.jsx("p",{className:"text-[13px] text-[#475569] leading-relaxed pl-2",children:p?.learning_strengths||(d?e.jsx(e.Fragment,{children:"Demonstrates engagement but faces challenges. Needs support with foundational topics."}):e.jsxs(e.Fragment,{children:["Excels in ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:t.weakestTopic}),". Demonstrates high engagement during interactive tests."]}))})]}),e.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-[14px] p-4 border border-rose-100/60 shadow-[0_1px_4px_rgba(0,0,0,0.04)] relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 w-1 h-full bg-rose-400 rounded-l-[14px]"}),e.jsxs("h4",{className:"text-[11px] font-bold text-rose-500 uppercase tracking-wider mb-2.5 flex items-center gap-1.5 pl-2",children:[e.jsx(fs,{className:"w-3.5 h-3.5"})," Next Steps"]}),e.jsx("ul",{className:"text-[13px] text-[#475569] leading-relaxed list-none p-0 m-0 space-y-1 pl-2",children:p?.next_steps_summary?e.jsx("li",{children:p.next_steps_summary}):t.struggles.length>0?t.struggles.map((z,de)=>e.jsxs("li",{children:["Must continue strengthening ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:z}),"."]},de)):e.jsxs("li",{children:["Focus on repetitive practice modules for ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:t.weakestTopic}),"."]})})]})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6 border-b border-[#f1f5f9] pb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Generated Learning Path"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{disabled:!p?.learning_path,onClick:async()=>{if(p)try{if(S){const z=await fl(t.id);N(!1),le.success(`Revoked ${z} assigned module(s) from ${t.name}.`)}else await pl(p,s),N(!0),le.success(`Learning path assigned to ${t.name}'s modules.`)}catch(z){console.error("[InterventionView] Action failed:",z),le.error(S?"Failed to revoke.":"Failed to assign learning path.")}},className:`${S?"bg-rose-50 hover:bg-rose-100 text-rose-700 border-rose-200":"bg-emerald-50 hover:bg-emerald-100 text-emerald-700 border-emerald-200"} border text-[11px] font-semibold rounded-full px-4 py-1.5 transition-colors shadow-[0_1px_4px_rgba(0,0,0,0.02)] flex items-center gap-1.5 disabled:opacity-50`,children:S?e.jsxs(e.Fragment,{children:[e.jsx(qt,{className:"w-3 h-3"})," Revoke"]}):e.jsxs(e.Fragment,{children:[e.jsx(ra,{className:"w-3 h-3"})," Assign to Student"]})}),e.jsxs("button",{disabled:A||v,onClick:async()=>{y(!0);try{const z=await xl(t.id);h(z)}catch(z){console.warn("[InterventionView] Regenerate failed:",z)}finally{y(!1)}V(z=>z+1)},className:"bg-[#f8fafc] hover:bg-white text-[#4f46e5] border border-[#e0e7ff] text-[11px] font-semibold rounded-full px-4 py-1.5 transition-colors shadow-[0_1px_4px_rgba(0,0,0,0.02)] flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(xs,{className:`w-3 h-3 ${v?"animate-spin":""}`})," ",v?"Analyzing...":"Regenerate"]})]})]}),e.jsxs(Mo,{name:"teacher-intervention-learning-path",loading:!1,fixture:null,fallback:null,children:[e.jsxs("div",{className:"mb-8 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mr-2",children:"Methodology:"}),(p?.learning_path?.methodology_tags||["Interactive","Video","Practice","Quiz"]).map(z=>e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:z},z))]}),e.jsx("div",{className:"relative border-l-2 border-[#e2e8f0] ml-[20px] space-y-[28px] pb-4",children:Rs.map((z,de)=>{let E=e.jsx(Za,{className:"w-4 h-4"}),R="bg-[#8b5cf6] shadow-[0_4px_10px_rgba(139,92,246,0.3)]",ve="text-purple-600",ee="group-hover:border-purple-200",Me="hover:bg-[#4f46e5]",K=e.jsx(xc,{className:"w-4 h-4 ml-0.5"});return z.type==="quiz"?(E=e.jsx(ir,{className:"w-4 h-4"}),R="bg-sky-500 shadow-[0_4px_10px_rgba(14,165,233,0.3)]",ve="text-sky-600",ee="group-hover:border-sky-200",Me="hover:bg-sky-500",K=e.jsx(zs,{className:"w-4 h-4"})):z.type==="assessment"&&(E=e.jsx(Sa,{className:"w-4 h-4"}),R="bg-emerald-500 shadow-[0_4px_10px_rgba(16,185,129,0.3)]",ve="text-emerald-600",ee="group-hover:bg-emerald-50"),e.jsxs(Re.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:de*.1},className:"relative pl-[32px] group",children:[e.jsx("div",{className:`absolute -left-[17px] top-1 w-8 h-8 rounded-full ${R} text-white flex items-center justify-center ring-4 ring-white group-hover:scale-110 transition-transform`,children:E}),e.jsxs("div",{onClick:()=>{p?.learning_path?.steps?.[de]&&g(p.learning_path.steps[de])},className:`${z.type==="assessment"?"bg-emerald-50/50 border-emerald-100":"bg-white border-[#f1f5f9]"} rounded-[14px] p-[18px] border shadow-[0_1px_4px_rgba(0,0,0,0.04)] flex justify-between items-center transition-colors cursor-pointer ${ee}`,children:[e.jsxs("div",{children:[e.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wider mb-1 block ${ve}`,children:["Step ",de+1," • ",z.type==="video"?"Video Lesson":z.type==="quiz"?"Practice":"Assessment"]}),e.jsx("p",{className:"font-semibold text-[#1e293b] text-[13px] mb-0.5",children:ks(z.title)}),e.jsxs("p",{className:"text-[#64748b] text-[11px] flex items-center gap-1.5",children:[z.type==="video"&&e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"w-3 h-3"})," ",z.duration]}),z.type==="quiz"&&e.jsxs(e.Fragment,{children:[e.jsx(ki,{className:"w-3 h-3"})," ",z.questions?`${z.questions} questions`:z.duration]}),z.type==="assessment"&&e.jsxs(e.Fragment,{children:[e.jsx(fs,{className:"w-3 h-3"})," ",z.questions?`${z.questions} assessment questions`:z.duration]}),z.competency&&e.jsx("span",{className:"ml-2 px-1.5 py-0.5 bg-indigo-50 text-indigo-600 text-[9px] font-mono rounded",children:z.competency})]})]}),z.type==="assessment"?e.jsx(hi,{className:"w-6 h-6 text-emerald-400"}):e.jsx("button",{className:`w-8 h-8 rounded-full bg-[#f8fafc] flex items-center justify-center text-[#64748b] ${Me} hover:text-white transition-colors border border-[#e2e8f0]`,children:K})]})]},z.id)})})]})]}),e.jsxs("div",{className:"relative bg-white/80 backdrop-blur-[12px] rounded-[18px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 z-10 bg-white/70 backdrop-blur-[2px] flex items-center justify-center rounded-[18px]",children:e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"inline-block px-4 py-2 bg-slate-100 border border-slate-200 rounded-full text-[13px] font-semibold text-slate-500",children:"🔒 Coming Soon"}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-2",children:"This feature is temporarily locked."})]})}),e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Targeted Lesson Generation"}),e.jsx(wt,{onClick:()=>V(z=>z+1),disabled:Ce,className:"bg-[#4f46e5] hover:bg-[#3730a3] text-white h-8 text-[11px] rounded-full px-4",children:Ce?"Loading...":"Regenerate"})]}),e.jsx("p",{className:"text-[13px] text-[#64748b] mb-6",children:"Configure inputs and requirements for AI lesson generation."}),e.jsxs("div",{className:"bg-[#f8fafc]/80 rounded-[14px] p-[20px] border border-[#f1f5f9] mb-6",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx(oa,{className:"w-4 h-4 text-[#4f46e5] shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-[13px] text-[#475569] leading-relaxed",children:["Class records alone are not enough for import-grounded lesson plans. Ensure course materials are uploaded via ",e.jsx("span",{className:"text-[#4f46e5] font-semibold",children:"Data Import"}),"."]})]}),e.jsxs("div",{className:"space-y-4 border-t border-[#e2e8f0] pt-5 mt-5",children:[e.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[e.jsx("span",{className:"text-[13px] font-medium text-[#1e293b] group-hover:text-[#4f46e5] transition-colors",children:"Allow sources requiring manual review"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:Pe,onChange:z=>G(z.target.checked)}),e.jsx("div",{className:"w-10 h-5 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#4f46e5]"})]})]}),e.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[e.jsx("span",{className:"text-[13px] font-medium text-[#1e293b] group-hover:text-[#4f46e5] transition-colors",children:"Allow unverified lesson draft"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:se,onChange:z=>M(z.target.checked)}),e.jsx("div",{className:"w-10 h-5 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#4f46e5]"})]})]})]})]}),e.jsxs(Mo,{name:"teacher-intervention-lesson-plan",loading:!1,fixture:null,fallback:null,children:[ge&&e.jsx("div",{className:"bg-[#FF8B8B]/14 border border-[#FF8B8B]/35 rounded-xl p-3 text-sm text-[#D66A6A] mb-4",children:ge}),D&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-[#f8fafc] border border-[#f1f5f9] rounded-[14px] p-5 shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("div",{className:"mb-3",children:e.jsx($o,{sources:re})}),e.jsx("p",{className:"text-[14px] font-semibold text-[#1e293b]",children:D.lessonTitle}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-2 mt-2",children:[e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:[e.jsx("span",{className:"font-semibold text-[#475569]",children:"Imported topics:"})," ",D.usedImportedTopics?"Yes":"No"," (",D.importedTopicCount,")"]}),e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:[e.jsx("span",{className:"font-semibold text-[#475569]",children:"Subject:"})," ",D.subject||"General Math"," (Q",D.quarter||1,")"]})]}),D.curriculumCompetency&&e.jsxs("p",{className:"text-[11px] text-[#4f46e5] font-semibold mt-2 bg-indigo-50/50 px-2 py-1 rounded inline-block",children:["Competency: ",D.curriculumCompetency]}),e.jsx("div",{className:"mt-3 flex items-center justify-between",children:e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:["Publish readiness: ",e.jsx("span",{className:`font-semibold ${D.publishReady?"text-emerald-600":"text-rose-500"}`,children:D.publishReady?"Ready":"Blocked"})]})}),D.warnings.length>0&&e.jsx("p",{className:"text-[11px] text-amber-600 mt-2 bg-amber-50 px-2 py-1.5 rounded",children:D.warnings.join(" ")})]}),D.lessonObjective&&e.jsxs("div",{className:"bg-white border border-[#e2e8f0] rounded-[14px] p-4 shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("p",{className:"text-[10px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5",children:"Lesson objective"}),e.jsx("p",{className:"text-[13px] text-[#1e293b]",children:D.lessonObjective})]}),D.realWorldHook&&e.jsxs("div",{className:"bg-indigo-50/50 border border-indigo-100 rounded-[14px] p-4 shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("p",{className:"text-[10px] font-semibold text-[#4f46e5] uppercase tracking-wider mb-1.5",children:"Real-life application"}),e.jsx("p",{className:"text-[13px] text-[#1e293b]",children:D.realWorldHook})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 mt-4",children:Es.map(z=>e.jsxs("div",{className:"border border-[#e2e8f0] rounded-[14px] p-4 bg-white shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[#1e293b]",children:z.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] mt-1",children:[z.estimatedMinutes," mins "," • "," ",z.strategy]}),e.jsx("p",{className:"text-[12px] text-[#475569] mt-2 bg-[#f8fafc] p-2 rounded-lg",children:z.objective}),e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-[10px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5",children:"Activities"}),z.activities.slice(0,2).map((de,E)=>e.jsxs("p",{className:"text-[11px] text-[#475569] mb-1 flex items-start gap-1",children:[e.jsx("span",{className:"text-[#94a3b8] mt-0.5",children:"•"})," ",e.jsx("span",{children:de})]},E))]})]},z.blockId))}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-4",children:[e.jsx(wt,{variant:"outline",onClick:()=>void Kt(),disabled:pe||!D,className:"border-[#cbd5e1] text-[#475569] hover:bg-[#f8fafc] text-[12px] h-9 rounded-full px-5",children:pe?e.jsx(Un,{className:"h-4 w-16"}):"Save Draft"}),e.jsx(wt,{onClick:()=>void Gs(),disabled:j||!D||!D.publishReady,className:"bg-[#10b981] hover:bg-[#059669] text-white text-[12px] h-9 rounded-full px-5",children:j?e.jsx(Un,{className:"h-4 w-24 bg-white/35"}):"Publish Lesson Plan"})]})]})]})]})]})}),e.jsx("aside",{className:"w-[320px] 2xl:w-[340px] bg-white/70 backdrop-blur-[24px] border-l border-white shadow-[-4px_0_24px_rgba(0,0,0,0.02)] flex flex-col h-full shrink-0 overflow-y-auto z-10 no-scrollbar relative",children:e.jsxs("div",{className:"p-[24px] space-y-[24px] flex flex-col items-center",children:[e.jsxs("div",{className:"flex flex-col items-center text-center w-full",children:[e.jsx("img",{src:t.avatar,alt:t.name,className:"w-[96px] h-[96px] rounded-full object-cover shadow-[0_8px_16px_rgba(0,0,0,0.1)] mb-4 border-4 border-white z-10 relative"}),e.jsx("h2",{className:"text-[20px] font-semibold text-[#1e293b] mb-1",children:t.name}),e.jsxs("p",{className:"text-[11px] font-semibold text-[#64748b] mb-3 uppercase tracking-wider",children:["ID: ",t.id.substring(0,8)]}),e.jsx("span",{className:`text-[11px] font-semibold px-3 py-1 rounded-[14px] border ${(p?.risk_level||"").includes("Critical")?"text-red-700 bg-red-50 border-red-200 animate-pulse":t.riskLevel==="high"||(p?.risk_level||"").includes("High")?"text-rose-600 bg-rose-50 border-rose-100":t.riskLevel==="medium"||(p?.risk_level||"").includes("Medium")?"text-amber-600 bg-amber-50 border-amber-100":"text-emerald-600 bg-emerald-50 border-emerald-100"}`,children:p?.risk_level||(t.riskLevel==="high"?"High Risk":t.riskLevel==="medium"?"Medium Risk":"Low Risk")})]}),e.jsxs("div",{className:"w-full grid grid-cols-2 gap-[12px]",children:[e.jsxs("div",{className:"bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Avg Score"}),e.jsxs("p",{className:"text-[20px] font-bold text-[#4f46e5]",children:[p?.avg_score||cs||t.avgScore,"%"]})]}),e.jsxs("div",{className:"bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Engagement"}),e.jsx("p",{className:"text-[20px] font-bold text-[#1e293b]",children:p?.engagement_level||((cs||t.avgScore)>80?"High":(cs||t.avgScore)>50?"Medium":"Low")})]}),e.jsxs("div",{className:"bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Last Active"}),e.jsx("p",{className:"text-[13px] font-semibold text-[#1e293b] mt-1",children:p?.last_active?new Date(p.last_active).toLocaleDateString():t.lastActive})]}),e.jsxs("div",{className:"bg-rose-50/60 rounded-[14px] p-4 border border-rose-100 text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-rose-600 uppercase tracking-wider mb-1",children:"Weakest Topic"}),e.jsx("p",{className:"text-[12px] font-semibold text-[#1e293b] mt-1 leading-snug break-words",title:p?.weakest_topic||t.weakestTopic,children:ks(p?.weakest_topic||t.weakestTopic||"")})]})]}),Yt&&Yt.total>0&&e.jsxs("div",{className:"w-full bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] flex items-center gap-3",children:[e.jsx(Bc,{size:18,className:Yt.completed===Yt.total?"text-emerald-500":"text-slate-400"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider",children:"Modules Completed"}),e.jsxs("p",{className:"text-[16px] font-bold text-[#1e293b]",children:[Yt.completed,"/",Yt.total]})]})]}),e.jsx("div",{className:"w-full flex flex-col gap-[10px]",children:e.jsxs("button",{onClick:async()=>{je("choose"),oe(!0)},className:"w-full flex items-center justify-center gap-2 bg-white hover:bg-[#f8fafc] text-[#475569] border border-[#cbd5e1] hover:border-[#94a3b8] text-[13px] font-semibold rounded-full px-4 py-3 shadow-[0_1px_4px_rgba(0,0,0,0.04)] transition-transform hover:scale-[1.02]",children:[e.jsx(ao,{className:"w-4 h-4"})," Export Materials"]})}),me&&Qr.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center p-4",onClick:()=>oe(!1),children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white rounded-[24px] shadow-[0_24px_64px_rgba(0,0,0,0.18)] w-full max-w-[460px] z-10 overflow-hidden",onClick:z=>z.stopPropagation(),children:[e.jsx("div",{className:"bg-gradient-to-r from-[#a855f7] to-[#9333ea] px-6 pt-5 pb-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ae==="bank"&&e.jsx("button",{onClick:()=>je("choose"),className:"w-7 h-7 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white transition-colors mr-1",children:e.jsx($s,{className:"w-4 h-4"})}),e.jsx("div",{className:"w-8 h-8 rounded-[8px] bg-white/20 flex items-center justify-center",children:e.jsx(Xr,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-bold text-white leading-tight",children:ae==="choose"?"Export Materials":"Choose a Quiz"}),e.jsx("p",{className:"text-[11px] text-white/70 font-medium",children:ae==="choose"?`For ${t.name}`:"Select a quiz from your bank"})]})]}),e.jsx("button",{onClick:()=>oe(!1),className:"w-7 h-7 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white transition-colors",children:e.jsx(qt,{className:"w-4 h-4"})})]})}),e.jsx("div",{className:"p-6",children:ae==="choose"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] text-[#64748b] mb-5 font-medium",children:"How would you like to proceed?"}),e.jsxs("button",{onClick:async()=>{oe(!1),le.info("Generating PDF report...");try{const{getExportPDFData:z}=await Cs(async()=>{const{getExportPDFData:Le}=await Promise.resolve().then(()=>om);return{getExportPDFData:Le}},void 0),de=await z(t.id),{default:E}=await Cs(async()=>{const{default:Le}=await import("./jspdf.es.min-CpWaCVL9.js").then(ft=>ft.j);return{default:Le}},__vite__mapDeps([12,0,1,2,3,4,5,6,7,8,9,10,11])),R=new E,ve=R.internal.pageSize.getWidth(),ee=20,Me=ve-ee*2;let K=20;const Xe=Le=>{K+Le>275&&(R.addPage(),K=20)},nt=()=>{R.setDrawColor(200,200,200),R.line(ee,K,ve-ee,K),K+=6},ke=(Le,ft=0)=>{const ut=R.splitTextToSize(Le,Me-ft);for(const Ft of ut)Xe(5),R.text(Ft,ee+ft,K),K+=5},jt=Le=>{Xe(16),K+=4,R.setFillColor(99,102,241),R.roundedRect(ee,K-4,Me,10,2,2,"F"),R.setTextColor(255,255,255),R.setFontSize(11),R.setFont("helvetica","bold"),R.text(Le,ee+4,K+3),R.setTextColor(0,0,0),K+=12};R.setFillColor(79,70,229),R.rect(0,0,ve,38,"F"),R.setTextColor(255,255,255),R.setFontSize(20),R.setFont("helvetica","bold"),R.text("MathPulse AI",ee,16),R.setFontSize(11),R.setFont("helvetica","normal"),R.text("Student Intervention Report",ee,24),R.setFontSize(9),R.text(`Generated: ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}`,ee,32),R.setTextColor(0,0,0),K=48,jt("Student Profile"),R.setFontSize(10),R.setFont("helvetica","normal");const Bt=[["Name",de.student_name],["Grade Level",de.grade_level||"N/A"],["Section",de.section||"N/A"],["Risk Level",de.risk_level],["Average Score",`${de.avg_score}%`],["Engagement",de.engagement_level],["Weakest Topic",ks(de.weakest_topic||"N/A")],["Last Active",de.last_active?new Date(de.last_active).toLocaleDateString():"Unknown"]];for(const[Le,ft]of Bt)Xe(6),R.setFont("helvetica","bold"),R.text(`${Le}:`,ee+2,K),R.setFont("helvetica","normal"),R.text(String(ft),ee+45,K),K+=6;if(K+=4,de.weak_topics?.length||Object.keys(de.accuracy_by_topic||{}).length){if(jt("Risk Assessment & Topic Analysis"),R.setFontSize(10),de.weak_topics?.length){R.setFont("helvetica","bold"),R.text("Weak Topics:",ee+2,K),K+=6,R.setFont("helvetica","normal");for(const ft of de.weak_topics)Xe(6),R.text(` • ${ks(ft)}`,ee+4,K),K+=5;K+=3}const Le=Object.entries(de.accuracy_by_topic||{});if(Le.length>0){R.setFont("helvetica","bold"),R.text("Topic Accuracy Breakdown:",ee+2,K),K+=7,R.setFontSize(9),R.setFont("helvetica","normal");for(const[ft,ut]of Le.sort(([,Ft],[,ss])=>Ft-ss)){Xe(7);const Ft=60,ss=ut/100*Ft;R.text(ft,ee+4,K),R.setFillColor(226,232,240),R.roundedRect(ee+70,K-3,Ft,4,1,1,"F"),R.setFillColor(ut>=70?34:ut>=50?245:239,ut>=70?197:ut>=50?158:68,ut>=70?94:ut>=50?11:68),ss>0&&R.roundedRect(ee+70,K-3,ss,4,1,1,"F"),R.text(`${Math.round(ut)}%`,ee+70+Ft+3,K),K+=7}K+=3}}if(jt("AI Analysis & Insights"),R.setFontSize(10),de.learning_strengths&&(R.setFont("helvetica","bold"),R.text("Learning Strengths:",ee+2,K),K+=6,R.setFont("helvetica","normal"),ke(de.learning_strengths,4),K+=4),de.next_steps_summary&&(R.setFont("helvetica","bold"),Xe(8),R.text("Recommended Next Steps:",ee+2,K),K+=6,R.setFont("helvetica","normal"),ke(de.next_steps_summary,4),K+=4),de.learning_path?.steps?.length){jt("Personalized Learning Path"),R.setFontSize(9),R.setFont("helvetica","italic"),R.text(`Estimated Duration: ${de.learning_path.estimated_duration_days} days | Primary Focus: ${ks(de.learning_path.primary_weak_topic)}`,ee+2,K),K+=8,R.setFont("helvetica","normal"),R.setFontSize(10);for(const Le of de.learning_path.steps){Xe(18),R.setFillColor(99,102,241),R.circle(ee+6,K,3,"F"),R.setTextColor(255,255,255),R.setFontSize(8),R.text(String(Le.step_number),ee+4.5,K+1.5),R.setTextColor(0,0,0),R.setFontSize(10),R.setFont("helvetica","bold"),R.text(ks(Le.title),ee+14,K+1),R.setFont("helvetica","normal"),R.setFontSize(9);const ft=`${Le.type.replace("_"," ")} • ${Le.duration_minutes} min • ${Le.difficulty}${Le.competency_tag?` • ${Le.competency_tag}`:""}`;if(R.setTextColor(100,116,139),R.text(ft,ee+14,K+6),R.setTextColor(0,0,0),K+=8,Le.description){R.setFontSize(9);const ut=R.splitTextToSize(Le.description,Me-16);for(const Ft of ut.slice(0,2))K+=5,Xe(5),R.text(Ft,ee+14,K)}K+=10}}if(de.teacher_recommendations?.length){jt("Teacher Recommendations"),R.setFontSize(10),R.setFont("helvetica","normal");for(let Le=0;Le{Je(!0),je("bank");try{const z=await Ni(s);Ke(z)}catch{Ke([])}finally{Je(!1)}},className:"w-full flex items-start gap-4 p-4 rounded-[16px] border border-slate-200 hover:border-[#a855f7] hover:shadow-[0_4px_12px_rgba(168,85,247,0.08)] hover:bg-purple-50/30 transition-all group mb-3 text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-[10px] bg-purple-50 border border-purple-100 flex items-center justify-center shrink-0 group-hover:bg-purple-100 transition-colors",children:e.jsx(ur,{className:"w-5 h-5 text-[#a855f7]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-bold text-[#1e293b] mb-0.5",children:"Choose from existing quizzes"}),e.jsx("p",{className:"text-[12px] text-[#64748b] font-medium",children:"Pick a quiz already in your Quiz Bank."})]})]}),e.jsxs("button",{onClick:()=>{oe(!1),Mt(!1),dt(!0)},className:"w-full flex items-start gap-4 p-4 rounded-[16px] border border-slate-200 hover:border-[#a855f7] hover:shadow-[0_4px_12px_rgba(168,85,247,0.08)] hover:bg-purple-50/30 transition-all group text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-[10px] bg-purple-50 border border-purple-100 flex items-center justify-center shrink-0 group-hover:bg-purple-100 transition-colors",children:e.jsx(bs,{className:"w-5 h-5 text-[#a855f7]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-bold text-[#1e293b] mb-0.5",children:"Create a new quiz"}),e.jsx("p",{className:"text-[12px] text-[#64748b] font-medium",children:"Use AI Quiz Maker. You can return here when done."})]})]})]}):e.jsx("div",{children:Ue?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-2 border-[#a855f7] border-t-transparent rounded-full animate-spin"}),e.jsx("p",{className:"text-[13px] text-[#64748b] font-medium",children:"Loading quizzes..."})]}):we.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 gap-3 text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-purple-50 flex items-center justify-center",children:e.jsx(ur,{className:"w-6 h-6 text-[#a855f7]"})}),e.jsx("p",{className:"text-[14px] font-semibold text-[#1e293b]",children:"No quizzes yet"}),e.jsx("p",{className:"text-[12px] text-[#64748b]",children:"Create your first quiz using the AI Quiz Maker."})]}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:we.map(z=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 rounded-[14px] border border-slate-200 hover:border-[#a855f7] hover:shadow-[0_2px_8px_rgba(168,85,247,0.08)] transition-all group",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[13px] font-bold text-[#1e293b] truncate",children:z.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] font-medium mt-0.5",children:[z.questions?.length??0," questions",z.gradeLevel?` · ${z.gradeLevel}`:"",z.metadata?.topicsCovered?.[0]?` · ${z.metadata.topicsCovered[0]}`:""]})]}),e.jsx("button",{onClick:()=>{oe(!1),le.success(`"${z.title}" selected for ${t.name}`)},className:"shrink-0 px-3 py-1.5 rounded-full bg-[#a855f7] text-white text-[11px] font-bold hover:bg-[#9333ea] transition-colors shadow-sm",children:"Assign"})]},z.id))})})})]})]}),document.body),ht&&Qr.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm",onClick:()=>{rt?It(!0):dt(!1)}}),e.jsxs("div",{className:"fixed top-0 right-0 z-[9999] h-full w-full max-w-[88vw] xl:max-w-[1080px] bg-white shadow-[-8px_0_40px_rgba(0,0,0,0.15)] flex flex-col",style:{animation:"slideInFromRight 0.3s cubic-bezier(0.16,1,0.3,1)"},children:[e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-slate-100 bg-white shrink-0",children:[e.jsxs("button",{onClick:()=>{rt?It(!0):dt(!1)},className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors bg-indigo-50 hover:bg-indigo-100 px-4 py-2 rounded-full",children:[e.jsx(cr,{className:"w-4 h-4"}),"Back to ",t.name]}),e.jsx("div",{className:"h-5 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-[8px] bg-gradient-to-br from-[#a855f7] to-[#9333ea] flex items-center justify-center",children:e.jsx(Xr,{className:"w-3.5 h-3.5 text-white"})}),e.jsx("span",{className:"text-[14px] font-bold text-[#1e293b]",children:"AI Quiz Maker"})]}),rt&&e.jsx("span",{className:"ml-auto text-[11px] font-semibold text-amber-600 bg-amber-50 border border-amber-200 px-2.5 py-0.5 rounded-full",children:"Quiz in progress"})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(bl,{onBack:()=>dt(!1),drawerMode:!0,gradeLevel:t.grade,onQuizGenerating:()=>Mt(!0),onQuizSaved:z=>{Mt(!1),le.success("Quiz saved! Close this panel or create another.",{action:{label:"Close Panel",onClick:()=>dt(!1)}})}})})]}),At&&e.jsxs("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4",children:[e.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:()=>It(!1)}),e.jsxs("div",{className:"relative bg-white rounded-[20px] shadow-[0_24px_60px_rgba(0,0,0,0.2)] w-full max-w-[380px] p-7 z-10",children:[e.jsx("div",{className:"w-11 h-11 rounded-full bg-amber-50 border border-amber-200 flex items-center justify-center mb-4",children:e.jsx(br,{className:"w-5 h-5 text-amber-500"})}),e.jsx("h3",{className:"text-[16px] font-bold text-[#1e293b] mb-2",children:"Discard quiz progress?"}),e.jsx("p",{className:"text-[13px] text-[#64748b] font-medium mb-6",children:"Your current quiz session will be lost if you close this panel. This cannot be undone."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>It(!1),className:"flex-1 py-2.5 rounded-full border border-slate-200 text-[13px] font-semibold text-[#475569] hover:bg-slate-50 transition-colors",children:"Keep editing"}),e.jsx("button",{onClick:()=>{It(!1),dt(!1),Mt(!1)},className:"flex-1 py-2.5 rounded-full bg-rose-500 hover:bg-rose-600 text-white text-[13px] font-semibold transition-colors",children:"Discard & close"})]})]})]}),e.jsx("style",{children:` +${de}`:E.learningPath;L(R)}catch{L("Unable to generate learning path. Please try again later."),fe("")}finally{W(!1)}})()},[t]);const js=u.useCallback(async()=>{ue(!0),B("");try{const z=t.classSectionId||Pt(f||"Grade 11",b||"Section A"),de=t.struggles.length>0?t.struggles[0]:t.weakestTopic,E=await Do({gradeLevel:f||t.grade||"Grade 11",subject:"general_math",quarter:1,moduleUnit:[f,b].filter(Boolean).join(" - ")||t.className,lessonTitle:`Grounded Lesson: ${de}`,learningCompetency:de,learnerLevel:t.avgScore<60?"support":t.avgScore<80?"developing":"advanced",classSectionId:z,className:[f,b].filter(Boolean).join(" - ")||t.className,focusTopics:t.struggles.length>0?t.struggles:[t.weakestTopic],topicCount:5,preferImportedTopics:m.lessonEnabled,allowReviewSources:Pe,allowUnverifiedLesson:se},!0);J(E),ce(E.curriculumSources||[]),Q(null),xt.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:z,className:[f,b].filter(Boolean).join(" - ")||t.className,metadata:{usedImportedTopics:E.usedImportedTopics,importedTopicCount:E.importedTopicCount,blockCount:E.blocks.length,publishReady:E.publishReady,sourceLegitimacyStatus:E.sourceLegitimacy.status,selfValidationPassed:E.selfValidation.passed,importGroundingEnabled:m.lessonEnabled}})}catch(z){let de=z instanceof Error?z.message:"Unable to generate lesson plan at this time.";if(z instanceof rr&&z.status===422)try{const R=JSON.parse(z.responseBody)?.detail;if(R?.selfValidation&&!se)try{const K=t.classSectionId||Pt(f||"Grade 11",b||"Section A"),Xe=t.struggles.length>0?t.struggles[0]:t.weakestTopic,nt=await Do({gradeLevel:f||t.grade||"Grade 11",subject:"general_math",quarter:1,moduleUnit:[f,b].filter(Boolean).join(" - ")||t.className,lessonTitle:`Grounded Lesson: ${Xe}`,learningCompetency:Xe,learnerLevel:t.avgScore<60?"support":t.avgScore<80?"developing":"advanced",classSectionId:K,className:[f,b].filter(Boolean).join(" - ")||t.className,focusTopics:t.struggles.length>0?t.struggles:[t.weakestTopic],topicCount:5,preferImportedTopics:m.lessonEnabled,allowReviewSources:Pe,allowUnverifiedLesson:!0},!0);J(nt),ce(nt.curriculumSources||[]),Q(null),B("");return}catch{}R?.message&&(de=R.message);const ve=R?.sourceLegitimacy?.issues||[],ee=R?.selfValidation?.issues||[],Me=[...ve,...ee].filter(Boolean).slice(0,3);Me.length>0&&(de=`${de} ${Me.join(" ")}`)}catch{}B(de),J(null),ce([]),xt.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:t.classSectionId||Pt(f||"Grade 11",b||"Section A"),className:[f,b].filter(Boolean).join(" - ")||t.className,metadata:{error:de,allowReviewSources:Pe,allowUnverifiedLesson:se,importGroundingEnabled:m.lessonEnabled}})}finally{ue(!1)}},[t,f,b,m.lessonEnabled,Pe,se]),Kt=u.useCallback(async()=>{if(!D)return le.error("Generate a lesson plan first."),null;$(!0);try{const z=await pm(D,s,{teacherName:a,studentId:t.id,studentName:t.name});return Q(z),le.success("Lesson plan saved as draft."),z}catch(z){return console.error("Failed to save lesson draft:",z),le.error(z instanceof Error?z.message:"Failed to save lesson draft."),null}finally{$(!1)}},[D,s,a,t.id,t.name]),Gs=u.useCallback(async()=>{if(!D){le.error("Generate a lesson plan first.");return}if(!D.publishReady){const z=[...D.sourceLegitimacy.issues,...D.selfValidation.issues].filter(Boolean).slice(0,2).join(" ");le.error(z||"Lesson is not publish-ready. Resolve legitimacy and validation checks first.");return}T(!0);try{let z=q;if(z||(z=await Kt()),!z)return;await hm(z),le.success("Lesson plan published to class content."),xt.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:D.classSectionId||t.classSectionId,className:D.className||t.className,metadata:{action:"publish_lesson_plan",lessonPlanId:z,publishReady:D.publishReady,sourceLegitimacyStatus:D.sourceLegitimacy.status,selfValidationPassed:D.selfValidation.passed}})}catch(z){console.error("Failed to publish lesson plan:",z),le.error(z instanceof Error?z.message:"Failed to publish lesson plan."),xt.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:D.classSectionId||t.classSectionId,className:D.className||t.className,metadata:{action:"publish_lesson_plan",error:z instanceof Error?z.message:"Failed to publish lesson plan."}})}finally{T(!1)}},[D,q,Kt,t.className,t.classSectionId]);u.useEffect(()=>{js()},[_]),u.useEffect(()=>{V(z=>z+1)},[t.id]),u.useEffect(()=>{ne("all"),Fe("all")},[D]),u.useMemo(()=>D?Array.from(new Set(D.blocks.map(z=>z.provenance?.sourceFile?.trim()).filter(z=>!!z))).sort((z,de)=>z.localeCompare(de)):[],[D]),u.useMemo(()=>D?Array.from(new Set(D.blocks.map(z=>z.provenance?.materialId?.trim()).filter(z=>!!z))).sort((z,de)=>z.localeCompare(de)):[],[D]);const Es=u.useMemo(()=>D?D.blocks.filter(z=>{const de=te==="all"||(z.provenance?.sourceFile||"").trim()===te,E=ze==="all"||(z.provenance?.materialId||"").trim()===ze;return de&&E}):[],[D,te,ze]),Rs=u.useMemo(()=>p?.learning_path?.steps?.length?p.learning_path.steps.map(z=>({id:z.step_number,type:z.type==="video_lesson"?"video":z.type==="assessment"?"assessment":"quiz",title:z.title,duration:`${z.duration_minutes} mins`,questions:z.num_items||void 0,icon:z.type==="video_lesson"?Za:z.type==="assessment"?Sa:z.type==="review"?xs:qr,competency:z.competency_tag,difficulty:z.difficulty,is_completed:z.is_completed})):[{id:1,type:"video",title:`${t.weakestTopic} Fundamentals`,duration:"8 mins",questions:void 0,icon:Za,competency:"",difficulty:"easy",is_completed:!1},{id:2,type:"quiz",title:`${t.weakestTopic} Practice`,duration:"12 mins",questions:10,icon:qr,competency:"",difficulty:"easy",is_completed:!1},{id:3,type:"assessment",title:"Final Check",duration:"10 mins",questions:5,icon:Sa,competency:"",difficulty:"medium",is_completed:!1}],[p,t.weakestTopic]),Ge=async()=>{if(!s){le.error("Unable to update section: teacher context missing");return}k(!0);try{await yr(t.id,f,b,s,new Date().getFullYear().toString(),a),await ll(t.id,f,b);const z={...t,grade:f,section:b,className:[f,b].filter(Boolean).join(" - "),classSectionId:Pt(f,b)};r(z),le.success("Student section assignment updated")}catch(z){console.error("Failed to update student section assignment:",z),le.error("Failed to update section assignment")}finally{k(!1)}};return e.jsxs(Re.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"w-full h-full flex overflow-hidden relative",children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-[24px] xl:p-[32px] no-scrollbar",children:e.jsxs("div",{className:"max-w-[1000px] mx-auto space-y-[24px]",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-[8px]",children:e.jsx("div",{children:e.jsxs("button",{onClick:o,className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors bg-white/60 hover:bg-white/80 px-[18px] py-2 rounded-full backdrop-blur-[12px] mb-[16px] w-max shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white/50",children:[e.jsx(cr,{className:"w-4 h-4"}),"Back to Analytics"]})})}),e.jsxs("div",{className:"bg-gradient-to-br from-[#ecfdf5] via-[#f0fdf4] to-[#f7fdf9] backdrop-blur-[12px] rounded-[20px] p-[24px] border border-emerald-100 shadow-[0_4px_16px_rgba(16,185,129,0.08)] relative overflow-hidden",children:[e.jsx("div",{className:"absolute right-[-20px] bottom-[-20px] opacity-[0.06] pointer-events-none",children:e.jsx(Pn,{className:"w-48 h-48 text-emerald-600"})}),e.jsxs("div",{className:"flex items-center gap-3 mb-5 relative z-10",children:[e.jsx("div",{className:"w-10 h-10 rounded-[12px] bg-gradient-to-br from-[#059669] to-[#10b981] flex items-center justify-center shrink-0 shadow-[0_4px_10px_rgba(5,150,105,0.3)]",children:e.jsx(Pn,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-[15px] font-bold text-[#1e293b]",children:"AI Analysis"}),e.jsxs("span",{className:"flex items-center gap-1 px-2.5 py-0.5 bg-emerald-500 text-white text-[10px] font-bold rounded-full uppercase tracking-wider shadow-sm",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse"}),"Insights Active"]})]})]}),ie&&e.jsx($o,{sources:re,className:"mb-4 relative z-10"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 w-full relative z-10",children:[e.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-[14px] p-4 border border-emerald-100/60 shadow-[0_1px_4px_rgba(0,0,0,0.04)] relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 w-1 h-full bg-emerald-400 rounded-l-[14px]"}),e.jsxs("h4",{className:"text-[11px] font-bold text-emerald-600 uppercase tracking-wider mb-2.5 flex items-center gap-1.5 pl-2",children:[e.jsx(ca,{className:"w-3.5 h-3.5"})," Learning Strengths"]}),e.jsx("p",{className:"text-[13px] text-[#475569] leading-relaxed pl-2",children:p?.learning_strengths||(d?e.jsx(e.Fragment,{children:"Demonstrates engagement but faces challenges. Needs support with foundational topics."}):e.jsxs(e.Fragment,{children:["Excels in ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:t.weakestTopic}),". Demonstrates high engagement during interactive tests."]}))})]}),e.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-[14px] p-4 border border-rose-100/60 shadow-[0_1px_4px_rgba(0,0,0,0.04)] relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 w-1 h-full bg-rose-400 rounded-l-[14px]"}),e.jsxs("h4",{className:"text-[11px] font-bold text-rose-500 uppercase tracking-wider mb-2.5 flex items-center gap-1.5 pl-2",children:[e.jsx(fs,{className:"w-3.5 h-3.5"})," Next Steps"]}),e.jsx("ul",{className:"text-[13px] text-[#475569] leading-relaxed list-none p-0 m-0 space-y-1 pl-2",children:p?.next_steps_summary?e.jsx("li",{children:p.next_steps_summary}):t.struggles.length>0?t.struggles.map((z,de)=>e.jsxs("li",{children:["Must continue strengthening ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:z}),"."]},de)):e.jsxs("li",{children:["Focus on repetitive practice modules for ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:t.weakestTopic}),"."]})})]})]})]}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-[12px] rounded-[18px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6 border-b border-[#f1f5f9] pb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Generated Learning Path"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{disabled:!p?.learning_path,onClick:async()=>{if(p)try{if(S){const z=await fl(t.id);N(!1),le.success(`Revoked ${z} assigned module(s) from ${t.name}.`)}else await pl(p,s),N(!0),le.success(`Learning path assigned to ${t.name}'s modules.`)}catch(z){console.error("[InterventionView] Action failed:",z),le.error(S?"Failed to revoke.":"Failed to assign learning path.")}},className:`${S?"bg-rose-50 hover:bg-rose-100 text-rose-700 border-rose-200":"bg-emerald-50 hover:bg-emerald-100 text-emerald-700 border-emerald-200"} border text-[11px] font-semibold rounded-full px-4 py-1.5 transition-colors shadow-[0_1px_4px_rgba(0,0,0,0.02)] flex items-center gap-1.5 disabled:opacity-50`,children:S?e.jsxs(e.Fragment,{children:[e.jsx(qt,{className:"w-3 h-3"})," Revoke"]}):e.jsxs(e.Fragment,{children:[e.jsx(ra,{className:"w-3 h-3"})," Assign to Student"]})}),e.jsxs("button",{disabled:A||v,onClick:async()=>{y(!0);try{const z=await xl(t.id);h(z)}catch(z){console.warn("[InterventionView] Regenerate failed:",z)}finally{y(!1)}V(z=>z+1)},className:"bg-[#f8fafc] hover:bg-white text-[#4f46e5] border border-[#e0e7ff] text-[11px] font-semibold rounded-full px-4 py-1.5 transition-colors shadow-[0_1px_4px_rgba(0,0,0,0.02)] flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(xs,{className:`w-3 h-3 ${v?"animate-spin":""}`})," ",v?"Analyzing...":"Regenerate"]})]})]}),e.jsxs(Mo,{name:"teacher-intervention-learning-path",loading:!1,fixture:null,fallback:null,children:[e.jsxs("div",{className:"mb-8 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mr-2",children:"Methodology:"}),(p?.learning_path?.methodology_tags||["Interactive","Video","Practice","Quiz"]).map(z=>e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:z},z))]}),e.jsx("div",{className:"relative border-l-2 border-[#e2e8f0] ml-[20px] space-y-[28px] pb-4",children:Rs.map((z,de)=>{let E=e.jsx(Za,{className:"w-4 h-4"}),R="bg-[#8b5cf6] shadow-[0_4px_10px_rgba(139,92,246,0.3)]",ve="text-purple-600",ee="group-hover:border-purple-200",Me="hover:bg-[#4f46e5]",K=e.jsx(xc,{className:"w-4 h-4 ml-0.5"});return z.type==="quiz"?(E=e.jsx(ir,{className:"w-4 h-4"}),R="bg-sky-500 shadow-[0_4px_10px_rgba(14,165,233,0.3)]",ve="text-sky-600",ee="group-hover:border-sky-200",Me="hover:bg-sky-500",K=e.jsx(zs,{className:"w-4 h-4"})):z.type==="assessment"&&(E=e.jsx(Sa,{className:"w-4 h-4"}),R="bg-emerald-500 shadow-[0_4px_10px_rgba(16,185,129,0.3)]",ve="text-emerald-600",ee="group-hover:bg-emerald-50"),e.jsxs(Re.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:de*.1},className:"relative pl-[32px] group",children:[e.jsx("div",{className:`absolute -left-[17px] top-1 w-8 h-8 rounded-full ${R} text-white flex items-center justify-center ring-4 ring-white group-hover:scale-110 transition-transform`,children:E}),e.jsxs("div",{onClick:()=>{p?.learning_path?.steps?.[de]&&g(p.learning_path.steps[de])},className:`${z.type==="assessment"?"bg-emerald-50/50 border-emerald-100":"bg-white border-[#f1f5f9]"} rounded-[14px] p-[18px] border shadow-[0_1px_4px_rgba(0,0,0,0.04)] flex justify-between items-center transition-colors cursor-pointer ${ee}`,children:[e.jsxs("div",{children:[e.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wider mb-1 block ${ve}`,children:["Step ",de+1," • ",z.type==="video"?"Video Lesson":z.type==="quiz"?"Practice":"Assessment"]}),e.jsx("p",{className:"font-semibold text-[#1e293b] text-[13px] mb-0.5",children:ks(z.title)}),e.jsxs("p",{className:"text-[#64748b] text-[11px] flex items-center gap-1.5",children:[z.type==="video"&&e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"w-3 h-3"})," ",z.duration]}),z.type==="quiz"&&e.jsxs(e.Fragment,{children:[e.jsx(ki,{className:"w-3 h-3"})," ",z.questions?`${z.questions} questions`:z.duration]}),z.type==="assessment"&&e.jsxs(e.Fragment,{children:[e.jsx(fs,{className:"w-3 h-3"})," ",z.questions?`${z.questions} assessment questions`:z.duration]}),z.competency&&e.jsx("span",{className:"ml-2 px-1.5 py-0.5 bg-indigo-50 text-indigo-600 text-[9px] font-mono rounded",children:z.competency})]})]}),z.type==="assessment"?e.jsx(hi,{className:"w-6 h-6 text-emerald-400"}):e.jsx("button",{className:`w-8 h-8 rounded-full bg-[#f8fafc] flex items-center justify-center text-[#64748b] ${Me} hover:text-white transition-colors border border-[#e2e8f0]`,children:K})]})]},z.id)})})]})]}),e.jsxs("div",{className:"relative bg-white/80 backdrop-blur-[12px] rounded-[18px] p-[24px] shadow-[0_1px_4px_rgba(0,0,0,0.04)] border border-white overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 z-10 bg-white/70 backdrop-blur-[2px] flex items-center justify-center rounded-[18px]",children:e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"inline-block px-4 py-2 bg-slate-100 border border-slate-200 rounded-full text-[13px] font-semibold text-slate-500",children:"🔒 Coming Soon"}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-2",children:"This feature is temporarily locked."})]})}),e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Targeted Lesson Generation"}),e.jsx(wt,{onClick:()=>V(z=>z+1),disabled:Ce,className:"bg-[#4f46e5] hover:bg-[#3730a3] text-white h-8 text-[11px] rounded-full px-4",children:Ce?"Loading...":"Regenerate"})]}),e.jsx("p",{className:"text-[13px] text-[#64748b] mb-6",children:"Configure inputs and requirements for AI lesson generation."}),e.jsxs("div",{className:"bg-[#f8fafc]/80 rounded-[14px] p-[20px] border border-[#f1f5f9] mb-6",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx(oa,{className:"w-4 h-4 text-[#4f46e5] shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-[13px] text-[#475569] leading-relaxed",children:["Class records alone are not enough for import-grounded lesson plans. Ensure course materials are uploaded via ",e.jsx("span",{className:"text-[#4f46e5] font-semibold",children:"Data Import"}),"."]})]}),e.jsxs("div",{className:"space-y-4 border-t border-[#e2e8f0] pt-5 mt-5",children:[e.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[e.jsx("span",{className:"text-[13px] font-medium text-[#1e293b] group-hover:text-[#4f46e5] transition-colors",children:"Allow sources requiring manual review"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:Pe,onChange:z=>G(z.target.checked)}),e.jsx("div",{className:"w-10 h-5 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#4f46e5]"})]})]}),e.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[e.jsx("span",{className:"text-[13px] font-medium text-[#1e293b] group-hover:text-[#4f46e5] transition-colors",children:"Allow unverified lesson draft"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:se,onChange:z=>M(z.target.checked)}),e.jsx("div",{className:"w-10 h-5 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#4f46e5]"})]})]})]})]}),e.jsxs(Mo,{name:"teacher-intervention-lesson-plan",loading:!1,fixture:null,fallback:null,children:[ge&&e.jsx("div",{className:"bg-[#FF8B8B]/14 border border-[#FF8B8B]/35 rounded-xl p-3 text-sm text-[#D66A6A] mb-4",children:ge}),D&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-[#f8fafc] border border-[#f1f5f9] rounded-[14px] p-5 shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("div",{className:"mb-3",children:e.jsx($o,{sources:re})}),e.jsx("p",{className:"text-[14px] font-semibold text-[#1e293b]",children:D.lessonTitle}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-2 mt-2",children:[e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:[e.jsx("span",{className:"font-semibold text-[#475569]",children:"Imported topics:"})," ",D.usedImportedTopics?"Yes":"No"," (",D.importedTopicCount,")"]}),e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:[e.jsx("span",{className:"font-semibold text-[#475569]",children:"Subject:"})," ",D.subject||"General Math"," (Q",D.quarter||1,")"]})]}),D.curriculumCompetency&&e.jsxs("p",{className:"text-[11px] text-[#4f46e5] font-semibold mt-2 bg-indigo-50/50 px-2 py-1 rounded inline-block",children:["Competency: ",D.curriculumCompetency]}),e.jsx("div",{className:"mt-3 flex items-center justify-between",children:e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:["Publish readiness: ",e.jsx("span",{className:`font-semibold ${D.publishReady?"text-emerald-600":"text-rose-500"}`,children:D.publishReady?"Ready":"Blocked"})]})}),D.warnings.length>0&&e.jsx("p",{className:"text-[11px] text-amber-600 mt-2 bg-amber-50 px-2 py-1.5 rounded",children:D.warnings.join(" ")})]}),D.lessonObjective&&e.jsxs("div",{className:"bg-white border border-[#e2e8f0] rounded-[14px] p-4 shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("p",{className:"text-[10px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5",children:"Lesson objective"}),e.jsx("p",{className:"text-[13px] text-[#1e293b]",children:D.lessonObjective})]}),D.realWorldHook&&e.jsxs("div",{className:"bg-indigo-50/50 border border-indigo-100 rounded-[14px] p-4 shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("p",{className:"text-[10px] font-semibold text-[#4f46e5] uppercase tracking-wider mb-1.5",children:"Real-life application"}),e.jsx("p",{className:"text-[13px] text-[#1e293b]",children:D.realWorldHook})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 mt-4",children:Es.map(z=>e.jsxs("div",{className:"border border-[#e2e8f0] rounded-[14px] p-4 bg-white shadow-[0_1px_4px_rgba(0,0,0,0.02)]",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[#1e293b]",children:z.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] mt-1",children:[z.estimatedMinutes," mins "," • "," ",z.strategy]}),e.jsx("p",{className:"text-[12px] text-[#475569] mt-2 bg-[#f8fafc] p-2 rounded-lg",children:z.objective}),e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-[10px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5",children:"Activities"}),z.activities.slice(0,2).map((de,E)=>e.jsxs("p",{className:"text-[11px] text-[#475569] mb-1 flex items-start gap-1",children:[e.jsx("span",{className:"text-[#94a3b8] mt-0.5",children:"•"})," ",e.jsx("span",{children:de})]},E))]})]},z.blockId))}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-4",children:[e.jsx(wt,{variant:"outline",onClick:()=>void Kt(),disabled:pe||!D,className:"border-[#cbd5e1] text-[#475569] hover:bg-[#f8fafc] text-[12px] h-9 rounded-full px-5",children:pe?e.jsx(Un,{className:"h-4 w-16"}):"Save Draft"}),e.jsx(wt,{onClick:()=>void Gs(),disabled:j||!D||!D.publishReady,className:"bg-[#10b981] hover:bg-[#059669] text-white text-[12px] h-9 rounded-full px-5",children:j?e.jsx(Un,{className:"h-4 w-24 bg-white/35"}):"Publish Lesson Plan"})]})]})]})]})]})}),e.jsx("aside",{className:"w-[320px] 2xl:w-[340px] bg-white/70 backdrop-blur-[24px] border-l border-white shadow-[-4px_0_24px_rgba(0,0,0,0.02)] flex flex-col h-full shrink-0 overflow-y-auto z-10 no-scrollbar relative",children:e.jsxs("div",{className:"p-[24px] space-y-[24px] flex flex-col items-center",children:[e.jsxs("div",{className:"flex flex-col items-center text-center w-full",children:[e.jsx("img",{src:t.avatar,alt:t.name,className:"w-[96px] h-[96px] rounded-full object-cover shadow-[0_8px_16px_rgba(0,0,0,0.1)] mb-4 border-4 border-white z-10 relative"}),e.jsx("h2",{className:"text-[20px] font-semibold text-[#1e293b] mb-1",children:t.name}),e.jsxs("p",{className:"text-[11px] font-semibold text-[#64748b] mb-3 uppercase tracking-wider",children:["ID: ",t.id.substring(0,8)]}),e.jsx("span",{className:`text-[11px] font-semibold px-3 py-1 rounded-[14px] border ${(p?.risk_level||"").includes("Critical")?"text-red-700 bg-red-50 border-red-200 animate-pulse":t.riskLevel==="high"||(p?.risk_level||"").includes("High")?"text-rose-600 bg-rose-50 border-rose-100":t.riskLevel==="medium"||(p?.risk_level||"").includes("Medium")?"text-amber-600 bg-amber-50 border-amber-100":"text-emerald-600 bg-emerald-50 border-emerald-100"}`,children:p?.risk_level||(t.riskLevel==="high"?"High Risk":t.riskLevel==="medium"?"Medium Risk":"Low Risk")})]}),e.jsxs("div",{className:"w-full grid grid-cols-2 gap-[12px]",children:[e.jsxs("div",{className:"bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Avg Score"}),e.jsxs("p",{className:"text-[20px] font-bold text-[#4f46e5]",children:[p?.avg_score||cs||t.avgScore,"%"]})]}),e.jsxs("div",{className:"bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Engagement"}),e.jsx("p",{className:"text-[20px] font-bold text-[#1e293b]",children:p?.engagement_level||((cs||t.avgScore)>80?"High":(cs||t.avgScore)>50?"Medium":"Low")})]}),e.jsxs("div",{className:"bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1",children:"Last Active"}),e.jsx("p",{className:"text-[13px] font-semibold text-[#1e293b] mt-1",children:p?.last_active?new Date(p.last_active).toLocaleDateString():t.lastActive})]}),e.jsxs("div",{className:"bg-rose-50/60 rounded-[14px] p-4 border border-rose-100 text-left flex flex-col justify-center",children:[e.jsx("p",{className:"text-[11px] font-semibold text-rose-600 uppercase tracking-wider mb-1",children:"Weakest Topic"}),e.jsx("p",{className:"text-[12px] font-semibold text-[#1e293b] mt-1 leading-snug break-words",title:p?.weakest_topic||t.weakestTopic,children:ks(p?.weakest_topic||t.weakestTopic||"")})]})]}),Yt&&Yt.total>0&&e.jsxs("div",{className:"w-full bg-white/80 rounded-[14px] p-4 border border-white shadow-[0_1px_4px_rgba(0,0,0,0.02)] flex items-center gap-3",children:[e.jsx(Bc,{size:18,className:Yt.completed===Yt.total?"text-emerald-500":"text-slate-400"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider",children:"Modules Completed"}),e.jsxs("p",{className:"text-[16px] font-bold text-[#1e293b]",children:[Yt.completed,"/",Yt.total]})]})]}),e.jsx("div",{className:"w-full flex flex-col gap-[10px]",children:e.jsxs("button",{onClick:async()=>{je("choose"),oe(!0)},className:"w-full flex items-center justify-center gap-2 bg-white hover:bg-[#f8fafc] text-[#475569] border border-[#cbd5e1] hover:border-[#94a3b8] text-[13px] font-semibold rounded-full px-4 py-3 shadow-[0_1px_4px_rgba(0,0,0,0.04)] transition-transform hover:scale-[1.02]",children:[e.jsx(ao,{className:"w-4 h-4"})," Export Materials"]})}),me&&Qr.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center p-4",onClick:()=>oe(!1),children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white rounded-[24px] shadow-[0_24px_64px_rgba(0,0,0,0.18)] w-full max-w-[460px] z-10 overflow-hidden",onClick:z=>z.stopPropagation(),children:[e.jsx("div",{className:"bg-gradient-to-r from-[#a855f7] to-[#9333ea] px-6 pt-5 pb-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ae==="bank"&&e.jsx("button",{onClick:()=>je("choose"),className:"w-7 h-7 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white transition-colors mr-1",children:e.jsx($s,{className:"w-4 h-4"})}),e.jsx("div",{className:"w-8 h-8 rounded-[8px] bg-white/20 flex items-center justify-center",children:e.jsx(Xr,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-bold text-white leading-tight",children:ae==="choose"?"Export Materials":"Choose a Quiz"}),e.jsx("p",{className:"text-[11px] text-white/70 font-medium",children:ae==="choose"?`For ${t.name}`:"Select a quiz from your bank"})]})]}),e.jsx("button",{onClick:()=>oe(!1),className:"w-7 h-7 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white transition-colors",children:e.jsx(qt,{className:"w-4 h-4"})})]})}),e.jsx("div",{className:"p-6",children:ae==="choose"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] text-[#64748b] mb-5 font-medium",children:"How would you like to proceed?"}),e.jsxs("button",{onClick:async()=>{oe(!1),le.info("Generating PDF report...");try{const{getExportPDFData:z}=await Cs(async()=>{const{getExportPDFData:Le}=await Promise.resolve().then(()=>om);return{getExportPDFData:Le}},void 0),de=await z(t.id),{default:E}=await Cs(async()=>{const{default:Le}=await import("./jspdf.es.min-CwsrHLQV.js").then(ft=>ft.j);return{default:Le}},__vite__mapDeps([12,0,1,2,3,4,5,6,7,8,9,10,11])),R=new E,ve=R.internal.pageSize.getWidth(),ee=20,Me=ve-ee*2;let K=20;const Xe=Le=>{K+Le>275&&(R.addPage(),K=20)},nt=()=>{R.setDrawColor(200,200,200),R.line(ee,K,ve-ee,K),K+=6},ke=(Le,ft=0)=>{const ut=R.splitTextToSize(Le,Me-ft);for(const Ft of ut)Xe(5),R.text(Ft,ee+ft,K),K+=5},jt=Le=>{Xe(16),K+=4,R.setFillColor(99,102,241),R.roundedRect(ee,K-4,Me,10,2,2,"F"),R.setTextColor(255,255,255),R.setFontSize(11),R.setFont("helvetica","bold"),R.text(Le,ee+4,K+3),R.setTextColor(0,0,0),K+=12};R.setFillColor(79,70,229),R.rect(0,0,ve,38,"F"),R.setTextColor(255,255,255),R.setFontSize(20),R.setFont("helvetica","bold"),R.text("MathPulse AI",ee,16),R.setFontSize(11),R.setFont("helvetica","normal"),R.text("Student Intervention Report",ee,24),R.setFontSize(9),R.text(`Generated: ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}`,ee,32),R.setTextColor(0,0,0),K=48,jt("Student Profile"),R.setFontSize(10),R.setFont("helvetica","normal");const Bt=[["Name",de.student_name],["Grade Level",de.grade_level||"N/A"],["Section",de.section||"N/A"],["Risk Level",de.risk_level],["Average Score",`${de.avg_score}%`],["Engagement",de.engagement_level],["Weakest Topic",ks(de.weakest_topic||"N/A")],["Last Active",de.last_active?new Date(de.last_active).toLocaleDateString():"Unknown"]];for(const[Le,ft]of Bt)Xe(6),R.setFont("helvetica","bold"),R.text(`${Le}:`,ee+2,K),R.setFont("helvetica","normal"),R.text(String(ft),ee+45,K),K+=6;if(K+=4,de.weak_topics?.length||Object.keys(de.accuracy_by_topic||{}).length){if(jt("Risk Assessment & Topic Analysis"),R.setFontSize(10),de.weak_topics?.length){R.setFont("helvetica","bold"),R.text("Weak Topics:",ee+2,K),K+=6,R.setFont("helvetica","normal");for(const ft of de.weak_topics)Xe(6),R.text(` • ${ks(ft)}`,ee+4,K),K+=5;K+=3}const Le=Object.entries(de.accuracy_by_topic||{});if(Le.length>0){R.setFont("helvetica","bold"),R.text("Topic Accuracy Breakdown:",ee+2,K),K+=7,R.setFontSize(9),R.setFont("helvetica","normal");for(const[ft,ut]of Le.sort(([,Ft],[,ss])=>Ft-ss)){Xe(7);const Ft=60,ss=ut/100*Ft;R.text(ft,ee+4,K),R.setFillColor(226,232,240),R.roundedRect(ee+70,K-3,Ft,4,1,1,"F"),R.setFillColor(ut>=70?34:ut>=50?245:239,ut>=70?197:ut>=50?158:68,ut>=70?94:ut>=50?11:68),ss>0&&R.roundedRect(ee+70,K-3,ss,4,1,1,"F"),R.text(`${Math.round(ut)}%`,ee+70+Ft+3,K),K+=7}K+=3}}if(jt("AI Analysis & Insights"),R.setFontSize(10),de.learning_strengths&&(R.setFont("helvetica","bold"),R.text("Learning Strengths:",ee+2,K),K+=6,R.setFont("helvetica","normal"),ke(de.learning_strengths,4),K+=4),de.next_steps_summary&&(R.setFont("helvetica","bold"),Xe(8),R.text("Recommended Next Steps:",ee+2,K),K+=6,R.setFont("helvetica","normal"),ke(de.next_steps_summary,4),K+=4),de.learning_path?.steps?.length){jt("Personalized Learning Path"),R.setFontSize(9),R.setFont("helvetica","italic"),R.text(`Estimated Duration: ${de.learning_path.estimated_duration_days} days | Primary Focus: ${ks(de.learning_path.primary_weak_topic)}`,ee+2,K),K+=8,R.setFont("helvetica","normal"),R.setFontSize(10);for(const Le of de.learning_path.steps){Xe(18),R.setFillColor(99,102,241),R.circle(ee+6,K,3,"F"),R.setTextColor(255,255,255),R.setFontSize(8),R.text(String(Le.step_number),ee+4.5,K+1.5),R.setTextColor(0,0,0),R.setFontSize(10),R.setFont("helvetica","bold"),R.text(ks(Le.title),ee+14,K+1),R.setFont("helvetica","normal"),R.setFontSize(9);const ft=`${Le.type.replace("_"," ")} • ${Le.duration_minutes} min • ${Le.difficulty}${Le.competency_tag?` • ${Le.competency_tag}`:""}`;if(R.setTextColor(100,116,139),R.text(ft,ee+14,K+6),R.setTextColor(0,0,0),K+=8,Le.description){R.setFontSize(9);const ut=R.splitTextToSize(Le.description,Me-16);for(const Ft of ut.slice(0,2))K+=5,Xe(5),R.text(Ft,ee+14,K)}K+=10}}if(de.teacher_recommendations?.length){jt("Teacher Recommendations"),R.setFontSize(10),R.setFont("helvetica","normal");for(let Le=0;Le{Je(!0),je("bank");try{const z=await Ni(s);Ke(z)}catch{Ke([])}finally{Je(!1)}},className:"w-full flex items-start gap-4 p-4 rounded-[16px] border border-slate-200 hover:border-[#a855f7] hover:shadow-[0_4px_12px_rgba(168,85,247,0.08)] hover:bg-purple-50/30 transition-all group mb-3 text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-[10px] bg-purple-50 border border-purple-100 flex items-center justify-center shrink-0 group-hover:bg-purple-100 transition-colors",children:e.jsx(ur,{className:"w-5 h-5 text-[#a855f7]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-bold text-[#1e293b] mb-0.5",children:"Choose from existing quizzes"}),e.jsx("p",{className:"text-[12px] text-[#64748b] font-medium",children:"Pick a quiz already in your Quiz Bank."})]})]}),e.jsxs("button",{onClick:()=>{oe(!1),Mt(!1),dt(!0)},className:"w-full flex items-start gap-4 p-4 rounded-[16px] border border-slate-200 hover:border-[#a855f7] hover:shadow-[0_4px_12px_rgba(168,85,247,0.08)] hover:bg-purple-50/30 transition-all group text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-[10px] bg-purple-50 border border-purple-100 flex items-center justify-center shrink-0 group-hover:bg-purple-100 transition-colors",children:e.jsx(bs,{className:"w-5 h-5 text-[#a855f7]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-bold text-[#1e293b] mb-0.5",children:"Create a new quiz"}),e.jsx("p",{className:"text-[12px] text-[#64748b] font-medium",children:"Use AI Quiz Maker. You can return here when done."})]})]})]}):e.jsx("div",{children:Ue?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-2 border-[#a855f7] border-t-transparent rounded-full animate-spin"}),e.jsx("p",{className:"text-[13px] text-[#64748b] font-medium",children:"Loading quizzes..."})]}):we.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 gap-3 text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-purple-50 flex items-center justify-center",children:e.jsx(ur,{className:"w-6 h-6 text-[#a855f7]"})}),e.jsx("p",{className:"text-[14px] font-semibold text-[#1e293b]",children:"No quizzes yet"}),e.jsx("p",{className:"text-[12px] text-[#64748b]",children:"Create your first quiz using the AI Quiz Maker."})]}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:we.map(z=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 rounded-[14px] border border-slate-200 hover:border-[#a855f7] hover:shadow-[0_2px_8px_rgba(168,85,247,0.08)] transition-all group",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[13px] font-bold text-[#1e293b] truncate",children:z.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] font-medium mt-0.5",children:[z.questions?.length??0," questions",z.gradeLevel?` · ${z.gradeLevel}`:"",z.metadata?.topicsCovered?.[0]?` · ${z.metadata.topicsCovered[0]}`:""]})]}),e.jsx("button",{onClick:()=>{oe(!1),le.success(`"${z.title}" selected for ${t.name}`)},className:"shrink-0 px-3 py-1.5 rounded-full bg-[#a855f7] text-white text-[11px] font-bold hover:bg-[#9333ea] transition-colors shadow-sm",children:"Assign"})]},z.id))})})})]})]}),document.body),ht&&Qr.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm",onClick:()=>{rt?It(!0):dt(!1)}}),e.jsxs("div",{className:"fixed top-0 right-0 z-[9999] h-full w-full max-w-[88vw] xl:max-w-[1080px] bg-white shadow-[-8px_0_40px_rgba(0,0,0,0.15)] flex flex-col",style:{animation:"slideInFromRight 0.3s cubic-bezier(0.16,1,0.3,1)"},children:[e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-slate-100 bg-white shrink-0",children:[e.jsxs("button",{onClick:()=>{rt?It(!0):dt(!1)},className:"flex items-center gap-2 text-[13px] font-semibold text-[#4f46e5] hover:text-[#3730a3] transition-colors bg-indigo-50 hover:bg-indigo-100 px-4 py-2 rounded-full",children:[e.jsx(cr,{className:"w-4 h-4"}),"Back to ",t.name]}),e.jsx("div",{className:"h-5 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-[8px] bg-gradient-to-br from-[#a855f7] to-[#9333ea] flex items-center justify-center",children:e.jsx(Xr,{className:"w-3.5 h-3.5 text-white"})}),e.jsx("span",{className:"text-[14px] font-bold text-[#1e293b]",children:"AI Quiz Maker"})]}),rt&&e.jsx("span",{className:"ml-auto text-[11px] font-semibold text-amber-600 bg-amber-50 border border-amber-200 px-2.5 py-0.5 rounded-full",children:"Quiz in progress"})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(bl,{onBack:()=>dt(!1),drawerMode:!0,gradeLevel:t.grade,onQuizGenerating:()=>Mt(!0),onQuizSaved:z=>{Mt(!1),le.success("Quiz saved! Close this panel or create another.",{action:{label:"Close Panel",onClick:()=>dt(!1)}})}})})]}),At&&e.jsxs("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4",children:[e.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:()=>It(!1)}),e.jsxs("div",{className:"relative bg-white rounded-[20px] shadow-[0_24px_60px_rgba(0,0,0,0.2)] w-full max-w-[380px] p-7 z-10",children:[e.jsx("div",{className:"w-11 h-11 rounded-full bg-amber-50 border border-amber-200 flex items-center justify-center mb-4",children:e.jsx(br,{className:"w-5 h-5 text-amber-500"})}),e.jsx("h3",{className:"text-[16px] font-bold text-[#1e293b] mb-2",children:"Discard quiz progress?"}),e.jsx("p",{className:"text-[13px] text-[#64748b] font-medium mb-6",children:"Your current quiz session will be lost if you close this panel. This cannot be undone."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>It(!1),className:"flex-1 py-2.5 rounded-full border border-slate-200 text-[13px] font-semibold text-[#475569] hover:bg-slate-50 transition-colors",children:"Keep editing"}),e.jsx("button",{onClick:()=>{It(!1),dt(!1),Mt(!1)},className:"flex-1 py-2.5 rounded-full bg-rose-500 hover:bg-rose-600 text-white text-[13px] font-semibold transition-colors",children:"Discard & close"})]})]})]}),e.jsx("style",{children:` @keyframes slideInFromRight { from { transform: translateX(100%); opacity: 0.6; } to { transform: translateX(0); opacity: 1; } diff --git a/assets/XPNotification-Dsc44Rs3.js b/assets/XPNotification-BKiP3rYx.js similarity index 92% rename from assets/XPNotification-Dsc44Rs3.js rename to assets/XPNotification-BKiP3rYx.js index c192fb412df0eb55c98244d849ab39bc68f3d333..2878a9758e742fdd1e31d0c39726833acd4d800e 100644 --- a/assets/XPNotification-Dsc44Rs3.js +++ b/assets/XPNotification-BKiP3rYx.js @@ -1 +1 @@ -import{r as l,b as n,j as e}from"./vendor-react-B4AQeu28.js";import{h as c,m as r,a7 as m}from"./index-BvEKrMkD.js";import{S as x}from"./sparkles-av0wSNZT.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const w=({xp:i,message:a,show:t,onComplete:s})=>(l.useEffect(()=>{if(t){const o=setTimeout(()=>{s()},3e3);return()=>clearTimeout(o)}},[t,s]),n.createPortal(e.jsx(c,{children:t&&e.jsx(r.div,{initial:{opacity:0,y:-50,scale:.8},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-20,scale:.9},transition:{type:"spring",damping:25,stiffness:200},className:"fixed top-8 left-1/2 -translate-x-1/2 z-[300]",style:{willChange:"transform, opacity"},children:e.jsxs("div",{className:"bg-gradient-to-r from-rose-400 via-orange-500 to-rose-500 text-white px-6 py-4 rounded-2xl shadow-2xl border-2 border-rose-300 flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center",children:e.jsx(m,{size:20,className:"text-white",fill:"currentColor"})}),e.jsx(r.div,{className:"absolute -top-1 -right-1",animate:{rotate:[0,360]},transition:{duration:2,repeat:1/0,ease:"linear"},style:{willChange:"transform"},children:e.jsx(x,{size:16,className:"text-rose-200"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold",children:a}),e.jsxs("p",{className:"text-2xl font-black",children:["+",i," XP"]})]})]})})}),document.body));export{w as default}; +import{r as l,b as n,j as e}from"./vendor-react-B4AQeu28.js";import{h as c,m as r,a7 as m}from"./index-BdLfAeGL.js";import{S as x}from"./sparkles-DnAkO9TX.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const w=({xp:i,message:a,show:t,onComplete:s})=>(l.useEffect(()=>{if(t){const o=setTimeout(()=>{s()},3e3);return()=>clearTimeout(o)}},[t,s]),n.createPortal(e.jsx(c,{children:t&&e.jsx(r.div,{initial:{opacity:0,y:-50,scale:.8},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-20,scale:.9},transition:{type:"spring",damping:25,stiffness:200},className:"fixed top-8 left-1/2 -translate-x-1/2 z-[300]",style:{willChange:"transform, opacity"},children:e.jsxs("div",{className:"bg-gradient-to-r from-rose-400 via-orange-500 to-rose-500 text-white px-6 py-4 rounded-2xl shadow-2xl border-2 border-rose-300 flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center",children:e.jsx(m,{size:20,className:"text-white",fill:"currentColor"})}),e.jsx(r.div,{className:"absolute -top-1 -right-1",animate:{rotate:[0,360]},transition:{duration:2,repeat:1/0,ease:"linear"},style:{willChange:"transform"},children:e.jsx(x,{size:16,className:"text-rose-200"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold",children:a}),e.jsxs("p",{className:"text-2xl font-black",children:["+",i," XP"]})]})]})})}),document.body));export{w as default}; diff --git a/assets/automationService-Ckfa20vv.js b/assets/automationService-BoxXP8NH.js similarity index 98% rename from assets/automationService-Ckfa20vv.js rename to assets/automationService-BoxXP8NH.js index cd395fd6193ef249ce087bdf716df58fc4cb4efc..861c481c5f08f3b2c3ad52e494a2285b8814ac83 100644 --- a/assets/automationService-Ckfa20vv.js +++ b/assets/automationService-BoxXP8NH.js @@ -1 +1 @@ -import{doc as g,collection as a,serverTimestamp as c,setDoc as l,addDoc as D,query as b,where as z,getDocs as A,updateDoc as Q,writeBatch as $}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as r,b5 as _}from"./index-BvEKrMkD.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const m=async(e,n,o,u,i)=>{try{const t=g(a(r,"notifications")),s={id:t.id,userId:e,type:n,title:o,message:u,read:!1,...i?{actionUrl:i}:{},createdAt:new Date},d={id:s.id,userId:s.userId,type:s.type,title:s.title,message:s.message,read:s.read,createdAt:c(),link:i||null};return await l(t,{...d}),s}catch(t){throw console.error("Error creating notification:",t),t}};async function M(e){if(!e)return 0;const n=a(r,"deepDiagnosticAssignments"),o=b(n,z("lrn","==",e));return(await A(o)).docs.filter(i=>{const t=i.data().status;return t==="pending"||t==="queued"||t==="in_progress"||t==="expired"}).length}async function x(e,n,o="Grade 11",u,i="iar_only",t="initial_assessment",s){if(t==="followup_diagnostic"){const d=a(r,"deepDiagnosticAssignments"),C=b(d,z("lrn","==",e)),f=await A(C);if(!f.empty){const p=$(r);let w=!1;for(const h of f.docs){const I=h.data().status;(I==="pending"||I==="queued")&&(p.update(h.ref,{status:"in_progress",startedAt:c()}),w=!0)}w&&await p.commit()}}return await l(g(r,"diagnosticResults",e),{lrn:e,results:n,gradeLevel:o,workflowMode:i,assessmentType:t,questionBreakdown:u||null,topicBreakdown:s||null,completedAt:c(),processed:!1,processing:!1}),{success:!0,event:"diagnostic_completed",lrn:e,message:`Diagnostic submitted for ${e}. Processing will begin automatically.`,remedialQuizzesCreated:0,notifications:["Your diagnostic results are being processed. Check back shortly!"]}}async function N(e){return await D(a(r,"quizResults"),{lrn:e.lrn,studentId:e.lrn,quizId:e.quizId,subject:e.subject,score:e.score,totalQuestions:e.totalQuestions,correctAnswers:e.correctAnswers,timeSpentSeconds:e.timeSpentSeconds,answers:e.answers||null,submittedAt:c()}),{success:!0,event:"quiz_submitted",lrn:e.lrn,message:`Quiz submitted for ${e.lrn}. Risk recalculation will run automatically.`,remedialQuizzesCreated:0,notifications:[`Quiz result recorded for ${e.subject}.`]}}async function W(e){return await _(e.lrn),await m(e.lrn,"reminder","Welcome to MathPulse AI!","Complete your diagnostic assessment to get started with personalised learning."),e.teacherId&&await m(e.teacherId,"message","New Student Enrolled",`${e.name} has joined. Diagnostic assessment is pending.`),{success:!0,event:"student_enrolled",lrn:e.lrn,message:`Student ${e.name} enrolled and initialised`,remedialQuizzesCreated:0,notifications:[`Welcome ${e.name}! Please complete the diagnostic assessment.`]}}async function G(e){return await D(a(r,"dataImports"),{teacherId:e.teacherId,studentCount:e.students.length,columnMapping:e.columnMapping,importedAt:c(),processed:!1}),await m(e.teacherId,"message","Data Import Processed",`Data import complete — ${e.students.length} student records processed.`),{success:!0,event:"data_imported",message:`Data import processed for ${e.students.length} students`,remedialQuizzesCreated:0,notifications:[`Data import complete — ${e.students.length} student records processed.`]}}async function Y(e){const n=g(r,"curriculumContent",e.contentId);return e.action==="delete"?await Q(n,{deleted:!0,deletedBy:e.adminId,deletedAt:c(),contentType:e.contentType,subjectId:e.subjectId||null}):await l(n,{contentType:e.contentType,subjectId:e.subjectId||null,details:e.details||null,updatedBy:e.adminId,action:e.action,updatedAt:c()},{merge:!0}),{success:!0,event:"content_updated",message:`Content ${e.action} processed for ${e.contentType}`,remedialQuizzesCreated:0,notifications:[]}}export{M as getPendingDeepDiagnosticCount,Y as triggerContentUpdated,G as triggerDataImported,x as triggerDiagnosticCompleted,N as triggerQuizSubmitted,W as triggerStudentEnrolled}; +import{doc as g,collection as a,serverTimestamp as c,setDoc as l,addDoc as D,query as b,where as z,getDocs as A,updateDoc as Q,writeBatch as $}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as r,b5 as _}from"./index-BdLfAeGL.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const m=async(e,n,o,u,i)=>{try{const t=g(a(r,"notifications")),s={id:t.id,userId:e,type:n,title:o,message:u,read:!1,...i?{actionUrl:i}:{},createdAt:new Date},d={id:s.id,userId:s.userId,type:s.type,title:s.title,message:s.message,read:s.read,createdAt:c(),link:i||null};return await l(t,{...d}),s}catch(t){throw console.error("Error creating notification:",t),t}};async function M(e){if(!e)return 0;const n=a(r,"deepDiagnosticAssignments"),o=b(n,z("lrn","==",e));return(await A(o)).docs.filter(i=>{const t=i.data().status;return t==="pending"||t==="queued"||t==="in_progress"||t==="expired"}).length}async function x(e,n,o="Grade 11",u,i="iar_only",t="initial_assessment",s){if(t==="followup_diagnostic"){const d=a(r,"deepDiagnosticAssignments"),C=b(d,z("lrn","==",e)),f=await A(C);if(!f.empty){const p=$(r);let w=!1;for(const h of f.docs){const I=h.data().status;(I==="pending"||I==="queued")&&(p.update(h.ref,{status:"in_progress",startedAt:c()}),w=!0)}w&&await p.commit()}}return await l(g(r,"diagnosticResults",e),{lrn:e,results:n,gradeLevel:o,workflowMode:i,assessmentType:t,questionBreakdown:u||null,topicBreakdown:s||null,completedAt:c(),processed:!1,processing:!1}),{success:!0,event:"diagnostic_completed",lrn:e,message:`Diagnostic submitted for ${e}. Processing will begin automatically.`,remedialQuizzesCreated:0,notifications:["Your diagnostic results are being processed. Check back shortly!"]}}async function N(e){return await D(a(r,"quizResults"),{lrn:e.lrn,studentId:e.lrn,quizId:e.quizId,subject:e.subject,score:e.score,totalQuestions:e.totalQuestions,correctAnswers:e.correctAnswers,timeSpentSeconds:e.timeSpentSeconds,answers:e.answers||null,submittedAt:c()}),{success:!0,event:"quiz_submitted",lrn:e.lrn,message:`Quiz submitted for ${e.lrn}. Risk recalculation will run automatically.`,remedialQuizzesCreated:0,notifications:[`Quiz result recorded for ${e.subject}.`]}}async function W(e){return await _(e.lrn),await m(e.lrn,"reminder","Welcome to MathPulse AI!","Complete your diagnostic assessment to get started with personalised learning."),e.teacherId&&await m(e.teacherId,"message","New Student Enrolled",`${e.name} has joined. Diagnostic assessment is pending.`),{success:!0,event:"student_enrolled",lrn:e.lrn,message:`Student ${e.name} enrolled and initialised`,remedialQuizzesCreated:0,notifications:[`Welcome ${e.name}! Please complete the diagnostic assessment.`]}}async function G(e){return await D(a(r,"dataImports"),{teacherId:e.teacherId,studentCount:e.students.length,columnMapping:e.columnMapping,importedAt:c(),processed:!1}),await m(e.teacherId,"message","Data Import Processed",`Data import complete — ${e.students.length} student records processed.`),{success:!0,event:"data_imported",message:`Data import processed for ${e.students.length} students`,remedialQuizzesCreated:0,notifications:[`Data import complete — ${e.students.length} student records processed.`]}}async function Y(e){const n=g(r,"curriculumContent",e.contentId);return e.action==="delete"?await Q(n,{deleted:!0,deletedBy:e.adminId,deletedAt:c(),contentType:e.contentType,subjectId:e.subjectId||null}):await l(n,{contentType:e.contentType,subjectId:e.subjectId||null,details:e.details||null,updatedBy:e.adminId,action:e.action,updatedAt:c()},{merge:!0}),{success:!0,event:"content_updated",message:`Content ${e.action} processed for ${e.contentType}`,remedialQuizzesCreated:0,notifications:[]}}export{M as getPendingDeepDiagnosticCount,Y as triggerContentUpdated,G as triggerDataImported,x as triggerDiagnosticCompleted,N as triggerQuizSubmitted,W as triggerStudentEnrolled}; diff --git a/assets/badge-check-Dir1sWA0.js b/assets/badge-check-4jI3r8US.js similarity index 91% rename from assets/badge-check-Dir1sWA0.js rename to assets/badge-check-4jI3r8US.js index c921eeee1a6765edee096bdb814bed3a9591ed6f..7c2511f96bd275e0484750e744e0b17e95dc9b6e 100644 --- a/assets/badge-check-Dir1sWA0.js +++ b/assets/badge-check-4jI3r8US.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/bell-C57aSZcx.js b/assets/bell-C5_RRTsA.js similarity index 91% rename from assets/bell-C57aSZcx.js rename to assets/bell-C5_RRTsA.js index 014a329865c9510eedeefd95aba1b925fcfb7686..0c5b2a179c533e55b69b5968a86fe41084fa32a0 100644 --- a/assets/bell-C57aSZcx.js +++ b/assets/bell-C5_RRTsA.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/button-Bfg1pO9T.js b/assets/button-BbJLXpfi.js similarity index 97% rename from assets/button-Bfg1pO9T.js rename to assets/button-BbJLXpfi.js index fa82a41500f2bef4224bd1cfab21695067cca65c..b301c015ac585b1ed984d641fc8b446e27b7c3ef 100644 --- a/assets/button-Bfg1pO9T.js +++ b/assets/button-BbJLXpfi.js @@ -1 +1 @@ -import{j as y}from"./vendor-react-B4AQeu28.js";import{S as k}from"./vendor-radix-C5nwdvGr.js";import{c as V}from"./vendor-charts-CAmziV1y.js";import{o as p}from"./index-BvEKrMkD.js";const g=n=>typeof n=="boolean"?`${n}`:n===0?"0":n,m=V,j=(n,r)=>e=>{var o;if(r?.variants==null)return m(n,e?.class,e?.className);const{variants:u,defaultVariants:i}=r,b=Object.keys(u).map(t=>{const a=e?.[t],d=i?.[t];if(a===null)return null;const s=g(a)||g(d);return u[t][s]}),v=e&&Object.entries(e).reduce((t,a)=>{let[d,s]=a;return s===void 0||(t[d]=s),t},{}),f=r==null||(o=r.compoundVariants)===null||o===void 0?void 0:o.reduce((t,a)=>{let{class:d,className:s,...h}=a;return Object.entries(h).every(x=>{let[c,l]=x;return Array.isArray(l)?l.includes({...i,...v}[c]):{...i,...v}[c]===l})?[...t,d,s]:t},[]);return m(n,b,f,e?.class,e?.className)},N=j("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}});function w({className:n,variant:r,size:e,asChild:o=!1,...u}){const i=o?k:"button";return y.jsx(i,{"data-slot":"button",className:p(N({variant:r,size:e,className:n})),...u})}export{w as B,j as c}; +import{j as y}from"./vendor-react-B4AQeu28.js";import{S as k}from"./vendor-radix-C5nwdvGr.js";import{c as V}from"./vendor-charts-CAmziV1y.js";import{o as p}from"./index-BdLfAeGL.js";const g=n=>typeof n=="boolean"?`${n}`:n===0?"0":n,m=V,j=(n,r)=>e=>{var o;if(r?.variants==null)return m(n,e?.class,e?.className);const{variants:u,defaultVariants:i}=r,b=Object.keys(u).map(t=>{const a=e?.[t],d=i?.[t];if(a===null)return null;const s=g(a)||g(d);return u[t][s]}),v=e&&Object.entries(e).reduce((t,a)=>{let[d,s]=a;return s===void 0||(t[d]=s),t},{}),f=r==null||(o=r.compoundVariants)===null||o===void 0?void 0:o.reduce((t,a)=>{let{class:d,className:s,...h}=a;return Object.entries(h).every(x=>{let[c,l]=x;return Array.isArray(l)?l.includes({...i,...v}[c]):{...i,...v}[c]===l})?[...t,d,s]:t},[]);return m(n,b,f,e?.class,e?.className)},N=j("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}});function w({className:n,variant:r,size:e,asChild:o=!1,...u}){const i=o?k:"button";return y.jsx(i,{"data-slot":"button",className:p(N({variant:r,size:e,className:n})),...u})}export{w as B,j as c}; diff --git a/assets/chart-column-DKW3TTRX.js b/assets/chart-column-Dl7iJ2BC.js similarity index 89% rename from assets/chart-column-DKW3TTRX.js rename to assets/chart-column-Dl7iJ2BC.js index 7375d4de8e5e4cd9304123a5aa1665e8696e6f82..f3b61992bd298c11903952fbc23978ec8214ce32 100644 --- a/assets/chart-column-DKW3TTRX.js +++ b/assets/chart-column-Dl7iJ2BC.js @@ -1,4 +1,4 @@ -import{e as t}from"./index-BvEKrMkD.js";/** +import{e as t}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chatService-ChYY3TEL.js b/assets/chatService-F4GRaS_M.js similarity index 97% rename from assets/chatService-ChYY3TEL.js rename to assets/chatService-F4GRaS_M.js index 7be4c2509f1d342c3682da81c4b1b4ffdd38557b..fb520418dd58e9e73406f117884f634dc6888b13 100644 --- a/assets/chatService-ChYY3TEL.js +++ b/assets/chatService-F4GRaS_M.js @@ -1 +1 @@ -import{doc as c,collection as u,getDoc as g,serverTimestamp as i,setDoc as w,updateDoc as p,query as l,where as d,orderBy as y,getDocs as A}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as a}from"./index-BvEKrMkD.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const Q=async(s,t="New Conversation")=>{try{const e=c(u(a,"chatSessions")),n={id:e.id,userId:s,title:t,messages:[],createdAt:new Date,updatedAt:new Date,isActive:!0};return await w(e,{...n,createdAt:i(),updatedAt:i()}),n}catch(e){throw console.error("Error creating chat session:",e),e}},R=async s=>{try{const t=l(u(a,"chatSessions"),d("userId","==",s),d("isActive","==",!0),y("updatedAt","desc"));return(await A(t)).docs.map(n=>{const r=n.data();return{...r,createdAt:r.createdAt?.toDate()||new Date,updatedAt:r.updatedAt?.toDate()||new Date}})}catch(t){return console.error("Error getting chat sessions:",t),[]}},b=async s=>{try{const t=await g(c(a,"chatSessions",s));if(t.exists()){const e=t.data();return{...e,createdAt:e.createdAt?.toDate()||new Date,updatedAt:e.updatedAt?.toDate()||new Date}}return null}catch(t){return console.error("Error getting chat session:",t),null}},q=async(s,t,e,n)=>{try{const r=c(u(a,"chatMessages")),o={id:r.id,userId:"",role:t,content:e,timestamp:new Date,...n?{context:n}:{}},m=await g(c(a,"chatSessions",s));m.exists()&&(o.userId=m.data().userId);const h={id:o.id,userId:o.userId,role:o.role,content:o.content,sessionId:s,timestamp:i()};return o.context&&(h.context=o.context),await w(r,h),await p(c(a,"chatSessions",s),{updatedAt:i()}),o}catch(r){throw console.error("Error adding message:",r),r}},B=async(s,t)=>{try{const e=l(u(a,"chatMessages"),d("sessionId","==",s),d("userId","==",t),y("timestamp","asc"));return(await A(e)).docs.map(r=>{const o=r.data();return{...o,timestamp:o.timestamp?.toDate()||new Date}})}catch(e){return console.error("Error getting session messages:",e),[]}},N=async(s,t)=>{try{await p(c(a,"chatSessions",s),{title:t,updatedAt:i()})}catch(e){throw console.error("Error updating session title:",e),e}},U=async s=>{try{await p(c(a,"chatSessions",s),{isActive:!1,updatedAt:i()})}catch(t){throw console.error("Error deleting session:",t),t}};export{q as addMessageToSession,Q as createChatSession,U as deleteSession,b as getChatSession,B as getSessionMessages,R as getUserChatSessions,N as updateSessionTitle}; +import{doc as c,collection as u,getDoc as g,serverTimestamp as i,setDoc as w,updateDoc as p,query as l,where as d,orderBy as y,getDocs as A}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as a}from"./index-BdLfAeGL.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const Q=async(s,t="New Conversation")=>{try{const e=c(u(a,"chatSessions")),n={id:e.id,userId:s,title:t,messages:[],createdAt:new Date,updatedAt:new Date,isActive:!0};return await w(e,{...n,createdAt:i(),updatedAt:i()}),n}catch(e){throw console.error("Error creating chat session:",e),e}},R=async s=>{try{const t=l(u(a,"chatSessions"),d("userId","==",s),d("isActive","==",!0),y("updatedAt","desc"));return(await A(t)).docs.map(n=>{const r=n.data();return{...r,createdAt:r.createdAt?.toDate()||new Date,updatedAt:r.updatedAt?.toDate()||new Date}})}catch(t){return console.error("Error getting chat sessions:",t),[]}},b=async s=>{try{const t=await g(c(a,"chatSessions",s));if(t.exists()){const e=t.data();return{...e,createdAt:e.createdAt?.toDate()||new Date,updatedAt:e.updatedAt?.toDate()||new Date}}return null}catch(t){return console.error("Error getting chat session:",t),null}},q=async(s,t,e,n)=>{try{const r=c(u(a,"chatMessages")),o={id:r.id,userId:"",role:t,content:e,timestamp:new Date,...n?{context:n}:{}},m=await g(c(a,"chatSessions",s));m.exists()&&(o.userId=m.data().userId);const h={id:o.id,userId:o.userId,role:o.role,content:o.content,sessionId:s,timestamp:i()};return o.context&&(h.context=o.context),await w(r,h),await p(c(a,"chatSessions",s),{updatedAt:i()}),o}catch(r){throw console.error("Error adding message:",r),r}},B=async(s,t)=>{try{const e=l(u(a,"chatMessages"),d("sessionId","==",s),d("userId","==",t),y("timestamp","asc"));return(await A(e)).docs.map(r=>{const o=r.data();return{...o,timestamp:o.timestamp?.toDate()||new Date}})}catch(e){return console.error("Error getting session messages:",e),[]}},N=async(s,t)=>{try{await p(c(a,"chatSessions",s),{title:t,updatedAt:i()})}catch(e){throw console.error("Error updating session title:",e),e}},U=async s=>{try{await p(c(a,"chatSessions",s),{isActive:!1,updatedAt:i()})}catch(t){throw console.error("Error deleting session:",t),t}};export{q as addMessageToSession,Q as createChatSession,U as deleteSession,b as getChatSession,B as getSessionMessages,R as getUserChatSessions,N as updateSessionTitle}; diff --git a/assets/check-BmWAQELM.js b/assets/check-DbVe23hB.js similarity index 85% rename from assets/check-BmWAQELM.js rename to assets/check-DbVe23hB.js index 78519905a74cf1453cb2b69fdbdee9b23c8afa94..9367e18a43572316b6693ce72d067da5d123a6e0 100644 --- a/assets/check-BmWAQELM.js +++ b/assets/check-DbVe23hB.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BvEKrMkD.js";/** +import{e as c}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chevron-left-DFU37_wB.js b/assets/chevron-left-CNwzgiLt.js similarity index 86% rename from assets/chevron-left-DFU37_wB.js rename to assets/chevron-left-CNwzgiLt.js index 12686d830db369983fbf5a98ed0973f69cebfd2b..2be230af0527da52e388fae3d07fa7b1918ff8b7 100644 --- a/assets/chevron-left-DFU37_wB.js +++ b/assets/chevron-left-CNwzgiLt.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chevron-right-CbKJd0ln.js b/assets/chevron-right-BRRve0zL.js similarity index 85% rename from assets/chevron-right-CbKJd0ln.js rename to assets/chevron-right-BRRve0zL.js index 8913d0c08af50e062ff109e67e05b70b7e9f0d8b..e75247bd1aed96238887ab7e5c400bfc3accb4a2 100644 --- a/assets/chevron-right-CbKJd0ln.js +++ b/assets/chevron-right-BRRve0zL.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BvEKrMkD.js";/** +import{e as o}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chevron-up-CDr90bpM.js b/assets/chevron-up-uSn_SWll.js similarity index 92% rename from assets/chevron-up-CDr90bpM.js rename to assets/chevron-up-uSn_SWll.js index 4f6fb5c42856609057f279b008ffd88c6f8abdd9..9e104d633c11a1cfb7a482511e59c2161b6d6e2c 100644 --- a/assets/chevron-up-CDr90bpM.js +++ b/assets/chevron-up-uSn_SWll.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BvEKrMkD.js";/** +import{e as o}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-alert-fPu7cawt.js b/assets/circle-alert-ByVTnT3r.js similarity index 90% rename from assets/circle-alert-fPu7cawt.js rename to assets/circle-alert-ByVTnT3r.js index 1fa21de9eb01241650067f87cf86e9d800ee42d8..c55cee9c426101e501e64eca9ae08c5197fa22b7 100644 --- a/assets/circle-alert-fPu7cawt.js +++ b/assets/circle-alert-ByVTnT3r.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-check-E415RSic.js b/assets/circle-check-CuVe-qlS.js similarity index 87% rename from assets/circle-check-E415RSic.js rename to assets/circle-check-CuVe-qlS.js index 7ea5d571ddcba59cbf3c4912e775ba5a28e2ee49..87bcacdc10573a896de2dfb9684f9a331c57a98e 100644 --- a/assets/circle-check-E415RSic.js +++ b/assets/circle-check-CuVe-qlS.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BvEKrMkD.js";/** +import{e as c}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-check-big-mtMsU82c.js b/assets/circle-check-big-B54zXy3k.js similarity index 88% rename from assets/circle-check-big-mtMsU82c.js rename to assets/circle-check-big-B54zXy3k.js index 6e759ee0f4115948f0aa2bec0ca95498d2d7b3b5..c725d42466954e4e002375947ed4c18f27ad7951 100644 --- a/assets/circle-check-big-mtMsU82c.js +++ b/assets/circle-check-big-B54zXy3k.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BvEKrMkD.js";/** +import{e as c}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-help-DeWZHKak.js b/assets/circle-help-CZDuv1Gp.js similarity index 89% rename from assets/circle-help-DeWZHKak.js rename to assets/circle-help-CZDuv1Gp.js index 45ec0caa887aadfab49825b5fe082c0aa0c40853..053bc768f255eaf8dbc2e2fd5a53f03c399e8299 100644 --- a/assets/circle-help-DeWZHKak.js +++ b/assets/circle-help-CZDuv1Gp.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BvEKrMkD.js";/** +import{e as c}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/clipboard-check-jJ306e7q.js b/assets/clipboard-check-hgJTQlzs.js similarity index 91% rename from assets/clipboard-check-jJ306e7q.js rename to assets/clipboard-check-hgJTQlzs.js index bf43c72cdf6af1a6079aebf6fd16aa7cb116833a..167219767287b61821f09ff3cc3f926a5db08c4d 100644 --- a/assets/clipboard-check-jJ306e7q.js +++ b/assets/clipboard-check-hgJTQlzs.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/clock-0vnF72R6.js b/assets/clock-CpBwkoND.js similarity index 87% rename from assets/clock-0vnF72R6.js rename to assets/clock-CpBwkoND.js index 0485055554dc97bdf70d00c24067076950739ced..8d4e6b9b796bd4574bc10daf460aeff068376e87 100644 --- a/assets/clock-0vnF72R6.js +++ b/assets/clock-CpBwkoND.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BvEKrMkD.js";/** +import{e as c}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/diagnosticService-BvH8S98K.js b/assets/diagnosticService-DmVYM_3F.js similarity index 93% rename from assets/diagnosticService-BvH8S98K.js rename to assets/diagnosticService-DmVYM_3F.js index 070b2131aac74b98a8453a90e81b7105eb31ead0..0f510206089b1fd07b3ef26c5a82e22f5eaf9a42 100644 --- a/assets/diagnosticService-BvH8S98K.js +++ b/assets/diagnosticService-DmVYM_3F.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{_ as w}from"./index-BvEKrMkD.js";const y="https://deign86-mathpulse-api-v3test.hf.space";async function P(g,h){const f=`${y}/api/diagnostic/generate`,{auth:i}=await w(async()=>{const{auth:e}=await import("./index-BvEKrMkD.js").then(a=>a.b7);return{auth:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),c=i.currentUser,l=async()=>{const e=new Headers({"Content-Type":"application/json"});if(c){const a=await c.getIdToken(!1);a&&e.set("Authorization",`Bearer ${a}`)}return e},u=async e=>fetch(f,{method:"POST",headers:await l(),body:JSON.stringify({strand:g,grade_level:h}),signal:e}),d=(e,a)=>{let t="Something went wrong. Please try again.";try{const s=JSON.parse(a);if(s.detail){const o=String(s.detail);o.includes("Database unavailable")||o.includes("unavailable")?t="Our servers are temporarily busy. Please try again in a moment.":o.includes("timeout")||o.includes("timed out")?t="The request timed out. Please check your connection and try again.":t=o}}catch{!e.ok&&a&&(t="Failed to start assessment. Please try again.")}return t},n=2,r=3e4;for(let e=1;e<=n;e++){const a=new AbortController,t=setTimeout(()=>a.abort(),r);try{const s=await u(a.signal);if(s.ok)return clearTimeout(t),s.json();if(s.status>=400&&s.status<500){clearTimeout(t);const m=await s.text().catch(()=>"");throw new Error(d(s,m))}const o=await s.text().catch(()=>""),p=d(s,o);if(clearTimeout(t),esetTimeout(T,m));continue}throw new Error(p)}catch(s){if(clearTimeout(t),s instanceof DOMException&&s.name==="AbortError"){if(e{const{auth:n}=await import("./index-BvEKrMkD.js").then(r=>r.b7);return{auth:n}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),l=c.currentUser;if(l){const n=await l.getIdToken(!1);n&&i.set("Authorization",`Bearer ${n}`)}const u=new AbortController,d=setTimeout(()=>u.abort(),6e4);try{const n=await fetch(f,{method:"POST",headers:i,body:JSON.stringify({test_id:g,responses:h}),signal:u.signal});if(!n.ok){const r=await n.text().catch(()=>"");let e="Something went wrong. Please try again.";try{const a=JSON.parse(r);if(a.detail){const t=String(a.detail);t.includes("session")||t.includes("not found")?e="Your assessment session has expired. Please restart the assessment.":t.includes("Database unavailable")||t.includes("unavailable")?e="Our servers are temporarily busy. Please try again in a moment.":t.includes("timeout")||t.includes("timed out")?e="The request timed out. Please check your connection and try again.":e=t}}catch{r.includes("404")||r.includes("not found")?e="Your assessment session has expired. Please restart the assessment.":r&&(e="Something went wrong. Please try again.")}throw new Error(e)}return n.json()}finally{clearTimeout(d)}}export{P as g,_ as s}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{_ as w}from"./index-BdLfAeGL.js";const y="https://deign86-mathpulse-api-v3test.hf.space";async function P(g,h){const f=`${y}/api/diagnostic/generate`,{auth:i}=await w(async()=>{const{auth:e}=await import("./index-BdLfAeGL.js").then(a=>a.b7);return{auth:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),c=i.currentUser,l=async()=>{const e=new Headers({"Content-Type":"application/json"});if(c){const a=await c.getIdToken(!1);a&&e.set("Authorization",`Bearer ${a}`)}return e},u=async e=>fetch(f,{method:"POST",headers:await l(),body:JSON.stringify({strand:g,grade_level:h}),signal:e}),d=(e,a)=>{let t="Something went wrong. Please try again.";try{const s=JSON.parse(a);if(s.detail){const o=String(s.detail);o.includes("Database unavailable")||o.includes("unavailable")?t="Our servers are temporarily busy. Please try again in a moment.":o.includes("timeout")||o.includes("timed out")?t="The request timed out. Please check your connection and try again.":t=o}}catch{!e.ok&&a&&(t="Failed to start assessment. Please try again.")}return t},n=2,r=3e4;for(let e=1;e<=n;e++){const a=new AbortController,t=setTimeout(()=>a.abort(),r);try{const s=await u(a.signal);if(s.ok)return clearTimeout(t),s.json();if(s.status>=400&&s.status<500){clearTimeout(t);const m=await s.text().catch(()=>"");throw new Error(d(s,m))}const o=await s.text().catch(()=>""),p=d(s,o);if(clearTimeout(t),esetTimeout(T,m));continue}throw new Error(p)}catch(s){if(clearTimeout(t),s instanceof DOMException&&s.name==="AbortError"){if(e{const{auth:n}=await import("./index-BdLfAeGL.js").then(r=>r.b7);return{auth:n}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),l=c.currentUser;if(l){const n=await l.getIdToken(!1);n&&i.set("Authorization",`Bearer ${n}`)}const u=new AbortController,d=setTimeout(()=>u.abort(),6e4);try{const n=await fetch(f,{method:"POST",headers:i,body:JSON.stringify({test_id:g,responses:h}),signal:u.signal});if(!n.ok){const r=await n.text().catch(()=>"");let e="Something went wrong. Please try again.";try{const a=JSON.parse(r);if(a.detail){const t=String(a.detail);t.includes("session")||t.includes("not found")?e="Your assessment session has expired. Please restart the assessment.":t.includes("Database unavailable")||t.includes("unavailable")?e="Our servers are temporarily busy. Please try again in a moment.":t.includes("timeout")||t.includes("timed out")?e="The request timed out. Please check your connection and try again.":e=t}}catch{r.includes("404")||r.includes("not found")?e="Your assessment session has expired. Please restart the assessment.":r&&(e="Something went wrong. Please try again.")}throw new Error(e)}return n.json()}finally{clearTimeout(d)}}export{P as g,_ as s}; diff --git a/assets/dialog-F21mi9j3.js b/assets/dialog-BW6ddbOv.js similarity index 96% rename from assets/dialog-F21mi9j3.js rename to assets/dialog-BW6ddbOv.js index 105153eabfe1a2b12c284ad9494e18829da2b66c..0859217c52e8e0c6dfc6bdc3029b25be0001cb2f 100644 --- a/assets/dialog-F21mi9j3.js +++ b/assets/dialog-BW6ddbOv.js @@ -1,4 +1,4 @@ -import{e as g,o as s}from"./index-BvEKrMkD.js";import{j as t,r as d}from"./vendor-react-B4AQeu28.js";import{b as m,c as l,d as p,T as n,D as i,P as u,O as r}from"./vendor-radix-C5nwdvGr.js";import{X as x}from"./x-BYtx1i07.js";/** +import{e as g,o as s}from"./index-BdLfAeGL.js";import{j as t,r as d}from"./vendor-react-B4AQeu28.js";import{b as m,c as l,d as p,T as n,D as i,P as u,O as r}from"./vendor-radix-C5nwdvGr.js";import{X as x}from"./x-BLhsirCD.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/dollar-sign-DWer_VPF.js b/assets/dollar-sign-BFLnKeOT.js similarity index 89% rename from assets/dollar-sign-DWer_VPF.js rename to assets/dollar-sign-BFLnKeOT.js index 64bd40148957f515d6c0151b47674c1568283b23..71abd89cf6075710f827c8172e4406aa6397f9dc 100644 --- a/assets/dollar-sign-DWer_VPF.js +++ b/assets/dollar-sign-BFLnKeOT.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/download-BYKPAk50.js b/assets/download-CPe9YOUv.js similarity index 89% rename from assets/download-BYKPAk50.js rename to assets/download-CPe9YOUv.js index af93066ad7c0ac383818323a2100d78315b1cf1d..ea4f3f69ead94a2b8d2c3ffd02be72fcbceb3a80 100644 --- a/assets/download-BYKPAk50.js +++ b/assets/download-CPe9YOUv.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BvEKrMkD.js";/** +import{e as o}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/eye-DbYh0OO3.js b/assets/eye-8D1uq8DN.js similarity index 96% rename from assets/eye-DbYh0OO3.js rename to assets/eye-8D1uq8DN.js index 1e9e4101b1cd299c7c04f8fcec052e91f6926f8d..49ff602a87521996d981e0a408479c31a89d5fde 100644 --- a/assets/eye-DbYh0OO3.js +++ b/assets/eye-8D1uq8DN.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/formatDistanceToNow-5Jvf3U0l.js b/assets/formatDistanceToNow-DQ9IJwBi.js similarity index 99% rename from assets/formatDistanceToNow-5Jvf3U0l.js rename to assets/formatDistanceToNow-DQ9IJwBi.js index 80debc0fa3419b7b35ccbe094e2074a75ca07db1..7fde81a9c81633dd6a8499ca351f76d3d7f6ad4c 100644 --- a/assets/formatDistanceToNow-5Jvf3U0l.js +++ b/assets/formatDistanceToNow-DQ9IJwBi.js @@ -1,4 +1,4 @@ -import{e as W,t as u,aa as S}from"./index-BvEKrMkD.js";/** +import{e as W,t as u,aa as S}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/funnel-CAdiZoOH.js b/assets/funnel-ijCItoBZ.js similarity index 90% rename from assets/funnel-CAdiZoOH.js rename to assets/funnel-ijCItoBZ.js index 0b715661e0f555e858df1d6861eb7b8f1a6802ed..8e82119831bb14eb9332d58cb463864cead80062 100644 --- a/assets/funnel-CAdiZoOH.js +++ b/assets/funnel-ijCItoBZ.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/gift-CL3L8vH3.js b/assets/gift-CHSGDZhC.js similarity index 91% rename from assets/gift-CL3L8vH3.js rename to assets/gift-CHSGDZhC.js index 41b9f8626945175e4c9b193aa41a887cd0fcc055..a4b5a0436e7957fb3e9acb4723801e696810acee 100644 --- a/assets/gift-CL3L8vH3.js +++ b/assets/gift-CHSGDZhC.js @@ -1,4 +1,4 @@ -import{e as t}from"./index-BvEKrMkD.js";/** +import{e as t}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/history-uiZLfMqH.js b/assets/history-VIZhCw1O.js similarity index 90% rename from assets/history-uiZLfMqH.js rename to assets/history-VIZhCw1O.js index b974a461cb1283e7facb23413b17eed941090b41..bad6ef5134461ccd929ba8bdd3dc2b6818cff790 100644 --- a/assets/history-uiZLfMqH.js +++ b/assets/history-VIZhCw1O.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/index-BvEKrMkD.js b/assets/index-BdLfAeGL.js similarity index 98% rename from assets/index-BvEKrMkD.js rename to assets/index-BdLfAeGL.js index 33db50aa561b3741b647ffbcbbcac43f78fbbf49..2ddcfa15838b6b753e6f106453dc0aa976a630a9 100644 --- a/assets/index-BvEKrMkD.js +++ b/assets/index-BdLfAeGL.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/automationService-Ckfa20vv.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/pipelineService-BVFD1ZML.js","assets/chatService-ChYY3TEL.js","assets/trackingService-SBoVE94r.js","assets/LoginPage-B_M2Kx_b.js","assets/button-Bfg1pO9T.js","assets/input-B3TmduBc.js","assets/sparkles-av0wSNZT.js","assets/mail-DahQBvd1.js","assets/eye-DbYh0OO3.js","assets/shield-check-X3NwQ434.js","assets/TeacherDashboard-ttPsdvb8.js","assets/ConfirmModal-DE1CbRDa.js","assets/x-BYtx1i07.js","assets/trash-2-B056YIHV.js","assets/log-out-BDL1J1Fs.js","assets/search-CHZcTJmD.js","assets/check-BmWAQELM.js","assets/plus-IoQaIojF.js","assets/NotificationDropdown-txVZGqve.js","assets/formatDistanceToNow-5Jvf3U0l.js","assets/bell-C57aSZcx.js","assets/circle-check-E415RSic.js","assets/circle-alert-fPu7cawt.js","assets/LogoutActionButton-Cu6gWsBL.js","assets/quizService-D6WAd8P5.js","assets/clock-0vnF72R6.js","assets/send-BivcIdIA.js","assets/circle-check-big-mtMsU82c.js","assets/tooltip-DDXcKYaB.js","assets/circle-help-DeWZHKak.js","assets/info-CMvRmbQw.js","assets/chevron-up-CDr90bpM.js","assets/minus-DRsrXXF5.js","assets/chart-column-DKW3TTRX.js","assets/skeleton-CU_hcmX-.js","assets/download-BYKPAk50.js","assets/chevron-left-DFU37_wB.js","assets/chevron-right-CbKJd0ln.js","assets/save-DAHVTL2X.js","assets/upload-COEzjD21.js","assets/lightbulb-BpvAgebC.js","assets/useQuery-a95tRwQa.js","assets/subjects-ChEJ6J55.js","assets/useCurriculum-CSvqmu2B.js","assets/ChatMarkdown-Chh6462P.js","assets/history-uiZLfMqH.js","assets/dialog-F21mi9j3.js","assets/vendor-xlsx-uZelXSz_.js","assets/moduleWatchService-Boczzqau.js","assets/clipboard-check-jJ306e7q.js","assets/badge-check-Dir1sWA0.js","assets/AdminDashboard-By-BB3KI.js","assets/Sidebar-CR8IPH6O.js","assets/shirt-DFiZ2C4J.js","assets/select-CU8TeDXy.js","assets/dollar-sign-DWer_VPF.js","assets/switch-kakgyvwt.js","assets/useSubjectAvailability-C0TzAHAR.js","assets/HeroBanner-Br6C2yH1.js","assets/RightSidebar-CjDA-c42.js","assets/quiz_battle_avatar-BXHPSput.js","assets/XPNotification-Dsc44Rs3.js","assets/index-B23D5AFn.js","assets/megaphone-DpNhcxX3.js","assets/SupplementalBanner-CyLKxz9O.js","assets/SupplementalPillCarousel-D522wnTT.js","assets/deepseekRagService-Bke9fSTt.js","assets/LearningPath-BhYUnmrP.js","assets/ModuleFolderCard-CS_0Dtn3.js","assets/CompetencyRadarChart-BIu0jpMm.js","assets/ModulesPage-BgmrOnnq.js","assets/ScientificCalculator-B-rMzwD3.js","assets/volume-x-C2kyFHU5.js","assets/confetti.module-C94ZD2ww.js","assets/gift-CL3L8vH3.js","assets/funnel-CAdiZoOH.js","assets/AIChatPage-DH58XfsA.js","assets/GradesPage-C8P7dxU8.js","assets/LeaderboardPage-GVWLWArd.js","assets/useFeatureAccess-BTg5PL53.js","assets/QuizBattlePage-H3hCehZd.js","assets/CompositeAvatar-DoKZfi7O.js","assets/avatarData-ChByUhv2.js","assets/AvatarShop-CnrlXF7V.js","assets/FloatingAITutor-CkFvbvHJ.js","assets/maximize-2-BUGGXJYn.js","assets/RewardsModal-BqWMkrYX.js","assets/ProfileModal-82NOIe2Y.js","assets/ProfilePictureUploader-Cd4j_44T.js","assets/SettingsModal-BcXV1uwF.js","assets/InitialAssessmentModal-Cri1vHPb.js","assets/diagnosticService-BvH8S98K.js","assets/AssessmentPage-DWkUbkQS.js","assets/DiagnosticBreakdown-KMY-Jwc3.js","assets/testResetService-DUw6qLIU.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/automationService-BoxXP8NH.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/pipelineService-h2NDr2Mk.js","assets/chatService-F4GRaS_M.js","assets/trackingService-DJ3_U-Mf.js","assets/LoginPage-Dp-x74N8.js","assets/button-BbJLXpfi.js","assets/input-CHfZS1wQ.js","assets/sparkles-DnAkO9TX.js","assets/mail-9RdsJqkx.js","assets/eye-8D1uq8DN.js","assets/shield-check-DqqR-L0T.js","assets/TeacherDashboard-CqJcvlfm.js","assets/ConfirmModal-DPzAgSP6.js","assets/x-BLhsirCD.js","assets/trash-2-f-pq6QuO.js","assets/log-out-CccGdaTy.js","assets/search-gQ2OCqgd.js","assets/check-DbVe23hB.js","assets/plus-Z9YkmuN1.js","assets/NotificationDropdown-DW0msTLi.js","assets/formatDistanceToNow-DQ9IJwBi.js","assets/bell-C5_RRTsA.js","assets/circle-check-CuVe-qlS.js","assets/circle-alert-ByVTnT3r.js","assets/LogoutActionButton-Baak8j6y.js","assets/quizService-DxWImmI3.js","assets/clock-CpBwkoND.js","assets/send-CxDLfaHq.js","assets/circle-check-big-B54zXy3k.js","assets/tooltip-Blvwukwg.js","assets/circle-help-CZDuv1Gp.js","assets/info-D1mJ7S8g.js","assets/chevron-up-uSn_SWll.js","assets/minus-rsVFzcwU.js","assets/chart-column-Dl7iJ2BC.js","assets/skeleton-SSuNGBG3.js","assets/download-CPe9YOUv.js","assets/chevron-left-CNwzgiLt.js","assets/chevron-right-BRRve0zL.js","assets/save-CUEUjfb0.js","assets/upload-CbDKucU9.js","assets/lightbulb-W3LO7x3u.js","assets/useQuery-fA8_Syr9.js","assets/subjects-Dw9HR29l.js","assets/useCurriculum-DZL96a-v.js","assets/ChatMarkdown-SgVutDBu.js","assets/history-VIZhCw1O.js","assets/dialog-BW6ddbOv.js","assets/vendor-xlsx-uZelXSz_.js","assets/moduleWatchService-Ck2BKbab.js","assets/clipboard-check-hgJTQlzs.js","assets/badge-check-4jI3r8US.js","assets/AdminDashboard-CMvLZSCj.js","assets/Sidebar-BohFsvbI.js","assets/shirt-iZ6vtR5i.js","assets/select-C3tB_0M-.js","assets/dollar-sign-BFLnKeOT.js","assets/switch-BZ2ceCBk.js","assets/useSubjectAvailability-BUrciGBC.js","assets/HeroBanner-BW-D6-hj.js","assets/RightSidebar-DRNR3ylv.js","assets/quiz_battle_avatar-BXHPSput.js","assets/XPNotification-BKiP3rYx.js","assets/index-oMQKBL9u.js","assets/megaphone-Cd4AJY3E.js","assets/SupplementalBanner-BaLhyCv2.js","assets/SupplementalPillCarousel-EeBQ4OFw.js","assets/deepseekRagService-Bke9fSTt.js","assets/LearningPath-BKjN0COS.js","assets/ModuleFolderCard-CXTwxNMY.js","assets/CompetencyRadarChart-CYjxrfwY.js","assets/ModulesPage-DdfzGaQY.js","assets/ScientificCalculator-DQTxoI7Z.js","assets/volume-x-BfFSlkII.js","assets/confetti.module-C94ZD2ww.js","assets/gift-CHSGDZhC.js","assets/funnel-ijCItoBZ.js","assets/AIChatPage-CEm6qhAI.js","assets/GradesPage-BXZfrLBa.js","assets/LeaderboardPage-C7BC2ZU8.js","assets/useFeatureAccess-BGJy4XRW.js","assets/QuizBattlePage-BgqU8ht-.js","assets/CompositeAvatar-DoKZfi7O.js","assets/avatarData-ChByUhv2.js","assets/AvatarShop-CU1RR7LT.js","assets/FloatingAITutor-ZRTH3xRj.js","assets/maximize-2-C5LwFHUQ.js","assets/RewardsModal-Duh63-te.js","assets/ProfileModal-DG84pnuP.js","assets/ProfilePictureUploader-SMuKdVoO.js","assets/SettingsModal-YXgi6gjA.js","assets/InitialAssessmentModal-DdNBSpH9.js","assets/diagnosticService-DmVYM_3F.js","assets/AssessmentPage-CNGTAZUT.js","assets/DiagnosticBreakdown-1Ae0p8Ht.js","assets/testResetService-DiMJKnvV.js"])))=>i.map(i=>d[i]); import{r as h,j as b,d as I,c as Rp,f as Mp}from"./vendor-react-B4AQeu28.js";import{initializeFirestore as Ip,memoryLocalCache as Dp,doc as U,getDoc as me,setDoc as Ce,serverTimestamp as ae,getDocFromServer as Xo,onSnapshot as en,query as Dt,limit as ks,orderBy as Sn,collection as et,getDocs as Fn,updateDoc as dt,arrayUnion as Fu,increment as fs,where as Rt,deleteDoc as br,Timestamp as jn,runTransaction as Op}from"./vendor-firebase-firestore-CNv3xXal.js";import{U as Lp,V as zp,Y as jp,Z as Np,$ as $p,a0 as Fp,a1 as Vp,a2 as Bp,a3 as Up}from"./vendor-firebase-core-D7GXCeNu.js";import{browserLocalPersistence as Ya,initializeAuth as Ja,browserSessionPersistence as qp,inMemoryPersistence as ec,GoogleAuthProvider as Gp,createUserWithEmailAndPassword as Wp,updateProfile as Hp,signInWithEmailAndPassword as Zp,signOut as Kp,onAuthStateChanged as Qp,updatePassword as Xp,updateEmail as Yp,deleteUser as Jp,EmailAuthProvider as em,reauthenticateWithCredential as tm}from"./vendor-firebase-auth-T_wvTOvf.js";import{g as nm}from"./vendor-firebase-storage-Bi7H_66d.js";import{g as sm}from"./vendor-firebase-analytics-rHarj5hR.js";import{R as rm,I as om,F as im}from"./vendor-radix-C5nwdvGr.js";import{c as am}from"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();var $r=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},cm=class extends $r{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Vu=new cm,lm={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},um=class{#e=lm;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},Yo=new um;function dm(e){setTimeout(e,0)}var fm=typeof window>"u"||"Deno"in globalThis;function wt(){}function hm(e,t){return typeof e=="function"?e(t):e}function pm(e){return typeof e=="number"&&e>=0&&e!==1/0}function mm(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Jo(e,t){return typeof e=="function"?e(t):e}function gm(e,t){return typeof e=="function"?e(t):e}function tc(e,t){const{type:n="all",exact:s,fetchStatus:r,predicate:o,queryKey:i,stale:a}=e;if(i){if(s){if(t.queryHash!==Vi(i,t.options))return!1}else if(!ps(t.queryKey,i))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||o&&!o(t))}function nc(e,t){const{exact:n,status:s,predicate:r,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(hs(t.options.mutationKey)!==hs(o))return!1}else if(!ps(t.options.mutationKey,o))return!1}return!(s&&t.state.status!==s||r&&!r(t))}function Vi(e,t){return(t?.queryKeyHashFn||hs)(e)}function hs(e){return JSON.stringify(e,(t,n)=>ei(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function ps(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ps(e[n],t[n])):!1}var ym=Object.prototype.hasOwnProperty;function Bu(e,t,n=0){if(e===t)return e;if(n>500)return t;const s=sc(e)&&sc(t);if(!s&&!(ei(e)&&ei(t)))return t;const o=(s?e:Object.keys(e)).length,i=s?t:Object.keys(t),a=i.length,c=s?new Array(a):{};let u=0;for(let d=0;d{Yo.setTimeout(t,e)})}function vm(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Bu(e,t):t}function wm(e,t,n=0){const s=[...e,t];return n&&s.length>n?s.slice(1):s}function xm(e,t,n=0){const s=[t,...e];return n&&s.length>n?s.slice(0,-1):s}var Bi=Symbol();function Uu(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Bi?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function MR(e,t){return typeof e=="function"?e(...t):!!e}function Sm(e,t,n){let s=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),e}var qu=(()=>{let e=()=>fm;return{isServer(){return e()},setIsServer(t){e=t}}})();function km(){let e,t;const n=new Promise((r,o)=>{e=r,t=o});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),e(r)},n.reject=r=>{s({status:"rejected",reason:r}),t(r)},n}var Tm=dm;function _m(){let e=[],t=0,n=a=>{a()},s=a=>{a()},r=Tm;const o=a=>{t?e.push(a):r(()=>{n(a)})},i=()=>{const a=e;e=[],a.length&&r(()=>{s(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||i()}return c},batchCalls:a=>(...c)=>{o(()=>{a(...c)})},schedule:o,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{s=a},setScheduler:a=>{r=a}}}var Xe=_m(),Pm=class extends $r{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vr=new Pm;function Em(e){return Math.min(1e3*2**e,3e4)}function Gu(e){return(e??"online")==="online"?vr.isOnline():!0}var ti=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Wu(e){let t=!1,n=0,s;const r=km(),o=()=>r.status!=="pending",i=g=>{if(!o()){const y=new ti(g);f(y),e.onCancel?.(y)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Vu.isFocused()&&(e.networkMode==="always"||vr.isOnline())&&e.canRun(),d=()=>Gu(e.networkMode)&&e.canRun(),l=g=>{o()||(s?.(),r.resolve(g))},f=g=>{o()||(s?.(),r.reject(g))},p=()=>new Promise(g=>{s=y=>{(o()||u())&&g(y)},e.onPause?.()}).then(()=>{s=void 0,o()||e.onContinue?.()}),m=()=>{if(o())return;let g;const y=n===0?e.initialPromise:void 0;try{g=y??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(l).catch(v=>{if(o())return;const k=e.retry??(qu.isServer()?0:3),S=e.retryDelay??Em,w=typeof S=="function"?S(n,v):S,T=k===!0||typeof k=="number"&&nu()?void 0:p()).then(()=>{t?f(v):m()})})};return{promise:r,status:()=>r.status,cancel:i,continue:()=>(s?.(),r),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?m():p().then(m),r)}}var Hu=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pm(this.gcTime)&&(this.#e=Yo.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(qu.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Yo.clearTimeout(this.#e),this.#e=void 0)}};function Cm(e){return{onFetch:(t,n)=>{const s=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},c=0;const u=async()=>{let d=!1;const l=m=>{Sm(m,()=>t.signal,()=>d=!0)},f=Uu(t.options,t.fetchOptions),p=async(m,g,y)=>{if(d)return Promise.reject(t.signal.reason);if(g==null&&m.pages.length)return Promise.resolve(m);const k=(()=>{const _={client:t.client,queryKey:t.queryKey,pageParam:g,direction:y?"backward":"forward",meta:t.options.meta};return l(_),_})(),S=await f(k),{maxPages:w}=t.options,T=y?xm:wm;return{pages:T(m.pages,S,w),pageParams:T(m.pageParams,g,w)}};if(r&&o.length){const m=r==="backward",g=m?Am:oc,y={pages:o,pageParams:i},v=g(s,y);a=await p(y,v,m)}else{const m=e??o.length;do{const g=c===0?i[0]??s.initialPageParam:oc(s,a);if(c>0&&g==null)break;a=await p(a,g),c++}while(ct.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function oc(e,{pages:t,pageParams:n}){const s=t.length-1;return t.length>0?e.getNextPageParam(t[s],t,n[s],n):void 0}function Am(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Rm=class extends Hu{#e;#t;#n;#r;#o;#s;#c;#i;constructor(e){super(),this.#i=!1,this.#c=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#r=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=ac(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#s?.promise}setOptions(e){if(this.options={...this.#c,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=ac(this.options);t.data!==void 0&&(this.setState(ic(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){const n=vm(this.state.data,e,this.options);return this.#a({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#a({type:"setState",state:e})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(wt).catch(wt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>gm(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Bi||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Jo(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!mm(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#s&&(this.#i||this.#l()?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#l(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#a({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#s?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},r=()=>{const c=Uu(this.options,t),d=(()=>{const l={client:this.#o,queryKey:this.queryKey,meta:this.meta};return s(l),l})();return this.#i=!1,this.options.persister?this.options.persister(c,d,this):c(d)},i=(()=>{const c={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:r};return s(c),c})();(this.#e==="infinite"?Cm(this.options.pages):this.options.behavior)?.onFetch(i,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#a({type:"fetch",meta:i.fetchOptions?.meta}),this.#s=Wu({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:c=>{c instanceof ti&&c.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(c,u)=>{this.#a({type:"failed",failureCount:c,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:()=>{this.#a({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0});try{const c=await this.#s.start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),this.#r.config.onSuccess?.(c,this),this.#r.config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof ti){if(c.silent)return this.#s.promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw this.#a({type:"error",error:c}),this.#r.config.onError?.(c,this),this.#r.config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Mm(n.data,this.options),fetchMeta:e.meta??null};case"success":const s={...n,...ic(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?s:void 0,s;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Xe.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Mm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Gu(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function ic(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function ac(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,s=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Im=class extends Hu{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Dm(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#o({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Wu({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(o,i)=>{this.#o({type:"failed",failureCount:o,error:i})},onPause:()=>{this.#o({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const s=this.state.status==="pending",r=!this.#r.canStart();try{if(s)t();else{this.#o({type:"pending",variables:e,isPaused:r}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const i=await this.options.onMutate?.(e,n);i!==this.state.context&&this.#o({type:"pending",context:i,variables:e,isPaused:r})}const o=await this.#r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#o({type:"success",data:o}),o}catch(o){try{await this.#n.config.onError?.(o,e,this.state.context,this,n)}catch(i){Promise.reject(i)}try{await this.options.onError?.(o,e,this.state.context,n)}catch(i){Promise.reject(i)}try{await this.#n.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,n)}catch(i){Promise.reject(i)}try{await this.options.onSettled?.(void 0,o,e,this.state.context,n)}catch(i){Promise.reject(i)}throw this.#o({type:"error",error:o}),o}finally{this.#n.runNext(this)}}#o(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Xe.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function Dm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Om=class extends $r{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const s=new Im({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(s),s}add(e){this.#e.add(e);const t=$s(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=$s(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=$s(e);if(typeof t=="string"){const s=this.#t.get(t)?.find(r=>r.state.status==="pending");return!s||s===e}else return!0}runNext(e){const t=$s(e);return typeof t=="string"?this.#t.get(t)?.find(s=>s!==e&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Xe.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>nc(t,n))}findAll(e={}){return this.getAll().filter(t=>nc(e,t))}notify(e){Xe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Xe.batch(()=>Promise.all(e.map(t=>t.continue().catch(wt))))}};function $s(e){return e.options.scope?.id}var Lm=class extends $r{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const s=t.queryKey,r=t.queryHash??Vi(s,t);let o=this.get(r);return o||(o=new Rm({client:e,queryKey:s,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(s)}),this.add(o)),o}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Xe.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>tc(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>tc(e,n)):t}notify(e){Xe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Xe.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Xe.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},zm=class{#e;#t;#n;#r;#o;#s;#c;#i;constructor(e={}){this.#e=e.queryCache||new Lm,this.#t=e.mutationCache||new Om,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#c=Vu.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vr.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#c?.(),this.#c=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),s=n.state.data;return s===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Jo(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(s))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const s=n.data;return[t,s]})}setQueryData(e,t,n){const s=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(s.queryHash)?.state.data,i=hm(t,o);if(i!==void 0)return this.#e.build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return Xe.batch(()=>this.#e.findAll(e).map(({queryKey:s})=>[s,this.setQueryData(s,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;Xe.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Xe.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},s=Xe.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(s).then(wt).catch(wt)}invalidateQueries(e,t={}){return Xe.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},s=Xe.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let o=r.fetch(void 0,n);return n.throwOnError||(o=o.catch(wt)),r.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(s).then(wt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Jo(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(wt).catch(wt)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(wt).catch(wt)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vr.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(hs(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(s=>{ps(e,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(hs(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(s=>{ps(e,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Vi(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Bi&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Zu=h.createContext(void 0),IR=e=>{const t=h.useContext(Zu);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},jm=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),b.jsx(Zu.Provider,{value:e,children:t}));/** * react-router v7.14.2 * @@ -221,11 +221,11 @@ Please change the parent to k(f,S,w)};let o;const i=Ir,a=!ih.jitless,u=a&&gS.value,d=t.catchall;let l;e._zod.parse=(f,p)=>{l??(l=s.value);const m=f.value;return i(m)?a&&u&&p?.async===!1&&p.jitless!==!0?(o||(o=r(t.shape)),f=o(f,p),d?vh([],m,f,p,l,e):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f)}});function Gl(e,t,n,s){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const r=e.filter(o=>!zn(o));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(i=>Tn(i,s,kn())))}),t)}const K1=C("$ZodUnion",(e,t)=>{ze.init(e,t),fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),fe(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>Aa(o.source)).join("|")})$`)}});const n=t.options.length===1,s=t.options[0]._zod.run;e._zod.parse=(r,o)=>{if(n)return s(r,o);let i=!1;const a=[];for(const c of t.options){const u=c._zod.run({value:r.value,issues:[]},o);if(u instanceof Promise)a.push(u),i=!0;else{if(u.issues.length===0)return u;a.push(u)}}return i?Promise.all(a).then(c=>Gl(c,r,e,o)):Gl(a,r,e,o)}}),Q1=C("$ZodIntersection",(e,t)=>{ze.init(e,t),e._zod.parse=(n,s)=>{const r=n.value,o=t.left._zod.run({value:r,issues:[]},s),i=t.right._zod.run({value:r,issues:[]},s);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>Wl(n,c,u)):Wl(n,o,i)}});function Mi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ws(e)&&ws(t)){const n=Object.keys(t),s=Object.keys(e).filter(o=>n.indexOf(o)!==-1),r={...e,...t};for(const o of s){const i=Mi(e[o],t[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};r[o]=i.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let s=0;sa.l&&a.r).map(([a])=>a);if(o.length&&r&&e.issues.push({...r,keys:o}),zn(e))return e;const i=Mi(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const X1=C("$ZodEnum",(e,t)=>{ze.init(e,t);const n=ah(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(r=>yS.has(typeof r)).map(r=>typeof r=="string"?Zr(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const i=r.value;return s.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:e}),r}}),Y1=C("$ZodTransform",(e,t)=>{ze.init(e,t),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new oh(e.constructor.name);const r=t.transform(n.value,n);if(s.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(n.value=i,n));if(r instanceof Promise)throw new $n;return n.value=r,n}});function Hl(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const wh=C("$ZodOptional",(e,t)=>{ze.init(e,t),e._zod.optin="optional",e._zod.optout="optional",fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),fe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Aa(n.source)})?$`):void 0}),e._zod.parse=(n,s)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(o=>Hl(o,n.value)):Hl(r,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,s)}}),J1=C("$ZodExactOptional",(e,t)=>{wh.init(e,t),fe(e._zod,"values",()=>t.innerType._zod.values),fe(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,s)=>t.innerType._zod.run(n,s)}),ek=C("$ZodNullable",(e,t)=>{ze.init(e,t),fe(e._zod,"optin",()=>t.innerType._zod.optin),fe(e._zod,"optout",()=>t.innerType._zod.optout),fe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Aa(n.source)}|null)$`):void 0}),fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,s)=>n.value===null?n:t.innerType._zod.run(n,s)}),tk=C("$ZodDefault",(e,t)=>{ze.init(e,t),e._zod.optin="optional",fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(o=>Zl(o,t)):Zl(r,t)}});function Zl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const nk=C("$ZodPrefault",(e,t)=>{ze.init(e,t),e._zod.optin="optional",fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,s)=>(s.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,s))}),sk=C("$ZodNonOptional",(e,t)=>{ze.init(e,t),fe(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(s=>s!==void 0)):void 0}),e._zod.parse=(n,s)=>{const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(o=>Kl(o,e)):Kl(r,e)}});function Kl(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const rk=C("$ZodCatch",(e,t)=>{ze.init(e,t),fe(e._zod,"optin",()=>t.innerType._zod.optin),fe(e._zod,"optout",()=>t.innerType._zod.optout),fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>Tn(i,s,kn()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(o=>Tn(o,s,kn()))},input:n.value}),n.issues=[]),n)}}),ok=C("$ZodPipe",(e,t)=>{ze.init(e,t),fe(e._zod,"values",()=>t.in._zod.values),fe(e._zod,"optin",()=>t.in._zod.optin),fe(e._zod,"optout",()=>t.out._zod.optout),fe(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,s)=>{if(s.direction==="backward"){const o=t.out._zod.run(n,s);return o instanceof Promise?o.then(i=>Zs(i,t.in,s)):Zs(o,t.in,s)}const r=t.in._zod.run(n,s);return r instanceof Promise?r.then(o=>Zs(o,t.out,s)):Zs(r,t.out,s)}});function Zs(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const ik=C("$ZodReadonly",(e,t)=>{ze.init(e,t),fe(e._zod,"propValues",()=>t.innerType._zod.propValues),fe(e._zod,"values",()=>t.innerType._zod.values),fe(e._zod,"optin",()=>t.innerType?._zod?.optin),fe(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(Ql):Ql(r)}});function Ql(e){return e.value=Object.freeze(e.value),e}const ak=C("$ZodCustom",(e,t)=>{jt.init(e,t),ze.init(e,t),e._zod.parse=(n,s)=>n,e._zod.check=n=>{const s=n.value,r=t.fn(s);if(r instanceof Promise)return r.then(o=>Xl(o,n,s,e));Xl(r,n,s,e)}});function Xl(e,t,n,s){if(!e){const r={code:"custom",input:n,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(r.params=s._zod.def.params),t.issues.push(xs(r))}}var Yl;class ck{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const s=n[0];return this._map.set(t,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const s={...this.get(n)??{}};delete s.id;const r={...s,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function lk(){return new ck}(Yl=globalThis).__zod_globalRegistry??(Yl.__zod_globalRegistry=lk());const as=globalThis.__zod_globalRegistry;function uk(e,t){return new e({type:"string",...K(t)})}function dk(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...K(t)})}function Jl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...K(t)})}function fk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...K(t)})}function hk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...K(t)})}function pk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...K(t)})}function mk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...K(t)})}function gk(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...K(t)})}function yk(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...K(t)})}function bk(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...K(t)})}function vk(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...K(t)})}function wk(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...K(t)})}function xk(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...K(t)})}function Sk(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...K(t)})}function kk(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...K(t)})}function Tk(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...K(t)})}function _k(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...K(t)})}function Pk(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...K(t)})}function Ek(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...K(t)})}function Ck(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...K(t)})}function Ak(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...K(t)})}function Rk(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...K(t)})}function Mk(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...K(t)})}function Ik(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...K(t)})}function Dk(e,t){return new e({type:"string",format:"date",check:"string_format",...K(t)})}function Ok(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...K(t)})}function Lk(e,t){return new e({type:"string",format:"duration",check:"string_format",...K(t)})}function zk(e){return new e({type:"unknown"})}function jk(e,t){return new e({type:"never",...K(t)})}function xh(e,t){return new a1({check:"max_length",...K(t),maximum:e})}function Or(e,t){return new c1({check:"min_length",...K(t),minimum:e})}function Sh(e,t){return new l1({check:"length_equals",...K(t),length:e})}function Nk(e,t){return new u1({check:"string_format",format:"regex",...K(t),pattern:e})}function $k(e){return new d1({check:"string_format",format:"lowercase",...K(e)})}function Fk(e){return new f1({check:"string_format",format:"uppercase",...K(e)})}function Vk(e,t){return new h1({check:"string_format",format:"includes",...K(t),includes:e})}function Bk(e,t){return new p1({check:"string_format",format:"starts_with",...K(t),prefix:e})}function Uk(e,t){return new m1({check:"string_format",format:"ends_with",...K(t),suffix:e})}function Zn(e){return new g1({check:"overwrite",tx:e})}function qk(e){return Zn(t=>t.normalize(e))}function Gk(){return Zn(e=>e.trim())}function Wk(){return Zn(e=>e.toLowerCase())}function Hk(){return Zn(e=>e.toUpperCase())}function Zk(){return Zn(e=>mS(e))}function Kk(e,t,n){return new e({type:"array",element:t,...K(n)})}function Qk(e,t,n){return new e({type:"custom",check:"custom",fn:t,...K(n)})}function Xk(e){const t=Yk(n=>(n.addIssue=s=>{if(typeof s=="string")n.issues.push(xs(s,n.value,t._zod.def));else{const r=s;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(xs(r))}},e(n.value,n)));return t}function Yk(e,t){const n=new jt({check:"custom",...K(t)});return n._zod.check=e,n}function kh(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??as,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function We(e,t,n={path:[],schemaPath:[]}){var s;const r=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i);const a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{const d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{const f=i.schema,p=t.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(e,t,f,d)}const l=e._zod.parent;l&&(i.ref||(i.ref=l),We(l,t,d),t.seen.get(l).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&Qe(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((s=i.schema).default??(s.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Th(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const i of e.seen.entries()){const a=e.metadataRegistry.get(i[0])?.id;if(a){const c=s.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(a,i[0])}}const r=i=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const l=e.external.registry.get(i[0])?.id,f=e.external.uri??(m=>m);if(l)return{ref:f(l)};const p=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===n)return{ref:"#"};const u=`#/${a}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},o=i=>{if(i[1].schema.$ref)return;const a=i[1],{ref:c,defId:u}=r(i);a.def={...a.schema},u&&(a.defId=u);const d=a.schema;for(const l in d)delete d[l];d.$ref=c};if(e.cycles==="throw")for(const i of e.seen.entries()){const a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const a=i[1];if(t===i[0]){o(i);continue}if(e.external){const u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}if(a.count>1&&e.reused==="ref"){o(i);continue}}}function _h(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i=>{const a=e.seen.get(i);if(a.ref===null)return;const c=a.def??a.schema,u={...c},d=a.ref;if(a.ref=null,d){s(d);const f=e.seen.get(d),p=f.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Object.assign(c,p),Object.assign(c,u),i._zod.parent===d)for(const g in c)g==="$ref"||g==="allOf"||g in u||delete c[g];if(p.$ref&&f.def)for(const g in c)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(c[g])===JSON.stringify(f.def[g])&&delete c[g]}const l=i._zod.parent;if(l&&l!==d){s(l);const f=e.seen.get(l);if(f?.schema.$ref&&(c.$ref=f.schema.$ref,f.def))for(const p in c)p==="$ref"||p==="allOf"||p in f.def&&JSON.stringify(c[p])===JSON.stringify(f.def[p])&&delete c[p]}e.override({zodSchema:i,jsonSchema:c,path:a.path??[]})};for(const i of[...e.seen.entries()].reverse())s(i[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(i)}Object.assign(r,n.def??n.schema);const o=e.external?.defs??{};for(const i of e.seen.entries()){const a=i[1];a.def&&a.defId&&(o[a.defId]=a.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{const i=JSON.parse(JSON.stringify(r));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Lr(t,"input",e.processors),output:Lr(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function Qe(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return Qe(s.element,n);if(s.type==="set")return Qe(s.valueType,n);if(s.type==="lazy")return Qe(s.getter(),n);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return Qe(s.innerType,n);if(s.type==="intersection")return Qe(s.left,n)||Qe(s.right,n);if(s.type==="record"||s.type==="map")return Qe(s.keyType,n)||Qe(s.valueType,n);if(s.type==="pipe")return Qe(s.in,n)||Qe(s.out,n);if(s.type==="object"){for(const r in s.shape)if(Qe(s.shape[r],n))return!0;return!1}if(s.type==="union"){for(const r of s.options)if(Qe(r,n))return!0;return!1}if(s.type==="tuple"){for(const r of s.items)if(Qe(r,n))return!0;return!!(s.rest&&Qe(s.rest,n))}return!1}const Jk=(e,t={})=>n=>{const s=kh({...n,processors:t});return We(e,s),Th(s,e),_h(s,e)},Lr=(e,t,n={})=>s=>{const{libraryOptions:r,target:o}=s??{},i=kh({...r??{},target:o,io:t,processors:n});return We(e,i),Th(i,e),_h(i,e)},eT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tT=(e,t,n,s)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof o=="number"&&(r.minLength=o),typeof i=="number"&&(r.maxLength=i),a&&(r.format=eT[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),u&&(r.contentEncoding=u),c&&c.size>0){const d=[...c];d.length===1?r.pattern=d[0].source:d.length>1&&(r.allOf=[...d.map(l=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},nT=(e,t,n,s)=>{n.not={}},sT=(e,t,n,s)=>{},rT=(e,t,n,s)=>{const r=e._zod.def,o=ah(r.entries);o.every(i=>typeof i=="number")&&(n.type="number"),o.every(i=>typeof i=="string")&&(n.type="string"),n.enum=o},oT=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},iT=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},aT=(e,t,n,s)=>{const r=n,o=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(r.minItems=i),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=We(o.element,t,{...s,path:[...s.path,"items"]})},cT=(e,t,n,s)=>{const r=n,o=e._zod.def;r.type="object",r.properties={};const i=o.shape;for(const u in i)r.properties[u]=We(i[u],t,{...s,path:[...s.path,"properties",u]});const a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{const d=o.shape[u]._zod;return t.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(r.required=Array.from(c)),o.catchall?._zod.def.type==="never"?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=We(o.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},lT=(e,t,n,s)=>{const r=e._zod.def,o=r.inclusive===!1,i=r.options.map((a,c)=>We(a,t,{...s,path:[...s.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=i:n.anyOf=i},uT=(e,t,n,s)=>{const r=e._zod.def,o=We(r.left,t,{...s,path:[...s.path,"allOf",0]}),i=We(r.right,t,{...s,path:[...s.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(i)?i.allOf:[i]];n.allOf=c},dT=(e,t,n,s)=>{const r=e._zod.def,o=We(r.innerType,t,s),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=r.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},fT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},hT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},pT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},mT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType;let i;try{i=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},gT=(e,t,n,s)=>{const r=e._zod.def,o=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;We(o,t,s);const i=t.seen.get(e);i.ref=o},yT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},Ph=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},bT=C("ZodISODateTime",(e,t)=>{R1.init(e,t),ke.init(e,t)});function vT(e){return Ik(bT,e)}const wT=C("ZodISODate",(e,t)=>{M1.init(e,t),ke.init(e,t)});function xT(e){return Dk(wT,e)}const ST=C("ZodISOTime",(e,t)=>{I1.init(e,t),ke.init(e,t)});function kT(e){return Ok(ST,e)}const TT=C("ZodISODuration",(e,t)=>{D1.init(e,t),ke.init(e,t)});function _T(e){return Lk(TT,e)}const PT=(e,t)=>{fh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>ES(e,n)},flatten:{value:n=>PS(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ri,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ri,2)}},isEmpty:{get(){return e.issues.length===0}}})},ht=C("ZodError",PT,{Parent:Error}),ET=Ma(ht),CT=Ia(ht),AT=Kr(ht),RT=Qr(ht),MT=RS(ht),IT=MS(ht),DT=IS(ht),OT=DS(ht),LT=OS(ht),zT=LS(ht),jT=zS(ht),NT=jS(ht),je=C("ZodType",(e,t)=>(ze.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Lr(e,"input"),output:Lr(e,"output")}}),e.toJSONSchema=Jk(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(rn(t,{checks:[...t.checks??[],...n.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),e.with=e.check,e.clone=(n,s)=>on(e,n,s),e.brand=()=>e,e.register=((n,s)=>(n.add(e,s),e)),e.parse=(n,s)=>ET(e,n,s,{callee:e.parse}),e.safeParse=(n,s)=>AT(e,n,s),e.parseAsync=async(n,s)=>CT(e,n,s,{callee:e.parseAsync}),e.safeParseAsync=async(n,s)=>RT(e,n,s),e.spa=e.safeParseAsync,e.encode=(n,s)=>MT(e,n,s),e.decode=(n,s)=>IT(e,n,s),e.encodeAsync=async(n,s)=>DT(e,n,s),e.decodeAsync=async(n,s)=>OT(e,n,s),e.safeEncode=(n,s)=>LT(e,n,s),e.safeDecode=(n,s)=>zT(e,n,s),e.safeEncodeAsync=async(n,s)=>jT(e,n,s),e.safeDecodeAsync=async(n,s)=>NT(e,n,s),e.refine=(n,s)=>e.check(M_(n,s)),e.superRefine=n=>e.check(I_(n)),e.overwrite=n=>e.check(Zn(n)),e.optional=()=>nu(e),e.exactOptional=()=>b_(e),e.nullable=()=>su(e),e.nullish=()=>nu(su(e)),e.nonoptional=n=>T_(e,n),e.array=()=>a_(e),e.or=n=>d_([e,n]),e.and=n=>h_(e,n),e.transform=n=>ru(e,g_(n)),e.default=n=>x_(e,n),e.prefault=n=>k_(e,n),e.catch=n=>P_(e,n),e.pipe=n=>ru(e,n),e.readonly=()=>A_(e),e.describe=n=>{const s=e.clone();return as.add(s,{description:n}),s},Object.defineProperty(e,"description",{get(){return as.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return as.get(e);const s=e.clone();return as.add(s,n[0]),s},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),Eh=C("_ZodString",(e,t)=>{Da.init(e,t),je.init(e,t),e._zod.processJSONSchema=(s,r,o)=>tT(e,s,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...s)=>e.check(Nk(...s)),e.includes=(...s)=>e.check(Vk(...s)),e.startsWith=(...s)=>e.check(Bk(...s)),e.endsWith=(...s)=>e.check(Uk(...s)),e.min=(...s)=>e.check(Or(...s)),e.max=(...s)=>e.check(xh(...s)),e.length=(...s)=>e.check(Sh(...s)),e.nonempty=(...s)=>e.check(Or(1,...s)),e.lowercase=s=>e.check($k(s)),e.uppercase=s=>e.check(Fk(s)),e.trim=()=>e.check(Gk()),e.normalize=(...s)=>e.check(qk(...s)),e.toLowerCase=()=>e.check(Wk()),e.toUpperCase=()=>e.check(Hk()),e.slugify=()=>e.check(Zk())}),$T=C("ZodString",(e,t)=>{Da.init(e,t),Eh.init(e,t),e.email=n=>e.check(dk(FT,n)),e.url=n=>e.check(gk(VT,n)),e.jwt=n=>e.check(Mk(n_,n)),e.emoji=n=>e.check(yk(BT,n)),e.guid=n=>e.check(Jl(eu,n)),e.uuid=n=>e.check(fk(Ks,n)),e.uuidv4=n=>e.check(hk(Ks,n)),e.uuidv6=n=>e.check(pk(Ks,n)),e.uuidv7=n=>e.check(mk(Ks,n)),e.nanoid=n=>e.check(bk(UT,n)),e.guid=n=>e.check(Jl(eu,n)),e.cuid=n=>e.check(vk(qT,n)),e.cuid2=n=>e.check(wk(GT,n)),e.ulid=n=>e.check(xk(WT,n)),e.base64=n=>e.check(Ck(JT,n)),e.base64url=n=>e.check(Ak(e_,n)),e.xid=n=>e.check(Sk(HT,n)),e.ksuid=n=>e.check(kk(ZT,n)),e.ipv4=n=>e.check(Tk(KT,n)),e.ipv6=n=>e.check(_k(QT,n)),e.cidrv4=n=>e.check(Pk(XT,n)),e.cidrv6=n=>e.check(Ek(YT,n)),e.e164=n=>e.check(Rk(t_,n)),e.datetime=n=>e.check(vT(n)),e.date=n=>e.check(xT(n)),e.time=n=>e.check(kT(n)),e.duration=n=>e.check(_T(n))});function Ch(e){return uk($T,e)}const ke=C("ZodStringFormat",(e,t)=>{we.init(e,t),Eh.init(e,t)}),FT=C("ZodEmail",(e,t)=>{x1.init(e,t),ke.init(e,t)}),eu=C("ZodGUID",(e,t)=>{v1.init(e,t),ke.init(e,t)}),Ks=C("ZodUUID",(e,t)=>{w1.init(e,t),ke.init(e,t)}),VT=C("ZodURL",(e,t)=>{S1.init(e,t),ke.init(e,t)}),BT=C("ZodEmoji",(e,t)=>{k1.init(e,t),ke.init(e,t)}),UT=C("ZodNanoID",(e,t)=>{T1.init(e,t),ke.init(e,t)}),qT=C("ZodCUID",(e,t)=>{_1.init(e,t),ke.init(e,t)}),GT=C("ZodCUID2",(e,t)=>{P1.init(e,t),ke.init(e,t)}),WT=C("ZodULID",(e,t)=>{E1.init(e,t),ke.init(e,t)}),HT=C("ZodXID",(e,t)=>{C1.init(e,t),ke.init(e,t)}),ZT=C("ZodKSUID",(e,t)=>{A1.init(e,t),ke.init(e,t)}),KT=C("ZodIPv4",(e,t)=>{O1.init(e,t),ke.init(e,t)}),QT=C("ZodIPv6",(e,t)=>{L1.init(e,t),ke.init(e,t)}),XT=C("ZodCIDRv4",(e,t)=>{z1.init(e,t),ke.init(e,t)}),YT=C("ZodCIDRv6",(e,t)=>{j1.init(e,t),ke.init(e,t)}),JT=C("ZodBase64",(e,t)=>{N1.init(e,t),ke.init(e,t)}),e_=C("ZodBase64URL",(e,t)=>{F1.init(e,t),ke.init(e,t)}),t_=C("ZodE164",(e,t)=>{V1.init(e,t),ke.init(e,t)}),n_=C("ZodJWT",(e,t)=>{U1.init(e,t),ke.init(e,t)}),s_=C("ZodUnknown",(e,t)=>{q1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>sT()});function tu(){return zk(s_)}const r_=C("ZodNever",(e,t)=>{G1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>nT(e,n,s)});function o_(e){return jk(r_,e)}const i_=C("ZodArray",(e,t)=>{W1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>aT(e,n,s,r),e.element=t.element,e.min=(n,s)=>e.check(Or(n,s)),e.nonempty=n=>e.check(Or(1,n)),e.max=(n,s)=>e.check(xh(n,s)),e.length=(n,s)=>e.check(Sh(n,s)),e.unwrap=()=>e.element});function a_(e,t){return Kk(i_,e,t)}const c_=C("ZodObject",(e,t)=>{Z1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>cT(e,n,s,r),fe(e,"shape",()=>t.shape),e.keyof=()=>p_(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:tu()}),e.loose=()=>e.clone({...e._zod.def,catchall:tu()}),e.strict=()=>e.clone({...e._zod.def,catchall:o_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>xS(e,n),e.safeExtend=n=>SS(e,n),e.merge=n=>kS(e,n),e.pick=n=>vS(e,n),e.omit=n=>wS(e,n),e.partial=(...n)=>TS(Ah,e,n[0]),e.required=(...n)=>_S(Rh,e,n[0])});function l_(e,t){const n={type:"object",shape:e??{},...K(t)};return new c_(n)}const u_=C("ZodUnion",(e,t)=>{K1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>lT(e,n,s,r),e.options=t.options});function d_(e,t){return new u_({type:"union",options:e,...K(t)})}const f_=C("ZodIntersection",(e,t)=>{Q1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>uT(e,n,s,r)});function h_(e,t){return new f_({type:"intersection",left:e,right:t})}const Ii=C("ZodEnum",(e,t)=>{X1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(s,r,o)=>rT(e,s,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(s,r)=>{const o={};for(const i of s)if(n.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ii({...t,checks:[],...K(r),entries:o})},e.exclude=(s,r)=>{const o={...t.entries};for(const i of s)if(n.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Ii({...t,checks:[],...K(r),entries:o})}});function p_(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Ii({type:"enum",entries:n,...K(t)})}const m_=C("ZodTransform",(e,t)=>{Y1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>iT(e,n),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new oh(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(xs(o,n.value,t));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(xs(i))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(o=>(n.value=o,n)):(n.value=r,n)}});function g_(e){return new m_({type:"transform",transform:e})}const Ah=C("ZodOptional",(e,t)=>{wh.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ph(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function nu(e){return new Ah({type:"optional",innerType:e})}const y_=C("ZodExactOptional",(e,t)=>{J1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ph(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function b_(e){return new y_({type:"optional",innerType:e})}const v_=C("ZodNullable",(e,t)=>{ek.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>dT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function su(e){return new v_({type:"nullable",innerType:e})}const w_=C("ZodDefault",(e,t)=>{tk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>hT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function x_(e,t){return new w_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():lh(t)}})}const S_=C("ZodPrefault",(e,t)=>{nk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>pT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function k_(e,t){return new S_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():lh(t)}})}const Rh=C("ZodNonOptional",(e,t)=>{sk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>fT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function T_(e,t){return new Rh({type:"nonoptional",innerType:e,...K(t)})}const __=C("ZodCatch",(e,t)=>{rk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>mT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function P_(e,t){return new __({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const E_=C("ZodPipe",(e,t)=>{ok.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>gT(e,n,s,r),e.in=t.in,e.out=t.out});function ru(e,t){return new E_({type:"pipe",in:e,out:t})}const C_=C("ZodReadonly",(e,t)=>{ik.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>yT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function A_(e){return new C_({type:"readonly",innerType:e})}const R_=C("ZodCustom",(e,t)=>{ak.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>oT(e,n)});function M_(e,t={}){return Qk(R_,e,t)}function I_(e){return Xk(e)}const D_=/[<>]/;function O_(e,t="User"){if(typeof e!="string")return t;const n=e.replace(/[<>]/g,"").replace(/\s+/g," ").trim();return n.length>0?n.slice(0,100):t}const L_=/^\+?[0-9 ()\-.]{7,20}$/,z_=Ch().trim().min(1,"Full name is required").max(100,"Full name must be 100 characters or fewer").refine(e=>!D_.test(e),{message:"Full name cannot contain < or > characters"}),j_=Ch().trim().max(20,"Phone number must be 20 characters or fewer").refine(e=>e.length===0||L_.test(e),{message:"Phone number must contain only digits and + ( ) - . spaces"}),N_=l_({name:z_,phone:j_.optional()});function OR(e){const t=N_.safeParse({name:e.name??"",phone:e.phone??""});return t.success?null:t.error.issues[0]?.message??"Invalid profile data"}new Gp;const Di="mathpulse.pendingAuthRole",Mh="mathpulse.lastAuthRole",$_=e=>{if(e==="admin")throw new Error("Admin account creation is restricted. Please contact an existing administrator.")},Oa=(e,t)=>{const n=e,s=new Error(n.message||t);return n.code&&(s.code=n.code),s},LR=e=>{try{localStorage.setItem(Di,e),localStorage.setItem(Mh,e)}catch{}},F_=()=>{try{const e=localStorage.getItem(Di);return localStorage.removeItem(Di),e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},V_=()=>{try{const e=localStorage.getItem(Mh);return e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},zR=async(e,t,n,s,r={})=>{try{$_(s);const i=(await Wp(ye,e,t)).user;return await Hp(i,{displayName:n}),await Ih(i,s,r)}catch(o){const i=o;throw console.error("[ERROR] Error signing up:",{code:i.code,message:i.message,fullError:o}),Oa(o,"Failed to create account")}},jR=async(e,t)=>{try{await Zp(ye,e,t)}catch(n){const s=n;throw console.error("[ERROR] Error signing in:",{code:s.code,message:s.message,fullError:n}),Oa(n,"Failed to sign in")}},ou=async()=>{try{await Kp(ye)}catch(e){throw console.error("Error signing out:",e),Oa(e,"Failed to sign out")}},Ih=async(e,t,n)=>{const s=`${Date.now()}`.slice(-12).padStart(12,"0"),r={uid:e.uid,email:e.email||"",name:e.displayName||n.name||"User",role:t,photo:e.photoURL||"",createdAt:ae(),updatedAt:ae()},o=(()=>{switch(t){case"student":return{lrn:n.lrn||s,grade:n.grade||"Grade 11",section:n.section||"Section A",classSectionId:n.classSectionId||"",adviserTeacherId:n.adviserTeacherId||"",adviserTeacherName:n.adviserTeacherName||"",schoolYear:n.schoolYear||"",school:n.school||"",enrollmentDate:new Date().toISOString().split("T")[0],major:n.major||"General",gpa:n.gpa||"0.00",level:1,currentXP:0,totalXP:0,atRiskSubjects:[],hasTakenDiagnostic:!1,iarAssessmentState:"not_started",startingQuarterG11:"Q1",recommendedPace:"normal"};case"teacher":return{teacherId:`TCH-${Date.now()}`,department:n.department||"Mathematics",subject:n.subject||"Mathematics",yearsOfExperience:n.yearsOfExperience||"0",qualification:n.qualification||"",students:[]};case"admin":return{adminId:`ADM-${Date.now()}`,position:n.position||"Administrator",department:n.department||"System"}}})(),i={...r,...o};return await Ce(U(L,"users",e.uid),i),i},La=async e=>{try{const t=U(L,"users",e),n=await me(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.error("Error getting user profile:",t),null}},B_=async e=>{try{const t=U(L,"users",e),n=await Xo(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.warn("[getUserProfileFromServer] Server read failed, falling back to cache:",t),La(e)}},U_=async(e,t)=>{try{const n=await La(e);if(!n)throw new Error("Profile not found");const s=["name","email","phone","photo","avatarLayers","gender"],r={student:["lrn","grade","section","school","enrollmentDate","major","gpa"],teacher:["department","subject","yearsOfExperience","qualification"],admin:["department","position"]},o=new Set([...s,...r[n.role]]),i={};Object.entries(t).forEach(([c,u])=>{if(!(u===void 0||!o.has(c))){if(c==="avatarLayers"&&typeof u=="object"&&u!==null){const d=u;i[c]={top:typeof d.top=="string"?d.top:"",bottom:typeof d.bottom=="string"?d.bottom:"",shoes:typeof d.shoes=="string"?d.shoes:"",accessory:typeof d.accessory=="string"?d.accessory:""};return}i[c]=u}});const a=U(L,"users",e);await Ce(a,{...i,updatedAt:ae()},{merge:!0})}catch(n){throw console.error("Error updating user profile:",n),n}},Dh=h.createContext({currentUser:null,userProfile:null,loading:!0,isLoggedIn:!1,userRole:"student",refreshProfile:async()=>{}}),Ms=()=>{const e=h.useContext(Dh);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e},q_=({children:e})=>{const[t,n]=h.useState(null),[s,r]=h.useState(null),[o,i]=h.useState(!0),[a,c]=h.useState("student"),u=f=>{if(!f)return null;const p=f.trim().toLowerCase();return p==="testteacher@school.edu"?"teacher":p==="testadmin@school.edu"?"admin":p==="teststudent@school.edu"?"student":null};h.useEffect(()=>Qp(ye,async p=>{if(i(!0),n(p),p){const m=F_()||V_()||u(p.email)||"student",g=m==="admin"?"student":m;let y=await La(p.uid);if(!y&&p.email){const v=g,k=p.displayName||"User";try{y=await Ih(p,v,{name:k}),v==="student"&&ee(async()=>{const{triggerStudentEnrolled:S}=await import("./automationService-Ckfa20vv.js");return{triggerStudentEnrolled:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])).then(({triggerStudentEnrolled:S})=>S({lrn:y?.lrn||p.uid,name:k,email:p.email||"",gradeLevel:""})).catch(S=>console.error("[WARN] Automation: enrollment pipeline failed:",S))}catch(S){console.error("[ERROR] AuthContext: Failed to auto-create profile:",S)}}if(y){if(c(y.role),r(y),ee(async()=>{const{doc:v,updateDoc:k,serverTimestamp:S}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{doc:v,updateDoc:k,serverTimestamp:S}},__vite__mapDeps([1,2])).then(({doc:v,updateDoc:k,serverTimestamp:S})=>{ee(async()=>{const{db:w}=await Promise.resolve().then(()=>pS);return{db:w}},void 0).then(({db:w})=>{k(v(w,"users",p.uid),{lastActive:S()}).catch(()=>{})})}),y.role==="student"){const v=y.classSectionId||"",k=y.adviserTeacherId||"";(v||k)&&ee(async()=>{const{setStudentContext:S}=await import("./pipelineService-BVFD1ZML.js");return{setStudentContext:S}},__vite__mapDeps([11,3,1,2,4,5,6,7,8,9,10])).then(({setStudentContext:S})=>{S(v,k)}).catch(()=>{})}}else c(g),r({uid:p.uid,email:p.email||"",name:p.displayName||"User",role:g,photo:p.photoURL||"",createdAt:new Date,updatedAt:new Date})}else c("student"),r(null);i(!1)}),[]);const d=async()=>{if(t){const f=await B_(t.uid);f&&r(f)}},l={currentUser:t,userProfile:s,loading:o,isLoggedIn:!!t,userRole:s?.role||a,refreshProfile:d};return b.jsx(Dh.Provider,{value:l,children:e})},G_=({children:e})=>{const{currentUser:t}=Ms(),[n,s]=h.useState(!1),[r,o]=h.useState(!0),[i,a]=h.useState("your teacher");return h.useEffect(()=>{if(!t?.uid){o(!1);return}const c=U(L,"users",t.uid);return en(c,async d=>{if(!d.exists()){o(!1);return}const l=d.data(),f=l?.teacherAckRequired===!0,p=l?.teacherAcknowledged===!0;if(f&&!p){s(!0);const m=l?.teacherId;if(m)try{const{getDoc:g}=await ee(async()=>{const{getDoc:v}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{getDoc:v}},__vite__mapDeps([1,2])),y=await g(U(L,"users",m));if(y.exists()){const v=y.data();a(O_(v?.displayName||v?.name,"your teacher"))}}catch{}}else s(!1);o(!1)},()=>{o(!1)})},[t?.uid]),r?b.jsx("div",{className:"flex items-center justify-center min-h-screen bg-slate-50",children:b.jsx(Nx,{className:"animate-spin text-slate-400",size:32})}):b.jsx(Uf,{mode:"wait",children:n?b.jsx(Nn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"flex items-center justify-center min-h-screen bg-slate-50 p-6",children:b.jsxs("div",{className:"max-w-md w-full bg-white border border-slate-200 rounded-2xl p-8 shadow-sm text-center space-y-6",children:[b.jsx("div",{className:"w-16 h-16 bg-rose-50 rounded-full flex items-center justify-center mx-auto",children:b.jsx(Fx,{className:"text-rose-500",size:28})}),b.jsxs("div",{children:[b.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"Progress Paused"}),b.jsxs("p",{className:"text-sm text-slate-500 mt-2",children:["Your learning path is temporarily paused while ",i," reviews your recent progress."]})]}),b.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 text-left",children:b.jsxs("div",{className:"flex items-start gap-3",children:[b.jsx(Ei,{className:"text-amber-500 flex-shrink-0 mt-0.5",size:16}),b.jsxs("div",{className:"text-sm text-amber-800",children:[b.jsx("p",{className:"font-semibold",children:"Why am I seeing this?"}),b.jsxs("p",{className:"mt-1",children:["The system detected that you may need additional support. ",i," has been notified and will reach out soon with a personalized plan."]})]})]})}),b.jsx("div",{className:"text-xs text-slate-400",children:"You can still review completed lessons and practice problems while you wait."})]})},"gate"):b.jsx(Nn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e},"content")})},W_=/(```[\s\S]*?```|`[^`\n]+`)/g,H_=/(\$\$[\s\S]*?\$\$|\$[^$\n]+\$|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]|\[(?![^[]*\]\()[^\]]+\]|(?]*>[\s\S]*?<\s*\/\s*think\s*>/gi,Q_=/<\s*\/?\s*think\b[^>]*>/gi,X_=/<\s*\/\s*think\s*>/gi,Y_=/<\s*(\/?)\s*think\b([\s\S]*?)>/gi,J_=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,eP=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,tP=/\bfinal\s+answer\s*:|(?:^|\n)\s*#{1,6}\s+\S|(?:^|\n)\s*(?:answer|solution)\s*:|(?:^|\n)\s*here(?:'s| is)\b|(?:^|\n)\s*(?:\d+[.)]|[-*])\s+\S/i,nP=/^\s*(?:okay|alright|let\s+me|i\s+should|i\s+need\s+to|i\s+will|wait|hmm|maybe|the\s+user\s+asked|let\s+us|let's)\b/i;function Oh(e){return e.replace(Y_,(t,n,s)=>`<${n?"/":""}think${s}>`)}function sP(e,t){t.lastIndex=0;let n=-1,s=t.exec(e);for(;s;)n=s.index+s[0].length,s=t.exec(e);return n}function rP(e){const t=Oh(e);if(/<\s*think\b/i.test(t))return"";const n=sP(t,X_);return n===-1?"":t.slice(n).trim()}function oP(e){const t=e.replace(/\r\n?/g,` +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const a=i[1];if(t===i[0]){o(i);continue}if(e.external){const u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}if(a.count>1&&e.reused==="ref"){o(i);continue}}}function _h(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i=>{const a=e.seen.get(i);if(a.ref===null)return;const c=a.def??a.schema,u={...c},d=a.ref;if(a.ref=null,d){s(d);const f=e.seen.get(d),p=f.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Object.assign(c,p),Object.assign(c,u),i._zod.parent===d)for(const g in c)g==="$ref"||g==="allOf"||g in u||delete c[g];if(p.$ref&&f.def)for(const g in c)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(c[g])===JSON.stringify(f.def[g])&&delete c[g]}const l=i._zod.parent;if(l&&l!==d){s(l);const f=e.seen.get(l);if(f?.schema.$ref&&(c.$ref=f.schema.$ref,f.def))for(const p in c)p==="$ref"||p==="allOf"||p in f.def&&JSON.stringify(c[p])===JSON.stringify(f.def[p])&&delete c[p]}e.override({zodSchema:i,jsonSchema:c,path:a.path??[]})};for(const i of[...e.seen.entries()].reverse())s(i[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(i)}Object.assign(r,n.def??n.schema);const o=e.external?.defs??{};for(const i of e.seen.entries()){const a=i[1];a.def&&a.defId&&(o[a.defId]=a.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{const i=JSON.parse(JSON.stringify(r));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Lr(t,"input",e.processors),output:Lr(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function Qe(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return Qe(s.element,n);if(s.type==="set")return Qe(s.valueType,n);if(s.type==="lazy")return Qe(s.getter(),n);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return Qe(s.innerType,n);if(s.type==="intersection")return Qe(s.left,n)||Qe(s.right,n);if(s.type==="record"||s.type==="map")return Qe(s.keyType,n)||Qe(s.valueType,n);if(s.type==="pipe")return Qe(s.in,n)||Qe(s.out,n);if(s.type==="object"){for(const r in s.shape)if(Qe(s.shape[r],n))return!0;return!1}if(s.type==="union"){for(const r of s.options)if(Qe(r,n))return!0;return!1}if(s.type==="tuple"){for(const r of s.items)if(Qe(r,n))return!0;return!!(s.rest&&Qe(s.rest,n))}return!1}const Jk=(e,t={})=>n=>{const s=kh({...n,processors:t});return We(e,s),Th(s,e),_h(s,e)},Lr=(e,t,n={})=>s=>{const{libraryOptions:r,target:o}=s??{},i=kh({...r??{},target:o,io:t,processors:n});return We(e,i),Th(i,e),_h(i,e)},eT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tT=(e,t,n,s)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof o=="number"&&(r.minLength=o),typeof i=="number"&&(r.maxLength=i),a&&(r.format=eT[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),u&&(r.contentEncoding=u),c&&c.size>0){const d=[...c];d.length===1?r.pattern=d[0].source:d.length>1&&(r.allOf=[...d.map(l=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},nT=(e,t,n,s)=>{n.not={}},sT=(e,t,n,s)=>{},rT=(e,t,n,s)=>{const r=e._zod.def,o=ah(r.entries);o.every(i=>typeof i=="number")&&(n.type="number"),o.every(i=>typeof i=="string")&&(n.type="string"),n.enum=o},oT=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},iT=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},aT=(e,t,n,s)=>{const r=n,o=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(r.minItems=i),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=We(o.element,t,{...s,path:[...s.path,"items"]})},cT=(e,t,n,s)=>{const r=n,o=e._zod.def;r.type="object",r.properties={};const i=o.shape;for(const u in i)r.properties[u]=We(i[u],t,{...s,path:[...s.path,"properties",u]});const a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{const d=o.shape[u]._zod;return t.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(r.required=Array.from(c)),o.catchall?._zod.def.type==="never"?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=We(o.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},lT=(e,t,n,s)=>{const r=e._zod.def,o=r.inclusive===!1,i=r.options.map((a,c)=>We(a,t,{...s,path:[...s.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=i:n.anyOf=i},uT=(e,t,n,s)=>{const r=e._zod.def,o=We(r.left,t,{...s,path:[...s.path,"allOf",0]}),i=We(r.right,t,{...s,path:[...s.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(i)?i.allOf:[i]];n.allOf=c},dT=(e,t,n,s)=>{const r=e._zod.def,o=We(r.innerType,t,s),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=r.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},fT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},hT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},pT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},mT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType;let i;try{i=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},gT=(e,t,n,s)=>{const r=e._zod.def,o=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;We(o,t,s);const i=t.seen.get(e);i.ref=o},yT=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},Ph=(e,t,n,s)=>{const r=e._zod.def;We(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},bT=C("ZodISODateTime",(e,t)=>{R1.init(e,t),ke.init(e,t)});function vT(e){return Ik(bT,e)}const wT=C("ZodISODate",(e,t)=>{M1.init(e,t),ke.init(e,t)});function xT(e){return Dk(wT,e)}const ST=C("ZodISOTime",(e,t)=>{I1.init(e,t),ke.init(e,t)});function kT(e){return Ok(ST,e)}const TT=C("ZodISODuration",(e,t)=>{D1.init(e,t),ke.init(e,t)});function _T(e){return Lk(TT,e)}const PT=(e,t)=>{fh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>ES(e,n)},flatten:{value:n=>PS(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ri,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ri,2)}},isEmpty:{get(){return e.issues.length===0}}})},ht=C("ZodError",PT,{Parent:Error}),ET=Ma(ht),CT=Ia(ht),AT=Kr(ht),RT=Qr(ht),MT=RS(ht),IT=MS(ht),DT=IS(ht),OT=DS(ht),LT=OS(ht),zT=LS(ht),jT=zS(ht),NT=jS(ht),je=C("ZodType",(e,t)=>(ze.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Lr(e,"input"),output:Lr(e,"output")}}),e.toJSONSchema=Jk(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(rn(t,{checks:[...t.checks??[],...n.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),e.with=e.check,e.clone=(n,s)=>on(e,n,s),e.brand=()=>e,e.register=((n,s)=>(n.add(e,s),e)),e.parse=(n,s)=>ET(e,n,s,{callee:e.parse}),e.safeParse=(n,s)=>AT(e,n,s),e.parseAsync=async(n,s)=>CT(e,n,s,{callee:e.parseAsync}),e.safeParseAsync=async(n,s)=>RT(e,n,s),e.spa=e.safeParseAsync,e.encode=(n,s)=>MT(e,n,s),e.decode=(n,s)=>IT(e,n,s),e.encodeAsync=async(n,s)=>DT(e,n,s),e.decodeAsync=async(n,s)=>OT(e,n,s),e.safeEncode=(n,s)=>LT(e,n,s),e.safeDecode=(n,s)=>zT(e,n,s),e.safeEncodeAsync=async(n,s)=>jT(e,n,s),e.safeDecodeAsync=async(n,s)=>NT(e,n,s),e.refine=(n,s)=>e.check(M_(n,s)),e.superRefine=n=>e.check(I_(n)),e.overwrite=n=>e.check(Zn(n)),e.optional=()=>nu(e),e.exactOptional=()=>b_(e),e.nullable=()=>su(e),e.nullish=()=>nu(su(e)),e.nonoptional=n=>T_(e,n),e.array=()=>a_(e),e.or=n=>d_([e,n]),e.and=n=>h_(e,n),e.transform=n=>ru(e,g_(n)),e.default=n=>x_(e,n),e.prefault=n=>k_(e,n),e.catch=n=>P_(e,n),e.pipe=n=>ru(e,n),e.readonly=()=>A_(e),e.describe=n=>{const s=e.clone();return as.add(s,{description:n}),s},Object.defineProperty(e,"description",{get(){return as.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return as.get(e);const s=e.clone();return as.add(s,n[0]),s},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),Eh=C("_ZodString",(e,t)=>{Da.init(e,t),je.init(e,t),e._zod.processJSONSchema=(s,r,o)=>tT(e,s,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...s)=>e.check(Nk(...s)),e.includes=(...s)=>e.check(Vk(...s)),e.startsWith=(...s)=>e.check(Bk(...s)),e.endsWith=(...s)=>e.check(Uk(...s)),e.min=(...s)=>e.check(Or(...s)),e.max=(...s)=>e.check(xh(...s)),e.length=(...s)=>e.check(Sh(...s)),e.nonempty=(...s)=>e.check(Or(1,...s)),e.lowercase=s=>e.check($k(s)),e.uppercase=s=>e.check(Fk(s)),e.trim=()=>e.check(Gk()),e.normalize=(...s)=>e.check(qk(...s)),e.toLowerCase=()=>e.check(Wk()),e.toUpperCase=()=>e.check(Hk()),e.slugify=()=>e.check(Zk())}),$T=C("ZodString",(e,t)=>{Da.init(e,t),Eh.init(e,t),e.email=n=>e.check(dk(FT,n)),e.url=n=>e.check(gk(VT,n)),e.jwt=n=>e.check(Mk(n_,n)),e.emoji=n=>e.check(yk(BT,n)),e.guid=n=>e.check(Jl(eu,n)),e.uuid=n=>e.check(fk(Ks,n)),e.uuidv4=n=>e.check(hk(Ks,n)),e.uuidv6=n=>e.check(pk(Ks,n)),e.uuidv7=n=>e.check(mk(Ks,n)),e.nanoid=n=>e.check(bk(UT,n)),e.guid=n=>e.check(Jl(eu,n)),e.cuid=n=>e.check(vk(qT,n)),e.cuid2=n=>e.check(wk(GT,n)),e.ulid=n=>e.check(xk(WT,n)),e.base64=n=>e.check(Ck(JT,n)),e.base64url=n=>e.check(Ak(e_,n)),e.xid=n=>e.check(Sk(HT,n)),e.ksuid=n=>e.check(kk(ZT,n)),e.ipv4=n=>e.check(Tk(KT,n)),e.ipv6=n=>e.check(_k(QT,n)),e.cidrv4=n=>e.check(Pk(XT,n)),e.cidrv6=n=>e.check(Ek(YT,n)),e.e164=n=>e.check(Rk(t_,n)),e.datetime=n=>e.check(vT(n)),e.date=n=>e.check(xT(n)),e.time=n=>e.check(kT(n)),e.duration=n=>e.check(_T(n))});function Ch(e){return uk($T,e)}const ke=C("ZodStringFormat",(e,t)=>{we.init(e,t),Eh.init(e,t)}),FT=C("ZodEmail",(e,t)=>{x1.init(e,t),ke.init(e,t)}),eu=C("ZodGUID",(e,t)=>{v1.init(e,t),ke.init(e,t)}),Ks=C("ZodUUID",(e,t)=>{w1.init(e,t),ke.init(e,t)}),VT=C("ZodURL",(e,t)=>{S1.init(e,t),ke.init(e,t)}),BT=C("ZodEmoji",(e,t)=>{k1.init(e,t),ke.init(e,t)}),UT=C("ZodNanoID",(e,t)=>{T1.init(e,t),ke.init(e,t)}),qT=C("ZodCUID",(e,t)=>{_1.init(e,t),ke.init(e,t)}),GT=C("ZodCUID2",(e,t)=>{P1.init(e,t),ke.init(e,t)}),WT=C("ZodULID",(e,t)=>{E1.init(e,t),ke.init(e,t)}),HT=C("ZodXID",(e,t)=>{C1.init(e,t),ke.init(e,t)}),ZT=C("ZodKSUID",(e,t)=>{A1.init(e,t),ke.init(e,t)}),KT=C("ZodIPv4",(e,t)=>{O1.init(e,t),ke.init(e,t)}),QT=C("ZodIPv6",(e,t)=>{L1.init(e,t),ke.init(e,t)}),XT=C("ZodCIDRv4",(e,t)=>{z1.init(e,t),ke.init(e,t)}),YT=C("ZodCIDRv6",(e,t)=>{j1.init(e,t),ke.init(e,t)}),JT=C("ZodBase64",(e,t)=>{N1.init(e,t),ke.init(e,t)}),e_=C("ZodBase64URL",(e,t)=>{F1.init(e,t),ke.init(e,t)}),t_=C("ZodE164",(e,t)=>{V1.init(e,t),ke.init(e,t)}),n_=C("ZodJWT",(e,t)=>{U1.init(e,t),ke.init(e,t)}),s_=C("ZodUnknown",(e,t)=>{q1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>sT()});function tu(){return zk(s_)}const r_=C("ZodNever",(e,t)=>{G1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>nT(e,n,s)});function o_(e){return jk(r_,e)}const i_=C("ZodArray",(e,t)=>{W1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>aT(e,n,s,r),e.element=t.element,e.min=(n,s)=>e.check(Or(n,s)),e.nonempty=n=>e.check(Or(1,n)),e.max=(n,s)=>e.check(xh(n,s)),e.length=(n,s)=>e.check(Sh(n,s)),e.unwrap=()=>e.element});function a_(e,t){return Kk(i_,e,t)}const c_=C("ZodObject",(e,t)=>{Z1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>cT(e,n,s,r),fe(e,"shape",()=>t.shape),e.keyof=()=>p_(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:tu()}),e.loose=()=>e.clone({...e._zod.def,catchall:tu()}),e.strict=()=>e.clone({...e._zod.def,catchall:o_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>xS(e,n),e.safeExtend=n=>SS(e,n),e.merge=n=>kS(e,n),e.pick=n=>vS(e,n),e.omit=n=>wS(e,n),e.partial=(...n)=>TS(Ah,e,n[0]),e.required=(...n)=>_S(Rh,e,n[0])});function l_(e,t){const n={type:"object",shape:e??{},...K(t)};return new c_(n)}const u_=C("ZodUnion",(e,t)=>{K1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>lT(e,n,s,r),e.options=t.options});function d_(e,t){return new u_({type:"union",options:e,...K(t)})}const f_=C("ZodIntersection",(e,t)=>{Q1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>uT(e,n,s,r)});function h_(e,t){return new f_({type:"intersection",left:e,right:t})}const Ii=C("ZodEnum",(e,t)=>{X1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(s,r,o)=>rT(e,s,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(s,r)=>{const o={};for(const i of s)if(n.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ii({...t,checks:[],...K(r),entries:o})},e.exclude=(s,r)=>{const o={...t.entries};for(const i of s)if(n.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Ii({...t,checks:[],...K(r),entries:o})}});function p_(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Ii({type:"enum",entries:n,...K(t)})}const m_=C("ZodTransform",(e,t)=>{Y1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>iT(e,n),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new oh(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(xs(o,n.value,t));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(xs(i))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(o=>(n.value=o,n)):(n.value=r,n)}});function g_(e){return new m_({type:"transform",transform:e})}const Ah=C("ZodOptional",(e,t)=>{wh.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ph(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function nu(e){return new Ah({type:"optional",innerType:e})}const y_=C("ZodExactOptional",(e,t)=>{J1.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ph(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function b_(e){return new y_({type:"optional",innerType:e})}const v_=C("ZodNullable",(e,t)=>{ek.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>dT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function su(e){return new v_({type:"nullable",innerType:e})}const w_=C("ZodDefault",(e,t)=>{tk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>hT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function x_(e,t){return new w_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():lh(t)}})}const S_=C("ZodPrefault",(e,t)=>{nk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>pT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function k_(e,t){return new S_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():lh(t)}})}const Rh=C("ZodNonOptional",(e,t)=>{sk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>fT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function T_(e,t){return new Rh({type:"nonoptional",innerType:e,...K(t)})}const __=C("ZodCatch",(e,t)=>{rk.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>mT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function P_(e,t){return new __({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const E_=C("ZodPipe",(e,t)=>{ok.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>gT(e,n,s,r),e.in=t.in,e.out=t.out});function ru(e,t){return new E_({type:"pipe",in:e,out:t})}const C_=C("ZodReadonly",(e,t)=>{ik.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>yT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function A_(e){return new C_({type:"readonly",innerType:e})}const R_=C("ZodCustom",(e,t)=>{ak.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,s,r)=>oT(e,n)});function M_(e,t={}){return Qk(R_,e,t)}function I_(e){return Xk(e)}const D_=/[<>]/;function O_(e,t="User"){if(typeof e!="string")return t;const n=e.replace(/[<>]/g,"").replace(/\s+/g," ").trim();return n.length>0?n.slice(0,100):t}const L_=/^\+?[0-9 ()\-.]{7,20}$/,z_=Ch().trim().min(1,"Full name is required").max(100,"Full name must be 100 characters or fewer").refine(e=>!D_.test(e),{message:"Full name cannot contain < or > characters"}),j_=Ch().trim().max(20,"Phone number must be 20 characters or fewer").refine(e=>e.length===0||L_.test(e),{message:"Phone number must contain only digits and + ( ) - . spaces"}),N_=l_({name:z_,phone:j_.optional()});function OR(e){const t=N_.safeParse({name:e.name??"",phone:e.phone??""});return t.success?null:t.error.issues[0]?.message??"Invalid profile data"}new Gp;const Di="mathpulse.pendingAuthRole",Mh="mathpulse.lastAuthRole",$_=e=>{if(e==="admin")throw new Error("Admin account creation is restricted. Please contact an existing administrator.")},Oa=(e,t)=>{const n=e,s=new Error(n.message||t);return n.code&&(s.code=n.code),s},LR=e=>{try{localStorage.setItem(Di,e),localStorage.setItem(Mh,e)}catch{}},F_=()=>{try{const e=localStorage.getItem(Di);return localStorage.removeItem(Di),e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},V_=()=>{try{const e=localStorage.getItem(Mh);return e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},zR=async(e,t,n,s,r={})=>{try{$_(s);const i=(await Wp(ye,e,t)).user;return await Hp(i,{displayName:n}),await Ih(i,s,r)}catch(o){const i=o;throw console.error("[ERROR] Error signing up:",{code:i.code,message:i.message,fullError:o}),Oa(o,"Failed to create account")}},jR=async(e,t)=>{try{await Zp(ye,e,t)}catch(n){const s=n;throw console.error("[ERROR] Error signing in:",{code:s.code,message:s.message,fullError:n}),Oa(n,"Failed to sign in")}},ou=async()=>{try{await Kp(ye)}catch(e){throw console.error("Error signing out:",e),Oa(e,"Failed to sign out")}},Ih=async(e,t,n)=>{const s=`${Date.now()}`.slice(-12).padStart(12,"0"),r={uid:e.uid,email:e.email||"",name:e.displayName||n.name||"User",role:t,photo:e.photoURL||"",createdAt:ae(),updatedAt:ae()},o=(()=>{switch(t){case"student":return{lrn:n.lrn||s,grade:n.grade||"Grade 11",section:n.section||"Section A",classSectionId:n.classSectionId||"",adviserTeacherId:n.adviserTeacherId||"",adviserTeacherName:n.adviserTeacherName||"",schoolYear:n.schoolYear||"",school:n.school||"",enrollmentDate:new Date().toISOString().split("T")[0],major:n.major||"General",gpa:n.gpa||"0.00",level:1,currentXP:0,totalXP:0,atRiskSubjects:[],hasTakenDiagnostic:!1,iarAssessmentState:"not_started",startingQuarterG11:"Q1",recommendedPace:"normal"};case"teacher":return{teacherId:`TCH-${Date.now()}`,department:n.department||"Mathematics",subject:n.subject||"Mathematics",yearsOfExperience:n.yearsOfExperience||"0",qualification:n.qualification||"",students:[]};case"admin":return{adminId:`ADM-${Date.now()}`,position:n.position||"Administrator",department:n.department||"System"}}})(),i={...r,...o};return await Ce(U(L,"users",e.uid),i),i},La=async e=>{try{const t=U(L,"users",e),n=await me(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.error("Error getting user profile:",t),null}},B_=async e=>{try{const t=U(L,"users",e),n=await Xo(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.warn("[getUserProfileFromServer] Server read failed, falling back to cache:",t),La(e)}},U_=async(e,t)=>{try{const n=await La(e);if(!n)throw new Error("Profile not found");const s=["name","email","phone","photo","avatarLayers","gender"],r={student:["lrn","grade","section","school","enrollmentDate","major","gpa"],teacher:["department","subject","yearsOfExperience","qualification"],admin:["department","position"]},o=new Set([...s,...r[n.role]]),i={};Object.entries(t).forEach(([c,u])=>{if(!(u===void 0||!o.has(c))){if(c==="avatarLayers"&&typeof u=="object"&&u!==null){const d=u;i[c]={top:typeof d.top=="string"?d.top:"",bottom:typeof d.bottom=="string"?d.bottom:"",shoes:typeof d.shoes=="string"?d.shoes:"",accessory:typeof d.accessory=="string"?d.accessory:""};return}i[c]=u}});const a=U(L,"users",e);await Ce(a,{...i,updatedAt:ae()},{merge:!0})}catch(n){throw console.error("Error updating user profile:",n),n}},Dh=h.createContext({currentUser:null,userProfile:null,loading:!0,isLoggedIn:!1,userRole:"student",refreshProfile:async()=>{}}),Ms=()=>{const e=h.useContext(Dh);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e},q_=({children:e})=>{const[t,n]=h.useState(null),[s,r]=h.useState(null),[o,i]=h.useState(!0),[a,c]=h.useState("student"),u=f=>{if(!f)return null;const p=f.trim().toLowerCase();return p==="testteacher@school.edu"?"teacher":p==="testadmin@school.edu"?"admin":p==="teststudent@school.edu"?"student":null};h.useEffect(()=>Qp(ye,async p=>{if(i(!0),n(p),p){const m=F_()||V_()||u(p.email)||"student",g=m==="admin"?"student":m;let y=await La(p.uid);if(!y&&p.email){const v=g,k=p.displayName||"User";try{y=await Ih(p,v,{name:k}),v==="student"&&ee(async()=>{const{triggerStudentEnrolled:S}=await import("./automationService-BoxXP8NH.js");return{triggerStudentEnrolled:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])).then(({triggerStudentEnrolled:S})=>S({lrn:y?.lrn||p.uid,name:k,email:p.email||"",gradeLevel:""})).catch(S=>console.error("[WARN] Automation: enrollment pipeline failed:",S))}catch(S){console.error("[ERROR] AuthContext: Failed to auto-create profile:",S)}}if(y){if(c(y.role),r(y),ee(async()=>{const{doc:v,updateDoc:k,serverTimestamp:S}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{doc:v,updateDoc:k,serverTimestamp:S}},__vite__mapDeps([1,2])).then(({doc:v,updateDoc:k,serverTimestamp:S})=>{ee(async()=>{const{db:w}=await Promise.resolve().then(()=>pS);return{db:w}},void 0).then(({db:w})=>{k(v(w,"users",p.uid),{lastActive:S()}).catch(()=>{})})}),y.role==="student"){const v=y.classSectionId||"",k=y.adviserTeacherId||"";(v||k)&&ee(async()=>{const{setStudentContext:S}=await import("./pipelineService-h2NDr2Mk.js");return{setStudentContext:S}},__vite__mapDeps([11,3,1,2,4,5,6,7,8,9,10])).then(({setStudentContext:S})=>{S(v,k)}).catch(()=>{})}}else c(g),r({uid:p.uid,email:p.email||"",name:p.displayName||"User",role:g,photo:p.photoURL||"",createdAt:new Date,updatedAt:new Date})}else c("student"),r(null);i(!1)}),[]);const d=async()=>{if(t){const f=await B_(t.uid);f&&r(f)}},l={currentUser:t,userProfile:s,loading:o,isLoggedIn:!!t,userRole:s?.role||a,refreshProfile:d};return b.jsx(Dh.Provider,{value:l,children:e})},G_=({children:e})=>{const{currentUser:t}=Ms(),[n,s]=h.useState(!1),[r,o]=h.useState(!0),[i,a]=h.useState("your teacher");return h.useEffect(()=>{if(!t?.uid){o(!1);return}const c=U(L,"users",t.uid);return en(c,async d=>{if(!d.exists()){o(!1);return}const l=d.data(),f=l?.teacherAckRequired===!0,p=l?.teacherAcknowledged===!0;if(f&&!p){s(!0);const m=l?.teacherId;if(m)try{const{getDoc:g}=await ee(async()=>{const{getDoc:v}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{getDoc:v}},__vite__mapDeps([1,2])),y=await g(U(L,"users",m));if(y.exists()){const v=y.data();a(O_(v?.displayName||v?.name,"your teacher"))}}catch{}}else s(!1);o(!1)},()=>{o(!1)})},[t?.uid]),r?b.jsx("div",{className:"flex items-center justify-center min-h-screen bg-slate-50",children:b.jsx(Nx,{className:"animate-spin text-slate-400",size:32})}):b.jsx(Uf,{mode:"wait",children:n?b.jsx(Nn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"flex items-center justify-center min-h-screen bg-slate-50 p-6",children:b.jsxs("div",{className:"max-w-md w-full bg-white border border-slate-200 rounded-2xl p-8 shadow-sm text-center space-y-6",children:[b.jsx("div",{className:"w-16 h-16 bg-rose-50 rounded-full flex items-center justify-center mx-auto",children:b.jsx(Fx,{className:"text-rose-500",size:28})}),b.jsxs("div",{children:[b.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"Progress Paused"}),b.jsxs("p",{className:"text-sm text-slate-500 mt-2",children:["Your learning path is temporarily paused while ",i," reviews your recent progress."]})]}),b.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 text-left",children:b.jsxs("div",{className:"flex items-start gap-3",children:[b.jsx(Ei,{className:"text-amber-500 flex-shrink-0 mt-0.5",size:16}),b.jsxs("div",{className:"text-sm text-amber-800",children:[b.jsx("p",{className:"font-semibold",children:"Why am I seeing this?"}),b.jsxs("p",{className:"mt-1",children:["The system detected that you may need additional support. ",i," has been notified and will reach out soon with a personalized plan."]})]})]})}),b.jsx("div",{className:"text-xs text-slate-400",children:"You can still review completed lessons and practice problems while you wait."})]})},"gate"):b.jsx(Nn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e},"content")})},W_=/(```[\s\S]*?```|`[^`\n]+`)/g,H_=/(\$\$[\s\S]*?\$\$|\$[^$\n]+\$|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]|\[(?![^[]*\]\()[^\]]+\]|(?]*>[\s\S]*?<\s*\/\s*think\s*>/gi,Q_=/<\s*\/?\s*think\b[^>]*>/gi,X_=/<\s*\/\s*think\s*>/gi,Y_=/<\s*(\/?)\s*think\b([\s\S]*?)>/gi,J_=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,eP=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,tP=/\bfinal\s+answer\s*:|(?:^|\n)\s*#{1,6}\s+\S|(?:^|\n)\s*(?:answer|solution)\s*:|(?:^|\n)\s*here(?:'s| is)\b|(?:^|\n)\s*(?:\d+[.)]|[-*])\s+\S/i,nP=/^\s*(?:okay|alright|let\s+me|i\s+should|i\s+need\s+to|i\s+will|wait|hmm|maybe|the\s+user\s+asked|let\s+us|let's)\b/i;function Oh(e){return e.replace(Y_,(t,n,s)=>`<${n?"/":""}think${s}>`)}function sP(e,t){t.lastIndex=0;let n=-1,s=t.exec(e);for(;s;)n=s.index+s[0].length,s=t.exec(e);return n}function rP(e){const t=Oh(e);if(/<\s*think\b/i.test(t))return"";const n=sP(t,X_);return n===-1?"":t.slice(n).trim()}function oP(e){const t=e.replace(/\r\n?/g,` `).trim();if(!t)return"";const n=tP.exec(t);return n&&typeof n.index=="number"?t.slice(n.index).trim():t.split(` `).map(o=>o.trim()).filter(o=>o&&nP.test(o)).length>=2?"":t}function Oi(e,t={}){if(!e||typeof e!="string")return"";let n=Oh(e),s="";for(;n!==s;)s=n,n=n.replace(K_,"");if(!t.preserveUnclosedThinkBlocks){const r=n.toLowerCase(),o=r.lastIndexOf("");o!==-1&&o>i&&(n=n.slice(0,o))}return n=n.replace(Q_,""),t.streamingSafeTail&&(n=n.replace(J_,"").replace(eP,"")),n}function iP(e){return Oi(e,{streamingSafeTail:!0}).trim()}function yt(e){const t=rP(e);if(t)return t;const n=Oi(e,{streamingSafeTail:!0}).trim();if(n)return n;const s=Oi(e,{streamingSafeTail:!0,preserveUnclosedThinkBlocks:!0}).trim();return oP(s)}function aP(e){return e.replace(Z_,t=>`$${t}$`)}function cP(e){const t=/[=\^{}\\_+\-*/<>]|x\d|y\d|a[12]|b[12]|c[12]|frac|sqrt|int|sum|prod|lim|sin|cos|tan|log|ln|alpha|beta|gamma|delta|theta|pi|omega|lambda|sigma/,n=/^https?:\/\//,s=o=>`$${o}$`,r=o=>`$$${o}$$`;if(e.startsWith("\\[")&&e.endsWith("\\]")||e.startsWith("[")&&e.endsWith("]")){const o=e.replace(/^\\?\[/,"").replace(/\\?\]$/,"").trim();return t.test(o)?r(o):e}if(e.startsWith("\\(")&&e.endsWith("\\)")||e.startsWith("(")&&e.endsWith(")")){const o=e.replace(/^\\?\(/,"").replace(/\\?\)$/,"").trim();return n.test(o)?e:t.test(o)?s(o):e}return e}function lP(e){let t=e.replace(/\\\[([\s\S]*?)\\\]/g,(n,s)=>`$$${s.replace(/\s+/g," ").trim()}$$`);return t=t.replace(/\[[\s\S]*?\]/g,n=>{if(n.includes("]("))return n;const s=n.slice(1,-1);return/[=\^{}\\_+\-*/<>]/.test(s)||/[a-z]\d|[a-z]_[a-z]|\b(frac|sqrt|int|sum|prod|lim|sin|cos|tan|log|ln|alpha|beta|gamma|delta|theta|pi|omega|lambda|sigma)\b/i.test(s)?"["+s.replace(/\s+/g," ").trim()+"]":n}),t}function uP(e){if(!e||typeof e!="string")return"";const n=yt(e).replace(/\r\n?/g,` `);return lP(n).split(W_).map((o,i)=>i%2===1?o:o.replace(/\\n/g,` -`).replace(/\\\\(?=(?:boxed|frac|sqrt|cdot|times|pm|mp|leq|geq|neq|approx|alpha|beta|gamma|delta|theta|pi|sum|int|left|right|begin|end)\b)/g,"\\").replace(/\\\$(?=\\)/g,"$").replace(/\\\$/g,"$").split(H_).map((f,p)=>p%2===1?cP(f):aP(f)).join("")).join("")}const dP=80;function Lo(e,t=dP){if(!e||typeof e!="string")return"";const n=uP(e).replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1").replace(/```(?:[a-zA-Z0-9_-]+\n)?([\s\S]*?)```/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\$\$([\s\S]+?)\$\$/g,"$1").replace(/\$([^$\n]+)\$/g,"$1").replace(/\\\(([\s\S]+?)\\\)/g,"$1").replace(/\\\[([\s\S]+?)\\\]/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s{0,3}>\s?/gm,"").replace(/^\s{0,3}(?:[-*+]|\d+\.)\s+/gm,"").replace(/^\s{0,3}(?:[-*_]\s?){3,}$/gm," ").replace(/\\boxed\{([^{}]+)\}/g,"$1").replace(/\\frac\{([^{}]+)\}\{([^{}]+)\}/g,"$1/$2").replace(/\\sqrt\{([^{}]+)\}/g,"sqrt($1)").replace(/\\(?:cdot|times)/g,"*").replace(/\\(alpha|beta|gamma|delta|theta|pi|sum|int|pm|mp|leq|geq|neq|approx)\b/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/_([^_\n]+)_/g,"$1").replace(/~~([^~]+)~~/g,"$1").replace(/\*{2,}|_{2,}|~{2,}/g,"").replace(/`+/g,"").replace(/\|/g," ").replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t)}const fP=/^\s*(?:hi|hello|hey|good\s+(?:morning|afternoon|evening))\b/i,hP=/\b(?:thanks|thank\s+you|thank\s+u|ty)\b/i,Lh=["Hi! I am MathPulse, your math tutor. I can help with algebra, geometry, calculus, and more. What math question would you like to try?","Hello! Great to see you. I am here for math topics and step-by-step solutions whenever you are ready."],zh=["You are very welcome. If you want, send another math question and we can work through it together.","Glad I could help. I am here anytime you want to practice more math."],iu=["That topic is outside my math scope, but I would be happy to help with mathematics like algebra, calculus, geometry, trigonometry, or statistics.","I focus on math-only support, so I may not be the best for that request. Share a math question and I will guide you step by step.","I am built for math tutoring, so I can best help with mathematical problems and explanations. If you want, ask me any math question next."],pP=["math","mathematics","algebra","geometry","trigonometry","calculus","statistics","probability","arithmetic","equation","inequality","function","graph","slope","derivative","integral","limit","matrix","determinant","fraction","percentage","ratio","polynomial","quadratic","logarithm","exponent","angle","triangle","circle","perimeter","area","volume","mean","median","mode","standard deviation","solve","simplify","factor","evaluate","compute","calculate","root","square root","cube root","nth root","sqrt"],mP=[/\d+\s*[%+\-*/^=]\s*[-+]?\d*/,/\b(?:sin|cos|tan|cot|sec|csc|log|ln|sqrt)\s*\(?/,/\b(?:differentiate|integrate|derive|proof|prove)\b/,/\b(?:x|y|z)\s*[=+\-*/^]\s*[-+]?\d/,/\b(?:square|cube|nth)?\s*root\b/i,/\b(?:what is|what's)\s*(?:the\s+)?(?:square\s+)?root\b/i,/\b\d+\s*\^\s*\d+/],gP=new Set(["go","continue","yes","ok","next","more"]),yP=[/\bshall\s+we\s+continue\b/i,/\b(?:would|do)\s+you\s+like\s+to\s+continue\b/i,/\b(?:want|need)\s+me\s+to\s+continue\b/i,/\bshould\s+(?:i|we)\s+continue\b/i,/\bcontinue\s*\?\s*$/i,/\b(?:ready\s+for|go\s+to)\s+the\s+next\s+step\b/i,/\bnext\s+step(?:s)?\s*\?\s*$/i,/\bkeep\s+going\s*\?\s*$/i],au="I can continue once I know which math problem you mean. Please share the problem again or tell me which step to continue.";function Qs(e){return e.length===0?"":e[Math.floor(Math.random()*e.length)]??e[0]}function bP(e){const t=(e??"").trim().toLowerCase();return t?pP.some(n=>t.includes(n))?!0:mP.some(n=>n.test(t)):!1}function vP(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function jh(e){const t=vP(e);return t?gP.has(t):!1}function cu(e){const t=(e??"").trim();return t?bP(t)?null:fP.test(t)?Qs(Lh):hP.test(t)?Qs(zh):Qs(iu):Qs(iu)}function wP(e){const t=(e?.latestAssistantMessage??"").trim();if(t)return t;const n=e?.history??[];for(let s=n.length-1;s>=0;s-=1){const r=n[s],o=(r?.role??"").toLowerCase(),i=(r?.content??"").trim();if(i&&(o==="assistant"||o==="ai"))return i}return null}function xP(e){const t=wP(e);return t?yP.some(n=>n.test(t)):!1}function SP(e){const t=e?.history??[];for(let n=t.length-1;n>=0;n-=1){const s=t[n],r=(s?.role??"").toLowerCase(),o=(s?.content??"").trim();if(o&&r==="user"&&!jh(o))return o}return null}function kP(e){return Lh.includes(e)||zh.includes(e)}function Nh(e,t){const n=cu(e);if(n===null)return null;if(!jh(e))return n;if(xP(t))return null;const s=SP(t);if(!s)return au;const r=cu(s);return r===null?null:kP(r)?au:r}const TP=2166136261,_P=16777619,za=e=>(e||"").trim().toLowerCase().replace(/\s+/g," "),lu=e=>{let t=TP;for(let n=0;n>>0).toString(36)},NR={modules:(e,t=[])=>["modules",e??"all",...t],topicMastery:(e,t)=>["topic-mastery",e,t??"all"],masteryHeatmap:()=>["mastery-heatmap"],avatarInventory:()=>["avatar-inventory"]},ja="mathpulse:chat-hint-cache:v1",PP=1200*1e3,Vt=new Map,Na=()=>typeof window<"u",$a=()=>Date.now(),Li=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),EP=e=>Li(e)&&typeof e.value=="string"&&typeof e.expiresAt=="number"&&Number.isFinite(e.expiresAt),CP=()=>{if(!Na())return{entries:{}};try{const e=sessionStorage.getItem(ja);if(!e)return{entries:{}};const t=JSON.parse(e);if(!Li(t)||!Li(t.entries))return{entries:{}};const n={};for(const[s,r]of Object.entries(t.entries)){if(!EP(r))continue;const o=r.value.trim();o&&(n[s]={value:o,expiresAt:r.expiresAt})}return{entries:n}}catch{return{entries:{}}}},zr=e=>{if(Na())try{const t={entries:e};sessionStorage.setItem(ja,JSON.stringify(t))}catch{}},AP=e=>{const t=$a(),n={};for(const[s,r]of Object.entries(e))r.expiresAt>t&&r.value.trim()&&(n[s]=r);return n},RP=e=>{Vt.clear();for(const[t,n]of Object.entries(e))Vt.set(t,n)},$h=()=>{try{const e=CP(),t=AP(e.entries);RP(t),zr(t)}catch{Vt.clear(),zr({})}},MP=e=>e.slice(-4).map(n=>`${n.role}:${za(n.content)}`).join("|"),IP=e=>{const t=za(e);return t?/\b(hint|clue|nudge|guide me|without giving( me)? the answer|step by step|next step)\b/.test(t):!1},DP=({userId:e,prompt:t,history:n=[]})=>{const s=za(t),r=MP(n);return["chat-hint",e,lu(s),lu(r||"no-history")].join(":")},OP=e=>{$h();const t=Vt.get(e);return t?t.expiresAt<=$a()?(Vt.delete(e),zr(Object.fromEntries(Vt.entries())),null):t.value:null},LP=(e,t,n=PP)=>{const s=(t||"").trim();if(!s)return;$h();const r={value:s,expiresAt:$a()+Math.max(1e3,n)};Vt.set(e,r),zr(Object.fromEntries(Vt.entries()))},zP=()=>{if(Vt.clear(),!!Na())try{sessionStorage.removeItem(ja)}catch{}},Fh=h.createContext(void 0);let zo=null,jo=null;const uu=()=>(zo||(zo=ee(()=>Promise.resolve().then(()=>tC),void 0)),zo),hn=()=>(jo||(jo=ee(()=>import("./chatService-ChYY3TEL.js"),__vite__mapDeps([12,1,2,3,4,5,6,7,8,9,10]))),jo),jP=new Set(["go","continue","next","more","yes","ok"]),NP=[/\b(?:end|finish|stop)\s+with(?:\s+the\s+(?:exact\s+)?(?:marker|text))?\s*[:\-]?\s*(["'`]?)([A-Za-z0-9_:\-]{2,96})\1/i,/\b(?:include|append)\s+(?:the\s+)?marker\s*[:\-]?\s*(["'`]?)([A-Za-z0-9_:\-]{2,96})\1/i];function Is(e){if(!e)return null;let t=e.trim();return!t||(t.length>=2&&t[0]===t[t.length-1]&&['"',"'","`"].includes(t[0])&&(t=t.slice(1,-1).trim()),t=t.replace(/[.,;\s]+$/g,""),!t)?null:t.slice(0,120)}function $P(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function Vh(e){const t=$P(e);return t?jP.has(t):!1}function FP(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.role!=="user")continue;const s=(n.content??"").trim();if(s&&!Vh(s))return s}return null}function VP(e){return["Continue the ongoing math explanation for the same user request.","Do not refuse or reset the topic if the request is mathematical.","Original user request:",e].join(` +`).replace(/\\\\(?=(?:boxed|frac|sqrt|cdot|times|pm|mp|leq|geq|neq|approx|alpha|beta|gamma|delta|theta|pi|sum|int|left|right|begin|end)\b)/g,"\\").replace(/\\\$(?=\\)/g,"$").replace(/\\\$/g,"$").split(H_).map((f,p)=>p%2===1?cP(f):aP(f)).join("")).join("")}const dP=80;function Lo(e,t=dP){if(!e||typeof e!="string")return"";const n=uP(e).replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1").replace(/```(?:[a-zA-Z0-9_-]+\n)?([\s\S]*?)```/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\$\$([\s\S]+?)\$\$/g,"$1").replace(/\$([^$\n]+)\$/g,"$1").replace(/\\\(([\s\S]+?)\\\)/g,"$1").replace(/\\\[([\s\S]+?)\\\]/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s{0,3}>\s?/gm,"").replace(/^\s{0,3}(?:[-*+]|\d+\.)\s+/gm,"").replace(/^\s{0,3}(?:[-*_]\s?){3,}$/gm," ").replace(/\\boxed\{([^{}]+)\}/g,"$1").replace(/\\frac\{([^{}]+)\}\{([^{}]+)\}/g,"$1/$2").replace(/\\sqrt\{([^{}]+)\}/g,"sqrt($1)").replace(/\\(?:cdot|times)/g,"*").replace(/\\(alpha|beta|gamma|delta|theta|pi|sum|int|pm|mp|leq|geq|neq|approx)\b/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/_([^_\n]+)_/g,"$1").replace(/~~([^~]+)~~/g,"$1").replace(/\*{2,}|_{2,}|~{2,}/g,"").replace(/`+/g,"").replace(/\|/g," ").replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t)}const fP=/^\s*(?:hi|hello|hey|good\s+(?:morning|afternoon|evening))\b/i,hP=/\b(?:thanks|thank\s+you|thank\s+u|ty)\b/i,Lh=["Hi! I am MathPulse, your math tutor. I can help with algebra, geometry, calculus, and more. What math question would you like to try?","Hello! Great to see you. I am here for math topics and step-by-step solutions whenever you are ready."],zh=["You are very welcome. If you want, send another math question and we can work through it together.","Glad I could help. I am here anytime you want to practice more math."],iu=["That topic is outside my math scope, but I would be happy to help with mathematics like algebra, calculus, geometry, trigonometry, or statistics.","I focus on math-only support, so I may not be the best for that request. Share a math question and I will guide you step by step.","I am built for math tutoring, so I can best help with mathematical problems and explanations. If you want, ask me any math question next."],pP=["math","mathematics","algebra","geometry","trigonometry","calculus","statistics","probability","arithmetic","equation","inequality","function","graph","slope","derivative","integral","limit","matrix","determinant","fraction","percentage","ratio","polynomial","quadratic","logarithm","exponent","angle","triangle","circle","perimeter","area","volume","mean","median","mode","standard deviation","solve","simplify","factor","evaluate","compute","calculate","root","square root","cube root","nth root","sqrt"],mP=[/\d+\s*[%+\-*/^=]\s*[-+]?\d*/,/\b(?:sin|cos|tan|cot|sec|csc|log|ln|sqrt)\s*\(?/,/\b(?:differentiate|integrate|derive|proof|prove)\b/,/\b(?:x|y|z)\s*[=+\-*/^]\s*[-+]?\d/,/\b(?:square|cube|nth)?\s*root\b/i,/\b(?:what is|what's)\s*(?:the\s+)?(?:square\s+)?root\b/i,/\b\d+\s*\^\s*\d+/],gP=new Set(["go","continue","yes","ok","next","more"]),yP=[/\bshall\s+we\s+continue\b/i,/\b(?:would|do)\s+you\s+like\s+to\s+continue\b/i,/\b(?:want|need)\s+me\s+to\s+continue\b/i,/\bshould\s+(?:i|we)\s+continue\b/i,/\bcontinue\s*\?\s*$/i,/\b(?:ready\s+for|go\s+to)\s+the\s+next\s+step\b/i,/\bnext\s+step(?:s)?\s*\?\s*$/i,/\bkeep\s+going\s*\?\s*$/i],au="I can continue once I know which math problem you mean. Please share the problem again or tell me which step to continue.";function Qs(e){return e.length===0?"":e[Math.floor(Math.random()*e.length)]??e[0]}function bP(e){const t=(e??"").trim().toLowerCase();return t?pP.some(n=>t.includes(n))?!0:mP.some(n=>n.test(t)):!1}function vP(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function jh(e){const t=vP(e);return t?gP.has(t):!1}function cu(e){const t=(e??"").trim();return t?bP(t)?null:fP.test(t)?Qs(Lh):hP.test(t)?Qs(zh):Qs(iu):Qs(iu)}function wP(e){const t=(e?.latestAssistantMessage??"").trim();if(t)return t;const n=e?.history??[];for(let s=n.length-1;s>=0;s-=1){const r=n[s],o=(r?.role??"").toLowerCase(),i=(r?.content??"").trim();if(i&&(o==="assistant"||o==="ai"))return i}return null}function xP(e){const t=wP(e);return t?yP.some(n=>n.test(t)):!1}function SP(e){const t=e?.history??[];for(let n=t.length-1;n>=0;n-=1){const s=t[n],r=(s?.role??"").toLowerCase(),o=(s?.content??"").trim();if(o&&r==="user"&&!jh(o))return o}return null}function kP(e){return Lh.includes(e)||zh.includes(e)}function Nh(e,t){const n=cu(e);if(n===null)return null;if(!jh(e))return n;if(xP(t))return null;const s=SP(t);if(!s)return au;const r=cu(s);return r===null?null:kP(r)?au:r}const TP=2166136261,_P=16777619,za=e=>(e||"").trim().toLowerCase().replace(/\s+/g," "),lu=e=>{let t=TP;for(let n=0;n>>0).toString(36)},NR={modules:(e,t=[])=>["modules",e??"all",...t],topicMastery:(e,t)=>["topic-mastery",e,t??"all"],masteryHeatmap:()=>["mastery-heatmap"],avatarInventory:()=>["avatar-inventory"]},ja="mathpulse:chat-hint-cache:v1",PP=1200*1e3,Vt=new Map,Na=()=>typeof window<"u",$a=()=>Date.now(),Li=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),EP=e=>Li(e)&&typeof e.value=="string"&&typeof e.expiresAt=="number"&&Number.isFinite(e.expiresAt),CP=()=>{if(!Na())return{entries:{}};try{const e=sessionStorage.getItem(ja);if(!e)return{entries:{}};const t=JSON.parse(e);if(!Li(t)||!Li(t.entries))return{entries:{}};const n={};for(const[s,r]of Object.entries(t.entries)){if(!EP(r))continue;const o=r.value.trim();o&&(n[s]={value:o,expiresAt:r.expiresAt})}return{entries:n}}catch{return{entries:{}}}},zr=e=>{if(Na())try{const t={entries:e};sessionStorage.setItem(ja,JSON.stringify(t))}catch{}},AP=e=>{const t=$a(),n={};for(const[s,r]of Object.entries(e))r.expiresAt>t&&r.value.trim()&&(n[s]=r);return n},RP=e=>{Vt.clear();for(const[t,n]of Object.entries(e))Vt.set(t,n)},$h=()=>{try{const e=CP(),t=AP(e.entries);RP(t),zr(t)}catch{Vt.clear(),zr({})}},MP=e=>e.slice(-4).map(n=>`${n.role}:${za(n.content)}`).join("|"),IP=e=>{const t=za(e);return t?/\b(hint|clue|nudge|guide me|without giving( me)? the answer|step by step|next step)\b/.test(t):!1},DP=({userId:e,prompt:t,history:n=[]})=>{const s=za(t),r=MP(n);return["chat-hint",e,lu(s),lu(r||"no-history")].join(":")},OP=e=>{$h();const t=Vt.get(e);return t?t.expiresAt<=$a()?(Vt.delete(e),zr(Object.fromEntries(Vt.entries())),null):t.value:null},LP=(e,t,n=PP)=>{const s=(t||"").trim();if(!s)return;$h();const r={value:s,expiresAt:$a()+Math.max(1e3,n)};Vt.set(e,r),zr(Object.fromEntries(Vt.entries()))},zP=()=>{if(Vt.clear(),!!Na())try{sessionStorage.removeItem(ja)}catch{}},Fh=h.createContext(void 0);let zo=null,jo=null;const uu=()=>(zo||(zo=ee(()=>Promise.resolve().then(()=>tC),void 0)),zo),hn=()=>(jo||(jo=ee(()=>import("./chatService-F4GRaS_M.js"),__vite__mapDeps([12,1,2,3,4,5,6,7,8,9,10]))),jo),jP=new Set(["go","continue","next","more","yes","ok"]),NP=[/\b(?:end|finish|stop)\s+with(?:\s+the\s+(?:exact\s+)?(?:marker|text))?\s*[:\-]?\s*(["'`]?)([A-Za-z0-9_:\-]{2,96})\1/i,/\b(?:include|append)\s+(?:the\s+)?marker\s*[:\-]?\s*(["'`]?)([A-Za-z0-9_:\-]{2,96})\1/i];function Is(e){if(!e)return null;let t=e.trim();return!t||(t.length>=2&&t[0]===t[t.length-1]&&['"',"'","`"].includes(t[0])&&(t=t.slice(1,-1).trim()),t=t.replace(/[.,;\s]+$/g,""),!t)?null:t.slice(0,120)}function $P(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function Vh(e){const t=$P(e);return t?jP.has(t):!1}function FP(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.role!=="user")continue;const s=(n.content??"").trim();if(s&&!Vh(s))return s}return null}function VP(e){return["Continue the ongoing math explanation for the same user request.","Do not refuse or reset the topic if the request is mathematical.","Original user request:",e].join(` `)}function BP(e){const t=(e??"").trim();if(!t)return null;for(const n of NP){const s=n.exec(t);if(!s)continue;const r=Is(s[2]);if(r)return r}return null}function UP(e,t){const n=Is(t);return n?e.toLowerCase().includes(n.toLowerCase()):!1}function zi(e,t,n,s){return n&&!UP(t,n)?!0:s?GP(e,t):!1}function qP(e){const t=e.trim();if(!t||[/```[^`]*$/,/\$\$[^$]*$/,/\$[^$\n]*$/,/\\\[[^\]]*$/,/\\\([^\)]*$/,/\\boxed\{[^}]*$/,/\\frac\{[^}]*\}\{?$/,/\\[a-zA-Z]+\s*$/,/(?:Step\s*\d+[:.]?)\s*$/i,/(?:Final\s*Answer[:.]?)\s*$/i].some(f=>f.test(t))||(t.match(/```/g)??[]).length%2!==0||(()=>{let f=0;for(let p=0;p=0&&t[g]==="\\";g-=1)m+=1;m%2===0&&(f+=1)}return f})()%2!==0)return!0;const o=(t.match(/\\left\b/g)??[]).length,i=(t.match(/\\right\b/g)??[]).length;if(o!==i)return!0;const a=[["(",")"],["[","]"],["{","}"]];for(const[f,p]of a){const m=(t.match(new RegExp(`\\${f}`,"g"))??[]).length,g=(t.match(new RegExp(`\\${p}`,"g"))??[]).length;if(m>g)return!0}if(t.length>=80&&/\b(?:and|or|but|because|since|so|then|which|that|where|when|with|for|to|from|of|in|on|at|by)\s*$/i.test(t))return!0;const c=t.split(/\r?\n/).map(f=>f.trim()).filter(Boolean),u=c.length>0?c[c.length-1]:t,d=/[.!?)]$/.test(u),l=/(?:=|\\boxed|\\int|d\/dx|f\(x\)|x\^\d+|\b\d+(?:\.\d+)?\b)\s*$/.test(u);return t.length>=140&&!d&&!l}function GP(e,t){const n=t.trim(),s=e.toLowerCase();if(!n||qP(n))return!0;const r=n.replace(/[#*_`>|\-]/g," ").replace(/\s+/g," ").trim();if(!r||r.length<24&&/(derivative|integral|equation|complete|explain|step)/.test(s))return!0;if(s.includes("derivative")&&s.includes("integral")){const o=n.toLowerCase(),i=/derivative|f'|d\/dx/.test(o),a=/integral|∫|\\int/.test(o);if(!i||!a)return!0}return!!((s.includes("complete equation")||s.includes("complete equations")||s.includes("step-by-step")||s.includes("step by step"))&&((n.match(/=|\\frac|\\int|∫|\\boxed|d\/dx|\b(dx|x\^\d+)\b/g)??[]).length<2||n.length<120))}function Mn(e){const t=e.split(/\n{2,}/).map(r=>r.trim()).filter(Boolean);if(t.length<=1)return e.trim();const n=new Set,s=[];for(const r of t){const o=r.toLowerCase().replace(/[#*_`]/g,"").replace(/\s+/g," ").trim();!o||n.has(o)||(n.add(o),s.push(r))}return s.join(` `).trim()}function Xs(e,t){const n=e.trim(),s=t.trim();if(!n)return Mn(s);if(!s)return Mn(n);const r=Math.min(n.length,s.length,220);for(let o=r;o>=24;o-=1){const i=n.slice(-o),a=s.slice(0,o);if(i===a)return Mn(`${n}${s.slice(o)}`.trim())}return n.endsWith(s)?Mn(n):s.startsWith(n)?Mn(s):Mn(`${n} @@ -709,9 +709,9 @@ I can help with a wide range of math topics. Try asking: - Arithmetic (fractions, percentages) - Logarithms, Exponents, Matrices -What would you like to learn about?`}const $R=()=>{const e=h.useContext(Fh);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},ZP=({children:e})=>{const{currentUser:t}=Ms(),[n,s]=h.useState([]),[r,o]=h.useState(null),[i,a]=h.useState(!1),[c,u]=h.useState(null),[d,l]=h.useState(!1),f=h.useRef(new Map);h.useEffect(()=>{if(!t){s([]),l(!1);return}(async()=>{try{const T=await hn(),_=await T.getUserChatSessions(t.uid),R=await Promise.all(_.map(async x=>{const P=(await T.getSessionMessages(x.id,t.uid)).map(V=>({id:V.id,sender:V.role==="user"?"user":"ai",text:V.role==="assistant"?yt(V.content):V.content,timestamp:V.timestamp instanceof Date?V.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):new Date(V.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}));return{id:x.id,title:x.title,date:x.updatedAt instanceof Date?x.updatedAt.toLocaleDateString():new Date(x.updatedAt).toLocaleDateString(),messageCount:P.length,preview:P.length>0&&Lo(P[P.length-1].text)||"No messages yet",topics:[],messages:P,createdAt:x.createdAt instanceof Date?x.createdAt:new Date(x.createdAt),updatedAt:x.updatedAt instanceof Date?x.updatedAt:new Date(x.updatedAt)}}));s(R)}catch(T){console.error("Error loading chat sessions:",T)}finally{l(!0)}})()},[t]);const p=w=>{if(w.length===0)return"New Chat";const T=w.find(x=>x.sender==="user")?.text||"",_=T.toLowerCase();if(_.includes("quadratic")||_.includes("ax² + bx + c"))return"Quadratic Equations Help";if(_.includes("derivative")||_.includes("calculus"))return"Derivatives & Calculus";if(_.includes("pythagor")||_.includes("right triangle"))return"Pythagorean Theorem";if(_.includes("trig")||_.includes("sin")||_.includes("cos"))return"Trigonometry Help";if(_.includes("area")||_.includes("perimeter"))return"Geometry - Area & Perimeter";if(_.includes("algebra")||_.includes("solve")&&_.includes("x"))return"Algebra Problem Solving";if(_.includes("factor"))return"Factoring Practice";if(_.includes("graph")||_.includes("plot"))return"Graphing Functions";if(_.includes("matrix")||_.includes("matrices"))return"Matrix Operations";if(_.includes("integral")||_.includes("integrate"))return"Integration Problems";if(_.includes("limit"))return"Limits in Calculus";if(_.includes("statistic")||_.includes("probability"))return"Statistics & Probability";const R=T.slice(0,40);return R.length{const T=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),_=new Date,R={id:T,title:w?p([w]):"New Chat",date:"Just now",messageCount:w?1:0,preview:w&&Lo(w.text)||"Start a new conversation...",topics:[],messages:w?[w]:[],createdAt:_,updatedAt:_};if(s(x=>[R,...x]),t){const x=w?p([w]):"New Chat",A=hn().then(async P=>{const V=await P.createChatSession(t.uid,x);return ee(async()=>{const{logChatSession:F}=await import("./trackingService-SBoVE94r.js");return{logChatSession:F}},__vite__mapDeps([13,1,2,3,4,5,6,7,8,9,10])).then(({logChatSession:F})=>F(t.uid,V.id,w?1:0).catch(()=>{})),w&&await P.addMessageToSession(V.id,w.sender==="user"?"user":"assistant",w.text),V.id}).catch(P=>(console.error("Error creating Firebase session:",P),T));f.current.set(T,A)}return T},[t]),g=h.useCallback((w,T)=>{s(R=>R.map(x=>{if(x.id===w){const A=[...x.messages,T];return{...x,messages:A,messageCount:A.length,preview:Lo(T.text)||x.preview,updatedAt:new Date,title:A.length===2?p(A):x.title}}return x}));const _=async R=>{const x=f.current.get(R);return x?await x:R};_(w).then(async R=>{await(await hn()).addMessageToSession(R,T.sender==="user"?"user":"assistant",T.text)}).catch(R=>console.error("Error persisting message:",R)),s(R=>{const x=R.find(A=>A.id===w);if(x&&x.messages.length===2){const A=p(x.messages);_(w).then(async P=>{await(await hn()).updateSessionTitle(P,A)}).catch(P=>console.error("Error updating title:",P))}return R})},[]),y=h.useCallback(async(w,T)=>{const _=T.trim(),R={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),sender:"user",text:_,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,R),u(w),a(!0);try{let x=null,A=null;const P=n.find(W=>W.id===w),F=[...P?.messages||[],R].map(W=>({role:W.sender==="user"?"user":"assistant",content:W.text})),H=Vh(_)?FP(F):null,re=H?VP(H):_,te=H??_,B=IP(_)?DP({userId:t?.uid||"anonymous",prompt:_,history:F}):null,ie=W=>{if(!B)return;const O=yt(W).trim();O&&LP(B,O)},oe=Nh(_,{history:F});if(oe){const W={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:oe,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,W);return}if(B){const W=OP(B);if(W){const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:W,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,O);return}}try{const W=await uu();x=W.apiService,A=W.ApiTimeoutError}catch(W){console.error("Failed to load API service for chat:",W);const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:Ys(te),timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,O);return}const ce=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});let D="",de=null;const He=WP(_),X=HP(_),J=BP(_),G=X||!!J,ne={sessionId:w,...J?{expectedEndMarker:J,completionMode:"marker"}:{}},xe=W=>zi(_,W,J,X),Z=W=>{W.trim()&&s(O=>O.map(le=>{if(le.id!==w)return le;if(!de){de=`stream-${typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString()}-${Math.random().toString(36).slice(2,8)}`;const Te={id:de,sender:"ai",text:W,timestamp:ce},Y=[...le.messages,Te];return{...le,messages:Y,messageCount:Y.length,updatedAt:new Date}}return{...le,messages:le.messages.map(Te=>Te.id===de?{...Te,text:W}:Te),updatedAt:new Date}}))},ue=()=>{if(!de)return;const W=de;s(O=>O.map(le=>{if(le.id!==w)return le;const Te=le.messages.filter(Y=>Y.id!==W);return{...le,messages:Te,messageCount:Te.length,updatedAt:new Date}}))};try{const{response:W}=await x.chat(re,F,Y=>{D+=Y,He&&Z(iP(D))},ne);let O=yt(W||D).trim();if(G&&O&&xe(O)){try{const Y=await x.chatSafe(du(_,O,J),F,ne),Ne=yt(Y.data.response).trim();O=Xs(O,Ne)}catch(Y){console.warn("Streaming completion repair failed:",Y)}if(G&&O&&xe(O))try{const Y=await x.chatSafe(fu(_,O,J),F,ne),Ne=yt(Y.data.response).trim();O=Xs(O,Ne)}catch(Y){console.warn("Streaming plain continuation repair failed:",Y)}if(G&&O&&xe(O))try{const Y=await x.chatSafe(hu(_,J),F,ne),Ne=yt(Y.data.response).trim();Ne&&(O=pu(_,O,Ne,J,X))}catch(Y){console.warn("Streaming full completion repair failed:",Y)}}const le=xe(O);(!O||le&&!G)&&(O=Ys(te,F)),ie(O),de&&ue();const Te={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ce};g(w,Te)}catch(W){A&&W instanceof A?console.warn(`Streaming timed out after ${W.timeoutMs}ms, falling back to non-streaming chat.`,W):console.warn("Streaming failed, falling back to non-streaming chat:",W),de&&ue();let O="";try{const Y=x??(await uu()).apiService,{data:Ne}=await Y.chatSafe(re,F,ne);if(O=yt(Ne.response).trim(),G&&O&&xe(O))try{const be=await Y.chatSafe(du(_,O,J),F,ne),Ae=yt(be.data.response).trim();O=Xs(O,Ae)}catch(be){console.warn("Non-stream completion repair failed:",be)}if(G&&O&&xe(O))try{const be=await Y.chatSafe(fu(_,O,J),F,ne),Ae=yt(be.data.response).trim();O=Xs(O,Ae)}catch(be){console.warn("Non-stream plain continuation repair failed:",be)}if(G&&O&&xe(O))try{const be=await Y.chatSafe(hu(_,J),F,ne),Ae=yt(be.data.response).trim();Ae&&(O=pu(_,O,Ae,J,X))}catch(be){console.warn("Non-stream full completion repair failed:",be)}}catch(Y){console.warn("Chat request failed, using local fallback response:",Y),O=Ys(te,F)}const le=xe(O);(!O||le&&!G)&&(O=Ys(te,F)),ie(O);const Te={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ce};g(w,Te)}if(P&&P.messages.length===1){const W=n.find(O=>O.id===w);if(W&&W.messages.length>1){const O=p(W.messages),le=f.current.get(w);(le||Promise.resolve(w)).then(async Y=>{await(await hn()).updateSessionTitle(Y,O)}).catch(Y=>console.error("Error updating title:",Y))}}}finally{a(!1),u(null)}},[n,g,t]),v=h.useCallback((w,T)=>{s(x=>x.map(A=>A.id===w?{...A,title:T}:A));const _=f.current.get(w);(_||Promise.resolve(w)).then(async x=>{await(await hn()).updateSessionTitle(x,T)}).catch(x=>console.error("Error updating session title:",x))},[]),k=h.useCallback(w=>{s(R=>R.filter(x=>x.id!==w)),r===w&&o(null);const T=f.current.get(w);(T||Promise.resolve(w)).then(async R=>{await(await hn()).deleteSession(R)}).catch(R=>console.error("Error deleting session:",R)),f.current.delete(w)},[r]),S=h.useCallback(()=>n.find(w=>w.id===r)||null,[n,r]);return b.jsx(Fh.Provider,{value:{sessions:n,activeSessionId:r,isLoading:i,loadingSessionId:c,sessionsLoaded:d,setActiveSessionId:o,createNewSession:m,addMessageToSession:g,sendMessage:y,updateSessionTitle:v,deleteSession:k,getActiveSession:S,generateTitleFromMessages:p},children:e})},KP=[{id:"first_lesson",title:"First Steps",description:"Complete your first lesson",icon:Oo,iconColor:"text-yellow-500",xpReward:50,condition:"lesson_complete",threshold:1,category:"learning"},{id:"lesson_10",title:"Dedicated Learner",description:"Complete 10 lessons",icon:Oo,iconColor:"text-blue-500",xpReward:200,condition:"lesson_complete",threshold:10,category:"learning"},{id:"lesson_50",title:"Knowledge Seeker",description:"Complete 50 lessons",icon:Ll,iconColor:"text-purple-500",xpReward:500,condition:"lesson_complete",threshold:50,category:"learning"},{id:"perfect_score",title:"Perfect Score",description:"Score 100% on any quiz",icon:$l,iconColor:"text-yellow-400",xpReward:150,condition:"perfect_score",category:"learning"},{id:"no_mistakes",title:"Flawless",description:"Complete a quiz with zero wrong answers",icon:jl,iconColor:"text-emerald-500",xpReward:100,condition:"quiz_no_mistakes",category:"learning"},{id:"speed_demon",title:"Speed Demon",description:"Complete a quiz in under 2 minutes",icon:Ci,iconColor:"text-orange-500",xpReward:100,condition:"speed_quiz",category:"learning"},{id:"quiz_10",title:"Quiz Enthusiast",description:"Complete 10 quizzes",icon:Tx,iconColor:"text-cyan-500",xpReward:200,condition:"quiz_complete",threshold:10,category:"learning"},{id:"quiz_50",title:"Quiz Champion",description:"Complete 50 quizzes",icon:Oo,iconColor:"text-indigo-500",xpReward:500,condition:"quiz_complete",threshold:50,category:"learning"},{id:"quiz_perfect",title:"Perfectionist",description:"Get 5 perfect quiz scores",icon:Hx,iconColor:"text-amber-400",xpReward:300,condition:"perfect_score",threshold:5,category:"learning"},{id:"study_streak",title:"Study Streak",description:"Maintain a 7-day lesson completion streak",icon:gr,iconColor:"text-red-500",xpReward:300,condition:"mastery_10",threshold:7,category:"learning"},{id:"first_battle",title:"First Blood",description:"Win your first Quiz Battle",icon:Ws,iconColor:"text-red-400",xpReward:100,condition:"battle_win",threshold:1,category:"battle"},{id:"battle_10",title:"Battle Veteran",description:"Win 10 Quiz Battles",icon:Ws,iconColor:"text-orange-400",xpReward:300,condition:"battle_win",threshold:10,category:"battle"},{id:"battle_50",title:"Battle Legend",description:"Win 50 Quiz Battles",icon:Ws,iconColor:"text-red-500",xpReward:1e3,condition:"battle_win",threshold:50,category:"battle"},{id:"undefeated",title:"Undefeated",description:"Win 5 battles in a row without losing",icon:zl,iconColor:"text-blue-500",xpReward:500,condition:"battle_undefeated",threshold:5,category:"battle"},{id:"quick_win",title:"Speed Battle",description:"Win a battle by answering all questions first",icon:Ci,iconColor:"text-yellow-500",xpReward:150,condition:"speed_quiz",category:"battle"},{id:"comeback",title:"The Comeback",description:"Win a battle after being behind in score",icon:qx,iconColor:"text-teal-500",xpReward:200,condition:"battle_comeback",category:"battle"},{id:"battle_master",title:"Battle Master",description:"Win 3 battles in a single day",icon:mr,iconColor:"text-yellow-500",xpReward:400,condition:"battle_win",threshold:3,category:"battle"},{id:"invincible",title:"Invincible",description:"Win 10 battles in a row",icon:zl,iconColor:"text-violet-500",xpReward:1e3,condition:"battle_undefeated",threshold:10,category:"battle"},{id:"first_blood_daily",title:"Early Bird",description:"Win your first battle of the day",icon:Kx,iconColor:"text-amber-500",xpReward:50,condition:"battle_win",threshold:1,category:"battle"},{id:"rival_crusher",title:"Rival Crusher",description:"Win 25 battles total",icon:Ws,iconColor:"text-rose-500",xpReward:750,condition:"battle_win",threshold:25,category:"battle"},{id:"mastery_10",title:"Week Warrior",description:"Maintain a 10-day learning streak",icon:gr,iconColor:"text-orange-500",xpReward:500,condition:"mastery_10",threshold:10,category:"mastery"},{id:"mastery_level",title:"Rising Star",description:"Reach level 5",icon:mr,iconColor:"text-yellow-400",xpReward:250,condition:"mastery_level",threshold:5,category:"mastery"},{id:"mastery_xp",title:"XP Hunter",description:"Earn a total of 5,000 XP",icon:Nl,iconColor:"text-emerald-500",xpReward:400,condition:"mastery_xp",threshold:5e3,category:"mastery"},{id:"mastery_all_lessons",title:"Curriculum Complete",description:"Complete all available lessons",icon:Ll,iconColor:"text-purple-500",xpReward:1e3,condition:"mastery_all_lessons",category:"mastery"},{id:"mastery_all_subjects",title:"Polymath",description:"Complete at least one lesson in every subject",icon:Dx,iconColor:"text-cyan-500",xpReward:500,condition:"mastery_all_subjects",category:"mastery"},{id:"mastery_assessment_perfect",title:"Assessment Perfect",description:"Score 100% on a diagnostic assessment",icon:jl,iconColor:"text-amber-500",xpReward:400,condition:"mastery_assessment_perfect",category:"mastery"},{id:"mastery_max_level",title:"Max Level",description:"Reach the maximum player level",icon:mr,iconColor:"text-yellow-500",xpReward:2e3,condition:"mastery_max_level",category:"mastery"},{id:"mastery_top_10",title:"Leaderboard Elite",description:"Reach the top 10 on the global leaderboard",icon:Dl,iconColor:"text-amber-400",xpReward:1e3,condition:"social_xp",category:"mastery"},{id:"explore_profile",title:"Identity Set",description:"Complete your user profile",icon:sS,iconColor:"text-blue-400",xpReward:50,condition:"explore_profile_complete",category:"exploration"},{id:"explore_first_friend",title:"Socialite",description:"Add your first friend",icon:Fl,iconColor:"text-green-500",xpReward:50,condition:"explore_friend_added",threshold:1,category:"exploration"},{id:"explore_daily_return",title:"Daily Visitor",description:"Return to the app 3 days in a row",icon:Ol,iconColor:"text-indigo-400",xpReward:100,condition:"social_daily_return",threshold:3,category:"exploration"},{id:"explore_10_friends",title:"Popular",description:"Have 10 friends on the platform",icon:oS,iconColor:"text-teal-500",xpReward:300,condition:"explore_friend_added",threshold:10,category:"exploration"},{id:"explore_all_features",title:"Explorer",description:"Use all major app features",icon:Ax,iconColor:"text-orange-400",xpReward:200,condition:"explore_profile_complete",category:"exploration"},{id:"explore_25_friends",title:"Social Butterfly",description:"Have 25 friends on the platform",icon:zx,iconColor:"text-pink-500",xpReward:500,condition:"explore_social",threshold:25,category:"exploration"},{id:"explore_xp_1000",title:"XP Milestone",description:"Earn your first 1,000 XP",icon:Nl,iconColor:"text-blue-500",xpReward:100,condition:"mastery_xp",threshold:1e3,category:"exploration"},{id:"social_first_friend",title:"Friendship Starter",description:"Send your first friend request",icon:Fl,iconColor:"text-green-400",xpReward:25,condition:"social_friend",threshold:1,category:"social"},{id:"social_helper",title:"Helpful Hand",description:"Contribute to the community",icon:Dl,iconColor:"text-cyan-500",xpReward:150,condition:"social_contribution",category:"social"},{id:"social_top_10",title:"Elite Status",description:"Reach the top 10 on the leaderboard",icon:$l,iconColor:"text-yellow-400",xpReward:500,condition:"social_xp",category:"social"},{id:"social_streak_30",title:"Dedicated Member",description:"Maintain a 30-day activity streak",icon:gr,iconColor:"text-red-400",xpReward:1e3,condition:"mastery_10",threshold:30,category:"social"},{id:"social_daily_7",title:"Weekly Visitor",description:"Return to the app 7 days in a row",icon:Ol,iconColor:"text-violet-400",xpReward:200,condition:"social_daily_return",threshold:7,category:"social"}];new Map(KP.map(e=>[e.id,e]));const No=async(e,t,n,s)=>{try{const r=U(L,"users",e),o=await me(r);if(!o.exists())throw new Error("User not found");const i=o.data(),a=i.currentXP||0,c=i.totalXP||0,u=i.xpMultiplier||1,d=Math.floor(t*u),l=a+d,f=c+d;let m=i.level||1;const g=f;let y=!1;for(;;){const S=Math.floor(100*Math.pow(1.5,m-1));let w=0;for(let T=1;T<=m;T++)w+=Math.floor(100*Math.pow(1.5,T-1));if(f>=w)m++,y=!0;else break}const v={currentXP:l,totalXP:f,level:m,updatedAt:ae()};u!==1&&(v.xpMultiplier=1),await dt(r,v);const k=U(et(L,"xpActivities"));return await Ce(k,{activityId:k.id,userId:e,type:n,xpEarned:t,description:s,timestamp:ae()}),{newLevel:m,leveledUp:y,xp:l,addedXp:t}}catch(r){throw console.error("Error awarding XP:",r),r}},FR=async(e,t=!1,n="all",s=10)=>{try{const r=Dt(et(L,"leaderboard"),Sn("totalXP","desc"),ks(s)),o=await Fn(r);return o.empty?[]:o.docs.map((i,a)=>{const c=i.data();return{userId:i.id,name:c.name||"Unknown",photo:c.photo,xp:c.totalXP||0,level:c.level||1,rank:a+1,weeklyXP:c.weeklyXP||0,monthlyXP:c.monthlyXP||0}})}catch(r){return console.error("Error getting leaderboard:",r),[]}},VR=(e,t,n=!1,s="all",r=10)=>{const o=Dt(et(L,"leaderboard"),Sn("totalXP","desc"),ks(r));return en(o,i=>{const a=i.docs.map((c,u)=>{const d=c.data();return{userId:c.id,name:d.name||"Unknown",photo:d.photo,xp:d.totalXP||0,level:d.level||1,rank:u+1,weeklyXP:d.weeklyXP||0,monthlyXP:d.monthlyXP||0}});e(a)},i=>{console.error("Error subscribing to leaderboard:",i),e([])})},BR=async e=>{try{const t=await me(U(L,"achievements",e));return t.exists()?t.data().achievements||[]:[]}catch(t){return console.error("Error getting user achievements:",t),[]}},UR=async(e,t,n)=>{try{const s=U(L,"users",e),r=await me(s);if(!r.exists())throw new Error("User not found");const o=r.data(),i=o.currentXP||0;if((o.ownedAvatarItems||[]).includes(t))return{success:!1,message:"You already own this item",currentXP:i};if(i{try{const n=U(L,"users",e),s=await me(n);if(!s.exists())throw new Error("User not found");return(s.data().ownedAvatarItems||[]).includes(t)?{success:!0,message:"Item already owned"}:(await dt(n,{ownedAvatarItems:Fu(t),updatedAt:ae()}),{success:!0,message:"Avatar item unlocked!"})}catch(n){return console.error("Error unlocking avatar item:",n),{success:!1,message:"Failed to unlock item"}}},Yr=3e4,Bh=3,Uh=1e3;class It extends Error{status;statusText;endpoint;responseBody;retryable;requestId;constructor(t){super(`API Error ${t.status} (${t.statusText}) on ${t.endpoint}: ${t.responseBody}`),this.name="ApiError",this.status=t.status,this.statusText=t.statusText,this.endpoint=t.endpoint,this.responseBody=t.responseBody,this.retryable=t.retryable,this.requestId=t.requestId}}class xn extends Error{endpoint;timeoutMs;constructor(t,n){super(`Request to ${t} timed out after ${n}ms`),this.name="ApiTimeoutError",this.endpoint=t,this.timeoutMs=n}}class jr extends Error{endpoint;originalError;constructor(t,n){super(`Network error on ${t}: ${n.message}`),this.name="ApiNetworkError",this.endpoint=t,this.originalError=n}}class Ve extends Error{endpoint;details;constructor(t,n){super(`Validation error before calling ${t}: ${n}`),this.name="ApiValidationError",this.endpoint=t,this.details=n}}const QP=new Set([408,429,500,502,503,504]);function XP(e){return QP.has(e)}function Fa(e){const t=`[API ${e.level.toUpperCase()}] ${e.timestamp} ${e.method} ${e.endpoint}`;switch(e.level){case"error":console.error(t,e.message,e.details??"");break;case"warn":console.warn(t,e.message,e.details??"");break;default:console.info(t,e.message,e.details??"")}}function At(e,t,n,s){Fa({timestamp:new Date().toISOString(),level:"info",endpoint:e,method:t,message:n,details:s})}function ji(e,t,n,s){Fa({timestamp:new Date().toISOString(),level:"warn",endpoint:e,method:t,message:n,details:s})}function Be(e,t,n,s){Fa({timestamp:new Date().toISOString(),level:"error",endpoint:e,method:t,message:n,details:s})}function YP(e,t,n=Yr){const s=new AbortController,r=setTimeout(()=>s.abort(),n);return{promise:fetch(e,{...t,signal:s.signal}).finally(()=>clearTimeout(r)),abort:()=>s.abort()}}let JP=e=>new Promise(t=>setTimeout(t,e));function mu(e){return JP(e)}function eE(e,t=Uh){const n=t*Math.pow(2,e),s=Math.random()*t;return Math.min(n+s,3e4)}async function gu(e,t={},n={}){const{maxRetries:s=Bh,timeoutMs:r=Yr,baseBackoffMs:o=Uh}=n,i=(t.method??"GET").toUpperCase();let a;for(let c=0;c<=s;c++){const u=Date.now();try{c>0&&At(e,i,`Retry attempt ${c}/${s}`);const{promise:d}=YP(e,t,r),l=await d,f=Date.now()-u;if(l.ok)return At(e,i,`${l.status} in ${f}ms`,{attempt:c}),await l.json();const p=await l.text().catch(()=>"Unable to read response body"),m=XP(l.status),g=new It({status:l.status,statusText:l.statusText,endpoint:e,responseBody:p,retryable:m,requestId:l.headers.get("x-request-id")??void 0});if(Be(e,i,`${l.status} ${l.statusText} in ${f}ms`,{attempt:c,responseBody:p.slice(0,500),retryable:m}),!m)throw g;if(l.status===429){const y=l.headers.get("retry-after");if(y){const v=parseInt(y,10);if(!isNaN(v)&&v>0){ji(e,i,`Rate limited. Waiting ${v}s (Retry-After header)`),await mu(v*1e3),a=g;continue}}}a=g}catch(d){const l=Date.now()-u;if(d instanceof It&&!d.retryable)throw d;if(d instanceof DOMException&&d.name==="AbortError"){const f=new xn(e,r);Be(e,i,`Timeout after ${l}ms`,{attempt:c,timeoutMs:r}),a=f}else if(d instanceof TypeError&&d.message.includes("fetch")){const f=new jr(e,d);Be(e,i,`Network error after ${l}ms: ${d.message}`,{attempt:c}),a=f}else d instanceof It?a=d:(a=d instanceof Error?d:new Error(String(d)),Be(e,i,`Unexpected error: ${a.message}`,{attempt:c}))}if(cs==null||s==="").map(([s])=>s);if(n.length>0)throw new Ve(e,`Missing required fields: ${n.join(", ")}`)}function De(e,t,n,s,r){if(typeof n!="number"||isNaN(n)||nr)throw new Ve(e,`${t} must be a number between ${s} and ${r}, got ${n}`)}function tE(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const nE=e=>{switch(e){case"success":return oE;case"info":return aE;case"warning":return iE;case"error":return cE;default:return null}},sE=Array(12).fill(0),rE=({visible:e,className:t})=>I.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},I.createElement("div",{className:"sonner-spinner"},sE.map((n,s)=>I.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),oE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),iE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),aE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),cE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),lE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},I.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),I.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),uE=()=>{const[e,t]=I.useState(document.hidden);return I.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Ni=1;class dE{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:s,...r}=t,o=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Ni++,i=this.toasts.find(c=>c.id===o),a=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),i?this.toasts=this.toasts.map(c=>c.id===o?(this.publish({...c,...t,id:o,title:s}),{...c,...t,id:o,dismissible:a,title:s}):c):this.addToast({title:s,...r,dismissible:a,id:o}),o},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(s=>s({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let s;n.loading!==void 0&&(s=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const r=Promise.resolve(t instanceof Function?t():t);let o=s!==void 0,i;const a=r.then(async u=>{if(i=["resolve",u],I.isValidElement(u))o=!1,this.create({id:s,type:"default",message:u});else if(hE(u)&&!u.ok){o=!1;const l=typeof n.error=="function"?await n.error(`HTTP error! status: ${u.status}`):n.error,f=typeof n.description=="function"?await n.description(`HTTP error! status: ${u.status}`):n.description,m=typeof l=="object"&&!I.isValidElement(l)?l:{message:l};this.create({id:s,type:"error",description:f,...m})}else if(u instanceof Error){o=!1;const l=typeof n.error=="function"?await n.error(u):n.error,f=typeof n.description=="function"?await n.description(u):n.description,m=typeof l=="object"&&!I.isValidElement(l)?l:{message:l};this.create({id:s,type:"error",description:f,...m})}else if(n.success!==void 0){o=!1;const l=typeof n.success=="function"?await n.success(u):n.success,f=typeof n.description=="function"?await n.description(u):n.description,m=typeof l=="object"&&!I.isValidElement(l)?l:{message:l};this.create({id:s,type:"success",description:f,...m})}}).catch(async u=>{if(i=["reject",u],n.error!==void 0){o=!1;const d=typeof n.error=="function"?await n.error(u):n.error,l=typeof n.description=="function"?await n.description(u):n.description,p=typeof d=="object"&&!I.isValidElement(d)?d:{message:d};this.create({id:s,type:"error",description:l,...p})}}).finally(()=>{o&&(this.dismiss(s),s=void 0),n.finally==null||n.finally.call(n)}),c=()=>new Promise((u,d)=>a.then(()=>i[0]==="reject"?d(i[1]):u(i[1])).catch(d));return typeof s!="string"&&typeof s!="number"?{unwrap:c}:Object.assign(s,{unwrap:c})},this.custom=(t,n)=>{const s=n?.id||Ni++;return this.create({jsx:t(s),id:s,...n}),s},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const st=new dE,fE=(e,t)=>{const n=t?.id||Ni++;return st.addToast({title:e,...t,id:n}),n},hE=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",pE=fE,mE=()=>st.toasts,gE=()=>st.getActiveToasts(),ct=Object.assign(pE,{success:st.success,info:st.info,warning:st.warning,error:st.error,custom:st.custom,message:st.message,promise:st.promise,dismiss:st.dismiss,loading:st.loading},{getHistory:mE,getToasts:gE});tE("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Js(e){return e.label!==void 0}const yE=3,bE="24px",vE="16px",yu=4e3,wE=356,xE=14,SE=45,kE=200;function _t(...e){return e.filter(Boolean).join(" ")}function TE(e){const[t,n]=e.split("-"),s=[];return t&&s.push(t),n&&s.push(n),s}const _E=e=>{var t,n,s,r,o,i,a,c,u;const{invert:d,toast:l,unstyled:f,interacting:p,setHeights:m,visibleToasts:g,heights:y,index:v,toasts:k,expanded:S,removeToast:w,defaultRichColors:T,closeButton:_,style:R,cancelButtonStyle:x,actionButtonStyle:A,className:P="",descriptionClassName:V="",duration:F,position:H,gap:re,expandByDefault:te,classNames:B,icons:ie,closeButtonAriaLabel:oe="Close toast"}=e,[ce,D]=I.useState(null),[de,He]=I.useState(null),[X,J]=I.useState(!1),[G,ne]=I.useState(!1),[xe,Z]=I.useState(!1),[ue,W]=I.useState(!1),[O,le]=I.useState(!1),[Te,Y]=I.useState(0),[Ne,be]=I.useState(0),Ae=I.useRef(l.duration||F||yu),it=I.useRef(null),at=I.useRef(null),Qn=v===0,to=v+1<=g,$e=l.type,Gt=l.dismissible!==!1,Ds=l.className||"",Os=l.descriptionClassName||"",En=I.useMemo(()=>y.findIndex(Q=>Q.toastId===l.id)||0,[y,l.id]),cn=I.useMemo(()=>{var Q;return(Q=l.closeButton)!=null?Q:_},[l.closeButton,_]),kt=I.useMemo(()=>l.duration||F||yu,[l.duration,F]),Xn=I.useRef(0),pt=I.useRef(0),Wt=I.useRef(0),Nt=I.useRef(null),[Ls,Ht]=H.split("-"),Zt=I.useMemo(()=>y.reduce((Q,Pe,Re)=>Re>=En?Q:Q+Pe.height,0),[y,En]),ln=uE(),no=l.invert||d,un=$e==="loading";pt.current=I.useMemo(()=>En*re+Zt,[En,Zt]),I.useEffect(()=>{Ae.current=kt},[kt]),I.useEffect(()=>{J(!0)},[]),I.useEffect(()=>{const Q=at.current;if(Q){const Pe=Q.getBoundingClientRect().height;return be(Pe),m(Re=>[{toastId:l.id,height:Pe,position:l.position},...Re]),()=>m(Re=>Re.filter(Fe=>Fe.toastId!==l.id))}},[m,l.id]),I.useLayoutEffect(()=>{if(!X)return;const Q=at.current,Pe=Q.style.height;Q.style.height="auto";const Re=Q.getBoundingClientRect().height;Q.style.height=Pe,be(Re),m(Fe=>Fe.find(Me=>Me.toastId===l.id)?Fe.map(Me=>Me.toastId===l.id?{...Me,height:Re}:Me):[{toastId:l.id,height:Re,position:l.position},...Fe])},[X,l.title,l.description,m,l.id,l.jsx,l.action,l.cancel]);const Tt=I.useCallback(()=>{ne(!0),Y(pt.current),m(Q=>Q.filter(Pe=>Pe.toastId!==l.id)),setTimeout(()=>{w(l)},kE)},[l,w,m,pt]);I.useEffect(()=>{if(l.promise&&$e==="loading"||l.duration===1/0||l.type==="loading")return;let Q;return S||p||ln?(()=>{if(Wt.current{Ae.current!==1/0&&(Xn.current=new Date().getTime(),Q=setTimeout(()=>{l.onAutoClose==null||l.onAutoClose.call(l,l),Tt()},Ae.current))})(),()=>clearTimeout(Q)},[S,p,l,$e,ln,Tt]),I.useEffect(()=>{l.delete&&(Tt(),l.onDismiss==null||l.onDismiss.call(l,l))},[Tt,l.delete]);function zs(){var Q;if(ie?.loading){var Pe;return I.createElement("div",{className:_t(B?.loader,l==null||(Pe=l.classNames)==null?void 0:Pe.loader,"sonner-loader"),"data-visible":$e==="loading"},ie.loading)}return I.createElement(rE,{className:_t(B?.loader,l==null||(Q=l.classNames)==null?void 0:Q.loader),visible:$e==="loading"})}const so=l.icon||ie?.[$e]||nE($e);var js,Cn;return I.createElement("li",{tabIndex:0,ref:at,className:_t(P,Ds,B?.toast,l==null||(t=l.classNames)==null?void 0:t.toast,B?.default,B?.[$e],l==null||(n=l.classNames)==null?void 0:n[$e]),"data-sonner-toast":"","data-rich-colors":(js=l.richColors)!=null?js:T,"data-styled":!(l.jsx||l.unstyled||f),"data-mounted":X,"data-promise":!!l.promise,"data-swiped":O,"data-removed":G,"data-visible":to,"data-y-position":Ls,"data-x-position":Ht,"data-index":v,"data-front":Qn,"data-swiping":xe,"data-dismissible":Gt,"data-type":$e,"data-invert":no,"data-swipe-out":ue,"data-swipe-direction":de,"data-expanded":!!(S||te&&X),"data-testid":l.testId,style:{"--index":v,"--toasts-before":v,"--z-index":k.length-v,"--offset":`${G?Te:pt.current}px`,"--initial-height":te?"auto":`${Ne}px`,...R,...l.style},onDragEnd:()=>{Z(!1),D(null),Nt.current=null},onPointerDown:Q=>{Q.button!==2&&(un||!Gt||(it.current=new Date,Y(pt.current),Q.target.setPointerCapture(Q.pointerId),Q.target.tagName!=="BUTTON"&&(Z(!0),Nt.current={x:Q.clientX,y:Q.clientY})))},onPointerUp:()=>{var Q,Pe,Re;if(ue||!Gt)return;Nt.current=null;const Fe=Number(((Q=at.current)==null?void 0:Q.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),An=Number(((Pe=at.current)==null?void 0:Pe.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Me=new Date().getTime()-((Re=it.current)==null?void 0:Re.getTime()),tt=ce==="x"?Fe:An,rt=Math.abs(tt)/Me;if(Math.abs(tt)>=SE||rt>.11){Y(pt.current),l.onDismiss==null||l.onDismiss.call(l,l),He(ce==="x"?Fe>0?"right":"left":An>0?"down":"up"),Tt(),W(!0);return}else{var Ue,Ze;(Ue=at.current)==null||Ue.style.setProperty("--swipe-amount-x","0px"),(Ze=at.current)==null||Ze.style.setProperty("--swipe-amount-y","0px")}le(!1),Z(!1),D(null)},onPointerMove:Q=>{var Pe,Re,Fe;if(!Nt.current||!Gt||((Pe=window.getSelection())==null?void 0:Pe.toString().length)>0)return;const Me=Q.clientY-Nt.current.y,tt=Q.clientX-Nt.current.x;var rt;const Ue=(rt=e.swipeDirections)!=null?rt:TE(H);!ce&&(Math.abs(tt)>1||Math.abs(Me)>1)&&D(Math.abs(tt)>Math.abs(Me)?"x":"y");let Ze={x:0,y:0};const dn=$t=>1/(1.5+Math.abs($t)/20);if(ce==="y"){if(Ue.includes("top")||Ue.includes("bottom"))if(Ue.includes("top")&&Me<0||Ue.includes("bottom")&&Me>0)Ze.y=Me;else{const $t=Me*dn(Me);Ze.y=Math.abs($t)0)Ze.x=tt;else{const $t=tt*dn(tt);Ze.x=Math.abs($t)0||Math.abs(Ze.y)>0)&&le(!0),(Re=at.current)==null||Re.style.setProperty("--swipe-amount-x",`${Ze.x}px`),(Fe=at.current)==null||Fe.style.setProperty("--swipe-amount-y",`${Ze.y}px`)}},cn&&!l.jsx&&$e!=="loading"?I.createElement("button",{"aria-label":oe,"data-disabled":un,"data-close-button":!0,onClick:un||!Gt?()=>{}:()=>{Tt(),l.onDismiss==null||l.onDismiss.call(l,l)},className:_t(B?.closeButton,l==null||(s=l.classNames)==null?void 0:s.closeButton)},(Cn=ie?.close)!=null?Cn:lE):null,($e||l.icon||l.promise)&&l.icon!==null&&(ie?.[$e]!==null||l.icon)?I.createElement("div",{"data-icon":"",className:_t(B?.icon,l==null||(r=l.classNames)==null?void 0:r.icon)},l.promise||l.type==="loading"&&!l.icon?l.icon||zs():null,l.type!=="loading"?so:null):null,I.createElement("div",{"data-content":"",className:_t(B?.content,l==null||(o=l.classNames)==null?void 0:o.content)},I.createElement("div",{"data-title":"",className:_t(B?.title,l==null||(i=l.classNames)==null?void 0:i.title)},l.jsx?l.jsx:typeof l.title=="function"?l.title():l.title),l.description?I.createElement("div",{"data-description":"",className:_t(V,Os,B?.description,l==null||(a=l.classNames)==null?void 0:a.description)},typeof l.description=="function"?l.description():l.description):null),I.isValidElement(l.cancel)?l.cancel:l.cancel&&Js(l.cancel)?I.createElement("button",{"data-button":!0,"data-cancel":!0,style:l.cancelButtonStyle||x,onClick:Q=>{Js(l.cancel)&&Gt&&(l.cancel.onClick==null||l.cancel.onClick.call(l.cancel,Q),Tt())},className:_t(B?.cancelButton,l==null||(c=l.classNames)==null?void 0:c.cancelButton)},l.cancel.label):null,I.isValidElement(l.action)?l.action:l.action&&Js(l.action)?I.createElement("button",{"data-button":!0,"data-action":!0,style:l.actionButtonStyle||A,onClick:Q=>{Js(l.action)&&(l.action.onClick==null||l.action.onClick.call(l.action,Q),!Q.defaultPrevented&&Tt())},className:_t(B?.actionButton,l==null||(u=l.classNames)==null?void 0:u.actionButton)},l.action.label):null)};function bu(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function PE(e,t){const n={};return[e,t].forEach((s,r)=>{const o=r===1,i=o?"--mobile-offset":"--offset",a=o?vE:bE;function c(u){["top","right","bottom","left"].forEach(d=>{n[`${i}-${d}`]=typeof u=="number"?`${u}px`:u})}typeof s=="number"||typeof s=="string"?c(s):typeof s=="object"?["top","right","bottom","left"].forEach(u=>{s[u]===void 0?n[`${i}-${u}`]=a:n[`${i}-${u}`]=typeof s[u]=="number"?`${s[u]}px`:s[u]}):c(a)}),n}const $o=I.forwardRef(function(t,n){const{id:s,invert:r,position:o="bottom-right",hotkey:i=["altKey","KeyT"],expand:a,closeButton:c,className:u,offset:d,mobileOffset:l,theme:f="light",richColors:p,duration:m,style:g,visibleToasts:y=yE,toastOptions:v,dir:k=bu(),gap:S=xE,icons:w,containerAriaLabel:T="Notifications"}=t,[_,R]=I.useState([]),x=I.useMemo(()=>s?_.filter(X=>X.toasterId===s):_.filter(X=>!X.toasterId),[_,s]),A=I.useMemo(()=>Array.from(new Set([o].concat(x.filter(X=>X.position).map(X=>X.position)))),[x,o]),[P,V]=I.useState([]),[F,H]=I.useState(!1),[re,te]=I.useState(!1),[B,ie]=I.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),oe=I.useRef(null),ce=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),D=I.useRef(null),de=I.useRef(!1),He=I.useCallback(X=>{R(J=>{var G;return(G=J.find(ne=>ne.id===X.id))!=null&&G.delete||st.dismiss(X.id),J.filter(({id:ne})=>ne!==X.id)})},[]);return I.useEffect(()=>st.subscribe(X=>{if(X.dismiss){requestAnimationFrame(()=>{R(J=>J.map(G=>G.id===X.id?{...G,delete:!0}:G))});return}setTimeout(()=>{Rp.flushSync(()=>{R(J=>{const G=J.findIndex(ne=>ne.id===X.id);return G!==-1?[...J.slice(0,G),{...J[G],...X},...J.slice(G+1)]:[X,...J]})})})}),[_]),I.useEffect(()=>{if(f!=="system"){ie(f);return}if(f==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ie("dark"):ie("light")),typeof window>"u")return;const X=window.matchMedia("(prefers-color-scheme: dark)");try{X.addEventListener("change",({matches:J})=>{ie(J?"dark":"light")})}catch{X.addListener(({matches:G})=>{try{ie(G?"dark":"light")}catch(ne){console.error(ne)}})}},[f]),I.useEffect(()=>{_.length<=1&&H(!1)},[_]),I.useEffect(()=>{const X=J=>{var G;if(i.every(Z=>J[Z]||J.code===Z)){var xe;H(!0),(xe=oe.current)==null||xe.focus()}J.code==="Escape"&&(document.activeElement===oe.current||(G=oe.current)!=null&&G.contains(document.activeElement))&&H(!1)};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[i]),I.useEffect(()=>{if(oe.current)return()=>{D.current&&(D.current.focus({preventScroll:!0}),D.current=null,de.current=!1)}},[oe.current]),I.createElement("section",{ref:n,"aria-label":`${T} ${ce}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},A.map((X,J)=>{var G;const[ne,xe]=X.split("-");return x.length?I.createElement("ol",{key:X,dir:k==="auto"?bu():k,tabIndex:-1,ref:oe,className:u,"data-sonner-toaster":!0,"data-sonner-theme":B,"data-y-position":ne,"data-x-position":xe,style:{"--front-toast-height":`${((G=P[0])==null?void 0:G.height)||0}px`,"--width":`${wE}px`,"--gap":`${S}px`,...g,...PE(d,l)},onBlur:Z=>{de.current&&!Z.currentTarget.contains(Z.relatedTarget)&&(de.current=!1,D.current&&(D.current.focus({preventScroll:!0}),D.current=null))},onFocus:Z=>{Z.target instanceof HTMLElement&&Z.target.dataset.dismissible==="false"||de.current||(de.current=!0,D.current=Z.relatedTarget)},onMouseEnter:()=>H(!0),onMouseMove:()=>H(!0),onMouseLeave:()=>{re||H(!1)},onDragEnd:()=>H(!1),onPointerDown:Z=>{Z.target instanceof HTMLElement&&Z.target.dataset.dismissible==="false"||te(!0)},onPointerUp:()=>te(!1)},x.filter(Z=>!Z.position&&J===0||Z.position===X).map((Z,ue)=>{var W,O;return I.createElement(_E,{key:Z.id,icons:w,index:ue,toast:Z,defaultRichColors:p,duration:(W=v?.duration)!=null?W:m,className:v?.className,descriptionClassName:v?.descriptionClassName,invert:r,visibleToasts:y,closeButton:(O=v?.closeButton)!=null?O:c,interacting:re,position:X,style:v?.style,unstyled:v?.unstyled,classNames:v?.classNames,cancelButtonStyle:v?.cancelButtonStyle,actionButtonStyle:v?.actionButtonStyle,closeButtonAriaLabel:v?.closeButtonAriaLabel,removeToast:He,toasts:x.filter(le=>le.position==Z.position),heights:P.filter(le=>le.position==Z.position),setHeights:V,expandByDefault:a,gap:S,expanded:F,swipeDirections:t.swipeDirections})})):null}))});function EE(e){const t=e.headers.get("retry-after")||e.headers.get("Retry-After");if(t){const n=parseInt(t,10);if(!isNaN(n)&&n>0)return n}return e.clone().json().then(n=>{if(n?.retry_after){const s=parseInt(n.retry_after,10);if(!isNaN(s)&&s>0)return s}}).catch(()=>{}),60}async function CE(e,t){const n=ye.currentUser;if(n)try{const s=U(L,"_analytics/rateLimitHits",n.uid);await Ce(s,{uid:n.uid,endpoint:e,retryAfter:t,timestamp:ae()},{merge:!0})}catch(s){console.warn("Failed to log rate limit hit:",s)}}const Fo=new Map;function AE(e,t){const n=`${e}-${Date.now()}`,s=Date.now()+t*1e3;ct.error(`You're going too fast! Please wait ${t} seconds before trying again.`,{duration:t*1e3,id:n});const r=Fo.get(e);r&&clearInterval(r.timerId);const o=window.setInterval(()=>{Math.ceil((s-Date.now())/1e3)<=0&&(clearInterval(o),Fo.delete(e),ct.dismiss(n))},1e3);Fo.set(e,{endpoint:e,endsAt:s,timerId:o})}async function RE(e,t){if(e.status!==429)return!1;const n=EE(e);return await CE(t,n),AE(t,n),window.dispatchEvent(new CustomEvent("rate-limit-hit",{detail:{endpoint:t,retryAfter:n,expiresAt:Date.now()+n*1e3}})),!0}const Ss="https://deign86-mathpulse-api-v3test.hf.space",Jr=(e,t)=>t,qh=(e,t)=>t,Vo=Jr(void 0,!0),vu=Jr(void 0,!0),wu=Jr(void 0,!0),xu=Jr(void 0,!0),Su=qh(void 0,9e4),Bo=qh(void 0,9e5);let Uo=!0,ku=0;const ME=6e4;async function IE(){const e="https://deign86-mathpulse-api-v3test.hf.space",t={"Content-Type":"application/json"},n=ye.currentUser;if(n)try{const r=await n.getIdToken(!1);r&&(t.Authorization=`Bearer ${r}`)}catch{}const s=await fetch(`${e}/api/rag/health`,{headers:t});if(!s.ok){const r=await s.text();throw new Error(`GET /api/rag/health failed: ${s.status} ${r}`)}return s.json()}async function DE(e){const t="https://deign86-mathpulse-api-v3test.hf.space",n={"Content-Type":"application/json"},s=ye.currentUser;if(s)try{const o=await s.getIdToken(!1);o&&(n.Authorization=`Bearer ${o}`)}catch{}const r=await fetch(`${t}/api/rag/lesson`,{method:"POST",headers:n,body:JSON.stringify(e)});if(!r.ok){const o=await r.text();throw new Error(`POST /api/rag/lesson failed: ${r.status} ${o}`)}return r.json()}async function OE(e){const t="https://deign86-mathpulse-api-v3test.hf.space",n={"Content-Type":"application/json"},s=ye.currentUser;if(s)try{const o=await s.getIdToken(!1);o&&(n.Authorization=`Bearer ${o}`)}catch{}const r=await fetch(`${t}/api/rag/generate-problem`,{method:"POST",headers:n,body:JSON.stringify(e)});if(!r.ok){const o=await r.text();throw new Error(`POST /api/rag/generate-problem failed: ${r.status} ${o}`)}return r.json()}async function LE(e){const t="https://deign86-mathpulse-api-v3test.hf.space",n={"Content-Type":"application/json"},s=ye.currentUser;if(s)try{const o=await s.getIdToken(!1);o&&(n.Authorization=`Bearer ${o}`)}catch{}const r=await fetch(`${t}/api/rag/analysis-context`,{method:"POST",headers:n,body:JSON.stringify(e)});if(!r.ok){const o=await r.text();throw new Error(`POST /api/rag/analysis-context failed: ${r.status} ${o}`)}return r.json()}const Et={maxRetries:Bh,timeoutMs:Yr,baseBackoffMs:1e3},Yt={...Et,timeoutMs:6e4},zE={...Yt,maxRetries:1,timeoutMs:45e3,baseBackoffMs:750},jE={...Et,maxRetries:1,timeoutMs:2e4,baseBackoffMs:500},rs={maxRetries:2,timeoutMs:12e4,baseBackoffMs:2e3},NE={maxRetries:0,timeoutMs:8e3,baseBackoffMs:500};let er=null;async function $E(){return er||(er=(async()=>{try{At("/health","GET","Warming up HuggingFace Space...");const e=new AbortController,t=setTimeout(()=>e.abort(),15e3),n=await fetch(`${Ss}/health`,{method:"GET",signal:e.signal});return clearTimeout(t),n.ok?(At("/health","GET","Backend warm and ready"),!0):(console.warn("[apiService] Backend health check returned",n.status),!1)}catch(e){return console.warn("[apiService] Backend warmup failed (cold start expected):",e),!1}})(),er)}async function j(e,t,n=Et){const s=`${Ss}${e}`,r=t?.method??"GET";At(e,r,"Starting request");const o=async a=>{const c=new Headers(t?.headers??{});!(t?.body instanceof FormData)&&!c.has("Content-Type")&&c.set("Content-Type","application/json");const u=ye.currentUser;if(u)try{const d=await u.getIdToken(a);d&&c.set("Authorization",`Bearer ${d}`)}catch(d){Be(e,r,"Failed to acquire Firebase ID token",d)}return{...t,headers:c}};let i=await o(!1);try{const a=await gu(s,i,n);return At(e,r,"Request succeeded"),a}catch(a){if(a instanceof It&&a.status===401&&ye.currentUser)try{At(e,r,"401 received, refreshing Firebase token and retrying once"),i=await o(!0);const c=await gu(s,i,n);return At(e,r,"Request succeeded after token refresh"),c}catch(c){throw c instanceof It?Be(e,r,`HTTP ${c.status}: ${c.responseBody.slice(0,300)}`):c instanceof xn?Be(e,r,`Timeout after ${c.timeoutMs}ms`):c instanceof jr?Be(e,r,`Network error: ${c.originalError.message}`):Be(e,r,`Unexpected: ${c instanceof Error?c.message:String(c)}`),c}throw a instanceof It?(Be(e,r,`HTTP ${a.status}: ${a.responseBody.slice(0,300)}`),a.status===429&&await RE(new Response(a.responseBody,{status:429,headers:{"retry-after":"60"}}),e)):a instanceof xn?Be(e,r,`Timeout after ${a.timeoutMs}ms`):a instanceof jr?Be(e,r,`Network error: ${a.originalError.message}`):Be(e,r,`Unexpected: ${a instanceof Error?a.message:String(a)}`),a}}async function Tu(e,t,n=Yr){const s=`${Ss}${e}`,r=t?.method??"GET";At(e,r,"Starting blob request");const o=async i=>{const a=new Headers(t?.headers??{}),c=ye.currentUser;if(c)try{const l=await c.getIdToken(i);l&&a.set("Authorization",`Bearer ${l}`)}catch(l){Be(e,r,"Failed to acquire Firebase ID token",l)}const u=new AbortController,d=setTimeout(()=>u.abort(),n);try{const l=await fetch(s,{...t,headers:a,signal:u.signal});if(!l.ok){const f=await l.text();throw new It({status:l.status,statusText:l.statusText||"Request Failed",endpoint:e,responseBody:f,retryable:l.status>=500||l.status===429})}return await l.blob()}finally{clearTimeout(d)}};try{return await o(!1)}catch(i){if(i instanceof It&&i.status===401&&ye.currentUser)return At(e,r,"401 received for blob request, refreshing Firebase token and retrying once"),o(!0);throw i}}const FE={response:"Sorry, the AI tutor is temporarily unavailable. Please try again in a moment."},VE={riskLevel:"Medium",confidence:0,analysis:{labels:[],scores:[]},risk_level:"medium",risk_score:0,top_factors:["Fallback risk response due to temporary service unavailability"]},BE={learningPath:"Unable to generate a learning path right now. Please try again later."},UE={insight:"Daily insight is temporarily unavailable. Please refresh later."},qE={expression:"",result:"Error: calculation service unavailable",steps:[],simplified:null,latex:null};function GE(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.riskLevel=="string"&&typeof t.confidence=="number"}function _u(e){if(typeof e!="object"||e===null)return!1;const t=e;return Array.isArray(t.questions)&&typeof t.totalPoints=="number"}const WE=e=>new Promise(t=>setTimeout(t,e));function HE(e){if(!e)return"Generation task failed without a detailed error.";if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){const t=e;if(typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return"Generation task failed due to an unknown error."}}return String(e)}const bt={getImportGroundedRolloutFlags(){return{quizEnabled:Vo,lessonEnabled:vu,feedbackEnabled:wu}},async reportImportGroundedFeedback(e){return wu?j("/api/feedback/import-grounded",{method:"POST",body:JSON.stringify(e)}):{success:!0,stored:!1,warnings:["Import-grounded feedback events are disabled by frontend rollout flag."]}},async health(){return j("/health",void 0,{...Et,timeoutMs:1e4})},async chat(e,t,n,s){Se("/api/chat",{message:e});const r={message:e,history:t??[],...s?.sessionId?{sessionId:s.sessionId}:{},...s?.expectedEndMarker?{expectedEndMarker:s.expectedEndMarker}:{},...s?.completionMode?{completionMode:s.completionMode}:{},...typeof s?.continuationMaxRounds=="number"?{continuationMaxRounds:Math.max(0,Math.floor(s.continuationMaxRounds))}:{},...s?.moduleContext?{moduleContext:s.moduleContext}:{}};if(n){const i=new AbortController;let a=null,c=null,u=null;const d=y=>{a||(a=y,i.abort())},l=()=>{c&&(clearTimeout(c),c=null),u&&(clearTimeout(u),u=null)},f=()=>{c&&clearTimeout(c),c=setTimeout(()=>d("idle"),Su)};u=setTimeout(()=>d("total"),Bo);const p=new Headers({"Content-Type":"application/json"}),m=ye.currentUser;if(m)try{const y=await m.getIdToken(!1);y&&p.set("Authorization",`Bearer ${y}`)}catch(y){Be("/api/chat/stream","POST","Failed to acquire Firebase ID token",y)}let g=null;try{f();const y=await fetch(`${Ss}/api/chat/stream`,{method:"POST",headers:p,body:JSON.stringify(r),signal:i.signal});if(!y.ok||!y.body){const _=await y.text().catch(()=>"Unable to read response body");throw new Error(`Streaming request failed (${y.status}): ${_.slice(0,300)}`)}g=y.body.getReader();const v=new TextDecoder;let k="",S="",w=!1;const T=_=>{const R=_.indexOf(` +What would you like to learn about?`}const $R=()=>{const e=h.useContext(Fh);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},ZP=({children:e})=>{const{currentUser:t}=Ms(),[n,s]=h.useState([]),[r,o]=h.useState(null),[i,a]=h.useState(!1),[c,u]=h.useState(null),[d,l]=h.useState(!1),f=h.useRef(new Map);h.useEffect(()=>{if(!t){s([]),l(!1);return}(async()=>{try{const T=await hn(),_=await T.getUserChatSessions(t.uid),R=await Promise.all(_.map(async x=>{const P=(await T.getSessionMessages(x.id,t.uid)).map(V=>({id:V.id,sender:V.role==="user"?"user":"ai",text:V.role==="assistant"?yt(V.content):V.content,timestamp:V.timestamp instanceof Date?V.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):new Date(V.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}));return{id:x.id,title:x.title,date:x.updatedAt instanceof Date?x.updatedAt.toLocaleDateString():new Date(x.updatedAt).toLocaleDateString(),messageCount:P.length,preview:P.length>0&&Lo(P[P.length-1].text)||"No messages yet",topics:[],messages:P,createdAt:x.createdAt instanceof Date?x.createdAt:new Date(x.createdAt),updatedAt:x.updatedAt instanceof Date?x.updatedAt:new Date(x.updatedAt)}}));s(R)}catch(T){console.error("Error loading chat sessions:",T)}finally{l(!0)}})()},[t]);const p=w=>{if(w.length===0)return"New Chat";const T=w.find(x=>x.sender==="user")?.text||"",_=T.toLowerCase();if(_.includes("quadratic")||_.includes("ax² + bx + c"))return"Quadratic Equations Help";if(_.includes("derivative")||_.includes("calculus"))return"Derivatives & Calculus";if(_.includes("pythagor")||_.includes("right triangle"))return"Pythagorean Theorem";if(_.includes("trig")||_.includes("sin")||_.includes("cos"))return"Trigonometry Help";if(_.includes("area")||_.includes("perimeter"))return"Geometry - Area & Perimeter";if(_.includes("algebra")||_.includes("solve")&&_.includes("x"))return"Algebra Problem Solving";if(_.includes("factor"))return"Factoring Practice";if(_.includes("graph")||_.includes("plot"))return"Graphing Functions";if(_.includes("matrix")||_.includes("matrices"))return"Matrix Operations";if(_.includes("integral")||_.includes("integrate"))return"Integration Problems";if(_.includes("limit"))return"Limits in Calculus";if(_.includes("statistic")||_.includes("probability"))return"Statistics & Probability";const R=T.slice(0,40);return R.length{const T=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),_=new Date,R={id:T,title:w?p([w]):"New Chat",date:"Just now",messageCount:w?1:0,preview:w&&Lo(w.text)||"Start a new conversation...",topics:[],messages:w?[w]:[],createdAt:_,updatedAt:_};if(s(x=>[R,...x]),t){const x=w?p([w]):"New Chat",A=hn().then(async P=>{const V=await P.createChatSession(t.uid,x);return ee(async()=>{const{logChatSession:F}=await import("./trackingService-DJ3_U-Mf.js");return{logChatSession:F}},__vite__mapDeps([13,1,2,3,4,5,6,7,8,9,10])).then(({logChatSession:F})=>F(t.uid,V.id,w?1:0).catch(()=>{})),w&&await P.addMessageToSession(V.id,w.sender==="user"?"user":"assistant",w.text),V.id}).catch(P=>(console.error("Error creating Firebase session:",P),T));f.current.set(T,A)}return T},[t]),g=h.useCallback((w,T)=>{s(R=>R.map(x=>{if(x.id===w){const A=[...x.messages,T];return{...x,messages:A,messageCount:A.length,preview:Lo(T.text)||x.preview,updatedAt:new Date,title:A.length===2?p(A):x.title}}return x}));const _=async R=>{const x=f.current.get(R);return x?await x:R};_(w).then(async R=>{await(await hn()).addMessageToSession(R,T.sender==="user"?"user":"assistant",T.text)}).catch(R=>console.error("Error persisting message:",R)),s(R=>{const x=R.find(A=>A.id===w);if(x&&x.messages.length===2){const A=p(x.messages);_(w).then(async P=>{await(await hn()).updateSessionTitle(P,A)}).catch(P=>console.error("Error updating title:",P))}return R})},[]),y=h.useCallback(async(w,T)=>{const _=T.trim(),R={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),sender:"user",text:_,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,R),u(w),a(!0);try{let x=null,A=null;const P=n.find(W=>W.id===w),F=[...P?.messages||[],R].map(W=>({role:W.sender==="user"?"user":"assistant",content:W.text})),H=Vh(_)?FP(F):null,re=H?VP(H):_,te=H??_,B=IP(_)?DP({userId:t?.uid||"anonymous",prompt:_,history:F}):null,ie=W=>{if(!B)return;const O=yt(W).trim();O&&LP(B,O)},oe=Nh(_,{history:F});if(oe){const W={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:oe,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,W);return}if(B){const W=OP(B);if(W){const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:W,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,O);return}}try{const W=await uu();x=W.apiService,A=W.ApiTimeoutError}catch(W){console.error("Failed to load API service for chat:",W);const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:Ys(te),timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(w,O);return}const ce=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});let D="",de=null;const He=WP(_),X=HP(_),J=BP(_),G=X||!!J,ne={sessionId:w,...J?{expectedEndMarker:J,completionMode:"marker"}:{}},xe=W=>zi(_,W,J,X),Z=W=>{W.trim()&&s(O=>O.map(le=>{if(le.id!==w)return le;if(!de){de=`stream-${typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString()}-${Math.random().toString(36).slice(2,8)}`;const Te={id:de,sender:"ai",text:W,timestamp:ce},Y=[...le.messages,Te];return{...le,messages:Y,messageCount:Y.length,updatedAt:new Date}}return{...le,messages:le.messages.map(Te=>Te.id===de?{...Te,text:W}:Te),updatedAt:new Date}}))},ue=()=>{if(!de)return;const W=de;s(O=>O.map(le=>{if(le.id!==w)return le;const Te=le.messages.filter(Y=>Y.id!==W);return{...le,messages:Te,messageCount:Te.length,updatedAt:new Date}}))};try{const{response:W}=await x.chat(re,F,Y=>{D+=Y,He&&Z(iP(D))},ne);let O=yt(W||D).trim();if(G&&O&&xe(O)){try{const Y=await x.chatSafe(du(_,O,J),F,ne),Ne=yt(Y.data.response).trim();O=Xs(O,Ne)}catch(Y){console.warn("Streaming completion repair failed:",Y)}if(G&&O&&xe(O))try{const Y=await x.chatSafe(fu(_,O,J),F,ne),Ne=yt(Y.data.response).trim();O=Xs(O,Ne)}catch(Y){console.warn("Streaming plain continuation repair failed:",Y)}if(G&&O&&xe(O))try{const Y=await x.chatSafe(hu(_,J),F,ne),Ne=yt(Y.data.response).trim();Ne&&(O=pu(_,O,Ne,J,X))}catch(Y){console.warn("Streaming full completion repair failed:",Y)}}const le=xe(O);(!O||le&&!G)&&(O=Ys(te,F)),ie(O),de&&ue();const Te={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ce};g(w,Te)}catch(W){A&&W instanceof A?console.warn(`Streaming timed out after ${W.timeoutMs}ms, falling back to non-streaming chat.`,W):console.warn("Streaming failed, falling back to non-streaming chat:",W),de&&ue();let O="";try{const Y=x??(await uu()).apiService,{data:Ne}=await Y.chatSafe(re,F,ne);if(O=yt(Ne.response).trim(),G&&O&&xe(O))try{const be=await Y.chatSafe(du(_,O,J),F,ne),Ae=yt(be.data.response).trim();O=Xs(O,Ae)}catch(be){console.warn("Non-stream completion repair failed:",be)}if(G&&O&&xe(O))try{const be=await Y.chatSafe(fu(_,O,J),F,ne),Ae=yt(be.data.response).trim();O=Xs(O,Ae)}catch(be){console.warn("Non-stream plain continuation repair failed:",be)}if(G&&O&&xe(O))try{const be=await Y.chatSafe(hu(_,J),F,ne),Ae=yt(be.data.response).trim();Ae&&(O=pu(_,O,Ae,J,X))}catch(be){console.warn("Non-stream full completion repair failed:",be)}}catch(Y){console.warn("Chat request failed, using local fallback response:",Y),O=Ys(te,F)}const le=xe(O);(!O||le&&!G)&&(O=Ys(te,F)),ie(O);const Te={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ce};g(w,Te)}if(P&&P.messages.length===1){const W=n.find(O=>O.id===w);if(W&&W.messages.length>1){const O=p(W.messages),le=f.current.get(w);(le||Promise.resolve(w)).then(async Y=>{await(await hn()).updateSessionTitle(Y,O)}).catch(Y=>console.error("Error updating title:",Y))}}}finally{a(!1),u(null)}},[n,g,t]),v=h.useCallback((w,T)=>{s(x=>x.map(A=>A.id===w?{...A,title:T}:A));const _=f.current.get(w);(_||Promise.resolve(w)).then(async x=>{await(await hn()).updateSessionTitle(x,T)}).catch(x=>console.error("Error updating session title:",x))},[]),k=h.useCallback(w=>{s(R=>R.filter(x=>x.id!==w)),r===w&&o(null);const T=f.current.get(w);(T||Promise.resolve(w)).then(async R=>{await(await hn()).deleteSession(R)}).catch(R=>console.error("Error deleting session:",R)),f.current.delete(w)},[r]),S=h.useCallback(()=>n.find(w=>w.id===r)||null,[n,r]);return b.jsx(Fh.Provider,{value:{sessions:n,activeSessionId:r,isLoading:i,loadingSessionId:c,sessionsLoaded:d,setActiveSessionId:o,createNewSession:m,addMessageToSession:g,sendMessage:y,updateSessionTitle:v,deleteSession:k,getActiveSession:S,generateTitleFromMessages:p},children:e})},KP=[{id:"first_lesson",title:"First Steps",description:"Complete your first lesson",icon:Oo,iconColor:"text-yellow-500",xpReward:50,condition:"lesson_complete",threshold:1,category:"learning"},{id:"lesson_10",title:"Dedicated Learner",description:"Complete 10 lessons",icon:Oo,iconColor:"text-blue-500",xpReward:200,condition:"lesson_complete",threshold:10,category:"learning"},{id:"lesson_50",title:"Knowledge Seeker",description:"Complete 50 lessons",icon:Ll,iconColor:"text-purple-500",xpReward:500,condition:"lesson_complete",threshold:50,category:"learning"},{id:"perfect_score",title:"Perfect Score",description:"Score 100% on any quiz",icon:$l,iconColor:"text-yellow-400",xpReward:150,condition:"perfect_score",category:"learning"},{id:"no_mistakes",title:"Flawless",description:"Complete a quiz with zero wrong answers",icon:jl,iconColor:"text-emerald-500",xpReward:100,condition:"quiz_no_mistakes",category:"learning"},{id:"speed_demon",title:"Speed Demon",description:"Complete a quiz in under 2 minutes",icon:Ci,iconColor:"text-orange-500",xpReward:100,condition:"speed_quiz",category:"learning"},{id:"quiz_10",title:"Quiz Enthusiast",description:"Complete 10 quizzes",icon:Tx,iconColor:"text-cyan-500",xpReward:200,condition:"quiz_complete",threshold:10,category:"learning"},{id:"quiz_50",title:"Quiz Champion",description:"Complete 50 quizzes",icon:Oo,iconColor:"text-indigo-500",xpReward:500,condition:"quiz_complete",threshold:50,category:"learning"},{id:"quiz_perfect",title:"Perfectionist",description:"Get 5 perfect quiz scores",icon:Hx,iconColor:"text-amber-400",xpReward:300,condition:"perfect_score",threshold:5,category:"learning"},{id:"study_streak",title:"Study Streak",description:"Maintain a 7-day lesson completion streak",icon:gr,iconColor:"text-red-500",xpReward:300,condition:"mastery_10",threshold:7,category:"learning"},{id:"first_battle",title:"First Blood",description:"Win your first Quiz Battle",icon:Ws,iconColor:"text-red-400",xpReward:100,condition:"battle_win",threshold:1,category:"battle"},{id:"battle_10",title:"Battle Veteran",description:"Win 10 Quiz Battles",icon:Ws,iconColor:"text-orange-400",xpReward:300,condition:"battle_win",threshold:10,category:"battle"},{id:"battle_50",title:"Battle Legend",description:"Win 50 Quiz Battles",icon:Ws,iconColor:"text-red-500",xpReward:1e3,condition:"battle_win",threshold:50,category:"battle"},{id:"undefeated",title:"Undefeated",description:"Win 5 battles in a row without losing",icon:zl,iconColor:"text-blue-500",xpReward:500,condition:"battle_undefeated",threshold:5,category:"battle"},{id:"quick_win",title:"Speed Battle",description:"Win a battle by answering all questions first",icon:Ci,iconColor:"text-yellow-500",xpReward:150,condition:"speed_quiz",category:"battle"},{id:"comeback",title:"The Comeback",description:"Win a battle after being behind in score",icon:qx,iconColor:"text-teal-500",xpReward:200,condition:"battle_comeback",category:"battle"},{id:"battle_master",title:"Battle Master",description:"Win 3 battles in a single day",icon:mr,iconColor:"text-yellow-500",xpReward:400,condition:"battle_win",threshold:3,category:"battle"},{id:"invincible",title:"Invincible",description:"Win 10 battles in a row",icon:zl,iconColor:"text-violet-500",xpReward:1e3,condition:"battle_undefeated",threshold:10,category:"battle"},{id:"first_blood_daily",title:"Early Bird",description:"Win your first battle of the day",icon:Kx,iconColor:"text-amber-500",xpReward:50,condition:"battle_win",threshold:1,category:"battle"},{id:"rival_crusher",title:"Rival Crusher",description:"Win 25 battles total",icon:Ws,iconColor:"text-rose-500",xpReward:750,condition:"battle_win",threshold:25,category:"battle"},{id:"mastery_10",title:"Week Warrior",description:"Maintain a 10-day learning streak",icon:gr,iconColor:"text-orange-500",xpReward:500,condition:"mastery_10",threshold:10,category:"mastery"},{id:"mastery_level",title:"Rising Star",description:"Reach level 5",icon:mr,iconColor:"text-yellow-400",xpReward:250,condition:"mastery_level",threshold:5,category:"mastery"},{id:"mastery_xp",title:"XP Hunter",description:"Earn a total of 5,000 XP",icon:Nl,iconColor:"text-emerald-500",xpReward:400,condition:"mastery_xp",threshold:5e3,category:"mastery"},{id:"mastery_all_lessons",title:"Curriculum Complete",description:"Complete all available lessons",icon:Ll,iconColor:"text-purple-500",xpReward:1e3,condition:"mastery_all_lessons",category:"mastery"},{id:"mastery_all_subjects",title:"Polymath",description:"Complete at least one lesson in every subject",icon:Dx,iconColor:"text-cyan-500",xpReward:500,condition:"mastery_all_subjects",category:"mastery"},{id:"mastery_assessment_perfect",title:"Assessment Perfect",description:"Score 100% on a diagnostic assessment",icon:jl,iconColor:"text-amber-500",xpReward:400,condition:"mastery_assessment_perfect",category:"mastery"},{id:"mastery_max_level",title:"Max Level",description:"Reach the maximum player level",icon:mr,iconColor:"text-yellow-500",xpReward:2e3,condition:"mastery_max_level",category:"mastery"},{id:"mastery_top_10",title:"Leaderboard Elite",description:"Reach the top 10 on the global leaderboard",icon:Dl,iconColor:"text-amber-400",xpReward:1e3,condition:"social_xp",category:"mastery"},{id:"explore_profile",title:"Identity Set",description:"Complete your user profile",icon:sS,iconColor:"text-blue-400",xpReward:50,condition:"explore_profile_complete",category:"exploration"},{id:"explore_first_friend",title:"Socialite",description:"Add your first friend",icon:Fl,iconColor:"text-green-500",xpReward:50,condition:"explore_friend_added",threshold:1,category:"exploration"},{id:"explore_daily_return",title:"Daily Visitor",description:"Return to the app 3 days in a row",icon:Ol,iconColor:"text-indigo-400",xpReward:100,condition:"social_daily_return",threshold:3,category:"exploration"},{id:"explore_10_friends",title:"Popular",description:"Have 10 friends on the platform",icon:oS,iconColor:"text-teal-500",xpReward:300,condition:"explore_friend_added",threshold:10,category:"exploration"},{id:"explore_all_features",title:"Explorer",description:"Use all major app features",icon:Ax,iconColor:"text-orange-400",xpReward:200,condition:"explore_profile_complete",category:"exploration"},{id:"explore_25_friends",title:"Social Butterfly",description:"Have 25 friends on the platform",icon:zx,iconColor:"text-pink-500",xpReward:500,condition:"explore_social",threshold:25,category:"exploration"},{id:"explore_xp_1000",title:"XP Milestone",description:"Earn your first 1,000 XP",icon:Nl,iconColor:"text-blue-500",xpReward:100,condition:"mastery_xp",threshold:1e3,category:"exploration"},{id:"social_first_friend",title:"Friendship Starter",description:"Send your first friend request",icon:Fl,iconColor:"text-green-400",xpReward:25,condition:"social_friend",threshold:1,category:"social"},{id:"social_helper",title:"Helpful Hand",description:"Contribute to the community",icon:Dl,iconColor:"text-cyan-500",xpReward:150,condition:"social_contribution",category:"social"},{id:"social_top_10",title:"Elite Status",description:"Reach the top 10 on the leaderboard",icon:$l,iconColor:"text-yellow-400",xpReward:500,condition:"social_xp",category:"social"},{id:"social_streak_30",title:"Dedicated Member",description:"Maintain a 30-day activity streak",icon:gr,iconColor:"text-red-400",xpReward:1e3,condition:"mastery_10",threshold:30,category:"social"},{id:"social_daily_7",title:"Weekly Visitor",description:"Return to the app 7 days in a row",icon:Ol,iconColor:"text-violet-400",xpReward:200,condition:"social_daily_return",threshold:7,category:"social"}];new Map(KP.map(e=>[e.id,e]));const No=async(e,t,n,s)=>{try{const r=U(L,"users",e),o=await me(r);if(!o.exists())throw new Error("User not found");const i=o.data(),a=i.currentXP||0,c=i.totalXP||0,u=i.xpMultiplier||1,d=Math.floor(t*u),l=a+d,f=c+d;let m=i.level||1;const g=f;let y=!1;for(;;){const S=Math.floor(100*Math.pow(1.5,m-1));let w=0;for(let T=1;T<=m;T++)w+=Math.floor(100*Math.pow(1.5,T-1));if(f>=w)m++,y=!0;else break}const v={currentXP:l,totalXP:f,level:m,updatedAt:ae()};u!==1&&(v.xpMultiplier=1),await dt(r,v);const k=U(et(L,"xpActivities"));return await Ce(k,{activityId:k.id,userId:e,type:n,xpEarned:t,description:s,timestamp:ae()}),{newLevel:m,leveledUp:y,xp:l,addedXp:t}}catch(r){throw console.error("Error awarding XP:",r),r}},FR=async(e,t=!1,n="all",s=10)=>{try{const r=Dt(et(L,"leaderboard"),Sn("totalXP","desc"),ks(s)),o=await Fn(r);return o.empty?[]:o.docs.map((i,a)=>{const c=i.data();return{userId:i.id,name:c.name||"Unknown",photo:c.photo,xp:c.totalXP||0,level:c.level||1,rank:a+1,weeklyXP:c.weeklyXP||0,monthlyXP:c.monthlyXP||0}})}catch(r){return console.error("Error getting leaderboard:",r),[]}},VR=(e,t,n=!1,s="all",r=10)=>{const o=Dt(et(L,"leaderboard"),Sn("totalXP","desc"),ks(r));return en(o,i=>{const a=i.docs.map((c,u)=>{const d=c.data();return{userId:c.id,name:d.name||"Unknown",photo:d.photo,xp:d.totalXP||0,level:d.level||1,rank:u+1,weeklyXP:d.weeklyXP||0,monthlyXP:d.monthlyXP||0}});e(a)},i=>{console.error("Error subscribing to leaderboard:",i),e([])})},BR=async e=>{try{const t=await me(U(L,"achievements",e));return t.exists()?t.data().achievements||[]:[]}catch(t){return console.error("Error getting user achievements:",t),[]}},UR=async(e,t,n)=>{try{const s=U(L,"users",e),r=await me(s);if(!r.exists())throw new Error("User not found");const o=r.data(),i=o.currentXP||0;if((o.ownedAvatarItems||[]).includes(t))return{success:!1,message:"You already own this item",currentXP:i};if(i{try{const n=U(L,"users",e),s=await me(n);if(!s.exists())throw new Error("User not found");return(s.data().ownedAvatarItems||[]).includes(t)?{success:!0,message:"Item already owned"}:(await dt(n,{ownedAvatarItems:Fu(t),updatedAt:ae()}),{success:!0,message:"Avatar item unlocked!"})}catch(n){return console.error("Error unlocking avatar item:",n),{success:!1,message:"Failed to unlock item"}}},Yr=3e4,Bh=3,Uh=1e3;class It extends Error{status;statusText;endpoint;responseBody;retryable;requestId;constructor(t){super(`API Error ${t.status} (${t.statusText}) on ${t.endpoint}: ${t.responseBody}`),this.name="ApiError",this.status=t.status,this.statusText=t.statusText,this.endpoint=t.endpoint,this.responseBody=t.responseBody,this.retryable=t.retryable,this.requestId=t.requestId}}class xn extends Error{endpoint;timeoutMs;constructor(t,n){super(`Request to ${t} timed out after ${n}ms`),this.name="ApiTimeoutError",this.endpoint=t,this.timeoutMs=n}}class jr extends Error{endpoint;originalError;constructor(t,n){super(`Network error on ${t}: ${n.message}`),this.name="ApiNetworkError",this.endpoint=t,this.originalError=n}}class Ve extends Error{endpoint;details;constructor(t,n){super(`Validation error before calling ${t}: ${n}`),this.name="ApiValidationError",this.endpoint=t,this.details=n}}const QP=new Set([408,429,500,502,503,504]);function XP(e){return QP.has(e)}function Fa(e){const t=`[API ${e.level.toUpperCase()}] ${e.timestamp} ${e.method} ${e.endpoint}`;switch(e.level){case"error":console.error(t,e.message,e.details??"");break;case"warn":console.warn(t,e.message,e.details??"");break;default:console.info(t,e.message,e.details??"")}}function At(e,t,n,s){Fa({timestamp:new Date().toISOString(),level:"info",endpoint:e,method:t,message:n,details:s})}function ji(e,t,n,s){Fa({timestamp:new Date().toISOString(),level:"warn",endpoint:e,method:t,message:n,details:s})}function Be(e,t,n,s){Fa({timestamp:new Date().toISOString(),level:"error",endpoint:e,method:t,message:n,details:s})}function YP(e,t,n=Yr){const s=new AbortController,r=setTimeout(()=>s.abort(),n);return{promise:fetch(e,{...t,signal:s.signal}).finally(()=>clearTimeout(r)),abort:()=>s.abort()}}let JP=e=>new Promise(t=>setTimeout(t,e));function mu(e){return JP(e)}function eE(e,t=Uh){const n=t*Math.pow(2,e),s=Math.random()*t;return Math.min(n+s,3e4)}async function gu(e,t={},n={}){const{maxRetries:s=Bh,timeoutMs:r=Yr,baseBackoffMs:o=Uh}=n,i=(t.method??"GET").toUpperCase();let a;for(let c=0;c<=s;c++){const u=Date.now();try{c>0&&At(e,i,`Retry attempt ${c}/${s}`);const{promise:d}=YP(e,t,r),l=await d,f=Date.now()-u;if(l.ok)return At(e,i,`${l.status} in ${f}ms`,{attempt:c}),await l.json();const p=await l.text().catch(()=>"Unable to read response body"),m=XP(l.status),g=new It({status:l.status,statusText:l.statusText,endpoint:e,responseBody:p,retryable:m,requestId:l.headers.get("x-request-id")??void 0});if(Be(e,i,`${l.status} ${l.statusText} in ${f}ms`,{attempt:c,responseBody:p.slice(0,500),retryable:m}),!m)throw g;if(l.status===429){const y=l.headers.get("retry-after");if(y){const v=parseInt(y,10);if(!isNaN(v)&&v>0){ji(e,i,`Rate limited. Waiting ${v}s (Retry-After header)`),await mu(v*1e3),a=g;continue}}}a=g}catch(d){const l=Date.now()-u;if(d instanceof It&&!d.retryable)throw d;if(d instanceof DOMException&&d.name==="AbortError"){const f=new xn(e,r);Be(e,i,`Timeout after ${l}ms`,{attempt:c,timeoutMs:r}),a=f}else if(d instanceof TypeError&&d.message.includes("fetch")){const f=new jr(e,d);Be(e,i,`Network error after ${l}ms: ${d.message}`,{attempt:c}),a=f}else d instanceof It?a=d:(a=d instanceof Error?d:new Error(String(d)),Be(e,i,`Unexpected error: ${a.message}`,{attempt:c}))}if(cs==null||s==="").map(([s])=>s);if(n.length>0)throw new Ve(e,`Missing required fields: ${n.join(", ")}`)}function De(e,t,n,s,r){if(typeof n!="number"||isNaN(n)||nr)throw new Ve(e,`${t} must be a number between ${s} and ${r}, got ${n}`)}function tE(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const nE=e=>{switch(e){case"success":return oE;case"info":return aE;case"warning":return iE;case"error":return cE;default:return null}},sE=Array(12).fill(0),rE=({visible:e,className:t})=>I.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},I.createElement("div",{className:"sonner-spinner"},sE.map((n,s)=>I.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),oE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),iE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),aE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),cE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},I.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),lE=I.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},I.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),I.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),uE=()=>{const[e,t]=I.useState(document.hidden);return I.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Ni=1;class dE{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:s,...r}=t,o=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Ni++,i=this.toasts.find(c=>c.id===o),a=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),i?this.toasts=this.toasts.map(c=>c.id===o?(this.publish({...c,...t,id:o,title:s}),{...c,...t,id:o,dismissible:a,title:s}):c):this.addToast({title:s,...r,dismissible:a,id:o}),o},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(s=>s({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let s;n.loading!==void 0&&(s=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const r=Promise.resolve(t instanceof Function?t():t);let o=s!==void 0,i;const a=r.then(async u=>{if(i=["resolve",u],I.isValidElement(u))o=!1,this.create({id:s,type:"default",message:u});else if(hE(u)&&!u.ok){o=!1;const l=typeof n.error=="function"?await n.error(`HTTP error! status: ${u.status}`):n.error,f=typeof n.description=="function"?await n.description(`HTTP error! status: ${u.status}`):n.description,m=typeof l=="object"&&!I.isValidElement(l)?l:{message:l};this.create({id:s,type:"error",description:f,...m})}else if(u instanceof Error){o=!1;const l=typeof n.error=="function"?await n.error(u):n.error,f=typeof n.description=="function"?await n.description(u):n.description,m=typeof l=="object"&&!I.isValidElement(l)?l:{message:l};this.create({id:s,type:"error",description:f,...m})}else if(n.success!==void 0){o=!1;const l=typeof n.success=="function"?await n.success(u):n.success,f=typeof n.description=="function"?await n.description(u):n.description,m=typeof l=="object"&&!I.isValidElement(l)?l:{message:l};this.create({id:s,type:"success",description:f,...m})}}).catch(async u=>{if(i=["reject",u],n.error!==void 0){o=!1;const d=typeof n.error=="function"?await n.error(u):n.error,l=typeof n.description=="function"?await n.description(u):n.description,p=typeof d=="object"&&!I.isValidElement(d)?d:{message:d};this.create({id:s,type:"error",description:l,...p})}}).finally(()=>{o&&(this.dismiss(s),s=void 0),n.finally==null||n.finally.call(n)}),c=()=>new Promise((u,d)=>a.then(()=>i[0]==="reject"?d(i[1]):u(i[1])).catch(d));return typeof s!="string"&&typeof s!="number"?{unwrap:c}:Object.assign(s,{unwrap:c})},this.custom=(t,n)=>{const s=n?.id||Ni++;return this.create({jsx:t(s),id:s,...n}),s},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const st=new dE,fE=(e,t)=>{const n=t?.id||Ni++;return st.addToast({title:e,...t,id:n}),n},hE=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",pE=fE,mE=()=>st.toasts,gE=()=>st.getActiveToasts(),ct=Object.assign(pE,{success:st.success,info:st.info,warning:st.warning,error:st.error,custom:st.custom,message:st.message,promise:st.promise,dismiss:st.dismiss,loading:st.loading},{getHistory:mE,getToasts:gE});tE("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Js(e){return e.label!==void 0}const yE=3,bE="24px",vE="16px",yu=4e3,wE=356,xE=14,SE=45,kE=200;function _t(...e){return e.filter(Boolean).join(" ")}function TE(e){const[t,n]=e.split("-"),s=[];return t&&s.push(t),n&&s.push(n),s}const _E=e=>{var t,n,s,r,o,i,a,c,u;const{invert:d,toast:l,unstyled:f,interacting:p,setHeights:m,visibleToasts:g,heights:y,index:v,toasts:k,expanded:S,removeToast:w,defaultRichColors:T,closeButton:_,style:R,cancelButtonStyle:x,actionButtonStyle:A,className:P="",descriptionClassName:V="",duration:F,position:H,gap:re,expandByDefault:te,classNames:B,icons:ie,closeButtonAriaLabel:oe="Close toast"}=e,[ce,D]=I.useState(null),[de,He]=I.useState(null),[X,J]=I.useState(!1),[G,ne]=I.useState(!1),[xe,Z]=I.useState(!1),[ue,W]=I.useState(!1),[O,le]=I.useState(!1),[Te,Y]=I.useState(0),[Ne,be]=I.useState(0),Ae=I.useRef(l.duration||F||yu),it=I.useRef(null),at=I.useRef(null),Qn=v===0,to=v+1<=g,$e=l.type,Gt=l.dismissible!==!1,Ds=l.className||"",Os=l.descriptionClassName||"",En=I.useMemo(()=>y.findIndex(Q=>Q.toastId===l.id)||0,[y,l.id]),cn=I.useMemo(()=>{var Q;return(Q=l.closeButton)!=null?Q:_},[l.closeButton,_]),kt=I.useMemo(()=>l.duration||F||yu,[l.duration,F]),Xn=I.useRef(0),pt=I.useRef(0),Wt=I.useRef(0),Nt=I.useRef(null),[Ls,Ht]=H.split("-"),Zt=I.useMemo(()=>y.reduce((Q,Pe,Re)=>Re>=En?Q:Q+Pe.height,0),[y,En]),ln=uE(),no=l.invert||d,un=$e==="loading";pt.current=I.useMemo(()=>En*re+Zt,[En,Zt]),I.useEffect(()=>{Ae.current=kt},[kt]),I.useEffect(()=>{J(!0)},[]),I.useEffect(()=>{const Q=at.current;if(Q){const Pe=Q.getBoundingClientRect().height;return be(Pe),m(Re=>[{toastId:l.id,height:Pe,position:l.position},...Re]),()=>m(Re=>Re.filter(Fe=>Fe.toastId!==l.id))}},[m,l.id]),I.useLayoutEffect(()=>{if(!X)return;const Q=at.current,Pe=Q.style.height;Q.style.height="auto";const Re=Q.getBoundingClientRect().height;Q.style.height=Pe,be(Re),m(Fe=>Fe.find(Me=>Me.toastId===l.id)?Fe.map(Me=>Me.toastId===l.id?{...Me,height:Re}:Me):[{toastId:l.id,height:Re,position:l.position},...Fe])},[X,l.title,l.description,m,l.id,l.jsx,l.action,l.cancel]);const Tt=I.useCallback(()=>{ne(!0),Y(pt.current),m(Q=>Q.filter(Pe=>Pe.toastId!==l.id)),setTimeout(()=>{w(l)},kE)},[l,w,m,pt]);I.useEffect(()=>{if(l.promise&&$e==="loading"||l.duration===1/0||l.type==="loading")return;let Q;return S||p||ln?(()=>{if(Wt.current{Ae.current!==1/0&&(Xn.current=new Date().getTime(),Q=setTimeout(()=>{l.onAutoClose==null||l.onAutoClose.call(l,l),Tt()},Ae.current))})(),()=>clearTimeout(Q)},[S,p,l,$e,ln,Tt]),I.useEffect(()=>{l.delete&&(Tt(),l.onDismiss==null||l.onDismiss.call(l,l))},[Tt,l.delete]);function zs(){var Q;if(ie?.loading){var Pe;return I.createElement("div",{className:_t(B?.loader,l==null||(Pe=l.classNames)==null?void 0:Pe.loader,"sonner-loader"),"data-visible":$e==="loading"},ie.loading)}return I.createElement(rE,{className:_t(B?.loader,l==null||(Q=l.classNames)==null?void 0:Q.loader),visible:$e==="loading"})}const so=l.icon||ie?.[$e]||nE($e);var js,Cn;return I.createElement("li",{tabIndex:0,ref:at,className:_t(P,Ds,B?.toast,l==null||(t=l.classNames)==null?void 0:t.toast,B?.default,B?.[$e],l==null||(n=l.classNames)==null?void 0:n[$e]),"data-sonner-toast":"","data-rich-colors":(js=l.richColors)!=null?js:T,"data-styled":!(l.jsx||l.unstyled||f),"data-mounted":X,"data-promise":!!l.promise,"data-swiped":O,"data-removed":G,"data-visible":to,"data-y-position":Ls,"data-x-position":Ht,"data-index":v,"data-front":Qn,"data-swiping":xe,"data-dismissible":Gt,"data-type":$e,"data-invert":no,"data-swipe-out":ue,"data-swipe-direction":de,"data-expanded":!!(S||te&&X),"data-testid":l.testId,style:{"--index":v,"--toasts-before":v,"--z-index":k.length-v,"--offset":`${G?Te:pt.current}px`,"--initial-height":te?"auto":`${Ne}px`,...R,...l.style},onDragEnd:()=>{Z(!1),D(null),Nt.current=null},onPointerDown:Q=>{Q.button!==2&&(un||!Gt||(it.current=new Date,Y(pt.current),Q.target.setPointerCapture(Q.pointerId),Q.target.tagName!=="BUTTON"&&(Z(!0),Nt.current={x:Q.clientX,y:Q.clientY})))},onPointerUp:()=>{var Q,Pe,Re;if(ue||!Gt)return;Nt.current=null;const Fe=Number(((Q=at.current)==null?void 0:Q.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),An=Number(((Pe=at.current)==null?void 0:Pe.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Me=new Date().getTime()-((Re=it.current)==null?void 0:Re.getTime()),tt=ce==="x"?Fe:An,rt=Math.abs(tt)/Me;if(Math.abs(tt)>=SE||rt>.11){Y(pt.current),l.onDismiss==null||l.onDismiss.call(l,l),He(ce==="x"?Fe>0?"right":"left":An>0?"down":"up"),Tt(),W(!0);return}else{var Ue,Ze;(Ue=at.current)==null||Ue.style.setProperty("--swipe-amount-x","0px"),(Ze=at.current)==null||Ze.style.setProperty("--swipe-amount-y","0px")}le(!1),Z(!1),D(null)},onPointerMove:Q=>{var Pe,Re,Fe;if(!Nt.current||!Gt||((Pe=window.getSelection())==null?void 0:Pe.toString().length)>0)return;const Me=Q.clientY-Nt.current.y,tt=Q.clientX-Nt.current.x;var rt;const Ue=(rt=e.swipeDirections)!=null?rt:TE(H);!ce&&(Math.abs(tt)>1||Math.abs(Me)>1)&&D(Math.abs(tt)>Math.abs(Me)?"x":"y");let Ze={x:0,y:0};const dn=$t=>1/(1.5+Math.abs($t)/20);if(ce==="y"){if(Ue.includes("top")||Ue.includes("bottom"))if(Ue.includes("top")&&Me<0||Ue.includes("bottom")&&Me>0)Ze.y=Me;else{const $t=Me*dn(Me);Ze.y=Math.abs($t)0)Ze.x=tt;else{const $t=tt*dn(tt);Ze.x=Math.abs($t)0||Math.abs(Ze.y)>0)&&le(!0),(Re=at.current)==null||Re.style.setProperty("--swipe-amount-x",`${Ze.x}px`),(Fe=at.current)==null||Fe.style.setProperty("--swipe-amount-y",`${Ze.y}px`)}},cn&&!l.jsx&&$e!=="loading"?I.createElement("button",{"aria-label":oe,"data-disabled":un,"data-close-button":!0,onClick:un||!Gt?()=>{}:()=>{Tt(),l.onDismiss==null||l.onDismiss.call(l,l)},className:_t(B?.closeButton,l==null||(s=l.classNames)==null?void 0:s.closeButton)},(Cn=ie?.close)!=null?Cn:lE):null,($e||l.icon||l.promise)&&l.icon!==null&&(ie?.[$e]!==null||l.icon)?I.createElement("div",{"data-icon":"",className:_t(B?.icon,l==null||(r=l.classNames)==null?void 0:r.icon)},l.promise||l.type==="loading"&&!l.icon?l.icon||zs():null,l.type!=="loading"?so:null):null,I.createElement("div",{"data-content":"",className:_t(B?.content,l==null||(o=l.classNames)==null?void 0:o.content)},I.createElement("div",{"data-title":"",className:_t(B?.title,l==null||(i=l.classNames)==null?void 0:i.title)},l.jsx?l.jsx:typeof l.title=="function"?l.title():l.title),l.description?I.createElement("div",{"data-description":"",className:_t(V,Os,B?.description,l==null||(a=l.classNames)==null?void 0:a.description)},typeof l.description=="function"?l.description():l.description):null),I.isValidElement(l.cancel)?l.cancel:l.cancel&&Js(l.cancel)?I.createElement("button",{"data-button":!0,"data-cancel":!0,style:l.cancelButtonStyle||x,onClick:Q=>{Js(l.cancel)&&Gt&&(l.cancel.onClick==null||l.cancel.onClick.call(l.cancel,Q),Tt())},className:_t(B?.cancelButton,l==null||(c=l.classNames)==null?void 0:c.cancelButton)},l.cancel.label):null,I.isValidElement(l.action)?l.action:l.action&&Js(l.action)?I.createElement("button",{"data-button":!0,"data-action":!0,style:l.actionButtonStyle||A,onClick:Q=>{Js(l.action)&&(l.action.onClick==null||l.action.onClick.call(l.action,Q),!Q.defaultPrevented&&Tt())},className:_t(B?.actionButton,l==null||(u=l.classNames)==null?void 0:u.actionButton)},l.action.label):null)};function bu(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function PE(e,t){const n={};return[e,t].forEach((s,r)=>{const o=r===1,i=o?"--mobile-offset":"--offset",a=o?vE:bE;function c(u){["top","right","bottom","left"].forEach(d=>{n[`${i}-${d}`]=typeof u=="number"?`${u}px`:u})}typeof s=="number"||typeof s=="string"?c(s):typeof s=="object"?["top","right","bottom","left"].forEach(u=>{s[u]===void 0?n[`${i}-${u}`]=a:n[`${i}-${u}`]=typeof s[u]=="number"?`${s[u]}px`:s[u]}):c(a)}),n}const $o=I.forwardRef(function(t,n){const{id:s,invert:r,position:o="bottom-right",hotkey:i=["altKey","KeyT"],expand:a,closeButton:c,className:u,offset:d,mobileOffset:l,theme:f="light",richColors:p,duration:m,style:g,visibleToasts:y=yE,toastOptions:v,dir:k=bu(),gap:S=xE,icons:w,containerAriaLabel:T="Notifications"}=t,[_,R]=I.useState([]),x=I.useMemo(()=>s?_.filter(X=>X.toasterId===s):_.filter(X=>!X.toasterId),[_,s]),A=I.useMemo(()=>Array.from(new Set([o].concat(x.filter(X=>X.position).map(X=>X.position)))),[x,o]),[P,V]=I.useState([]),[F,H]=I.useState(!1),[re,te]=I.useState(!1),[B,ie]=I.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),oe=I.useRef(null),ce=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),D=I.useRef(null),de=I.useRef(!1),He=I.useCallback(X=>{R(J=>{var G;return(G=J.find(ne=>ne.id===X.id))!=null&&G.delete||st.dismiss(X.id),J.filter(({id:ne})=>ne!==X.id)})},[]);return I.useEffect(()=>st.subscribe(X=>{if(X.dismiss){requestAnimationFrame(()=>{R(J=>J.map(G=>G.id===X.id?{...G,delete:!0}:G))});return}setTimeout(()=>{Rp.flushSync(()=>{R(J=>{const G=J.findIndex(ne=>ne.id===X.id);return G!==-1?[...J.slice(0,G),{...J[G],...X},...J.slice(G+1)]:[X,...J]})})})}),[_]),I.useEffect(()=>{if(f!=="system"){ie(f);return}if(f==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ie("dark"):ie("light")),typeof window>"u")return;const X=window.matchMedia("(prefers-color-scheme: dark)");try{X.addEventListener("change",({matches:J})=>{ie(J?"dark":"light")})}catch{X.addListener(({matches:G})=>{try{ie(G?"dark":"light")}catch(ne){console.error(ne)}})}},[f]),I.useEffect(()=>{_.length<=1&&H(!1)},[_]),I.useEffect(()=>{const X=J=>{var G;if(i.every(Z=>J[Z]||J.code===Z)){var xe;H(!0),(xe=oe.current)==null||xe.focus()}J.code==="Escape"&&(document.activeElement===oe.current||(G=oe.current)!=null&&G.contains(document.activeElement))&&H(!1)};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[i]),I.useEffect(()=>{if(oe.current)return()=>{D.current&&(D.current.focus({preventScroll:!0}),D.current=null,de.current=!1)}},[oe.current]),I.createElement("section",{ref:n,"aria-label":`${T} ${ce}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},A.map((X,J)=>{var G;const[ne,xe]=X.split("-");return x.length?I.createElement("ol",{key:X,dir:k==="auto"?bu():k,tabIndex:-1,ref:oe,className:u,"data-sonner-toaster":!0,"data-sonner-theme":B,"data-y-position":ne,"data-x-position":xe,style:{"--front-toast-height":`${((G=P[0])==null?void 0:G.height)||0}px`,"--width":`${wE}px`,"--gap":`${S}px`,...g,...PE(d,l)},onBlur:Z=>{de.current&&!Z.currentTarget.contains(Z.relatedTarget)&&(de.current=!1,D.current&&(D.current.focus({preventScroll:!0}),D.current=null))},onFocus:Z=>{Z.target instanceof HTMLElement&&Z.target.dataset.dismissible==="false"||de.current||(de.current=!0,D.current=Z.relatedTarget)},onMouseEnter:()=>H(!0),onMouseMove:()=>H(!0),onMouseLeave:()=>{re||H(!1)},onDragEnd:()=>H(!1),onPointerDown:Z=>{Z.target instanceof HTMLElement&&Z.target.dataset.dismissible==="false"||te(!0)},onPointerUp:()=>te(!1)},x.filter(Z=>!Z.position&&J===0||Z.position===X).map((Z,ue)=>{var W,O;return I.createElement(_E,{key:Z.id,icons:w,index:ue,toast:Z,defaultRichColors:p,duration:(W=v?.duration)!=null?W:m,className:v?.className,descriptionClassName:v?.descriptionClassName,invert:r,visibleToasts:y,closeButton:(O=v?.closeButton)!=null?O:c,interacting:re,position:X,style:v?.style,unstyled:v?.unstyled,classNames:v?.classNames,cancelButtonStyle:v?.cancelButtonStyle,actionButtonStyle:v?.actionButtonStyle,closeButtonAriaLabel:v?.closeButtonAriaLabel,removeToast:He,toasts:x.filter(le=>le.position==Z.position),heights:P.filter(le=>le.position==Z.position),setHeights:V,expandByDefault:a,gap:S,expanded:F,swipeDirections:t.swipeDirections})})):null}))});function EE(e){const t=e.headers.get("retry-after")||e.headers.get("Retry-After");if(t){const n=parseInt(t,10);if(!isNaN(n)&&n>0)return n}return e.clone().json().then(n=>{if(n?.retry_after){const s=parseInt(n.retry_after,10);if(!isNaN(s)&&s>0)return s}}).catch(()=>{}),60}async function CE(e,t){const n=ye.currentUser;if(n)try{const s=U(L,"_analytics/rateLimitHits",n.uid);await Ce(s,{uid:n.uid,endpoint:e,retryAfter:t,timestamp:ae()},{merge:!0})}catch(s){console.warn("Failed to log rate limit hit:",s)}}const Fo=new Map;function AE(e,t){const n=`${e}-${Date.now()}`,s=Date.now()+t*1e3;ct.error(`You're going too fast! Please wait ${t} seconds before trying again.`,{duration:t*1e3,id:n});const r=Fo.get(e);r&&clearInterval(r.timerId);const o=window.setInterval(()=>{Math.ceil((s-Date.now())/1e3)<=0&&(clearInterval(o),Fo.delete(e),ct.dismiss(n))},1e3);Fo.set(e,{endpoint:e,endsAt:s,timerId:o})}async function RE(e,t){if(e.status!==429)return!1;const n=EE(e);return await CE(t,n),AE(t,n),window.dispatchEvent(new CustomEvent("rate-limit-hit",{detail:{endpoint:t,retryAfter:n,expiresAt:Date.now()+n*1e3}})),!0}const Ss="https://deign86-mathpulse-api-v3test.hf.space",Jr=(e,t)=>t,qh=(e,t)=>t,Vo=Jr(void 0,!0),vu=Jr(void 0,!0),wu=Jr(void 0,!0),xu=Jr(void 0,!0),Su=qh(void 0,9e4),Bo=qh(void 0,9e5);let Uo=!0,ku=0;const ME=6e4;async function IE(){const e="https://deign86-mathpulse-api-v3test.hf.space",t={"Content-Type":"application/json"},n=ye.currentUser;if(n)try{const r=await n.getIdToken(!1);r&&(t.Authorization=`Bearer ${r}`)}catch{}const s=await fetch(`${e}/api/rag/health`,{headers:t});if(!s.ok){const r=await s.text();throw new Error(`GET /api/rag/health failed: ${s.status} ${r}`)}return s.json()}async function DE(e){const t="https://deign86-mathpulse-api-v3test.hf.space",n={"Content-Type":"application/json"},s=ye.currentUser;if(s)try{const o=await s.getIdToken(!1);o&&(n.Authorization=`Bearer ${o}`)}catch{}const r=await fetch(`${t}/api/rag/lesson`,{method:"POST",headers:n,body:JSON.stringify(e)});if(!r.ok){const o=await r.text();throw new Error(`POST /api/rag/lesson failed: ${r.status} ${o}`)}return r.json()}async function OE(e){const t="https://deign86-mathpulse-api-v3test.hf.space",n={"Content-Type":"application/json"},s=ye.currentUser;if(s)try{const o=await s.getIdToken(!1);o&&(n.Authorization=`Bearer ${o}`)}catch{}const r=await fetch(`${t}/api/rag/generate-problem`,{method:"POST",headers:n,body:JSON.stringify(e)});if(!r.ok){const o=await r.text();throw new Error(`POST /api/rag/generate-problem failed: ${r.status} ${o}`)}return r.json()}async function LE(e){const t="https://deign86-mathpulse-api-v3test.hf.space",n={"Content-Type":"application/json"},s=ye.currentUser;if(s)try{const o=await s.getIdToken(!1);o&&(n.Authorization=`Bearer ${o}`)}catch{}const r=await fetch(`${t}/api/rag/analysis-context`,{method:"POST",headers:n,body:JSON.stringify(e)});if(!r.ok){const o=await r.text();throw new Error(`POST /api/rag/analysis-context failed: ${r.status} ${o}`)}return r.json()}const Et={maxRetries:Bh,timeoutMs:Yr,baseBackoffMs:1e3},Yt={...Et,timeoutMs:6e4},zE={...Yt,maxRetries:1,timeoutMs:45e3,baseBackoffMs:750},jE={...Et,maxRetries:1,timeoutMs:2e4,baseBackoffMs:500},rs={maxRetries:2,timeoutMs:12e4,baseBackoffMs:2e3},NE={maxRetries:0,timeoutMs:8e3,baseBackoffMs:500};let er=null;async function $E(){return er||(er=(async()=>{try{At("/health","GET","Warming up HuggingFace Space...");const e=new AbortController,t=setTimeout(()=>e.abort(),15e3),n=await fetch(`${Ss}/health`,{method:"GET",signal:e.signal});return clearTimeout(t),n.ok?(At("/health","GET","Backend warm and ready"),!0):(console.warn("[apiService] Backend health check returned",n.status),!1)}catch(e){return console.warn("[apiService] Backend warmup failed (cold start expected):",e),!1}})(),er)}async function j(e,t,n=Et){const s=`${Ss}${e}`,r=t?.method??"GET";At(e,r,"Starting request");const o=async a=>{const c=new Headers(t?.headers??{});!(t?.body instanceof FormData)&&!c.has("Content-Type")&&c.set("Content-Type","application/json");const u=ye.currentUser;if(u)try{const d=await u.getIdToken(a);d&&c.set("Authorization",`Bearer ${d}`)}catch(d){Be(e,r,"Failed to acquire Firebase ID token",d)}return{...t,headers:c}};let i=await o(!1);try{const a=await gu(s,i,n);return At(e,r,"Request succeeded"),a}catch(a){if(a instanceof It&&a.status===401&&ye.currentUser)try{At(e,r,"401 received, refreshing Firebase token and retrying once"),i=await o(!0);const c=await gu(s,i,n);return At(e,r,"Request succeeded after token refresh"),c}catch(c){throw c instanceof It?Be(e,r,`HTTP ${c.status}: ${c.responseBody.slice(0,300)}`):c instanceof xn?Be(e,r,`Timeout after ${c.timeoutMs}ms`):c instanceof jr?Be(e,r,`Network error: ${c.originalError.message}`):Be(e,r,`Unexpected: ${c instanceof Error?c.message:String(c)}`),c}throw a instanceof It?(Be(e,r,`HTTP ${a.status}: ${a.responseBody.slice(0,300)}`),a.status===429&&await RE(new Response(a.responseBody,{status:429,headers:{"retry-after":"60"}}),e)):a instanceof xn?Be(e,r,`Timeout after ${a.timeoutMs}ms`):a instanceof jr?Be(e,r,`Network error: ${a.originalError.message}`):Be(e,r,`Unexpected: ${a instanceof Error?a.message:String(a)}`),a}}async function Tu(e,t,n=Yr){const s=`${Ss}${e}`,r=t?.method??"GET";At(e,r,"Starting blob request");const o=async i=>{const a=new Headers(t?.headers??{}),c=ye.currentUser;if(c)try{const l=await c.getIdToken(i);l&&a.set("Authorization",`Bearer ${l}`)}catch(l){Be(e,r,"Failed to acquire Firebase ID token",l)}const u=new AbortController,d=setTimeout(()=>u.abort(),n);try{const l=await fetch(s,{...t,headers:a,signal:u.signal});if(!l.ok){const f=await l.text();throw new It({status:l.status,statusText:l.statusText||"Request Failed",endpoint:e,responseBody:f,retryable:l.status>=500||l.status===429})}return await l.blob()}finally{clearTimeout(d)}};try{return await o(!1)}catch(i){if(i instanceof It&&i.status===401&&ye.currentUser)return At(e,r,"401 received for blob request, refreshing Firebase token and retrying once"),o(!0);throw i}}const FE={response:"Sorry, the AI tutor is temporarily unavailable. Please try again in a moment."},VE={riskLevel:"Medium",confidence:0,analysis:{labels:[],scores:[]},risk_level:"medium",risk_score:0,top_factors:["Fallback risk response due to temporary service unavailability"]},BE={learningPath:"Unable to generate a learning path right now. Please try again later."},UE={insight:"Daily insight is temporarily unavailable. Please refresh later."},qE={expression:"",result:"Error: calculation service unavailable",steps:[],simplified:null,latex:null};function GE(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.riskLevel=="string"&&typeof t.confidence=="number"}function _u(e){if(typeof e!="object"||e===null)return!1;const t=e;return Array.isArray(t.questions)&&typeof t.totalPoints=="number"}const WE=e=>new Promise(t=>setTimeout(t,e));function HE(e){if(!e)return"Generation task failed without a detailed error.";if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){const t=e;if(typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return"Generation task failed due to an unknown error."}}return String(e)}const bt={getImportGroundedRolloutFlags(){return{quizEnabled:Vo,lessonEnabled:vu,feedbackEnabled:wu}},async reportImportGroundedFeedback(e){return wu?j("/api/feedback/import-grounded",{method:"POST",body:JSON.stringify(e)}):{success:!0,stored:!1,warnings:["Import-grounded feedback events are disabled by frontend rollout flag."]}},async health(){return j("/health",void 0,{...Et,timeoutMs:1e4})},async chat(e,t,n,s){Se("/api/chat",{message:e});const r={message:e,history:t??[],...s?.sessionId?{sessionId:s.sessionId}:{},...s?.expectedEndMarker?{expectedEndMarker:s.expectedEndMarker}:{},...s?.completionMode?{completionMode:s.completionMode}:{},...typeof s?.continuationMaxRounds=="number"?{continuationMaxRounds:Math.max(0,Math.floor(s.continuationMaxRounds))}:{},...s?.moduleContext?{moduleContext:s.moduleContext}:{}};if(n){const i=new AbortController;let a=null,c=null,u=null;const d=y=>{a||(a=y,i.abort())},l=()=>{c&&(clearTimeout(c),c=null),u&&(clearTimeout(u),u=null)},f=()=>{c&&clearTimeout(c),c=setTimeout(()=>d("idle"),Su)};u=setTimeout(()=>d("total"),Bo);const p=new Headers({"Content-Type":"application/json"}),m=ye.currentUser;if(m)try{const y=await m.getIdToken(!1);y&&p.set("Authorization",`Bearer ${y}`)}catch(y){Be("/api/chat/stream","POST","Failed to acquire Firebase ID token",y)}let g=null;try{f();const y=await fetch(`${Ss}/api/chat/stream`,{method:"POST",headers:p,body:JSON.stringify(r),signal:i.signal});if(!y.ok||!y.body){const _=await y.text().catch(()=>"Unable to read response body");throw new Error(`Streaming request failed (${y.status}): ${_.slice(0,300)}`)}g=y.body.getReader();const v=new TextDecoder;let k="",S="",w=!1;const T=_=>{const R=_.indexOf(` `),x=_.indexOf(`\r \r `);return R===-1&&x===-1?null:R===-1?{index:x,length:4}:x===-1?{index:R,length:2}:Rbt.chat(e,t,void 0,n),FE,"chat")},async predictRisk(e){Se("/api/predict-risk",{engagementScore:e.engagementScore,avgQuizScore:e.avgQuizScore,attendance:e.attendance,assignmentCompletion:e.assignmentCompletion}),De("/api/predict-risk","engagementScore",e.engagementScore,0,100),De("/api/predict-risk","avgQuizScore",e.avgQuizScore,0,100),De("/api/predict-risk","attendance",e.attendance,0,100),De("/api/predict-risk","assignmentCompletion",e.assignmentCompletion,0,100);const t=await j("/api/predict-risk",{method:"POST",body:JSON.stringify(e)});if(!GE(t))throw Be("/api/predict-risk","POST","Invalid response shape",t),new Error("Invalid risk prediction response from server");return t},async predictRiskSafe(e){return ss(()=>bt.predictRisk(e),VE,"predictRisk")},async predictRiskBatch(e){if(!Array.isArray(e)||e.length===0)throw new Ve("/api/predict-risk/batch","students array must not be empty");return j("/api/predict-risk/batch",{method:"POST",body:JSON.stringify({students:e})})},async getLearningPath(e){if(Se("/api/learning-path",{weaknesses:e.weaknesses,gradeLevel:e.gradeLevel}),!Array.isArray(e.weaknesses)||e.weaknesses.length===0)throw new Ve("/api/learning-path","weaknesses must be a non-empty array");return j("/api/learning-path",{method:"POST",body:JSON.stringify(e)},Yt)},async getLearningPathSafe(e){return ss(()=>bt.getLearningPath(e),BE,"getLearningPath")},async getDailyInsight(e,t){if(!Array.isArray(e.students)||e.students.length===0)throw new Ve("/api/analytics/daily-insight","students array must not be empty");return j("/api/analytics/daily-insight",{method:"POST",body:JSON.stringify(e),signal:t?.signal},Yt)},async getDailyInsightSafe(e){return ss(()=>bt.getDailyInsight(e),UE,"getDailyInsight")},async getImportedClassOverview(e){if(!e?.forceRefresh&&!Uo&&Date.now()!r||r.size===0))throw new Ve("/api/upload/class-records","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new Ve("/api/upload/class-records","One or more files exceed the 10 MB size limit");const s=new FormData;return n.forEach(r=>s.append("files",r)),t?.classSectionId&&s.append("classSectionId",t.classSectionId),t?.className&&s.append("className",t.className),s.append("datasetIntent",t?.datasetIntent??"synthetic_student_records"),j("/api/upload/class-records",{method:"POST",body:s},rs)},async downloadClassRecordTemplate(e){const t=new URLSearchParams;e?.quarter&&t.set("quarter",e.quarter),e?.school_year&&t.set("school_year",e.school_year),e?.subject&&t.set("subject",e.subject);const n=t.toString();return Tu(`/api/templates/class-records${n?`?${n}`:""}`,{method:"GET"},3e4)},async uploadClassRecordTemplate(e,t){if(!e||e.size===0)throw new Ve("/api/class-records/upload","File must be non-empty");if(e.size>10*1024*1024)throw new Ve("/api/class-records/upload","File exceeds the 10 MB size limit");const n=new FormData;return n.append("file",e),t?.subject&&n.append("subject",t.subject),t?.quarter&&n.append("quarter",t.quarter),t?.gradeLevel&&n.append("gradeLevel",t.gradeLevel),j("/api/class-records/upload",{method:"POST",body:n},rs)},async previewStudentAccountImport(e,t){if(!e||e.size===0)throw new Ve("/api/import/student-accounts/preview","A non-empty file is required");if(e.size>10*1024*1024)throw new Ve("/api/import/student-accounts/preview","File exceeds 10 MB size limit");const n=new FormData;return n.append("file",e),t?.classSectionId&&n.append("classSectionId",t.classSectionId),t?.className&&n.append("className",t.className),t?.defaultGrade&&n.append("defaultGrade",t.defaultGrade),t?.defaultSection&&n.append("defaultSection",t.defaultSection),j("/api/import/student-accounts/preview",{method:"POST",body:n},rs)},async commitStudentAccountImport(e){return Se("/api/import/student-accounts/commit",{previewToken:e.previewToken}),j("/api/import/student-accounts/commit",{method:"POST",body:JSON.stringify(e)},Et)},async createStudentAccount(e){Se("/api/teacher/create-student-account",{name:e.name,email:e.email,temporaryPassword:e.temporaryPassword,adviserTeacherId:e.adviserTeacherId});const t={name:e.name,email:e.email,temporary_password:e.temporaryPassword,lrn:e.lrn??null,grade:e.grade??null,section:e.section??null,class_section_id:e.classSectionId??null,adviser_teacher_id:e.adviserTeacherId,adviser_teacher_name:e.adviserTeacherName??null,school_year:e.schoolYear??null};return j("/api/teacher/create-student-account",{method:"POST",body:JSON.stringify(t)},Et)},async getAdminUsers(e){const t=e?.page??1,n=e?.pageSize??25;De("/api/admin/users","page",t,1,1e4),De("/api/admin/users","pageSize",n,1,200);const s=new URLSearchParams;return s.set("page",String(t)),s.set("pageSize",String(n)),e?.search?.trim()&&s.set("search",e.search.trim()),e?.role?.trim()&&s.set("role",e.role.trim()),e?.status?.trim()&&s.set("status",e.status.trim()),e?.grade?.trim()&&s.set("grade",e.grade.trim()),e?.section?.trim()&&s.set("section",e.section.trim()),e?.classSectionId?.trim()&&s.set("classSectionId",e.classSectionId.trim()),j(`/api/admin/users?${s.toString()}`,{method:"GET"},jE)},async updateAdminUser(e,t){const n=e.trim();Se("/api/admin/users",{uid:n});const s=new URLSearchParams;return s.set("uid",n),j(`/api/admin/users?${s.toString()}`,{method:"PATCH",body:JSON.stringify(t)},Et)},async bulkAdminUsers(e){return Se("/api/admin/users/bulk-action",{action:e.action}),j("/api/admin/users/bulk-action",{method:"POST",body:JSON.stringify(e)},Et)},async createAdminUser(e){if(Se("/api/admin/users",{name:e.name,email:e.email,password:e.password,confirmPassword:e.confirmPassword,role:e.role,status:e.status,grade:e.grade,section:e.section}),e.role.trim().toLowerCase()==="student"&&!e.lrn?.trim())throw new Ve("/api/admin/users","lrn is required for student accounts");return j("/api/admin/users",{method:"POST",body:JSON.stringify(e)},Et)},async deleteAdminUser(e){const t=e.trim();Se("/api/admin/users",{uid:t});const n=new URLSearchParams;return n.set("uid",t),j(`/api/admin/users?${n.toString()}`,{method:"DELETE"},Et)},async getRiskRefreshMonitor(e){const t=e?.limit??10;De("/api/upload/class-records/risk-refresh/recent","limit",t,1,50);const n=new URLSearchParams;return n.set("limit",String(t)),e?.classSectionId&&n.set("classSectionId",e.classSectionId),j(`/api/upload/class-records/risk-refresh/recent?${n.toString()}`)},async getImportGroundedTelemetrySummary(e){const t=e?.days??7,n=e?.limit??5e3;De("/api/feedback/import-grounded/summary","days",t,1,30),De("/api/feedback/import-grounded/summary","limit",n,100,2e4);const s=new URLSearchParams;return s.set("days",String(t)),s.set("limit",String(n)),e?.classSectionId&&s.set("classSectionId",e.classSectionId),j(`/api/feedback/import-grounded/summary?${s.toString()}`)},async getImportGroundedAccessAudit(e){const t=e?.days??7,n=e?.limit??200;De("/api/import-grounded/access-audit","days",t,1,30),De("/api/import-grounded/access-audit","limit",n,1,1e3);const s=new URLSearchParams;return s.set("days",String(t)),s.set("limit",String(n)),s.set("export","json"),e?.classSectionId&&s.set("classSectionId",e.classSectionId),j(`/api/import-grounded/access-audit?${s.toString()}`)},async exportImportGroundedAccessAuditCsv(e){const t=e?.days??7,n=e?.limit??200;De("/api/import-grounded/access-audit","days",t,1,30),De("/api/import-grounded/access-audit","limit",n,1,1e3);const s=new URLSearchParams;return s.set("days",String(t)),s.set("limit",String(n)),s.set("export","csv"),e?.classSectionId&&s.set("classSectionId",e.classSectionId),Tu(`/api/import-grounded/access-audit?${s.toString()}`,{method:"GET"},3e4)},async uploadCourseMaterials(e,t){const n=Array.isArray(e)?e:[e];if(n.length===0)throw new Ve("/api/upload/course-materials","At least one file is required");if(n.some(r=>!r||r.size===0))throw new Ve("/api/upload/course-materials","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new Ve("/api/upload/course-materials","One or more files exceed the 10 MB size limit");const s=new FormData;return n.forEach(r=>s.append("files",r)),t?.classSectionId&&s.append("classSectionId",t.classSectionId),t?.className&&s.append("className",t.className),j("/api/upload/course-materials",{method:"POST",body:s},rs)},async uploadTeacherMaterial(e,t){const n=new FormData;return n.append("file",e),t?.teacherId&&n.append("teacherId",t.teacherId),t?.classId&&n.append("classId",t.classId),t?.gradeLevel&&n.append("gradeLevel",t.gradeLevel),t?.subject&&n.append("subject",t.subject),t?.quarter&&n.append("quarter",t.quarter),t?.strandOrTrack&&n.append("strandOrTrack",t.strandOrTrack),j("/api/teacher-materials/upload",{method:"POST",body:n},rs)},async getRecentCourseMaterials(e){const t=e?.limit??10;De("/api/upload/course-materials/recent","limit",t,1,50);const n=new URLSearchParams;return n.set("limit",String(t)),e?.classSectionId&&n.set("classSectionId",e.classSectionId),j(`/api/upload/course-materials/recent?${n.toString()}`)},async getCourseMaterialTopics(e){const t=e?.limit??20;De("/api/course-materials/topics","limit",t,1,50);const n=new URLSearchParams;return n.set("limit",String(t)),e?.classSectionId&&n.set("classSectionId",e.classSectionId),e?.materialId&&n.set("materialId",e.materialId),j(`/api/course-materials/topics?${n.toString()}`)},async generateLessonPlan(e){Se("/api/lesson/generate",{gradeLevel:e.gradeLevel});const t={...e,preferImportedTopics:vu&&(e.preferImportedTopics??!0)};if(xu){const n=await bt.submitLessonPlanAsync(t),r=(await bt.waitForTaskResult(n.taskId,{timeoutMs:24e4,pollIntervalMs:1500})).result;if(!r||typeof r!="object")throw new Error("Lesson generation completed without a valid result payload.");return r}return j("/api/lesson/generate",{method:"POST",body:JSON.stringify(t)},Yt)},async generateQuiz(e,t){if(Se("/api/quiz/generate",{topics:e.topics,gradeLevel:e.gradeLevel}),!Array.isArray(e.topics)||e.topics.length===0)throw new Ve("/api/quiz/generate","topics must be a non-empty array");const n={...e,preferImportedTopics:Vo&&(e.preferImportedTopics??!0)};if(xu){const r=await bt.submitQuizAsync(n);t?.onTaskCreated?.(r.taskId);const i=(await bt.waitForTaskResult(r.taskId,{timeoutMs:24e4,pollIntervalMs:1500,onProgress:t?.onProgress})).result;if(!i||typeof i!="object")throw new Error("Quiz generation completed without a valid result payload.");if(!_u(i))throw new Error("Invalid quiz generation response from async task payload.");return i}const s=await j("/api/quiz/generate",{method:"POST",body:JSON.stringify(n)},Yt);if(!_u(s))throw Be("/api/quiz/generate","POST","Invalid response shape",s),new Error("Invalid quiz generation response from server");return s},async previewQuiz(e){Se("/api/quiz/preview",{topics:e.topics,gradeLevel:e.gradeLevel});const t={...e,preferImportedTopics:Vo&&(e.preferImportedTopics??!0)};return j("/api/quiz/preview",{method:"POST",body:JSON.stringify(t)},Yt)},async submitLessonPlanAsync(e){return j("/api/lesson/generate-async",{method:"POST",body:JSON.stringify(e)},Yt)},async submitQuizAsync(e){return j("/api/quiz/generate-async",{method:"POST",body:JSON.stringify(e)},Yt)},async getTaskStatus(e){return Se("/api/tasks/{taskId}",{taskId:e}),j(`/api/tasks/${encodeURIComponent(e)}`)},async listTasks(e){const t=new URLSearchParams;e?.limit!=null&&(De("/api/tasks","limit",e.limit,1,200),t.set("limit",String(e.limit))),e?.status&&t.set("status",e.status),e?.includeResults!=null&&t.set("include_results",String(e.includeResults));const n=t.toString();return j(`/api/tasks${n?`?${n}`:""}`)},async cancelTask(e){return Se("/api/tasks/{taskId}/cancel",{taskId:e}),j(`/api/tasks/${encodeURIComponent(e)}/cancel`,{method:"POST"})},async waitForTaskResult(e,t){const n=t?.timeoutMs??18e4,s=t?.pollIntervalMs??1500,r=Date.now();for(;Date.now()-r<=n;){const o=await bt.getTaskStatus(e);if(t?.onProgress?.(o),o.status==="completed")return o;if(o.status==="failed"||o.status==="cancelled")throw new Error(HE(o.error));await WE(s)}throw new Error(`Async generation task timed out after ${Math.round(n/1e3)} seconds.`)},async getQuizTopics(e){const t=e?`?gradeLevel=${encodeURIComponent(e)}`:"";return j(`/api/quiz/topics${t}`)},async getStudentCompetency(e,t){return Se("/api/quiz/student-competency",{studentId:e}),j("/api/quiz/student-competency",{method:"POST",body:JSON.stringify({studentId:e,quizHistory:t})})},async evaluateExpression(e){return Se("/api/calculator/evaluate",{expression:e}),j("/api/calculator/evaluate",{method:"POST",body:JSON.stringify({expression:e})})},async evaluateExpressionSafe(e){return ss(()=>bt.evaluateExpression(e),{...qE,expression:e},"evaluateExpression")},async automationDiagnosticCompleted(e){return Se("/api/automation/diagnostic-completed",{lrn:e.lrn,results:e.results}),j("/api/automation/diagnostic-completed",{method:"POST",body:JSON.stringify(e)})},async automationQuizSubmitted(e){return Se("/api/automation/quiz-submitted",{lrn:e.lrn,quizId:e.quizId,subject:e.subject}),j("/api/automation/quiz-submitted",{method:"POST",body:JSON.stringify(e)})},async automationStudentEnrolled(e){return Se("/api/automation/student-enrolled",{lrn:e.lrn,name:e.name,email:e.email}),j("/api/automation/student-enrolled",{method:"POST",body:JSON.stringify(e)})},async automationDataImported(e){return Se("/api/automation/data-imported",{teacherId:e.teacherId,students:e.students}),j("/api/automation/data-imported",{method:"POST",body:JSON.stringify(e)})},async automationContentUpdated(e){return Se("/api/automation/content-updated",{adminId:e.adminId,action:e.action,contentType:e.contentType,contentId:e.contentId}),j("/api/automation/content-updated",{method:"POST",body:JSON.stringify(e)})},getInferenceMetrics:async()=>j("/api/ops/inference-metrics",{method:"GET"}),getModelConfig:async()=>j("/api/admin/model-config",{method:"GET"}),setModelProfile:async e=>j("/api/admin/model-config/profile",{method:"POST",body:JSON.stringify({profile:e})}),setModelOverride:async(e,t)=>j("/api/admin/model-config/override",{method:"POST",body:JSON.stringify({key:e,value:t})}),resetModelConfig:async()=>j("/api/admin/model-config/reset",{method:"DELETE"}),uploadModulePdf:async e=>{const t=ye.currentUser,n=t?await t.getIdToken():void 0,s=await fetch(`${Ss}/api/admin/upload-pdf`,{method:"POST",headers:n?{Authorization:`Bearer ${n}`}:{},body:e});if(!s.ok){const r=await s.json().catch(()=>({detail:"Upload failed"}));throw new Error(r.detail||`Upload failed (${s.status})`)}return s.json()},reingestModulePdf:async(e,t)=>{const n=ye.currentUser?await ye.currentUser.getIdToken():void 0;return j("/api/admin/reingest-pdf",{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({subjectId:e,storagePath:t})})},getRagHealth:async()=>j("/api/rag/health",{method:"GET"}),adminDeleteFile:async(e,t)=>j("/api/admin/delete-file",{method:"POST",body:JSON.stringify({fileId:e,collection:t})}),async generateInterventionPlan(e){return j("/api/class-records/intervention-plan",{method:"POST",body:JSON.stringify(e)})},async fetchClassRecords(e){const t=new URLSearchParams;e?.limit&&t.set("limit",String(e.limit)),e?.after&&t.set("after",e.after);const n=t.toString();return j(`/api/class-records${n?`?${n}`:""}`,{method:"GET"})},async fetchQuizBattleResults(e){const t=new URLSearchParams;e?.classId&&t.set("classId",e.classId),e?.limit&&t.set("limit",String(e.limit)),e?.after&&t.set("after",e.after);const n=t.toString();return j(`/api/quiz-battle/results${n?`?${n}`:""}`,{method:"GET"})},async fetchUploadStudents(e,t){const n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.after&&n.set("after",t.after);const s=n.toString();return j(`/api/class-records/${e}/students${s?`?${s}`:""}`,{method:"GET"})},async generateClassReport(e){return j(`/api/class-records/${e}/ai-report`,{method:"POST"})},async generateQuizFromModule(e){return j(`/api/teacher-materials/${e}/generate-quiz`,{method:"POST"})},async getStudentRecommendations(e){return j(`/api/student/${e}/recommendations`,{method:"GET"})}};async function ZE(e,t,n,s){Se("/api/rag/lesson",{topic:e,subject:t,quarter:n}),De("/api/rag/lesson","quarter",n,1,4);const r=await j("/api/rag/lesson",{method:"POST",body:JSON.stringify({topic:e,subject:t,quarter:n,lessonTitle:s?.lessonTitle,learningCompetency:s?.learningCompetency,moduleUnit:s?.moduleUnit,learnerLevel:s?.learnerLevel})}),o=(r.sources||[]).map(i=>({...i,sourceFile:i.source_file||i.sourceFile,content:i.content||i.content,contentDomain:i.content_domain||i.contentDomain,chunkType:i.chunk_type||i.chunkType}));return{explanation:r.explanation,sources:o,retrievalConfidence:r.retrievalConfidence,retrievalBand:r.retrievalBand,retrievalQuery:r.retrievalQuery,needsReview:r.needsReview}}async function KE(e,t,n,s){Se("/api/rag/generate-problem",{topic:e,subject:t,quarter:n,difficulty:s}),De("/api/rag/generate-problem","quarter",n,1,4);const r=await j("/api/rag/generate-problem",{method:"POST",body:JSON.stringify({topic:e,subject:t,quarter:n,difficulty:s})}),o=(r.sources||[]).map(i=>({...i,sourceFile:i.source_file||i.sourceFile}));return{problem:r.problem,solution:r.solution,competencyReference:r.competencyReference,sources:o}}async function QE(e,t){return!Array.isArray(e)||e.length===0?"":(await j("/api/rag/analysis-context",{method:"POST",body:JSON.stringify({weakTopics:e,subject:t})})).curriculumContext||""}async function XE(e){const t=e?`?grade_level=${encodeURIComponent(e)}`:"";return j(`/api/curriculum/subjects${t}`)}async function YE(e){try{return await j(`/api/curriculum/subjects/${e}`)}catch{return null}}async function JE(e){try{return await j(`/api/curriculum/subjects/${e}/topics`)}catch{return[]}}async function eC(e,t){try{return await j(`/api/curriculum/subjects/${e}/topics/${t}`)}catch{return null}}const tC=Object.freeze(Object.defineProperty({__proto__:null,ApiError:It,ApiNetworkError:jr,ApiTimeoutError:xn,ApiValidationError:Ve,apiFetch:j,apiService:bt,fetchAnalysisCurriculumContext:QE,generateGroundedProblem:KE,generateRagLesson:DE,generateRagProblem:OE,getCurriculumGroundedLesson:ZE,getCurriculumSubject:YE,getCurriculumSubjects:XE,getCurriculumTopic:eC,getCurriculumTopics:JE,getRagAnalysisContext:LE,getRagHealth:IE,warmupBackend:$E},Symbol.toStringTag,{value:"Module"})),Gh="competencyProfiles",GR=async e=>{const t=U(L,Gh,e),n=await me(t);return n.exists()?n.data():null},nC=async(e,t)=>{const{strengths:n,weaknesses:s,borderline:r}=t.proficiencyProfile,o=n.length>0?n[0]:null,i=s.length>0?s[0]:null,a=t.proficiencyProfile.suggestedStartingModule,c={uid:e,lastAssessmentDate:ae(),lastAssessmentType:t.assessmentType,overallScore:t.rawScore,competencies:Object.fromEntries(Object.entries(t.competencyScores).map(([u,d])=>[u,{score:d.score,correct:d.correct,attempted:d.attempted,lastAttemptedAt:ae()}])),primaryWeakness:i,primaryStrength:o,suggestedModule:a,updatedAt:ae()};await Ce(U(L,Gh,e),c,{merge:!0})},eo=async e=>{const t={userId:e,subjects:{},lessons:{},quizAttempts:[],totalLessonsCompleted:0,totalQuizzesCompleted:0,averageScore:0,updatedAt:new Date};return await Ce(U(L,"progress",e),t),t},sC=async e=>{try{const t=U(L,"progress",e),n=await me(t);if(n.exists()){const s=n.data();return{...s,updatedAt:s.updatedAt?.toDate()||new Date}}return await eo(e)}catch(t){return console.error("Error getting user progress:",t),null}},WR=(e,t)=>{const n=U(L,"progress",e);return en(n,s=>{if(!s.exists()){t(null);return}const r=s.data();t({...r,updatedAt:r.updatedAt?.toDate?.()||new Date})},s=>{console.error("Error subscribing to user progress:",s),t(null)})},HR=async(e,t,n)=>{const s=Math.max(0,Math.min(100,n)),r=U(L,"progress",e);await Ce(r,{[`lessons.${t}.lessonId`]:t,[`lessons.${t}.progressPercent`]:s,updatedAt:ae()},{merge:!0})},ZR=async(e,t,n,s,r)=>{const o=U(L,"progress",e),i=await me(o);if(!i.exists())return 0;const c=i.data().subjects?.[t]?.modulesProgress?.[n];if(!c)return 0;const u=Math.max(1,s+r),d=c.lessonsCompleted?.length||0,l=c.quizzesCompleted?.length||0,f=Math.round((d+l)/u*100);return await Ce(o,{[`subjects.${t}.modulesProgress.${n}.progress`]:f,[`subjects.${t}.modulesProgress.${n}.lastAccessedAt`]:ae(),updatedAt:ae()},{merge:!0}),f},KR=async(e,t,n,s,r,o=50,i,a)=>{try{const c=U(L,"progress",e);let u=await me(c);u.exists()||(await eo(e),u=await me(c));const d=u.data(),l={lessonId:s,completed:!0,completedAt:new Date,timeSpent:r,...i!==void 0&&{quizCompleted:i},...a!==void 0&&{quizScore:a}};d.subjects||(d.subjects={}),d.subjects[t]||(d.subjects[t]={subjectId:t,progress:0,completedModules:0,totalModules:0,modulesProgress:{}});const f=d.subjects[t];f.modulesProgress[n]||(f.modulesProgress[n]={moduleId:n,subjectId:t,progress:0,lessonsCompleted:[],quizzesCompleted:[],startedAt:new Date,lastAccessedAt:new Date});const p=f.modulesProgress[n],m=!p.lessonsCompleted.includes(s);m&&(p.lessonsCompleted.push(s),p.lastAccessedAt=new Date),await Ce(c,{[`lessons.${s}`]:l,[`subjects.${t}.modulesProgress.${n}`]:p,...m&&{totalLessonsCompleted:fs(1)},updatedAt:ae()},{merge:!0}),await Wh(e,o,"lesson_complete",`Completed lesson: ${s}`),await Va(e);try{const{emitPipelineEvent:g,getStudentContext:y}=await ee(async()=>{const{emitPipelineEvent:k,getStudentContext:S}=await import("./pipelineService-BVFD1ZML.js");return{emitPipelineEvent:k,getStudentContext:S}},__vite__mapDeps([11,3,1,2,4,5,6,7,8,9,10])),v=y();v&&g({student_id:e,event_type:"lesson",event_data:{lesson_id:s,is_completed:!0,time_spent_seconds:r},occurred_at:new Date().toISOString(),class_id:v.classId,teacher_id:v.teacherId})}catch{}}catch(c){throw console.error("Error completing lesson:",c),c}},QR=async(e,t,n,s,r,o)=>{try{const i=U(L,"progress",e);let a=await me(i);a.exists()||(await eo(e),a=await me(i));const c=a.data(),u={quizId:t,attemptNumber:(c.quizAttempts?.filter(l=>l.quizId===t).length||0)+1,score:s,completedAt:new Date,timeSpent:o,answers:r},d=!c.quizAttempts?.some(l=>l.quizId===t);await dt(i,{quizAttempts:[...c.quizAttempts||[],u],...d&&{totalQuizzesCompleted:fs(1)},updatedAt:ae()}),await Va(e)}catch(i){throw console.error("Error recording practice quiz:",i),i}},XR=async(e,t,n,s,r,o,i,a)=>{try{const c=U(L,"progress",e);let u=await me(c);u.exists()||(await eo(e),u=await me(c));const d=u.data(),l={quizId:s,attemptNumber:(d.quizAttempts?.filter(y=>y.quizId===s).length||0)+1,score:r,completedAt:new Date,timeSpent:i,answers:o},f=a!==void 0?a:Math.floor(r/100*100);d.subjects||(d.subjects={}),d.subjects[t]||(d.subjects[t]={subjectId:t,progress:0,completedModules:0,totalModules:0,modulesProgress:{}});const p=d.subjects[t];p.modulesProgress[n]||(p.modulesProgress[n]={moduleId:n,subjectId:t,progress:0,lessonsCompleted:[],quizzesCompleted:[],startedAt:new Date,lastAccessedAt:new Date});const m=p.modulesProgress[n],g=!m.quizzesCompleted.includes(s);g&&(m.quizzesCompleted.push(s),m.lastAccessedAt=new Date),await dt(c,{quizAttempts:[...d.quizAttempts||[],l],[`subjects.${t}.modulesProgress.${n}`]:m,...g&&{totalQuizzesCompleted:fs(1)},updatedAt:ae()}),await Wh(e,f,"quiz_complete",`Completed quiz: ${s} (Score: ${r}%)`),await Va(e);try{const{emitPipelineEvent:y,getStudentContext:v}=await ee(async()=>{const{emitPipelineEvent:S,getStudentContext:w}=await import("./pipelineService-BVFD1ZML.js");return{emitPipelineEvent:S,getStudentContext:w}},__vite__mapDeps([11,3,1,2,4,5,6,7,8,9,10])),k=v();k&&y({student_id:e,event_type:"quiz",event_data:{quiz_id:s,score:r,source:"module_quiz",total_questions:o.length,correct_answers:o.filter(S=>S.isCorrect).length},occurred_at:new Date().toISOString(),class_id:k.classId,teacher_id:k.teacherId})}catch{}}catch(c){throw console.error("Error completing quiz:",c),c}},Wh=async(e,t,n,s)=>{try{const r=U(L,"users",e);let o=1;try{const u=(await me(r)).data();u?.xpMultiplier&&typeof u.xpMultiplier=="number"&&(o=u.xpMultiplier)}catch{}const i=Math.round(t*o);await dt(r,{currentXP:fs(i),totalXP:fs(i),updatedAt:ae()});const a=U(et(L,"xpActivities"));await Ce(a,{activityId:a.id,userId:e,type:n,xpEarned:i,description:s,timestamp:ae()})}catch(r){console.error("Error awarding XP:",r)}},Va=async e=>{try{const t=U(L,"progress",e),n=await me(t);if(!n.exists())return;const s=n.data(),r=s.quizAttempts||[],o=r.length>0?Math.round(r.reduce((c,u)=>c+u.score,0)/r.length):0,i={},a=s.subjects||{};for(const[c,u]of Object.entries(a)){const d=u.modulesProgress||{},l=Object.values(d);if(l.length>0){const f=Math.round(l.reduce((p,m)=>p+(m.progress||0),0)/l.length);i[`subjects.${c}.progress`]=f}}await Ce(t,{averageScore:o,...i,updatedAt:ae()},{merge:!0}),await rC(e,o)}catch(t){console.error("Error recalculating progress aggregates:",t)}},rC=async(e,t)=>{try{const{isAtRiskByScore:n}=await ee(async()=>{const{isAtRiskByScore:i}=await import("./riskEngine-DpxF1Vjk.js");return{isAtRiskByScore:i}},[]);let s=n(t);if(!s)try{const i=U(L,"managedStudents",e),a=await me(i);if(a.exists()){const c=a.data()?.riskStatus;c&&["intervene","critical","at_risk"].includes(c)&&(s=!0)}}catch{}const r=s?"High":"Low",o=U(L,"users",e);await Ce(o,{overallRisk:r,updatedAt:ae()},{merge:!0})}catch(n){console.error("Error syncing overallRisk:",n)}},yr={notifications:{emailNotifications:!0,pushNotifications:!0,soundEnabled:!0,notificationTypes:{quizReminders:!0,newContent:!0,achievements:!0,streakAlerts:!0,weeklySummary:!0},quietHours:{start:"22:00",end:"08:00"}},pushPreferences:{pushEnabled:!0,achievement:!0,quiz_battle:!0,daily_reward:!0,assignment:!0,grade_posted:!0,streak_reminder:!0,leaderboard:!0,system:!0},appearance:{darkMode:!1,fontSize:16,compactView:!1,reduceAnimations:!1},privacy:{profileVisibility:"everyone",showActivityStatus:!0,dataSharing:!0},learning:{dailyXpGoal:100,preferredStudyTime:"evening",autoPlayLessons:!1,showHints:!0,quizDifficultyPreference:"adaptive",studyReminderTime:"18:00"},adminPanel:{siteName:"MathPulse AI",siteDescription:"AI-Powered Mathematics Learning Platform",defaultLanguage:"English",maintenanceMode:!1,enforceStrongPasswords:!0,sessionTimeoutMinutes:60,aiTutorEnabled:!0,aiAutoRecommendations:!0,aiRiskAlertsEnabled:!0,gradingScale:"percentage",passingGrade:75,parentSummaryEmails:!0,teacherDigestEmails:!0,weeklyPlatformReport:!0,autoBackupEnabled:!1,backupFrequency:"weekly"}},oC=300*1e3,iC=1800*1e3,$i=new zm({defaultOptions:{queries:{staleTime:oC,gcTime:iC,retry:1,refetchOnWindowFocus:!1}}}),aC=async()=>{await $i.cancelQueries(),$i.clear()},Pu={quizDefaults:{timeLimitMinutes:30,passingScore:75,maxAttempts:3},classPreferences:{autoEnroll:!1,classVisibility:"public"},studentAnalyticsVisibility:!0,notifyOnSubmission:!0,notifyOnStudentActivity:!1},Eu={maintenanceMode:!1,defaultGradeLevel:"Grade 11",defaultCurriculum:"STEM",maxClassSize:50,auditLogVisible:!0,aiConfig:{modelName:"deepseek-chat",temperature:.7,endpoint:"https://api.deepseek.com"}},cC="preferences",Ba=()=>JSON.parse(JSON.stringify(yr)),Hh=e=>{const t=Ba();return e?{...t,...e,notifications:{...t.notifications,...e.notifications,notificationTypes:{...t.notifications.notificationTypes,...e.notifications?.notificationTypes},quietHours:{...t.notifications.quietHours,...e.notifications?.quietHours}},pushPreferences:{...t.pushPreferences,...e.pushPreferences},appearance:{...t.appearance,...e.appearance},privacy:{...t.privacy,...e.privacy},learning:{...t.learning,...e.learning},adminPanel:{...t.adminPanel,...e.adminPanel}}:t},Ua=e=>U(L,"users",e,"settings",cC),Zh=async e=>{const t=Ua(e),n=await me(t);if(!n.exists()){const s=Ba();return await Ce(t,{...s,createdAt:ae(),updatedAt:ae()}),s}return Hh(n.data())},lC=async(e,t)=>{const n=await Zh(e),s=Hh({...n,...t});return await Ce(Ua(e),{...s,updatedAt:ae()},{merge:!0}),s},Kh="mathpulse_appearance",uC=e=>{const t=document.documentElement;t.style.setProperty("--font-size",`${e.appearance.fontSize}px`),t.dataset.density=e.appearance.compactView?"compact":"comfortable",e.appearance.reduceAnimations?t.classList.add("reduced-motion"):t.classList.remove("reduced-motion"),e.appearance.darkMode?t.classList.add("smart-dark"):t.classList.remove("smart-dark");try{localStorage.setItem(Kh,JSON.stringify(e.appearance))}catch{}},dC=()=>{try{const e=localStorage.getItem(Kh);if(!e)return;const t=JSON.parse(e),n=document.documentElement;n.style.setProperty("--font-size",`${t.fontSize}px`),n.dataset.density=t.compactView?"compact":"comfortable",t.reduceAnimations&&n.classList.add("reduced-motion"),t.darkMode&&n.classList.add("smart-dark")}catch{}},fC=async()=>{try{if(await aC(),zP(),localStorage.clear(),sessionStorage.clear(),"caches"in window){const e=await caches.keys();await Promise.all(e.map(t=>caches.delete(t)))}}catch(e){throw console.error("Failed clearing client cache:",e),new Error("Unable to clear cache on this device.")}},hC=async e=>{const t=U(L,"users",e),n=await me(t),s=await me(Ua(e)),r=["progress","xpActivities","achievements","notifications","tasks","chatSessions","chatMessages"],o=await Promise.all(r.map(async i=>{const a=Dt(et(L,i),Rt("userId","==",e)),c=await Fn(a);return{collectionName:i,items:c.docs.map(u=>({id:u.id,...u.data()}))}}));return{exportedAt:new Date().toISOString(),user:n.exists()?{id:n.id,...n.data()}:null,settings:s.exists()?s.data():Ba(),collections:o.reduce((i,a)=>(i[a.collectionName]=a.items,i),{})}},qa=async e=>{const t=ye.currentUser;if(!t||!t.email)throw new Error("No user logged in");const n=em.credential(t.email,e);await tm(t,n)},YR=async(e,t)=>{if(await qa(e),!ye.currentUser)throw new Error("Re-auth failed");await Yp(ye.currentUser,t)},JR=async(e,t)=>{if(await qa(e),!ye.currentUser)throw new Error("Re-auth failed");await Xp(ye.currentUser,t)},eM=async(e,t)=>{if(await qa(e),!ye.currentUser)throw new Error("Re-auth failed");await Jp(ye.currentUser);try{const{deleteDoc:n}=await ee(async()=>{const{deleteDoc:s}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{deleteDoc:s}},__vite__mapDeps([1,2]));await n(U(L,"users",t))}catch{}},Qh=e=>U(L,"users",e,"settings","teacherPreferences"),pC=async e=>{const t=await me(Qh(e));return t.exists()?{...Pu,...t.data()}:{...Pu}},tM=async(e,t)=>{const n=await pC(e),s={...n,...t,quizDefaults:{...n.quizDefaults,...t.quizDefaults},classPreferences:{...n.classPreferences,...t.classPreferences}};return await Ce(Qh(e),{...s,updatedAt:ae()},{merge:!0}),s},Xh=()=>U(L,"system","config"),mC=async()=>{const e=await me(Xh());return e.exists()?{...Eu,...e.data()}:{...Eu}},nM=async e=>{const t=await mC(),n={...t,...e,aiConfig:{...t.aiConfig,...e.aiConfig}};return await Ce(Xh(),{...n,updatedAt:ae()},{merge:!0}),n};function Yh(e){const t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Jh(e){const t=Yh(e);return t.setHours(0,0,0,0),t}function gC(e){const t=Yh(e);return t.setHours(23,59,59,999),t}function Kn(){const e=ye.currentUser?.uid??null;return e||console.warn("[notificationFirestoreService] Skipping Firestore call — user not authenticated"),e}const yC=e=>{const t=e.data(),n=t.createdAt,s=n instanceof jn?n.toDate():n instanceof Date?n:new Date;return{id:e.id,userId:t.userId,type:t.type,title:t.title,message:t.message,isRead:t.isRead,createdAt:s,metadata:t.metadata,actionUrl:t.actionUrl}},bC=async e=>{if(!Kn())throw new Error("Cannot create notification — not authenticated");try{const n=U(et(L,"notifications",e.userId,"items")),s={userId:e.userId,type:e.type,title:e.title,message:e.message,isRead:!1,createdAt:ae(),...e.metadata?{metadata:e.metadata}:{},...e.actionUrl?{actionUrl:e.actionUrl}:{}};return await Ce(n,s),n.id}catch(n){throw console.error("[notificationFirestoreService] Error creating notification:",n),n}},vC=async(e,t)=>{if(Kn())try{const n=U(L,"notifications",e,"items",t),s=dt(n,{isRead:!0}).catch(i=>console.warn("[firestore] markAsRead subcollection skipped:",i)),r=U(L,"notifications",t),o=dt(r,{isRead:!0,read:!0}).catch(i=>console.warn("[firestore] markAsRead top-level skipped:",i));await Promise.all([s,o])}catch(n){throw console.error("[notificationFirestoreService] Error marking as read:",n),n}},wC=async e=>{if(Kn())try{const t=Dt(et(L,"notifications",e,"items"),Rt("isRead","==",!1)),s=(await Fn(t)).docs.map(r=>dt(r.ref,{isRead:!0}));try{const r=Dt(et(L,"notifications"),Rt("userId","==",e),Rt("read","==",!1)),o=await Fn(r);for(const i of o.docs)s.push(dt(i.ref,{isRead:!0,read:!0}))}catch(r){console.warn("[notificationFirestoreService] Top-level markAllAsRead skipped:",r)}await Promise.all(s)}catch(t){throw console.error("[notificationFirestoreService] Error marking all as read:",t),t}},xC=async(e,t)=>{try{const n=U(L,"notifications",e,"items",t),s=br(n).catch(i=>console.warn("[firestore] deleteNotification subcollection skipped:",i)),r=U(L,"notifications",t),o=br(r).catch(i=>console.warn("[firestore] deleteNotification top-level skipped:",i));await Promise.all([s,o])}catch(n){throw console.error("[notificationFirestoreService] Error deleting notification:",n),n}},SC=(e,t)=>{const n=Kn();if(!n||n!==e)return console.warn("[notificationFirestoreService] subscribeToNotifications skipped — auth UID mismatch or not signed in"),t([]),()=>{};const s=Dt(et(L,"notifications",e,"items"),Sn("createdAt","desc")),r=Dt(et(L,"notifications"),Rt("userId","==",e),Sn("createdAt","desc"));let o=[],i=[],a=!1,c=!1;const u=()=>{const f=new Map;for(const m of i)f.set(m.id,m);for(const m of o)f.set(m.id,m);const p=Array.from(f.values()).sort((m,g)=>g.createdAt.getTime()-m.createdAt.getTime());t(p)},d=en(s,f=>{o=f.docs.map(p=>yC(p)),a=!0,c&&u()},()=>{a=!0,c&&u()}),l=en(r,f=>{i=f.docs.map(p=>{const m=p.data(),g=m.createdAt,y=g instanceof jn?g.toDate():g instanceof Date?g:new Date;return{id:p.id,userId:m.userId,type:m.type||"message",title:m.title,message:m.message,isRead:m.isRead??m.read??!1,createdAt:y,metadata:m.metadata,actionUrl:m.actionUrl||m.link}}),c=!0,a&&u()},()=>{c=!0,a&&u()});return()=>{d(),l()}},kC=async e=>{if(!Kn())return!1;try{const t=new Date,n=Jh(t),s=gC(t),r=Dt(et(L,"notifications",e,"items"),Rt("type","==","daily_checkin"),Rt("createdAt",">=",n),Rt("createdAt","<=",s),Sn("createdAt","asc"),ks(1));return!(await Fn(r)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking daily check-in:",t),!1}},TC=async e=>{if(!Kn())return!1;try{const n=Jh(new Date),s=Dt(et(L,"notifications",e,"items"),Rt("type","==","streak_reminder"),Rt("createdAt",">=",n),Sn("createdAt","asc"),ks(1));return!(await Fn(s)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking reminder:",t),!1}};async function ep(e){try{await bC(e)}catch(t){console.error("[NotificationService] Failed to create notification:",t)}}function _C(e){const t=h.useRef(!1);h.useEffect(()=>{if(!e||t.current)return;t.current=!0,(async()=>{try{if(await kC(e)||await TC(e))return;await ep({userId:e,type:"streak_reminder",title:"Don't forget your daily check-in!",message:"Check in today to keep your streak alive and earn bonus XP."})}catch(s){console.error("[useDailyCheckInReminder] Error:",s)}})()},[e])}const tp=h.createContext(null),qo=({children:e})=>{const{currentUser:t,userProfile:n}=Ms(),[s,r]=h.useState([]),[o,i]=h.useState(!0),a=t?.uid??null,c=h.useRef([]);_C(n?.role==="student"?a:null),h.useEffect(()=>{if(!a)return r([]),i(!1),()=>{};i(!0);const m=SC(a,g=>{r(g),i(!1)});return()=>m()},[a]),h.useEffect(()=>{c.current=s},[s]);const u=h.useMemo(()=>s.filter(m=>!m.isRead).length,[s]),d=h.useCallback(async m=>{a&&await vC(a,m)},[a]),l=h.useCallback(async()=>{if(!a)return;const m=c.current;console.log("[markAllAsRead] prev count:",m.filter(g=>!g.isRead).length,"notifications:",m.length),r(g=>g.map(y=>y.isRead?y:{...y,isRead:!0})),console.log("[markAllAsRead] optimistic update applied, new count should be 0");try{await wC(a),console.log("[markAllAsRead] Firestore update succeeded")}catch(g){console.error("[markAllAsRead] Firestore update failed:",g),r(m)}},[a]),f=h.useCallback(async m=>{a&&await xC(a,m)},[a]),p=h.useMemo(()=>({notifications:s,unreadCount:u,isLoading:o,markAsRead:d,markAllAsRead:l,deleteNotification:f}),[s,u,o,d,l,f]);return b.jsx(tp.Provider,{value:p,children:e})},sM=()=>{const e=h.useContext(tp);if(!e)throw new Error("useNotifications must be used within a NotificationProvider");return e},Cu="/firebase-messaging-sw.js";let Go=null,Au=!1,Wo=!1;async function Ga(){if(!Au){try{Wo=await Bp()}catch{Wo=!1}Au=!0}return Wo?(Go||(Go=Up(Ut)),Go):null}async function PC(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.getRegistration(Cu);return e||await navigator.serviceWorker.register(Cu,{scope:"/"})}catch(e){return console.warn("[pushNotificationService] SW registration failed:",e),null}}async function np(e){if(!e||typeof window>"u"||typeof Notification>"u")return null;const t=await Ga();if(!t)return console.warn("[pushNotificationService] FCM not supported in this browser."),null;let n;try{if(Notification.permission==="granted")n="granted";else{if(Notification.permission==="denied")return null;n=await Notification.requestPermission()}}catch(i){return console.warn("[pushNotificationService] permission prompt failed:",i),null}if(n!=="granted")return null;const s="BCydYLOb7oDjcaIwvBq8VUbNE7AzIBSdNbPXHDvSBC9B_2COzlK16MlCLJbDmNynf0yFkx_ZvTLPQYlhiu-C91Q".trim();if(!s)return console.warn("[pushNotificationService] VITE_FIREBASE_VAPID_KEY missing — cannot fetch FCM token."),null;const r=await PC();if(!r)return null;let o=null;try{o=await Vp(t,{vapidKey:s,serviceWorkerRegistration:r})}catch(i){return console.warn("[pushNotificationService] getToken failed:",i),null}if(!o)return null;try{const i=U(L,"users",e,"fcmTokens",o),a={token:o,userId:e,platform:"web",userAgent:typeof navigator<"u"?navigator.userAgent:"",createdAt:ae(),updatedAt:ae(),active:!0};await Ce(i,a,{merge:!0})}catch(i){console.warn("[pushNotificationService] persisting token failed:",i)}return o}function sp(e){let t,n=!1;return Ga().then(s=>{n||!s||(t=Fp(s,e))}),()=>{n=!0,t?.()}}async function rp(e,t){if(!(!e||!t)){try{const n=U(L,"users",e,"fcmTokens",t);await dt(n,{active:!1,updatedAt:ae()})}catch(n){console.warn("[pushNotificationService] marking token inactive failed:",n)}try{const n=await Ga();n&&await $p(n)}catch(n){console.warn("[pushNotificationService] deleteToken failed:",n)}}}const rM=Object.freeze(Object.defineProperty({__proto__:null,deregisterPushToken:rp,onForegroundMessage:sp,requestPushPermissionAndRegister:np},Symbol.toStringTag,{value:"Module"})),EC={achievement:"achievement_unlocked",quiz_battle:"system_alert",daily_reward:"daily_checkin",assignment:"new_assignment",grade_posted:"quiz_result",streak_reminder:"streak_reminder",leaderboard:"system_alert",system:"system_alert"};function CC(e){return e?EC[e]??"system_alert":"system_alert"}function AC(){const{currentUser:e}=Ms(),t=Gi(),n=h.useRef(null),s=h.useRef(null);return h.useEffect(()=>{const o=e?.uid??null;if(s.current=o,!o)return;let i,a=!1;return(async()=>{const c=await np(o);a||(n.current=c,c&&(i=sp(u=>{const d=u.notification??{},l=u.data??{},f=d.title||l.title||"MathPulse AI",p=d.body||l.body||"",m=l.notificationType;ep({userId:o,type:CC(m),title:f,message:p,actionUrl:l.url,metadata:{...l,source:"fcm_foreground",fcmType:m??null}})})))})(),()=>{a=!0,i?.()}},[e?.uid]),h.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const o=i=>{const a=i.data;if(!a||a.type!=="NOTIFICATION_CLICK")return;const c=a.url||"/";try{const u=c.startsWith("http")?new URL(c).pathname:c;t(u)}catch{window.location.href=c}};return navigator.serviceWorker.addEventListener("message",o),()=>navigator.serviceWorker.removeEventListener("message",o)},[t]),{unregister:async()=>{const o=s.current,i=n.current;!o||!i||(await rp(o,i),n.current=null)}}}const Ho=()=>(AC(),null),RC=(e,t)=>{const n=new Array(e.length+t.length);for(let s=0;s({classGroupId:e,validator:t}),op=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Nr="-",Ru=[],IC="arbitrary..",DC=e=>{const t=LC(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return OC(i);const a=i.split(Nr),c=a[0]===""&&a.length>1?1:0;return ip(a,c,t)},getConflictingClassGroupIds:(i,a)=>{if(a){const c=s[i],u=n[i];return c?u?RC(u,c):c:u||Ru}return n[i]||Ru}}},ip=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const u=ip(e,t+1,o);if(u)return u}const i=n.validators;if(i===null)return;const a=t===0?e.join(Nr):e.slice(t).join(Nr),c=i.length;for(let u=0;ue.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),s=t.slice(0,n);return s?IC+s:void 0})(),LC=e=>{const{theme:t,classGroups:n}=e;return zC(n,t)},zC=(e,t)=>{const n=op();for(const s in e){const r=e[s];Wa(r,n,s,t)}return n},Wa=(e,t,n,s)=>{const r=e.length;for(let o=0;o{if(typeof e=="string"){NC(e,t,n);return}if(typeof e=="function"){$C(e,t,n,s);return}FC(e,t,n,s)},NC=(e,t,n)=>{const s=e===""?t:ap(t,e);s.classGroupId=n},$C=(e,t,n,s)=>{if(VC(e)){Wa(e(s),t,n,s);return}t.validators===null&&(t.validators=[]),t.validators.push(MC(n,e))},FC=(e,t,n,s)=>{const r=Object.entries(e),o=r.length;for(let i=0;i{let n=e;const s=t.split(Nr),r=s.length;for(let o=0;o"isThemeGetter"in e&&e.isThemeGetter===!0,BC=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),s=Object.create(null);const r=(o,i)=>{n[o]=i,t++,t>e&&(t=0,s=n,n=Object.create(null))};return{get(o){let i=n[o];if(i!==void 0)return i;if((i=s[o])!==void 0)return r(o,i),i},set(o,i){o in n?n[o]=i:r(o,i)}}},Fi="!",Mu=":",UC=[],Iu=(e,t,n,s,r)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:s,isExternal:r}),qC=e=>{const{prefix:t,experimentalParseClassName:n}=e;let s=r=>{const o=[];let i=0,a=0,c=0,u;const d=r.length;for(let g=0;gc?u-c:void 0;return Iu(o,p,f,m)};if(t){const r=t+Mu,o=s;s=i=>i.startsWith(r)?o(i.slice(r.length)):Iu(UC,!1,i,void 0,!0)}if(n){const r=s;s=o=>n({className:o,parseClassName:r})}return s},GC=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,s)=>{t.set(n,1e6+s)}),n=>{const s=[];let r=[];for(let o=0;o0&&(r.sort(),s.push(...r),r=[]),s.push(i)):r.push(i)}return r.length>0&&(r.sort(),s.push(...r)),s}},WC=e=>({cache:BC(e.cacheSize),parseClassName:qC(e),sortModifiers:GC(e),...DC(e)}),HC=/\s+/,ZC=(e,t)=>{const{parseClassName:n,getClassGroupId:s,getConflictingClassGroupIds:r,sortModifiers:o}=t,i=[],a=e.trim().split(HC);let c="";for(let u=a.length-1;u>=0;u-=1){const d=a[u],{isExternal:l,modifiers:f,hasImportantModifier:p,baseClassName:m,maybePostfixModifierPosition:g}=n(d);if(l){c=d+(c.length>0?" "+c:c);continue}let y=!!g,v=s(y?m.substring(0,g):m);if(!v){if(!y){c=d+(c.length>0?" "+c:c);continue}if(v=s(m),!v){c=d+(c.length>0?" "+c:c);continue}y=!1}const k=f.length===0?"":f.length===1?f[0]:o(f).join(":"),S=p?k+Fi:k,w=S+v;if(i.indexOf(w)>-1)continue;i.push(w);const T=r(v,y);for(let _=0;_0?" "+c:c)}return c},KC=(...e)=>{let t=0,n,s,r="";for(;t{if(typeof e=="string")return e;let t,n="";for(let s=0;s{let n,s,r,o;const i=c=>{const u=t.reduce((d,l)=>l(d),e());return n=WC(u),s=n.cache.get,r=n.cache.set,o=a,a(c)},a=c=>{const u=s(c);if(u)return u;const d=ZC(c,n);return r(c,d),d};return o=i,(...c)=>o(KC(...c))},XC=[],Ie=e=>{const t=n=>n[e]||XC;return t.isThemeGetter=!0,t},lp=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,up=/^\((?:(\w[\w-]*):)?(.+)\)$/i,YC=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,JC=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,eA=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,tA=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,nA=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,sA=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Kt=e=>YC.test(e),se=e=>!!e&&!Number.isNaN(Number(e)),Qt=e=>!!e&&Number.isInteger(Number(e)),Zo=e=>e.endsWith("%")&&se(e.slice(0,-1)),Ft=e=>JC.test(e),dp=()=>!0,rA=e=>eA.test(e)&&!tA.test(e),Ha=()=>!1,oA=e=>nA.test(e),iA=e=>sA.test(e),aA=e=>!z(e)&&!$(e),cA=e=>an(e,pp,Ha),z=e=>lp.test(e),pn=e=>an(e,mp,rA),Du=e=>an(e,gA,se),lA=e=>an(e,yp,dp),uA=e=>an(e,gp,Ha),Ou=e=>an(e,fp,Ha),dA=e=>an(e,hp,iA),tr=e=>an(e,bp,oA),$=e=>up.test(e),os=e=>Pn(e,mp),fA=e=>Pn(e,gp),Lu=e=>Pn(e,fp),hA=e=>Pn(e,pp),pA=e=>Pn(e,hp),nr=e=>Pn(e,bp,!0),mA=e=>Pn(e,yp,!0),an=(e,t,n)=>{const s=lp.exec(e);return s?s[1]?t(s[1]):n(s[2]):!1},Pn=(e,t,n=!1)=>{const s=up.exec(e);return s?s[1]?t(s[1]):n:!1},fp=e=>e==="position"||e==="percentage",hp=e=>e==="image"||e==="url",pp=e=>e==="length"||e==="size"||e==="bg-size",mp=e=>e==="length",gA=e=>e==="number",gp=e=>e==="family-name",yp=e=>e==="number"||e==="weight",bp=e=>e==="shadow",yA=()=>{const e=Ie("color"),t=Ie("font"),n=Ie("text"),s=Ie("font-weight"),r=Ie("tracking"),o=Ie("leading"),i=Ie("breakpoint"),a=Ie("container"),c=Ie("spacing"),u=Ie("radius"),d=Ie("shadow"),l=Ie("inset-shadow"),f=Ie("text-shadow"),p=Ie("drop-shadow"),m=Ie("blur"),g=Ie("perspective"),y=Ie("aspect"),v=Ie("ease"),k=Ie("animate"),S=()=>["auto","avoid","all","avoid-page","page","left","right","column"],w=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...w(),$,z],_=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto","contain","none"],x=()=>[$,z,c],A=()=>[Kt,"full","auto",...x()],P=()=>[Qt,"none","subgrid",$,z],V=()=>["auto",{span:["full",Qt,$,z]},Qt,$,z],F=()=>[Qt,"auto",$,z],H=()=>["auto","min","max","fr",$,z],re=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],te=()=>["start","end","center","stretch","center-safe","end-safe"],B=()=>["auto",...x()],ie=()=>[Kt,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],oe=()=>[Kt,"screen","full","dvw","lvw","svw","min","max","fit",...x()],ce=()=>[Kt,"screen","full","lh","dvh","lvh","svh","min","max","fit",...x()],D=()=>[e,$,z],de=()=>[...w(),Lu,Ou,{position:[$,z]}],He=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",hA,cA,{size:[$,z]}],J=()=>[Zo,os,pn],G=()=>["","none","full",u,$,z],ne=()=>["",se,os,pn],xe=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ue=()=>[se,Zo,Lu,Ou],W=()=>["","none",m,$,z],O=()=>["none",se,$,z],le=()=>["none",se,$,z],Te=()=>[se,$,z],Y=()=>[Kt,"full",...x()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ft],breakpoint:[Ft],color:[dp],container:[Ft],"drop-shadow":[Ft],ease:["in","out","in-out"],font:[aA],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ft],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ft],shadow:[Ft],spacing:["px",se],text:[Ft],"text-shadow":[Ft],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Kt,z,$,y]}],container:["container"],columns:[{columns:[se,z,$,a]}],"break-after":[{"break-after":S()}],"break-before":[{"break-before":S()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:T()}],overflow:[{overflow:_()}],"overflow-x":[{"overflow-x":_()}],"overflow-y":[{"overflow-y":_()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:A()}],"inset-x":[{"inset-x":A()}],"inset-y":[{"inset-y":A()}],start:[{"inset-s":A(),start:A()}],end:[{"inset-e":A(),end:A()}],"inset-bs":[{"inset-bs":A()}],"inset-be":[{"inset-be":A()}],top:[{top:A()}],right:[{right:A()}],bottom:[{bottom:A()}],left:[{left:A()}],visibility:["visible","invisible","collapse"],z:[{z:[Qt,"auto",$,z]}],basis:[{basis:[Kt,"full","auto",a,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[se,Kt,"auto","initial","none",z]}],grow:[{grow:["",se,$,z]}],shrink:[{shrink:["",se,$,z]}],order:[{order:[Qt,"first","last","none",$,z]}],"grid-cols":[{"grid-cols":P()}],"col-start-end":[{col:V()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":P()}],"row-start-end":[{row:V()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":H()}],"auto-rows":[{"auto-rows":H()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...re(),"normal"]}],"justify-items":[{"justify-items":[...te(),"normal"]}],"justify-self":[{"justify-self":["auto",...te()]}],"align-content":[{content:["normal",...re()]}],"align-items":[{items:[...te(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...te(),{baseline:["","last"]}]}],"place-content":[{"place-content":re()}],"place-items":[{"place-items":[...te(),"baseline"]}],"place-self":[{"place-self":["auto",...te()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pbs:[{pbs:x()}],pbe:[{pbe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:B()}],mx:[{mx:B()}],my:[{my:B()}],ms:[{ms:B()}],me:[{me:B()}],mbs:[{mbs:B()}],mbe:[{mbe:B()}],mt:[{mt:B()}],mr:[{mr:B()}],mb:[{mb:B()}],ml:[{ml:B()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:ie()}],"inline-size":[{inline:["auto",...oe()]}],"min-inline-size":[{"min-inline":["auto",...oe()]}],"max-inline-size":[{"max-inline":["none",...oe()]}],"block-size":[{block:["auto",...ce()]}],"min-block-size":[{"min-block":["auto",...ce()]}],"max-block-size":[{"max-block":["none",...ce()]}],w:[{w:[a,"screen",...ie()]}],"min-w":[{"min-w":[a,"screen","none",...ie()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[i]},...ie()]}],h:[{h:["screen","lh",...ie()]}],"min-h":[{"min-h":["screen","lh","none",...ie()]}],"max-h":[{"max-h":["screen","lh",...ie()]}],"font-size":[{text:["base",n,os,pn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,mA,lA]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Zo,z]}],"font-family":[{font:[fA,uA,t]}],"font-features":[{"font-features":[z]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,z]}],"line-clamp":[{"line-clamp":[se,"none",$,Du]}],leading:[{leading:[o,...x()]}],"list-image":[{"list-image":["none",$,z]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,z]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:D()}],"text-color":[{text:D()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...xe(),"wavy"]}],"text-decoration-thickness":[{decoration:[se,"from-font","auto",$,pn]}],"text-decoration-color":[{decoration:D()}],"underline-offset":[{"underline-offset":[se,"auto",$,z]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:x()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,z]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,z]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:de()}],"bg-repeat":[{bg:He()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Qt,$,z],radial:["",$,z],conic:[Qt,$,z]},pA,dA]}],"bg-color":[{bg:D()}],"gradient-from-pos":[{from:J()}],"gradient-via-pos":[{via:J()}],"gradient-to-pos":[{to:J()}],"gradient-from":[{from:D()}],"gradient-via":[{via:D()}],"gradient-to":[{to:D()}],rounded:[{rounded:G()}],"rounded-s":[{"rounded-s":G()}],"rounded-e":[{"rounded-e":G()}],"rounded-t":[{"rounded-t":G()}],"rounded-r":[{"rounded-r":G()}],"rounded-b":[{"rounded-b":G()}],"rounded-l":[{"rounded-l":G()}],"rounded-ss":[{"rounded-ss":G()}],"rounded-se":[{"rounded-se":G()}],"rounded-ee":[{"rounded-ee":G()}],"rounded-es":[{"rounded-es":G()}],"rounded-tl":[{"rounded-tl":G()}],"rounded-tr":[{"rounded-tr":G()}],"rounded-br":[{"rounded-br":G()}],"rounded-bl":[{"rounded-bl":G()}],"border-w":[{border:ne()}],"border-w-x":[{"border-x":ne()}],"border-w-y":[{"border-y":ne()}],"border-w-s":[{"border-s":ne()}],"border-w-e":[{"border-e":ne()}],"border-w-bs":[{"border-bs":ne()}],"border-w-be":[{"border-be":ne()}],"border-w-t":[{"border-t":ne()}],"border-w-r":[{"border-r":ne()}],"border-w-b":[{"border-b":ne()}],"border-w-l":[{"border-l":ne()}],"divide-x":[{"divide-x":ne()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ne()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...xe(),"hidden","none"]}],"divide-style":[{divide:[...xe(),"hidden","none"]}],"border-color":[{border:D()}],"border-color-x":[{"border-x":D()}],"border-color-y":[{"border-y":D()}],"border-color-s":[{"border-s":D()}],"border-color-e":[{"border-e":D()}],"border-color-bs":[{"border-bs":D()}],"border-color-be":[{"border-be":D()}],"border-color-t":[{"border-t":D()}],"border-color-r":[{"border-r":D()}],"border-color-b":[{"border-b":D()}],"border-color-l":[{"border-l":D()}],"divide-color":[{divide:D()}],"outline-style":[{outline:[...xe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[se,$,z]}],"outline-w":[{outline:["",se,os,pn]}],"outline-color":[{outline:D()}],shadow:[{shadow:["","none",d,nr,tr]}],"shadow-color":[{shadow:D()}],"inset-shadow":[{"inset-shadow":["none",l,nr,tr]}],"inset-shadow-color":[{"inset-shadow":D()}],"ring-w":[{ring:ne()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:D()}],"ring-offset-w":[{"ring-offset":[se,pn]}],"ring-offset-color":[{"ring-offset":D()}],"inset-ring-w":[{"inset-ring":ne()}],"inset-ring-color":[{"inset-ring":D()}],"text-shadow":[{"text-shadow":["none",f,nr,tr]}],"text-shadow-color":[{"text-shadow":D()}],opacity:[{opacity:[se,$,z]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[se]}],"mask-image-linear-from-pos":[{"mask-linear-from":ue()}],"mask-image-linear-to-pos":[{"mask-linear-to":ue()}],"mask-image-linear-from-color":[{"mask-linear-from":D()}],"mask-image-linear-to-color":[{"mask-linear-to":D()}],"mask-image-t-from-pos":[{"mask-t-from":ue()}],"mask-image-t-to-pos":[{"mask-t-to":ue()}],"mask-image-t-from-color":[{"mask-t-from":D()}],"mask-image-t-to-color":[{"mask-t-to":D()}],"mask-image-r-from-pos":[{"mask-r-from":ue()}],"mask-image-r-to-pos":[{"mask-r-to":ue()}],"mask-image-r-from-color":[{"mask-r-from":D()}],"mask-image-r-to-color":[{"mask-r-to":D()}],"mask-image-b-from-pos":[{"mask-b-from":ue()}],"mask-image-b-to-pos":[{"mask-b-to":ue()}],"mask-image-b-from-color":[{"mask-b-from":D()}],"mask-image-b-to-color":[{"mask-b-to":D()}],"mask-image-l-from-pos":[{"mask-l-from":ue()}],"mask-image-l-to-pos":[{"mask-l-to":ue()}],"mask-image-l-from-color":[{"mask-l-from":D()}],"mask-image-l-to-color":[{"mask-l-to":D()}],"mask-image-x-from-pos":[{"mask-x-from":ue()}],"mask-image-x-to-pos":[{"mask-x-to":ue()}],"mask-image-x-from-color":[{"mask-x-from":D()}],"mask-image-x-to-color":[{"mask-x-to":D()}],"mask-image-y-from-pos":[{"mask-y-from":ue()}],"mask-image-y-to-pos":[{"mask-y-to":ue()}],"mask-image-y-from-color":[{"mask-y-from":D()}],"mask-image-y-to-color":[{"mask-y-to":D()}],"mask-image-radial":[{"mask-radial":[$,z]}],"mask-image-radial-from-pos":[{"mask-radial-from":ue()}],"mask-image-radial-to-pos":[{"mask-radial-to":ue()}],"mask-image-radial-from-color":[{"mask-radial-from":D()}],"mask-image-radial-to-color":[{"mask-radial-to":D()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":w()}],"mask-image-conic-pos":[{"mask-conic":[se]}],"mask-image-conic-from-pos":[{"mask-conic-from":ue()}],"mask-image-conic-to-pos":[{"mask-conic-to":ue()}],"mask-image-conic-from-color":[{"mask-conic-from":D()}],"mask-image-conic-to-color":[{"mask-conic-to":D()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:de()}],"mask-repeat":[{mask:He()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,z]}],filter:[{filter:["","none",$,z]}],blur:[{blur:W()}],brightness:[{brightness:[se,$,z]}],contrast:[{contrast:[se,$,z]}],"drop-shadow":[{"drop-shadow":["","none",p,nr,tr]}],"drop-shadow-color":[{"drop-shadow":D()}],grayscale:[{grayscale:["",se,$,z]}],"hue-rotate":[{"hue-rotate":[se,$,z]}],invert:[{invert:["",se,$,z]}],saturate:[{saturate:[se,$,z]}],sepia:[{sepia:["",se,$,z]}],"backdrop-filter":[{"backdrop-filter":["","none",$,z]}],"backdrop-blur":[{"backdrop-blur":W()}],"backdrop-brightness":[{"backdrop-brightness":[se,$,z]}],"backdrop-contrast":[{"backdrop-contrast":[se,$,z]}],"backdrop-grayscale":[{"backdrop-grayscale":["",se,$,z]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[se,$,z]}],"backdrop-invert":[{"backdrop-invert":["",se,$,z]}],"backdrop-opacity":[{"backdrop-opacity":[se,$,z]}],"backdrop-saturate":[{"backdrop-saturate":[se,$,z]}],"backdrop-sepia":[{"backdrop-sepia":["",se,$,z]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,z]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[se,"initial",$,z]}],ease:[{ease:["linear","initial",v,$,z]}],delay:[{delay:[se,$,z]}],animate:[{animate:["none",k,$,z]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,z]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:O()}],"rotate-x":[{"rotate-x":O()}],"rotate-y":[{"rotate-y":O()}],"rotate-z":[{"rotate-z":O()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:Te()}],"skew-x":[{"skew-x":Te()}],"skew-y":[{"skew-y":Te()}],transform:[{transform:[$,z,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Y()}],"translate-x":[{"translate-x":Y()}],"translate-y":[{"translate-y":Y()}],"translate-z":[{"translate-z":Y()}],"translate-none":["translate-none"],accent:[{accent:D()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:D()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,z]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mbs":[{"scroll-mbs":x()}],"scroll-mbe":[{"scroll-mbe":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pbs":[{"scroll-pbs":x()}],"scroll-pbe":[{"scroll-pbe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,z]}],fill:[{fill:["none",...D()]}],"stroke-w":[{stroke:[se,os,pn,Du]}],stroke:[{stroke:["none",...D()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},bA=QC(yA);function bn(...e){return bA(am(e))}function vA({className:e,...t}){return b.jsx(rm,{"data-slot":"avatar",className:bn("relative flex size-10 shrink-0 overflow-hidden rounded-full",e),...t})}function zu({className:e,...t}){return b.jsx(om,{"data-slot":"avatar-image",className:bn("aspect-square size-full",e),...t})}function wA({className:e,...t}){return b.jsx(im,{"data-slot":"avatar-fallback",className:bn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}function xA(e){return e==="male"?"/icons/male-student.png":e==="female"?"/icons/female-student.png":"/icons/neutral-student.png"}const SA=e=>{const t=(e||"").trim();return t?t.split(/\s+/).slice(0,2).map(n=>n[0]?.toUpperCase()).join(""):"U"},kA=({src:e,name:t,gender:n,className:s,fallbackClassName:r,imageClassName:o})=>{const i=SA(t),a=xA(n);return b.jsxs(vA,{className:bn("shrink-0",s),children:[e?b.jsx(zu,{src:e,alt:t||"User",className:bn("object-cover",o)}):b.jsx(zu,{src:a,alt:t||"User",className:bn("object-cover",o)}),b.jsx(wA,{className:bn("bg-gradient-to-br from-violet-500 to-indigo-600 text-white font-display font-bold text-xs select-none",r),children:i})]})},TA={Functions:"Functions and Graphs",BusinessMath:"Business and Financial Mathematics",Logic:"Logic and Reasoning"},oM={Functions:"gm-q2-functions-graphs",BusinessMath:"gm-q1-business-finance",Logic:"gm-q4-propositions-syllogisms-fallacies"},_A=e=>{const t=e.trim().toLowerCase();return t==="functions"||t.includes("function")?"Functions":t==="businessmath"||t.includes("business")?"BusinessMath":t==="logic"||t.includes("reason")?"Logic":null},PA=[{lessonId:"gm-q1-bf-1",lessonTitle:"Represent business transactions and financial goals using variables and equations.",moduleId:"gm-q1-business-finance",subjectId:"gen-math",subject:"General Mathematics",quarter:1,competencyCode:"GM11-BF-1",learningCompetency:"Represent business transactions and financial goals using variables and equations.",storagePath:"curriculum/general_math/GENERAL-MATHEMATICS-1.pdf",sourceFile:"GENERAL-MATHEMATICS-1.pdf"},{lessonId:"gm-q1-pss-1",lessonTitle:"Identify and describe arithmetic and geometric patterns in data.",moduleId:"gm-q1-patterns-sequences-series",subjectId:"gen-math",subject:"General Mathematics",quarter:1,competencyCode:"GM11-PSS-1",learningCompetency:"Identify and describe arithmetic and geometric patterns in data.",storagePath:"curriculum/general_math/GENERAL-MATHEMATICS-1.pdf",sourceFile:"GENERAL-MATHEMATICS-1.pdf"},{lessonId:"gm-q1-fass-1",lessonTitle:"Use arithmetic and geometric series to estimate cumulative financial outcomes.",moduleId:"gm-q1-financial-application-sequences-series",subjectId:"gen-math",subject:"General Mathematics",quarter:1,competencyCode:"GM11-FASS-1",learningCompetency:"Use arithmetic and geometric series to estimate cumulative financial outcomes.",storagePath:"curriculum/gen_math_sdo/SDO_Navotas_Gen.Math_SHS_1stSem.FV.pdf",sourceFile:"SDO_Navotas_Gen.Math_SHS_1stSem.FV.pdf"},{lessonId:"bm-q1-1",lessonTitle:"Translate verbal phrases to mathematical expressions; model business scenarios using linear equations and inequalities.",moduleId:"bm-q1-business-math",subjectId:"business-math",subject:"Business Mathematics",quarter:1,competencyCode:"ABM_BM11BS-Ia-b-1",learningCompetency:"Translate verbal phrases to mathematical expressions; model business scenarios using linear equations and inequalities.",storagePath:"curriculum/business_math/SDO_Navotas_Bus.Math_SHS_1stSem.FV.pdf",sourceFile:"SDO_Navotas_Bus.Math_SHS_1stSem.FV.pdf"},{lessonId:"stat-q1-1",lessonTitle:"Define and describe random variables and their types.",moduleId:"stat-q1-probability",subjectId:"stats-prob",subject:"Statistics and Probability",quarter:1,competencyCode:"SP_SHS11-Ia-1",learningCompetency:"Define and describe random variables and their types.",storagePath:"curriculum/stat_prob/SDO_Navotas_STAT_PROB_SHS_1stSem.FV.pdf",sourceFile:"SDO_Navotas_STAT_PROB_SHS_1stSem_FV.pdf"},{lessonId:"bc-q3-lf-1",lessonTitle:"Evaluate limits using limit theorems.",moduleId:"bc-q3-limits-of-functions",subjectId:"basic-calc",subject:"Basic Calculus",quarter:3,competencyCode:"BC12-LF-1",learningCompetency:"Evaluate limits using limit theorems.",storagePath:"curriculum/basic_calc/SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf",sourceFile:"SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf"},{lessonId:"bc-q3-d-1",lessonTitle:"Apply the limit definition of the derivative.",moduleId:"bc-q3-derivatives",subjectId:"basic-calc",subject:"Basic Calculus",quarter:3,competencyCode:"BC12-D-1",learningCompetency:"Apply the limit definition of the derivative.",storagePath:"curriculum/basic_calc/SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf",sourceFile:"SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf"},{lessonId:"bc-q3-i-1",lessonTitle:"Determine antiderivatives of functions.",moduleId:"bc-q3-integration",subjectId:"basic-calc",subject:"Basic Calculus",quarter:3,competencyCode:"BC12-I-1",learningCompetency:"Determine antiderivatives of functions.",storagePath:"curriculum/basic_calc/SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf",sourceFile:"SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf"}],EA=Object.fromEntries(PA.map(e=>[e.competencyCode,{lessonId:e.lessonId,storagePath:e.storagePath,sourceFile:e.sourceFile}])),ju=[{id:"deped-strengthened-gm",title:"DepEd Strengthened SHS General Mathematics Guide",url:"https://www.deped.gov.ph/"},{id:"deped-approved-exemplars",title:"Approved SHS Lesson Exemplars and Activity Sheets",url:"https://www.deped.gov.ph/"}],Za={"gen-math":{id:"gen-math",label:"General Mathematics",color:"#1f4ea8",accent:"#3f7cff"},"business-math":{id:"business-math",label:"Business Mathematics",color:"#166534",accent:"#22c55e"},"stats-prob":{id:"stats-prob",label:"Statistics and Probability",color:"#6b21a8",accent:"#a855f7"}},CA={"Grade 11":["gen-math"]},AA="Foundational competency flow with guided examples, step-by-step vocabulary support, and scaffolded checkpoints.",nt=(e,t,n,s,r,o,i,a,c,u,d,l)=>({id:e,subjectId:t,subject:Za[t].label,quarter:n,moduleTitle:s,moduleDescription:r,contentDomain:o,competencyGroup:i,competencies:a,performanceStandard:c,realWorldTheme:u,grade_level_availability:d,recommended_grade_level:l,sources:[ju[0],ju[1]]}),RA=[nt("gm-q1-business-finance","gen-math","Q1","Business and Finance","Interpret business contexts using mathematical models for pricing, savings, and financial planning.","Business Mathematics","GM-Q1-BF",[{code:"GM11-BF-1",outcome:"Represent business transactions and financial goals using variables and equations."},{code:"GM11-BF-2",outcome:"Analyze financial options using ratio, percent change, and margin reasoning."},{code:"GM11-BF-3",outcome:"Justify practical decisions with mathematically sound comparisons."}],"Produces a finance decision brief that explains and defends a chosen option using quantitative evidence.","Household budgeting and MSME pricing",["Grade 11"],"Grade 11"),nt("gm-q1-patterns-sequences-series","gen-math","Q1","Patterns, Sequences, and Series","Investigate arithmetic and geometric patterns, then model recurring structures in real settings.","Patterns and Algebraic Thinking","GM-Q1-PSS",[{code:"GM11-PSS-1",outcome:"Identify and describe arithmetic and geometric patterns in data."},{code:"GM11-PSS-2",outcome:"Construct explicit and recursive rules for sequences."},{code:"GM11-PSS-3",outcome:"Solve contextual problems involving finite series."}],"Creates a pattern model with formula, table, and verbal interpretation for a real-life process.","Savings goals and production growth",["Grade 11"],"Grade 11"),nt("gm-q1-financial-application-sequences-series","gen-math","Q1","Financial Application of Sequences and Series","Apply sequence and series models in annuities, installment planning, and long-term savings behavior.","Financial Applications","GM-Q1-FASS",[{code:"GM11-FASS-1",outcome:"Use arithmetic and geometric series to estimate cumulative financial outcomes."},{code:"GM11-FASS-2",outcome:"Compare payment plans and saving schemes using sequence-based models."}],"Builds a comparative recommendation report for financial plans grounded in sequence and series computations.","Installment plans and savings projections",["Grade 11"],"Grade 11"),nt("gm-q2-measurement-conversion","gen-math","Q2","Measurement and Conversion","Convert and validate units in practical settings involving length, area, volume, and rate.","Measurement","GM-Q2-MC",[{code:"GM11-MC-1",outcome:"Perform unit conversions accurately across metric and mixed contexts."},{code:"GM11-MC-2",outcome:"Evaluate measurement precision and reasonableness in applied tasks."}],"Produces an accurate conversion workflow with checks for reasonableness and precision.","Construction estimates and food production",["Grade 11"],"Grade 11"),nt("gm-q2-functions-graphs","gen-math","Q2","Functions and Their Graphs","Model relationships using function notation, tables, and graphs to explain changing quantities.","Functions","GM-Q2-FG",[{code:"GM11-FG-1",outcome:"Represent real-life relationships as functions and interpret domain/range."},{code:"GM11-FG-2",outcome:"Analyze function behavior from tables, equations, and graphs."},{code:"GM11-FG-3",outcome:"Use graph interpretation to support contextual conclusions."}],"Submits a function modeling portfolio with equation selection and graph-based interpretation.","Transport fare, utility consumption, and growth trends",["Grade 11"],"Grade 11"),nt("gm-q2-piecewise-functions","gen-math","Q2","Piecewise Functions","Use piecewise definitions to model tiered pricing, conditional rates, and policy thresholds.","Functions","GM-Q2-PF",[{code:"GM11-PF-1",outcome:"Translate threshold-based scenarios into piecewise functions."},{code:"GM11-PF-2",outcome:"Evaluate and graph piecewise functions for decision-making."}],"Constructs and defends a piecewise model for a threshold-driven policy scenario.","Electricity billing tiers and shipping rates",["Grade 11"],"Grade 11"),nt("gm-q2-statistical-variables","gen-math","Q2","Statistical Variables","Differentiate variable types and build data representations suitable for statistical analysis.","Data and Statistics","GM-Q2-SV",[{code:"GM11-SV-1",outcome:"Classify variables and choose appropriate data representations."},{code:"GM11-SV-2",outcome:"Interpret variable distributions and detect potential data issues."}],"Prepares a data profile report with justified variable treatment and representation choices.","School survey dashboards",["Grade 11"],"Grade 11"),nt("gm-q3-basic-trigonometry","gen-math","Q3","Basic Trigonometry","Solve right-triangle and angle problems using trigonometric ratios in practical contexts.","Geometry and Trigonometry","GM-Q3-BT",[{code:"GM11-BT-1",outcome:"Apply trigonometric ratios to solve angle and distance problems."},{code:"GM11-BT-2",outcome:"Interpret trigonometric results in measurement contexts."}],"Creates a field-measurement solution set that justifies method and interpretation.","Building height and slope analysis",["Grade 11"],"Grade 11"),nt("gm-q3-practical-applications-measurement","gen-math","Q3","Practical Applications of Measurement","Integrate measurement methods to solve multi-step tasks in planning, costing, and logistics.","Measurement Applications","GM-Q3-PAM",[{code:"GM11-PAM-1",outcome:"Select and apply measurement methods in practical multi-step tasks."},{code:"GM11-PAM-2",outcome:"Estimate uncertainty and communicate justified approximations."}],"Delivers a practical measurement plan with justified estimates and assumptions.","Project costing and logistics planning",["Grade 11"],"Grade 11"),nt("gm-q3-transformational-geometry-volume-capacity","gen-math","Q3","Transformational Geometry / Volume and Capacity","Use geometric transformations and solid measurement to solve design and storage problems.","Geometry","GM-Q3-TGVC",[{code:"GM11-TGVC-1",outcome:"Analyze geometric transformations in patterned and engineered layouts."},{code:"GM11-TGVC-2",outcome:"Compute volume and capacity for practical container and space tasks."}],"Produces a geometry-based layout and capacity justification for a real constraint.","Packaging and facility layout",["Grade 11"],"Grade 11"),nt("gm-q3-random-variables-sampling","gen-math","Q3","Random Variables and Sampling","Model uncertainty and sampling behavior to support evidence-based conclusions.","Probability and Sampling","GM-Q3-RVS",[{code:"GM11-RVS-1",outcome:"Define random variables and compute basic expected outcomes."},{code:"GM11-RVS-2",outcome:"Explain sampling methods and sampling bias in practical studies."},{code:"GM11-RVS-3",outcome:"Interpret sampling outcomes in context."}],"Presents a sampling design and interpretation memo for a study question.","Consumer preference and public opinion studies",["Grade 11"],"Grade 11"),nt("gm-q4-compound-interest-annuities-loans","gen-math","Q4","Compound Interest, Annuities, and Loans","Evaluate long-term financial commitments using compound growth and annuity structures.","Financial Mathematics","GM-Q4-CIAL",[{code:"GM11-CIAL-1",outcome:"Compute and compare compound interest outcomes across periods and rates."},{code:"GM11-CIAL-2",outcome:"Model annuity and loan payment structures for planning decisions."},{code:"GM11-CIAL-3",outcome:"Assess affordability and sustainability of borrowing plans."}],"Builds a defensible personal finance plan covering savings and borrowing scenarios.","Education financing and long-term savings",["Grade 11"],"Grade 11"),nt("gm-q4-hypothesis-testing-regression","gen-math","Q4","Hypothesis Testing and Regression","Use inferential reasoning and regression modeling to evaluate data-driven claims.","Statistics","GM-Q4-HTR",[{code:"GM11-HTR-1",outcome:"Formulate and interpret hypotheses using context-appropriate tests."},{code:"GM11-HTR-2",outcome:"Develop and interpret regression models for trend analysis."}],"Produces an evidence report with hypothesis decision and regression-backed interpretation.","School performance and market trend analysis",["Grade 11"],"Grade 11"),nt("gm-q4-propositions-syllogisms-fallacies","gen-math","Q4","Logical Propositions, Syllogisms, and Fallacies","Evaluate arguments using formal logic, syllogistic forms, and fallacy detection.","Logic and Reasoning","GM-Q4-PSF",[{code:"GM11-PSF-1",outcome:"Translate statements into logical propositions and evaluate validity."},{code:"GM11-PSF-2",outcome:"Test syllogistic arguments and identify common fallacies."},{code:"GM11-PSF-3",outcome:"Construct sound arguments supported by formal reasoning."}],"Submits a logic audit that classifies validity and fallacies in real arguments.","Media literacy and policy argument review",["Grade 11"],"Grade 11")];function MA(e,t){return`${e.moduleDescription} ${AA}`}function IA(e,t){const n=t==="Grade 11"?"22 min":"18 min";return e.competencies.map((s,r)=>{const o=EA[s.code];return{id:o?.lessonId??`${e.id}-l${r+1}`,title:s.outcome,duration:n,completed:!1,locked:!1,description:`${s.code} · ${s.outcome}`,competencyCode:s.code,subjectId:e.subjectId,subject:e.subject,quarter:parseInt(e.quarter.replace("Q","")),learningCompetency:s.outcome,...o&&{storagePath:o.storagePath,sourceFile:o.sourceFile}}})}function DA(e){const t=[];let s=0;for(let r=0;ri.code),type:s===Math.ceil(e.competencies.length/2)?"module":"practice"})}return t}function OA(e,t){return t.map((n,s)=>({id:`${e.id}-q${s+1}`,title:n.title,questions:Math.max(8,n.competencyCodes.length*5),duration:n.type==="module"?"22 min":"15 min",completed:!1,locked:s>0,type:n.type}))}function LA(e){const t=(e||"").trim();if(!t)return"Grade 11";const n=t.match(/(\d{1,2})/);if(n){const s=parseInt(n[1],10);return s>=11&&s<=12?`Grade ${s}`:"Grade 11"}if(/^grade\s*\d{1,2}$/i.test(t)){const s=parseInt(t.replace(/grade\s*/i,""),10);if(s>=11&&s<=12)return`Grade ${s}`}return"Grade 11"}function zA(e){if(!Array.isArray(e)||e.length===0)return null;const t=new Set(["gen-math","business-math","stats-prob"]),n=e.map(s=>s.trim().toLowerCase()).map(s=>s==="gen-math"||s==="general-mathematics"||s==="general mathematics"?"gen-math":s==="business-math"||s==="business mathematics"||s==="bm"?"business-math":s==="stats-prob"||s==="statistics and probability"||s==="statistics"?"stats-prob":null).filter(s=>s!==null&&t.has(s));return n.length>0?n:null}function jA(e){return LA(e)}function NA(e,t){const n=zA(t),s=CA[e];return n?s.filter(r=>n.includes(r)):s}function $A(e,t){const n=NA(e,t);return RA.filter(s=>s.grade_level_availability.includes(e)).filter(s=>n.includes(s.subjectId)).map(s=>{const r=DA(s),o=IA(s,e),i=OA(s,r),a=Za[s.subjectId],c=o.some(l=>l.storagePath&&l.storagePath.length>0),u=s.isAvailable??c??!0,d=u?"available":"coming_soon";return{id:s.id,title:s.moduleTitle,description:MA(s),lessons:o,quizzes:i,progress:0,color:"bg-white",iconColor:"text-slate-700",accentColor:"bg-slate-700",subjectId:s.subjectId,subject:s.subject,subjectColor:a.color,subjectAccentColor:a.accent,grade_level_availability:s.grade_level_availability,recommended_grade_level:s.recommended_grade_level,active_grade_level:e,quarter:s.quarter,content_domain:s.contentDomain,competency_group:s.competencyGroup,competencies:s.competencies,performance_standard:s.performanceStandard,real_world_theme:s.realWorldTheme,lesson_count:o.length,quiz_count:i.length,is_visible_for_grade:s.grade_level_availability.includes(e),curriculum_aligned_label:"Curriculum-aligned",module_sources:s.sources,module_assessments:r,isAvailable:u,moduleStatus:d}})}const iM=Za,FA=()=>{const e=new Date,t=e.getMonth(),n=e.getFullYear();return t>=7?`${n}-${n+1}-1`:t>=5?`${n-1}-${n}-summer`:`${n-1}-${n}-2`},vp=async e=>{const{uid:t,score:n,subject:s,title:r}=e,o=s||r||"General";let i="";return await Op(L,async a=>{const c=U(L,"users",t,"gradeSummary","current"),u=await a.get(c);let d;if(!u.exists())d={overallGpa:n/100*4,averageScore:n,quizzesCompleted:1,subjectPerformance:{[o]:{totalScore:n,count:1,avgScore:n}},lastUpdated:jn.now()};else{const m=u.data(),g=(m.quizzesCompleted||0)+1,v=((m.averageScore||0)*(m.quizzesCompleted||0)+n)/g,k=m.subjectPerformance||{},S=k[o]||{totalScore:0,count:0},w=S.count+1,T=S.totalScore+n,_=T/w;d={overallGpa:v/100*4,averageScore:v,quizzesCompleted:g,subjectPerformance:{...k,[o]:{totalScore:T,count:w,avgScore:_}},lastUpdated:jn.now()}}a.set(c,d,{merge:!0});const l=et(L,"users",t,"assessments"),f=U(l);i=f.id;const p={title:e.title,subject:o,type:e.type,score:e.score,totalQuestions:e.totalQuestions,completedAt:jn.now(),risk:e.risk,intervention:e.intervention,xpEarned:e.xpEarned,badgeUnlocked:e.badgeUnlocked,semester:FA(),createdAt:ae()};a.set(f,p)}),i},VA=(e,t)=>{const n=U(L,"users",e,"gradeSummary","current");return en(n,s=>{s.exists()?t(s.data()):t(null)},s=>{console.error("[gradesService] subscribeToGradeSummary error:",s),t(null)})},BA=(e,t)=>{const n=Dt(et(L,"users",e,"assessments"),Sn("completedAt","desc"),ks(20));return en(n,s=>{const r=[];s.forEach(o=>{r.push({id:o.id,...o.data()})}),t(r)},s=>{console.error("[gradesService] subscribeToAssessments error:",s),t([])})},aM=Object.freeze(Object.defineProperty({__proto__:null,saveAssessmentResult:vp,subscribeToAssessments:BA,subscribeToGradeSummary:VA},Symbol.toStringTag,{value:"Module"}));function UA(e){const{assessmentId:t,overallScorePercent:n,overallRisk:s,intervention:r,proficiencyProfile:o}=e,i=GA(n),a=WA(n,s,o),c=HA(s,r),u=o?.strengths??[],d=o?.weaknesses??[];return{status:"ready",headline:i,summary:a,strengths:u,weaknesses:d,recommendation:c,latestAssessmentId:t,latestScorePercent:n,latestRiskLevel:wp(s),updatedAt:new Date}}async function qA(e,t){const n=U(L,"users",e,"dashboardSummary","heroBannerModal");await Ce(n,{...t,updatedAt:ae()})}async function cM(e){const t=U(L,"users",e,"dashboardSummary","heroBannerModal"),n=await me(t);if(!n.exists())return null;const s=n.data();return{status:s.status??"not_started",headline:s.headline??"",summary:s.summary??"",strengths:s.strengths??[],weaknesses:s.weaknesses??[],recommendation:s.recommendation??"",latestAssessmentId:s.latestAssessmentId??"",latestScorePercent:s.latestScorePercent??0,latestRiskLevel:s.latestRiskLevel??"",updatedAt:xp(s.updatedAt)}}function lM(e,t){const n=U(L,"users",e,"dashboardSummary","heroBannerModal");return en(n,s=>{if(!s.exists()){t(null);return}const r=s.data();t({status:r.status??"not_started",headline:r.headline??"",summary:r.summary??"",strengths:r.strengths??[],weaknesses:r.weaknesses??[],recommendation:r.recommendation??"",latestAssessmentId:r.latestAssessmentId??"",latestScorePercent:r.latestScorePercent??0,latestRiskLevel:r.latestRiskLevel??"",updatedAt:xp(r.updatedAt)})},s=>{console.warn("[heroBannerSummaryService] Subscription error:",s),t(null)})}function GA(e){return e>=80?"Outstanding performance! 🎉":e>=65?"Good job — keep it up!":e>=50?"You're making progress!":"Let's build your foundation"}function WA(e,t,n){const s=n?.strengths??[],r=n?.weaknesses??[];if(s.length>0&&r.length>0){const o=s[0],i=r[0];return`You show stronger understanding in ${o}, while ${i} needs more attention. Keep practicing to strengthen your weaker areas!`}return s.length>0?"Great work! You demonstrated strong understanding. Focus on maintaining your performance and expanding your skills.":r.length>0?"You have some areas to work on. With guided practice and focused review, you can build a stronger foundation in the topics that need attention.":e>=70?"You performed well overall! You have a solid foundation. Continue practicing to maintain and expand your skills.":e>=50?"You showed understanding in several areas. Keep practicing and review the topics where you lost points.":"The diagnostic shows there are foundational topics to work on. Don't worry — with consistent practice, you'll build confidence and improve!"}function HA(e,t,n){return t&&t.trim().length>0?t:(wp(e),e==="critical"||e==="high"?"We recommend starting with foundational lessons and guided practice to build confidence. Focus on one topic at a time, and don't hesitate to review earlier material.":e==="moderate"?"Start with guided review lessons to strengthen your foundation, then progressively tackle more challenging problems.":"Continue practicing regularly and review topics you find challenging. Your personalized learning path will guide you to the right lessons.")}function wp(e){switch(e){case"low":return"Low";case"moderate":return"Moderate";case"high":return"High";case"critical":return"Critical";default:return e.charAt(0).toUpperCase()+e.slice(1)}}function xp(e){return e?e instanceof Date?e:e instanceof jn?e.toDate():typeof e=="string"||typeof e=="number"?new Date(e):new Date:new Date}const ZA=h.lazy(()=>ee(()=>import("./LoginPage-B_M2Kx_b.js"),__vite__mapDeps([14,3,15,7,8,16,17,18,19,20,1,2,4,5,6,9,10]))),KA=h.lazy(()=>ee(()=>import("./TeacherDashboard-ttPsdvb8.js"),__vite__mapDeps([21,3,15,7,8,16,22,23,24,25,1,2,4,5,6,9,10,26,27,28,29,30,31,32,33,17,34,35,36,37,38,39,40,19,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61]))),QA=h.lazy(()=>ee(()=>import("./AdminDashboard-By-BB3KI.js"),__vite__mapDeps([62,3,63,34,25,39,7,23,48,47,44,64,22,15,8,24,1,2,4,5,6,9,10,65,42,27,16,53,50,29,30,31,32,33,17,57,46,20,26,36,19,41,18,28,49,52,66,67,68,40]))),Nu=h.lazy(()=>ee(()=>import("./Sidebar-CR8IPH6O.js").then(e=>e.b),__vite__mapDeps([63,3,34,25,39,7,23,48,47,44,64]))),XA=h.lazy(()=>ee(()=>import("./HeroBanner-Br6C2yH1.js"),__vite__mapDeps([69,3,57,7,23,8,1,2,33,32,17,4,5,6,9,10]))),YA=h.lazy(()=>ee(()=>import("./RightSidebar-CjDA-c42.js"),__vite__mapDeps([70,3,71,38,39,7,48,1,2,4,5,6,8,9,10]))),JA=h.lazy(()=>ee(()=>import("./XPNotification-Dsc44Rs3.js"),__vite__mapDeps([72,3,17,1,2,4,5,6,7,8,9,10]))),eR=h.lazy(()=>ee(()=>import("./index-B23D5AFn.js"),__vite__mapDeps([73,3,33,74,31,38,60,30,24,23,1,2,4,5,6,7,8,9,10])).then(e=>({default:e.NotificationBell})));h.lazy(()=>ee(()=>import("./SupplementalBanner-CyLKxz9O.js"),__vite__mapDeps([75,3,23,17,48,1,2,4,5,6,7,8,9,10])));const tR=h.lazy(()=>ee(()=>import("./SupplementalPillCarousel-D522wnTT.js"),__vite__mapDeps([76,3,77,7,59,1,2,33,42,31,36,48,17,23,4,5,6,8,9,10]))),nR=h.lazy(()=>ee(()=>import("./LearningPath-BhYUnmrP.js"),__vite__mapDeps([78,3,79,68,1,2,77,36,31,41,4,5,6,7,8,9,10]))),sR=h.lazy(()=>ee(()=>import("./CompetencyRadarChart-BIu0jpMm.js"),__vite__mapDeps([80,3,1,2,53,44,17,8,4,5,6,7,9,10])).then(e=>({default:e.CompetencyRadarChart}))),rR=h.lazy(()=>ee(()=>import("./ModulesPage-BgmrOnnq.js"),__vite__mapDeps([81,3,52,1,2,79,68,77,36,31,41,15,7,8,9,10,0,4,5,6,35,82,42,23,27,83,47,48,51,38,40,13,60,53,44,61,32,56,66,84,85,54,59,26,86,17]))),oR=h.lazy(()=>ee(()=>import("./AIChatPage-DH58XfsA.js"),__vite__mapDeps([87,3,15,7,8,16,55,9,10,1,2,4,5,6,28,26,24,47,37]))),iR=h.lazy(()=>ee(()=>import("./GradesPage-C8P7dxU8.js"),__vite__mapDeps([88,3,15,7,8,53,44,54,1,2,46,32,33,86,4,5,6,9,10]))),aR=h.lazy(()=>ee(()=>import("./LeaderboardPage-GVWLWArd.js"),__vite__mapDeps([89,3,23,36,61,90,1,2,4,5,6,7,8,9,10]))),cR=h.lazy(()=>ee(()=>import("./QuizBattlePage-H3hCehZd.js"),__vite__mapDeps([91,3,71,53,44,1,2,15,7,8,65,42,27,16,67,45,83,92,93,17,56,48,4,5,6,9,10]))),lR=h.lazy(()=>ee(()=>import("./AvatarShop-CnrlXF7V.js"),__vite__mapDeps([94,3,7,90,1,2,39,92,93,49,23,64,17,4,5,6,8,9,10]))),uR=h.lazy(()=>ee(()=>import("./FloatingAITutor-CkFvbvHJ.js"),__vite__mapDeps([95,3,1,2,96,43,23,37,4,5,6,7,8,9,10]))),dR=h.lazy(()=>ee(()=>import("./RewardsModal-BqWMkrYX.js"),__vite__mapDeps([97,3,1,2,23,4,5,6,7,8,9,10]))),Ko=h.lazy(()=>ee(()=>import("./ProfileModal-82NOIe2Y.js"),__vite__mapDeps([98,3,15,7,8,16,65,42,27,99,4,2,5,23,43,28,50,18,40,49,1,6,9,10]))),fR=h.lazy(()=>ee(()=>import("./ConfirmModal-DE1CbRDa.js"),__vite__mapDeps([22,3,15,7,8,23,24,25,1,2,4,5,6,9,10]))),Qo=h.lazy(()=>ee(()=>import("./SettingsModal-BcXV1uwF.js"),__vite__mapDeps([100,3,65,7,42,27,15,8,16,67,22,23,24,25,1,2,4,5,6,9,10,99,43,28,50,31,46,40,85,44,74,36,19]))),hR=h.lazy(()=>ee(()=>import("./ScientificCalculator-B-rMzwD3.js"),__vite__mapDeps([82,3,42,23,1,2,4,5,6,7,8,9,10]))),pR=h.lazy(()=>ee(()=>import("./InitialAssessmentModal-Cri1vHPb.js"),__vite__mapDeps([101,3,15,7,8,102,1,2,23,38,4,5,6,9,10]))),mR=h.lazy(()=>ee(()=>import("./AssessmentPage-DWkUbkQS.js"),__vite__mapDeps([103,3,15,7,8,102,96,23,36,38,48,1,2,4,5,6,9,10]))),gR=h.lazy(()=>ee(()=>import("./DiagnosticBreakdown-KMY-Jwc3.js"),__vite__mapDeps([104,3,1,2,23,36,51,32,44,42,4,5,6,7,8,9,10]))),yR=()=>{const{isLoggedIn:e,userProfile:t,userRole:n,loading:s,refreshProfile:r}=Ms();Gi();const o=zt(),i=b.jsx("div",{className:"flex min-h-[320px] items-center justify-center text-sm font-semibold text-slate-500",children:"Loading content..."}),a=b.jsx("div",{className:"pb-4 text-sm font-semibold text-slate-500",children:"Loading dashboard content..."}),c=b.jsx("div",{className:"h-11 w-11 shrink-0 rounded-xl bg-[#edf1f7]","aria-hidden":"true"}),u=b.jsx("div",{className:"h-screen w-72 border-r border-[#dde3eb] bg-white/70","aria-hidden":"true"}),d=b.jsx("div",{className:"min-h-[240px] rounded-3xl border border-[#dde3eb] bg-white/70","aria-hidden":"true"}),[l,f]=h.useState("Dashboard"),p=h.useRef(!1),[m,g]=h.useState(null),y=h.useRef(null),v=h.useRef(null),[k,S]=h.useState(!1),[w,T]=h.useState(!1),[_,R]=h.useState(!1),[x,A]=h.useState(!1);h.useEffect(()=>{(async()=>{try{const M=await me(U(L,"settings","general"));M.exists()&&M.data()?.maintenanceMode===!0?(R(!0),e&&n!=="admin"&&await ou()):R(!1)}catch{}A(!0)})()},[e,n]);const P=t,[V,F]=h.useState(P?.level||1),[H,re]=h.useState(P?.currentXP||0),[te,B]=h.useState(P?.totalXP||0),ie=Math.floor(100*Math.pow(1.5,V-1));let oe=0;for(let E=1;E{const E=P?.learnerCurriculumAssignments?.subjects??P?.assignedSubjects??P?.curriculumAssignedSubjects??[];return Array.isArray(E)?E:[]},[P]),He=h.useMemo(()=>$A(D,de),[D,de]),X=h.useMemo(()=>Object.fromEntries(He.map(E=>[E.id,E.moduleStatus])),[He]),[J,G]=h.useState({collapsed:!1}),ne={Dashboard:"/",Modules:"/modules","AI Chat":"/chat",Assessment:"/assessment","Quiz Battle":"/battle",Leaderboard:"/leaderboard",Grades:"/grades","Avatar Studio":"/avatar"},xe={"/":"Dashboard","/modules":"Modules","/chat":"AI Chat","/assessment":"Assessment","/battle":"Quiz Battle","/leaderboard":"Leaderboard","/grades":"Grades","/avatar":"Avatar Studio"};h.useEffect(()=>{const E=xe[o.pathname]||"Dashboard";f(E)},[o.pathname]),h.useEffect(()=>{const E=()=>{const M=xe[window.location.pathname]||"Dashboard";f(M)};return window.addEventListener("popstate",E),()=>window.removeEventListener("popstate",E)},[]);const Z=(E,M)=>{if(l==="Avatar Studio"&&p.current&&E!=="Avatar Studio"){g(E);return}M?Ds(M):E==="Modules"&&l!=="Modules"&&Ds(null),E==="Quiz Battle"&&l!=="Quiz Battle"?(G({collapsed:k}),S(!0)):l==="Quiz Battle"&&E!=="Quiz Battle"&&S(J.collapsed),f(E);const q=ne[E];q&&window.location.pathname!==q&&window.history.pushState({},"",q),T(!1)},[ue,W]=h.useState(!1),[O,le]=h.useState({show:!1,xp:0,message:""}),[Te,Y]=h.useState(!1),[Ne,be]=h.useState(!1),[Ae,it]=h.useState(!1),[at,Qn]=h.useState(!1),[to,$e]=h.useState({}),[Gt,Ds]=h.useState(null),[Os,En]=h.useState(!1),[cn,kt]=h.useState(yr),[Xn,pt]=h.useState(""),[Wt,Nt]=h.useState(!1),[Ls,Ht]=h.useState(!1),[Zt,ln]=h.useState(null),[no,un]=h.useState(!1),[Tt,zs]=h.useState(!1),[so,js]=h.useState(0),[Cn,Q]=h.useState(!1),[Pe,Re]=h.useState(!1),[Fe,An]=h.useState(""),[Me,tt]=h.useState([]),[rt,Ue]=h.useState(P?.atRiskSubjects||[]),[Ze,dn]=h.useState(P?.priorityTopics||[]),[$t,ro]=h.useState(P?.gpa||"0");h.useEffect(()=>{e&&n==="student"&&t&&sC(t.uid).then(E=>{E&&E.averageScore>0&&ro(Math.round(E.averageScore).toString())}).catch(E=>console.error("Error loading progress for GPA:",E))},[e,n,t]);const[Yn,Ka]=h.useState(!1);h.useEffect(()=>{P&&n==="student"?(F(P.level||1),re(P.currentXP||0),B(P.totalXP||0),Ue(P.atRiskSubjects||[]),dn(P.priorityTopics||[]),Ka(!0)):n!=="student"&&Ka(!0)},[t,n]),h.useEffect(()=>{if(!e||n!=="student"){Nt(!1);return}let E=!1;const M=()=>{E||Nt(!0)},q=window.requestIdleCallback,pe=window.cancelIdleCallback,ho=window.setTimeout(M,800),po=window.requestAnimationFrame(()=>{q||M()}),mt=q?.(()=>{M()},{timeout:500});return()=>{E=!0,window.clearTimeout(ho),window.cancelAnimationFrame(po),mt!==void 0&&pe&&pe(mt)}},[e,n]),h.useEffect(()=>{$e({})},[t?.uid]);const oo=h.useMemo(()=>{const E=new Set;return rt.map(q=>_A(q)).filter(q=>q!==null).filter(q=>E.has(q)?!1:(E.add(q),!0))},[rt]),io=h.useMemo(()=>{const E=Ze.length>0?Ze:oo,M=new Set;return E.filter(q=>M.has(q)?!1:(M.add(q),!0))},[Ze,oo]),kp=()=>{Ht(!0)};h.useEffect(()=>{const E=()=>Ht(!0);return window.addEventListener("mathpulse:open-assessment",E),()=>window.removeEventListener("mathpulse:open-assessment",E)},[]),h.useEffect(()=>{if(!e||n!=="student"||!Yn||!t?.uid)return;let E=!1;return(async()=>{try{un(!!P?.assessmentDismissed),zs(!!P?.initialAssessmentCompleted);const q=await Xo(U(L,"diagnosticResults",t.uid)).catch(()=>me(U(L,"diagnosticResults",t.uid))),pe=await Xo(U(L,"competencyProfiles",t.uid)).catch(()=>me(U(L,"competencyProfiles",t.uid)));if(E)return;const ho=q.exists()&&q.data()?.status==="completed",po=pe.exists()&&pe.data()?.overallScore>0;if(!ho&&!po){ln(!1);const mt=setTimeout(()=>{!E&&!no&&!Tt&&(sessionStorage.getItem("mathpulse_iar_session_dismissed")==="true"||Ht(!0))},1e3);return()=>clearTimeout(mt)}else{if(ln(!0),q.exists()){const mt=q.data();mt?.riskProfile&&(Ue(mt.riskProfile.weak_domains||[]),dn(mt.riskProfile.critical_gaps||[]))}if(pe.exists()){const mt=pe.data();mt?.primaryWeakness&&Ue(Xa=>[...new Set([...Xa,mt.primaryWeakness])])}}}catch(q){console.error("[diagnostic] Firestore check failed:",q)}})(),()=>{E=!0}},[e,n,Yn,t?.uid,so]);const Tp=[...rt].sort().join("|"),Jn=t?.uid?`mathpulse_supplemental_dismissed_${t.uid}`:null;h.useEffect(()=>{if(!Jn){pt("");return}try{const E=localStorage.getItem(Jn)||"";pt(E)}catch{pt("")}},[Jn]);const _p=()=>{if(pt(""),!!Jn)try{localStorage.removeItem(Jn)}catch{}};rt.length>0,h.useEffect(()=>{(async()=>{if(!t?.uid){kt(yr);return}try{const M=await Zh(t.uid);kt(M)}catch(M){console.error("Error loading user settings:",M),kt(yr)}})()},[t?.uid]),h.useEffect(()=>{uC(cn)},[cn]);const Pp=(E,M)=>{Ht(!1),An(E),tt(M),Q(!0)},Qa=async E=>{if(Q(!1),ln(!0),Re(!0),E.xpEarned>0&&t?.uid)try{await No(t.uid,E.xpEarned,"manual","Diagnostic assessment completed"),ct.success(`Assessment complete! +${E.xpEarned} XP earned. ${E.badgeUnlocked.replace("_"," ")} badge unlocked!`)}catch{ct.success("Assessment complete!")}else ct.success("Assessment complete!");if(t?.uid&&E.competencyScores&&E.proficiencyProfile)try{await nC(t.uid,{uid:t.uid,assessmentId:`assessment-${Date.now()}`,completedAt:new Date,rawScore:E.overallScorePercent,totalQuestions:Object.values(E.competencyScores).reduce((M,q)=>M+q.attempted,0),correctAnswers:Object.values(E.competencyScores).reduce((M,q)=>M+q.correct,0),timeSpentSeconds:0,competencyScores:E.competencyScores,recommendations:E.proficiencyProfile.weaknesses.map(M=>`Focus on ${M}`),proficiencyProfile:E.proficiencyProfile,assessmentType:"initial"})}catch(M){console.error("[WARN] Failed to save competency profile:",M)}if(t?.uid)try{const M=UA({assessmentId:Fe?`assessment-${Fe}`:`assessment-${Date.now()}`,overallScorePercent:E.overallScorePercent,overallRisk:E.overallRisk,intervention:E.intervention,proficiencyProfile:E.proficiencyProfile});await qA(t.uid,M)}catch(M){console.error("[App] Failed to save hero banner summary:",M)}if(t?.uid){try{const M=await me(U(L,"diagnosticResults",t.uid));if(M.exists()){const q=M.data();q?.riskProfile&&(Ue(q.riskProfile.weak_domains||[]),dn(q.riskProfile.critical_gaps||[]))}_p()}catch(M){console.error("[diagnostic] Failed to refresh risk data:",M)}try{await dt(U(L,"users",t.uid),{initialAssessmentCompleted:!0,assessmentDismissed:!1,assessmentCompletedAt:ae()}),await No(t.uid,50,"initial_assessment","Initial assessment completed")}catch(M){console.error("[App] Failed to persist assessment completion:",M)}try{await vp({uid:t.uid,testId:Fe||"diagnostic",title:"Diagnostic Assessment",subject:"General Mathematics",type:"diagnostic",score:E.overallScorePercent,totalQuestions:Object.values(E.competencyScores||{}).reduce((M,q)=>M+q.attempted,0),risk:E.overallRisk,intervention:E.intervention,xpEarned:E.xpEarned,badgeUnlocked:E.badgeUnlocked})}catch(M){console.error("[App] Failed to persist grade result:",M)}}},Ep=()=>{f("AI Chat")},Cp=async(E,M)=>{if(t)try{const q=await No(t.uid,E,"manual",M);re(q.xp),q.leveledUp&&F(q.newLevel),B(pe=>pe+E),await r(),le({show:!0,xp:E,message:M})}catch(q){console.error("Error awarding XP:",q)}},ao=async()=>{try{await ou(),$e({}),f("Dashboard"),Y(!1)}catch(E){console.error("Error logging out:",E)}},Rn=async E=>{if(!t){it(!1),be(!1);return}const M={};["name","email","phone","photo","avatarLayers","gender","lrn","grade","section","school","enrollmentDate","major","gpa","department","subject","yearsOfExperience","qualification","position"].forEach(pe=>{E[pe]!==void 0&&(M[pe]=E[pe])});try{await U_(t.uid,M),$e(pe=>({...pe,...M})),it(!1),be(!1),ct.success("Profile updated successfully")}catch(pe){console.error("Error saving profile:",pe),ct.error("Failed to update profile")}},co=async E=>{if(t?.uid)try{const M=await lC(t.uid,E);kt(M),ct.success("Settings saved successfully")}catch(M){throw console.error("Error saving settings:",M),ct.error("Failed to save settings"),M}},lo=async()=>{if(!t?.uid)return;const E=await hC(t.uid),M=new Blob([JSON.stringify(E,null,2)],{type:"application/json"}),q=URL.createObjectURL(M),pe=document.createElement("a");pe.href=q,pe.download=`mathpulse-data-export-${t.uid}-${Date.now()}.json`,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe),URL.revokeObjectURL(q),ct.success("Data export downloaded")},uo=async()=>{await fC(),ct.success("Local cache cleared")},fo=async()=>{if(!t)throw new Error("No active profile found.");const E=n==="student"?P?.lrn||t.uid:void 0;n==="student"&&(await br(U(L,"diagnosticResults",t.uid)).catch(()=>{}),await br(U(L,"competencyProfiles",t.uid)).catch(()=>{}));const{resetTestingDataForRole:M}=await ee(async()=>{const{resetTestingDataForRole:pe}=await import("./testResetService-DUw6qLIU.js");return{resetTestingDataForRole:pe}},__vite__mapDeps([105,1,2,3,4,5,6,7,8,9,10])),q=await M({uid:t.uid,role:n,lrn:E});n==="student"&&(F(1),re(0),B(0),Ue([]),dn([]),ln(null),un(!1),zs(!1),ro("0"),f("Dashboard"),r(),js(pe=>pe+1)),ct.success(q.summary)},Ke=t?{uid:t.uid,name:t.name,email:t.email,phone:t.phone||"",photo:t.photo||"",avatarLayers:t.avatarLayers,role:t.role,...n==="student"&&P?{lrn:P.lrn,grade:P.grade,section:P.section,school:P.school,enrollmentDate:P.enrollmentDate,major:P.major,gpa:$t}:{},...to}:{uid:void 0,name:"User",email:"",phone:"",photo:"",avatarLayers:void 0,role:n},Ns=Ke.name.trim().split(/\s+/).find(E=>/\p{L}/u.test(E))||Ke.name.trim()||"User";if(h.useEffect(()=>{const E=M=>{if(!(M.target instanceof HTMLInputElement||M.target instanceof HTMLTextAreaElement)&&M.altKey)switch(M.key.toLowerCase()){case"d":M.preventDefault(),Z("Dashboard");break;case"m":M.preventDefault(),Z("Modules");break;case"c":M.preventDefault(),Z("AI Chat");break;case"g":M.preventDefault(),Z("Grades");break;case"b":M.preventDefault(),Z("Quiz Battle");break;case"s":M.preventDefault(),be(!0);break;case"p":M.preventDefault(),it(!0);break;case"k":M.preventDefault(),Qn(q=>!q);break}};if(e&&n==="student")return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e,n]),h.useEffect(()=>{const E=M=>{const q=M.detail;q?.tab&&e&&Z(q.tab)};return window.addEventListener("mathpulse:navigate",E),()=>window.removeEventListener("mathpulse:navigate",E)},[e]),s)return b.jsx(ns,{});if(_&&(!e||n!=="admin"))return b.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-[#f8fafc] to-[#eef2ff] p-6",children:b.jsxs("div",{className:"bg-white rounded-2xl shadow-xl border border-slate-200 p-8 max-w-md w-full text-center",children:[b.jsx("div",{className:"w-16 h-16 rounded-full bg-amber-100 flex items-center justify-center mx-auto mb-5",children:b.jsx(Ei,{className:"w-8 h-8 text-amber-600"})}),b.jsx("h1",{className:"text-xl font-bold text-[#1e293b] mb-2",children:"System Under Maintenance"}),b.jsx("p",{className:"text-sm text-[#64748b] leading-relaxed mb-4",children:"MathPulse AI is currently undergoing scheduled maintenance. All user sessions have been paused and your progress has been saved."}),b.jsx("p",{className:"text-xs text-[#94a3b8]",children:"Please check back shortly. We apologize for the inconvenience."})]})});if(!e)return b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading sign in..."}),children:b.jsx(ZA,{})});if(!(n!=="student"||Yn))return b.jsx(ns,{message:"Preparing your dashboard..."});if(n==="teacher")return b.jsx(qo,{children:b.jsxs(b.Fragment,{children:[b.jsx(Ho,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading teacher dashboard..."}),children:b.jsx(KA,{onLogout:ao,onOpenProfile:()=>it(!0),onOpenSettings:()=>be(!0)})}),Ae&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ko,{isOpen:Ae,onClose:()=>it(!1),profileData:Ke,onSave:Rn})}),Ne&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Qo,{isOpen:Ne,onClose:()=>be(!1),profileData:Ke,onSave:Rn,settingsData:cn,onSaveSettings:co,onApplySettingsPreview:kt,onExportData:lo,onClearCache:uo,onResetData:fo})}),b.jsx($o,{position:"top-right",richColors:!0,closeButton:!0})]})});if(n==="admin")return b.jsx(qo,{children:b.jsxs(b.Fragment,{children:[b.jsx(Ho,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading admin dashboard..."}),children:b.jsx(QA,{onLogout:ao,onOpenProfile:()=>it(!0),onOpenSettings:()=>be(!0)})}),Ae&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ko,{isOpen:Ae,onClose:()=>it(!1),profileData:Ke,onSave:Rn})}),Ne&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Qo,{isOpen:Ne,onClose:()=>be(!1),profileData:Ke,onSave:Rn,settingsData:cn,onSaveSettings:co,onApplySettingsPreview:kt,onExportData:lo,onClearCache:uo,onResetData:fo})}),b.jsx($o,{position:"top-right",richColors:!0,closeButton:!0})]})});const Ap=b.jsx(qo,{children:b.jsxs(b.Fragment,{children:[b.jsx(Ho,{}),b.jsx(ZP,{children:b.jsxs("div",{className:"flex h-screen w-full bg-[#f8faff] overflow-hidden",children:[b.jsx("div",{className:"hidden lg:block",children:b.jsx(h.Suspense,{fallback:u,children:b.jsx(Nu,{activeTab:l,setActiveTab:Z,userRole:n,onOpenSettings:()=>be(!0),onLogout:()=>Y(!0),sidebarCollapsed:k,setSidebarCollapsed:S,forceCollapsed:l==="Quiz Battle"})})}),w&&b.jsxs(b.Fragment,{children:[b.jsx("button",{"aria-label":"Close navigation",className:"fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-[1px] lg:hidden",onClick:()=>T(!1)}),b.jsx("div",{className:"fixed inset-y-0 left-0 z-50 p-3 lg:hidden",children:b.jsx(h.Suspense,{fallback:u,children:b.jsx(Nu,{mode:"mobile",onRequestClose:()=>T(!1),activeTab:l,setActiveTab:Z,userRole:n,onOpenSettings:()=>{be(!0),T(!1)},onLogout:()=>{Y(!0),T(!1)},sidebarCollapsed:!1})})})]}),b.jsxs("div",{className:"flex-1 min-h-0 flex flex-col min-w-0 bg-gradient-to-br from-indigo-200 via-fuchsia-50 to-orange-100 relative z-10 shadow-[rgba(124,58,237,0.05)_0px_0px_30px_inset]",children:[b.jsx("div",{className:"absolute inset-0 bg-math-pattern opacity-30 pointer-events-none mix-blend-multiply z-0"}),b.jsxs("header",{className:"bg-white/90 backdrop-blur-md border-b border-[#dde3eb] px-3 sm:px-6 py-2 sm:py-3 flex flex-row items-center justify-between gap-2 sm:gap-3 sticky top-0 z-30 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[b.jsx("button",{className:"lg:hidden p-2 rounded-xl bg-[#edf1f7] hover:bg-[#dde3eb] text-[#5a6578] hover:text-primary transition-colors",onClick:()=>T(!0),"aria-label":"Open navigation",children:b.jsx(Bx,{size:20})}),b.jsxs("div",{className:"min-w-0",children:[b.jsx("h1",{className:"text-base sm:text-xl font-display font-bold text-[#0a1628] leading-tight truncate",children:l==="Grades"?"Assessment":l==="Leaderboard"?"Leadership Board":l}),b.jsxs("p",{className:"hidden sm:block text-xs text-[#5a6578] font-body truncate",children:["Welcome back, ",Ke.name.split(" ")[0],"!"]})]}),b.jsxs("div",{className:"hidden md:flex items-center gap-2 ml-2",children:[b.jsxs("button",{onClick:()=>W(!0),className:"flex items-center gap-1.5 px-3 py-1.5 bg-rose-50 hover:bg-rose-100 border border-rose-200/60 rounded-lg transition-colors cursor-pointer group",title:"View Rewards & Progress",children:[b.jsx(mr,{className:"h-3.5 w-3.5 text-rose-500","aria-hidden":"true"}),b.jsxs("span",{className:"text-xs font-display font-bold text-rose-700",children:["Lv ",V]})]}),b.jsxs("button",{onClick:()=>W(!0),className:"flex items-center gap-2 px-3 py-1.5 bg-violet-50 hover:bg-violet-100 border border-violet-200/60 rounded-lg transition-colors cursor-pointer w-[180px] xl:w-[200px] justify-between",title:`${ce}/${ie} XP to next level`,children:[b.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b.jsx(Ci,{className:"h-3.5 w-3.5 text-violet-500","aria-hidden":"true"}),b.jsxs("span",{className:"text-xs font-display font-bold text-violet-700 whitespace-nowrap",children:[H," XP"]})]}),b.jsx("div",{className:"h-1.5 flex-1 min-w-0 bg-violet-100 rounded-full overflow-hidden",children:b.jsx("div",{className:"h-full bg-violet-500 rounded-full transition-all e-w",style:{"--w":`${Math.max(0,Math.min(100,ce/ie*100))}%`}})})]}),b.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-orange-50 border border-orange-200/60 rounded-lg",children:[b.jsx(gr,{className:"h-3.5 w-3.5 text-orange-500","aria-hidden":"true"}),b.jsx("span",{className:"text-xs font-display font-bold text-orange-700",children:"Daily Rewards"})]})]})]}),b.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 shrink-0",children:[b.jsx("button",{onClick:()=>Qn(E=>!E),className:"p-3 rounded-xl bg-[#edf1f7] hover:bg-[#dde3eb] text-[#5a6578] hover:text-primary transition-all group",title:"Scientific Calculator (Alt+K)",children:b.jsx(Px,{size:20,className:"group-hover:scale-110 transition-transform"})}),b.jsx(h.Suspense,{fallback:c,children:b.jsx(eR,{})}),b.jsxs("button",{onClick:()=>it(!0),className:"flex items-center gap-2.5 h-11 shrink-0 bg-[#edf1f7] hover:bg-[#dde3eb] p-1.5 pr-3 rounded-lg cursor-pointer transition-all group","aria-label":`Profile: ${Ke.name}`,children:[b.jsx(kA,{src:Ke.photo,name:Ke.name,className:"w-8 h-8 rounded-lg"}),b.jsx("div",{className:"hidden sm:block text-left min-w-0 flex-1",children:b.jsx("p",{className:"text-sm font-semibold text-[#0a1628] leading-none group-hover:text-primary transition-colors font-body truncate",children:Ns})})]})]})]}),b.jsx("main",{ref:v,className:`flex-1 min-h-0 ${l==="AI Chat"||l==="Modules"?"overflow-hidden p-0":"p-3 lg:p-4 overflow-y-auto pb-24 sm:pb-28"}`,children:b.jsx(Uf,{mode:"wait",children:b.jsx(Nn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.25,ease:[.22,1,.36,1]},className:l==="AI Chat"||l==="Modules"?"h-full min-h-0":"",children:l==="Dashboard"?b.jsx("div",{className:"px-4 sm:px-6 xl:px-10 py-6 sm:py-8",children:b.jsxs("div",{className:"grid grid-cols-12 gap-6 sm:gap-8 lg:gap-10",children:[b.jsxs("div",{className:"col-span-12 xl:col-span-9 flex flex-col gap-10 lg:gap-14 pt-0",children:[b.jsx(h.Suspense,{fallback:d,children:b.jsx(XA,{userName:Ns,userLevel:V,avatarLayers:Ke.avatarLayers,onContinueLearning:()=>Z("Modules"),showAssessmentTooltip:!Zt&&Zt!==null,onOpenAssessment:kp,studentId:t?.uid,assessmentCompleted:Zt===!0})}),Wt&&Zt&&oo.length>0&&b.jsxs("div",{className:"rounded-2xl border border-amber-300 bg-amber-50 px-5 py-4 shadow-sm dark:border-amber-400/40 dark:bg-amber-400/10",children:[b.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[b.jsxs("div",{children:[b.jsxs("p",{className:"inline-flex items-center gap-2 text-sm font-black text-amber-900 dark:text-amber-200",children:[b.jsx(Ei,{className:"h-4 w-4"}),"Assessment Focus Review"]}),b.jsx("p",{className:"mt-1 text-sm text-amber-900/85 dark:text-amber-100/90",children:"Your latest diagnostic flagged these topics for review. Modules are prioritized based on this focus order."})]}),b.jsxs("button",{type:"button",onClick:()=>Z("Modules"),className:"inline-flex items-center gap-1.5 rounded-xl bg-amber-600 px-3 py-2 text-xs font-bold text-white transition-colors hover:bg-amber-700",children:["Open Modules",b.jsx(bx,{className:"h-3.5 w-3.5"})]})]}),b.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:io.map((E,M)=>b.jsxs("span",{className:"rounded-full bg-white/90 px-3 py-1 text-xs font-semibold text-amber-900 shadow-sm dark:bg-amber-100/20 dark:text-amber-100",children:[M+1,". ",TA[E]]},E))})]}),Wt&&(P?.flaggedTopics?.length||rt.length>0)&&b.jsx(h.Suspense,{fallback:a,children:b.jsx(tR,{flaggedTopics:P?.flaggedTopics||[],atRiskSubjects:rt,moduleStatusMap:X,studentId:t?.uid,onTopicClick:E=>{Z("Modules",E)},onNavigateToPrerequisite:E=>{Z("Modules",E)}})}),Yn&&Wt&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(nR,{modules:He,onNavigateToModules:E=>Z("Modules",E),atRiskSubjects:rt,priorityTopics:io})})}),Yn&&Wt&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(sR,{})})})]}),b.jsx("div",{className:"col-span-12 xl:col-span-3 pt-2",children:Wt?b.jsx(h.Suspense,{fallback:d,children:b.jsx(YA,{currentUserId:t?.uid||"",onOpenRewards:()=>W(!0),onOpenLeaderboard:()=>f("Leaderboard"),onNavigateToModules:()=>f("Modules"),onNavigateToQuizBattle:()=>Z("Quiz Battle"),userLevel:V,userPhoto:Ke.photo,currentXP:ce,xpToNextLevel:ie,overallXP:H,userName:Ns})}):d})]})}):l==="Modules"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(rR,{onEarnXP:Cp,atRiskSubjects:rt,priorityTopics:io,initialModuleId:Gt,isInQuizMode:Os,setIsInQuizMode:En,hasCompletedDiagnostic:Zt??!1})}):l==="Leaderboard"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(aR,{currentUserPhoto:Ke.photo})}):l==="Quiz Battle"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(cR,{})}):l==="AI Chat"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(oR,{})}):l==="Grades"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(iR,{})}):l==="Avatar Studio"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(lR,{onSaveProfile:E=>{$e(M=>({...M,avatarLayers:E}))},onNavigateToModules:()=>Z("Modules"),unsavedChangesRef:p,pendingNavigation:m,onConfirmLeave:()=>{const E=m;g(null),E&&setTimeout(()=>Z(E),0)},onCancelNavigation:()=>g(null)})}):b.jsxs("div",{className:"flex-1 flex items-center justify-center text-[#a8a5b3] font-medium font-body",children:[l," Content Coming Soon"]})},l)})}),l!=="AI Chat"&&!Os&&b.jsx(h.Suspense,{fallback:null,children:b.jsx("div",{className:"fixed bottom-4 right-4 sm:bottom-8 sm:right-8 z-50",children:b.jsx(uR,{constraintsRef:y,onFullScreen:Ep})})}),b.jsx(h.Suspense,{fallback:null,children:b.jsx(JA,{xp:O.xp,message:O.message,show:O.show,onComplete:()=>le(E=>({...E,show:!1}))})}),ue&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(dR,{isOpen:ue,onClose:()=>W(!1),userLevel:V,currentXP:ce,xpToNextLevel:ie,totalXP:te,userId:t?.uid||""})}),Ae&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ko,{isOpen:Ae,onClose:()=>it(!1),profileData:Ke,onSave:Rn})}),Te&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(fR,{isOpen:Te,onClose:()=>Y(!1),onConfirm:ao,title:"Confirm Logout",message:"Are you sure you want to log out? Your progress is saved automatically.",confirmText:"Logout",cancelText:"Stay",type:"warning",icon:"logout"})}),Ne&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Qo,{isOpen:Ne,onClose:()=>be(!1),profileData:Ke,onSave:Rn,settingsData:cn,onSaveSettings:co,onApplySettingsPreview:kt,onExportData:lo,onClearCache:uo,onResetData:fo})}),at&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(hR,{isOpen:at,onClose:()=>Qn(!1)})}),Ls&&!Cn&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(pR,{isOpen:Ls&&!Cn,onClose:()=>Ht(!1),onDismiss:()=>{Ht(!1),un(!0)},userId:t?.uid||"",strand:P?.major||"STEM",gradeLevel:P?.grade||"Grade 11",onAssessmentStart:Pp,onAssessmentComplete:Qa})}),Cn&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(mR,{testId:Fe,questions:Me,userName:Ns,onComplete:Qa,onCancel:()=>{Q(!1),f("Dashboard")}})}),Pe&&t?.uid&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(gR,{userId:t.uid,mode:"fullscreen",onClose:()=>{Re(!1),f("Dashboard")}})})]})]})}),b.jsx($o,{position:"top-right",richColors:!0,closeButton:!0})]})});return b.jsx(G_,{children:Ap})},sr="mathpulse_chunk_reload_attempted",bR=[/Failed to fetch dynamically imported module/i,/Loading chunk \d+ failed/i,/Importing a module script failed/i,/error loading dynamically imported module/i];function $u(e){return e?.message?bR.some(t=>t.test(e.message)):!1}class vR extends h.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){if(console.error("[ErrorBoundary] Caught render error:",t.message,n.componentStack),$u(t))try{sessionStorage.getItem(sr)||(sessionStorage.setItem(sr,String(Date.now())),console.warn("[ErrorBoundary] Stale chunk detected — reloading to recover."),window.location.reload())}catch{}}handleReset=()=>{try{sessionStorage.removeItem(sr)}catch{}this.setState({hasError:!1,error:null})};render(){if(this.state.hasError){if($u(this.state.error)){let t=!1;try{t=!!sessionStorage.getItem(sr)}catch{}if(!t)return null}return this.props.fallback?this.props.fallback:b.jsx("div",{className:"flex min-h-screen flex-col items-center justify-center bg-slate-50 p-8 text-center",children:b.jsxs("div",{className:"max-w-md rounded-xl border border-slate-200 bg-white p-8 shadow-sm",children:[b.jsx("h2",{className:"mb-2 text-xl font-semibold text-slate-900",children:"Something went wrong"}),b.jsx("p",{className:"mb-6 text-sm text-slate-600",children:"The application encountered an unexpected error. Please try refreshing the page."}),this.state.error&&b.jsx("pre",{className:"mb-6 max-h-24 overflow-auto rounded bg-red-50 p-3 text-left text-xs text-red-700",children:this.state.error.message}),b.jsx("button",{onClick:this.handleReset,className:"rounded-lg bg-blue-600 px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Try again"}),b.jsx("button",{onClick:()=>window.location.reload(),className:"ml-3 rounded-lg border border-slate-300 bg-white px-6 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50",children:"Refresh page"})]})})}return this.props.children}}dC();try{sessionStorage.removeItem("mathpulse_chunk_reload_attempted")}catch{}typeof window<"u"&&(window.addEventListener("error",e=>{console.error("[global] Uncaught error:",e.error?.message??e.message)}),window.addEventListener("unhandledrejection",e=>{console.error("[global] Unhandled promise rejection:",e.reason?.message??e.reason),e.preventDefault()}));{const e=(...t)=>{};console.log=e,console.info=e,console.debug=e}const Sp=document.getElementById("root");if(!Sp)throw new Error("Root element not found");Mp.createRoot(Sp).render(b.jsx(vR,{children:b.jsx(sy,{children:b.jsx(jm,{client:$i,children:b.jsx(q_,{children:b.jsx(yR,{})})})})}));export{gr as $,Dl as A,Tx as B,Px as C,sS as D,sM as E,$l as F,Ll as G,Ol as H,RA as I,uS as J,ns as K,Fx as L,Bx as M,Sx as N,kA as O,QE as P,xn as Q,qx as R,jr as S,Nl as T,oS as U,zl as V,vA as W,zu as X,wA as Y,Ci as Z,ee as _,bx as a,mC as a$,IR as a0,Dx as a1,Ws as a2,lM as a3,cM as a4,VR as a5,mr as a6,Hx as a7,qo as a8,ep as a9,Yo as aA,Vu as aB,Mm as aC,vm as aD,Xe as aE,MR as aF,$R as aG,VA as aH,BA as aI,XE as aJ,BR as aK,FR as aL,fS as aM,sh as aN,La as aO,UR as aP,U_ as aQ,KP as aR,zx as aS,Ax as aT,Kx as aU,OR as aV,Pu as aW,Eu as aX,tM as aY,nM as aZ,pC as a_,gC as aa,_A as ab,oM as ac,WR as ad,QR as ae,KR as af,ZR as ag,HR as ah,XR as ai,No as aj,qR as ak,jA as al,$A as am,GR as an,iM as ao,LE as ap,TA as aq,$r as ar,km as as,gm as at,RR as au,Jo as av,wt as aw,qu as ax,pm as ay,mm as az,Oo as b,yr as b0,JR as b1,YR as b2,eM as b3,Ut as b4,eo as b5,uP as b6,pS as b7,tC as b8,rM as b9,aM as ba,zR as c,jR as d,he as e,Jh as f,L as g,Uf as h,Fl as i,ct as j,ye as k,ZE as l,Nn as m,bt as n,bn as o,It as p,Nx as q,jl as r,LR as s,Yh as t,Ms as u,xA as v,j as w,NR as x,Ei as y,sC as z}; +`);if(!F){x=T(k);continue}if(P==="chunk"){let H=F;try{const re=JSON.parse(F);typeof re?.chunk=="string"&&(H=re.chunk)}catch{}H&&(S+=H,n(H),f())}else if(P==="error"){let H="Streaming failed on server.";try{const re=JSON.parse(F);typeof re?.detail=="string"&&re.detail.trim()&&(H=re.detail)}catch{F.trim()&&(H=F.trim())}throw new Error(H)}x=T(k)}}if(w)return{response:S};throw new Error("Stream closed before end event.")}catch(y){throw a==="idle"?new xn("/api/chat/stream",Su):a==="total"?new xn("/api/chat/stream",Bo):y instanceof DOMException&&y.name==="AbortError"?new xn("/api/chat/stream",Bo):y}finally{if(l(),g)try{await g.cancel()}catch{}}}return await j("/api/chat",{method:"POST",body:JSON.stringify(r)},zE)},async chatSafe(e,t,n){return ss(()=>bt.chat(e,t,void 0,n),FE,"chat")},async predictRisk(e){Se("/api/predict-risk",{engagementScore:e.engagementScore,avgQuizScore:e.avgQuizScore,attendance:e.attendance,assignmentCompletion:e.assignmentCompletion}),De("/api/predict-risk","engagementScore",e.engagementScore,0,100),De("/api/predict-risk","avgQuizScore",e.avgQuizScore,0,100),De("/api/predict-risk","attendance",e.attendance,0,100),De("/api/predict-risk","assignmentCompletion",e.assignmentCompletion,0,100);const t=await j("/api/predict-risk",{method:"POST",body:JSON.stringify(e)});if(!GE(t))throw Be("/api/predict-risk","POST","Invalid response shape",t),new Error("Invalid risk prediction response from server");return t},async predictRiskSafe(e){return ss(()=>bt.predictRisk(e),VE,"predictRisk")},async predictRiskBatch(e){if(!Array.isArray(e)||e.length===0)throw new Ve("/api/predict-risk/batch","students array must not be empty");return j("/api/predict-risk/batch",{method:"POST",body:JSON.stringify({students:e})})},async getLearningPath(e){if(Se("/api/learning-path",{weaknesses:e.weaknesses,gradeLevel:e.gradeLevel}),!Array.isArray(e.weaknesses)||e.weaknesses.length===0)throw new Ve("/api/learning-path","weaknesses must be a non-empty array");return j("/api/learning-path",{method:"POST",body:JSON.stringify(e)},Yt)},async getLearningPathSafe(e){return ss(()=>bt.getLearningPath(e),BE,"getLearningPath")},async getDailyInsight(e,t){if(!Array.isArray(e.students)||e.students.length===0)throw new Ve("/api/analytics/daily-insight","students array must not be empty");return j("/api/analytics/daily-insight",{method:"POST",body:JSON.stringify(e),signal:t?.signal},Yt)},async getDailyInsightSafe(e){return ss(()=>bt.getDailyInsight(e),UE,"getDailyInsight")},async getImportedClassOverview(e){if(!e?.forceRefresh&&!Uo&&Date.now()!r||r.size===0))throw new Ve("/api/upload/class-records","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new Ve("/api/upload/class-records","One or more files exceed the 10 MB size limit");const s=new FormData;return n.forEach(r=>s.append("files",r)),t?.classSectionId&&s.append("classSectionId",t.classSectionId),t?.className&&s.append("className",t.className),s.append("datasetIntent",t?.datasetIntent??"synthetic_student_records"),j("/api/upload/class-records",{method:"POST",body:s},rs)},async downloadClassRecordTemplate(e){const t=new URLSearchParams;e?.quarter&&t.set("quarter",e.quarter),e?.school_year&&t.set("school_year",e.school_year),e?.subject&&t.set("subject",e.subject);const n=t.toString();return Tu(`/api/templates/class-records${n?`?${n}`:""}`,{method:"GET"},3e4)},async uploadClassRecordTemplate(e,t){if(!e||e.size===0)throw new Ve("/api/class-records/upload","File must be non-empty");if(e.size>10*1024*1024)throw new Ve("/api/class-records/upload","File exceeds the 10 MB size limit");const n=new FormData;return n.append("file",e),t?.subject&&n.append("subject",t.subject),t?.quarter&&n.append("quarter",t.quarter),t?.gradeLevel&&n.append("gradeLevel",t.gradeLevel),j("/api/class-records/upload",{method:"POST",body:n},rs)},async previewStudentAccountImport(e,t){if(!e||e.size===0)throw new Ve("/api/import/student-accounts/preview","A non-empty file is required");if(e.size>10*1024*1024)throw new Ve("/api/import/student-accounts/preview","File exceeds 10 MB size limit");const n=new FormData;return n.append("file",e),t?.classSectionId&&n.append("classSectionId",t.classSectionId),t?.className&&n.append("className",t.className),t?.defaultGrade&&n.append("defaultGrade",t.defaultGrade),t?.defaultSection&&n.append("defaultSection",t.defaultSection),j("/api/import/student-accounts/preview",{method:"POST",body:n},rs)},async commitStudentAccountImport(e){return Se("/api/import/student-accounts/commit",{previewToken:e.previewToken}),j("/api/import/student-accounts/commit",{method:"POST",body:JSON.stringify(e)},Et)},async createStudentAccount(e){Se("/api/teacher/create-student-account",{name:e.name,email:e.email,temporaryPassword:e.temporaryPassword,adviserTeacherId:e.adviserTeacherId});const t={name:e.name,email:e.email,temporary_password:e.temporaryPassword,lrn:e.lrn??null,grade:e.grade??null,section:e.section??null,class_section_id:e.classSectionId??null,adviser_teacher_id:e.adviserTeacherId,adviser_teacher_name:e.adviserTeacherName??null,school_year:e.schoolYear??null};return j("/api/teacher/create-student-account",{method:"POST",body:JSON.stringify(t)},Et)},async getAdminUsers(e){const t=e?.page??1,n=e?.pageSize??25;De("/api/admin/users","page",t,1,1e4),De("/api/admin/users","pageSize",n,1,200);const s=new URLSearchParams;return s.set("page",String(t)),s.set("pageSize",String(n)),e?.search?.trim()&&s.set("search",e.search.trim()),e?.role?.trim()&&s.set("role",e.role.trim()),e?.status?.trim()&&s.set("status",e.status.trim()),e?.grade?.trim()&&s.set("grade",e.grade.trim()),e?.section?.trim()&&s.set("section",e.section.trim()),e?.classSectionId?.trim()&&s.set("classSectionId",e.classSectionId.trim()),j(`/api/admin/users?${s.toString()}`,{method:"GET"},jE)},async updateAdminUser(e,t){const n=e.trim();Se("/api/admin/users",{uid:n});const s=new URLSearchParams;return s.set("uid",n),j(`/api/admin/users?${s.toString()}`,{method:"PATCH",body:JSON.stringify(t)},Et)},async bulkAdminUsers(e){return Se("/api/admin/users/bulk-action",{action:e.action}),j("/api/admin/users/bulk-action",{method:"POST",body:JSON.stringify(e)},Et)},async createAdminUser(e){if(Se("/api/admin/users",{name:e.name,email:e.email,password:e.password,confirmPassword:e.confirmPassword,role:e.role,status:e.status,grade:e.grade,section:e.section}),e.role.trim().toLowerCase()==="student"&&!e.lrn?.trim())throw new Ve("/api/admin/users","lrn is required for student accounts");return j("/api/admin/users",{method:"POST",body:JSON.stringify(e)},Et)},async deleteAdminUser(e){const t=e.trim();Se("/api/admin/users",{uid:t});const n=new URLSearchParams;return n.set("uid",t),j(`/api/admin/users?${n.toString()}`,{method:"DELETE"},Et)},async getRiskRefreshMonitor(e){const t=e?.limit??10;De("/api/upload/class-records/risk-refresh/recent","limit",t,1,50);const n=new URLSearchParams;return n.set("limit",String(t)),e?.classSectionId&&n.set("classSectionId",e.classSectionId),j(`/api/upload/class-records/risk-refresh/recent?${n.toString()}`)},async getImportGroundedTelemetrySummary(e){const t=e?.days??7,n=e?.limit??5e3;De("/api/feedback/import-grounded/summary","days",t,1,30),De("/api/feedback/import-grounded/summary","limit",n,100,2e4);const s=new URLSearchParams;return s.set("days",String(t)),s.set("limit",String(n)),e?.classSectionId&&s.set("classSectionId",e.classSectionId),j(`/api/feedback/import-grounded/summary?${s.toString()}`)},async getImportGroundedAccessAudit(e){const t=e?.days??7,n=e?.limit??200;De("/api/import-grounded/access-audit","days",t,1,30),De("/api/import-grounded/access-audit","limit",n,1,1e3);const s=new URLSearchParams;return s.set("days",String(t)),s.set("limit",String(n)),s.set("export","json"),e?.classSectionId&&s.set("classSectionId",e.classSectionId),j(`/api/import-grounded/access-audit?${s.toString()}`)},async exportImportGroundedAccessAuditCsv(e){const t=e?.days??7,n=e?.limit??200;De("/api/import-grounded/access-audit","days",t,1,30),De("/api/import-grounded/access-audit","limit",n,1,1e3);const s=new URLSearchParams;return s.set("days",String(t)),s.set("limit",String(n)),s.set("export","csv"),e?.classSectionId&&s.set("classSectionId",e.classSectionId),Tu(`/api/import-grounded/access-audit?${s.toString()}`,{method:"GET"},3e4)},async uploadCourseMaterials(e,t){const n=Array.isArray(e)?e:[e];if(n.length===0)throw new Ve("/api/upload/course-materials","At least one file is required");if(n.some(r=>!r||r.size===0))throw new Ve("/api/upload/course-materials","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new Ve("/api/upload/course-materials","One or more files exceed the 10 MB size limit");const s=new FormData;return n.forEach(r=>s.append("files",r)),t?.classSectionId&&s.append("classSectionId",t.classSectionId),t?.className&&s.append("className",t.className),j("/api/upload/course-materials",{method:"POST",body:s},rs)},async uploadTeacherMaterial(e,t){const n=new FormData;return n.append("file",e),t?.teacherId&&n.append("teacherId",t.teacherId),t?.classId&&n.append("classId",t.classId),t?.gradeLevel&&n.append("gradeLevel",t.gradeLevel),t?.subject&&n.append("subject",t.subject),t?.quarter&&n.append("quarter",t.quarter),t?.strandOrTrack&&n.append("strandOrTrack",t.strandOrTrack),j("/api/teacher-materials/upload",{method:"POST",body:n},rs)},async getRecentCourseMaterials(e){const t=e?.limit??10;De("/api/upload/course-materials/recent","limit",t,1,50);const n=new URLSearchParams;return n.set("limit",String(t)),e?.classSectionId&&n.set("classSectionId",e.classSectionId),j(`/api/upload/course-materials/recent?${n.toString()}`)},async getCourseMaterialTopics(e){const t=e?.limit??20;De("/api/course-materials/topics","limit",t,1,50);const n=new URLSearchParams;return n.set("limit",String(t)),e?.classSectionId&&n.set("classSectionId",e.classSectionId),e?.materialId&&n.set("materialId",e.materialId),j(`/api/course-materials/topics?${n.toString()}`)},async generateLessonPlan(e){Se("/api/lesson/generate",{gradeLevel:e.gradeLevel});const t={...e,preferImportedTopics:vu&&(e.preferImportedTopics??!0)};if(xu){const n=await bt.submitLessonPlanAsync(t),r=(await bt.waitForTaskResult(n.taskId,{timeoutMs:24e4,pollIntervalMs:1500})).result;if(!r||typeof r!="object")throw new Error("Lesson generation completed without a valid result payload.");return r}return j("/api/lesson/generate",{method:"POST",body:JSON.stringify(t)},Yt)},async generateQuiz(e,t){if(Se("/api/quiz/generate",{topics:e.topics,gradeLevel:e.gradeLevel}),!Array.isArray(e.topics)||e.topics.length===0)throw new Ve("/api/quiz/generate","topics must be a non-empty array");const n={...e,preferImportedTopics:Vo&&(e.preferImportedTopics??!0)};if(xu){const r=await bt.submitQuizAsync(n);t?.onTaskCreated?.(r.taskId);const i=(await bt.waitForTaskResult(r.taskId,{timeoutMs:24e4,pollIntervalMs:1500,onProgress:t?.onProgress})).result;if(!i||typeof i!="object")throw new Error("Quiz generation completed without a valid result payload.");if(!_u(i))throw new Error("Invalid quiz generation response from async task payload.");return i}const s=await j("/api/quiz/generate",{method:"POST",body:JSON.stringify(n)},Yt);if(!_u(s))throw Be("/api/quiz/generate","POST","Invalid response shape",s),new Error("Invalid quiz generation response from server");return s},async previewQuiz(e){Se("/api/quiz/preview",{topics:e.topics,gradeLevel:e.gradeLevel});const t={...e,preferImportedTopics:Vo&&(e.preferImportedTopics??!0)};return j("/api/quiz/preview",{method:"POST",body:JSON.stringify(t)},Yt)},async submitLessonPlanAsync(e){return j("/api/lesson/generate-async",{method:"POST",body:JSON.stringify(e)},Yt)},async submitQuizAsync(e){return j("/api/quiz/generate-async",{method:"POST",body:JSON.stringify(e)},Yt)},async getTaskStatus(e){return Se("/api/tasks/{taskId}",{taskId:e}),j(`/api/tasks/${encodeURIComponent(e)}`)},async listTasks(e){const t=new URLSearchParams;e?.limit!=null&&(De("/api/tasks","limit",e.limit,1,200),t.set("limit",String(e.limit))),e?.status&&t.set("status",e.status),e?.includeResults!=null&&t.set("include_results",String(e.includeResults));const n=t.toString();return j(`/api/tasks${n?`?${n}`:""}`)},async cancelTask(e){return Se("/api/tasks/{taskId}/cancel",{taskId:e}),j(`/api/tasks/${encodeURIComponent(e)}/cancel`,{method:"POST"})},async waitForTaskResult(e,t){const n=t?.timeoutMs??18e4,s=t?.pollIntervalMs??1500,r=Date.now();for(;Date.now()-r<=n;){const o=await bt.getTaskStatus(e);if(t?.onProgress?.(o),o.status==="completed")return o;if(o.status==="failed"||o.status==="cancelled")throw new Error(HE(o.error));await WE(s)}throw new Error(`Async generation task timed out after ${Math.round(n/1e3)} seconds.`)},async getQuizTopics(e){const t=e?`?gradeLevel=${encodeURIComponent(e)}`:"";return j(`/api/quiz/topics${t}`)},async getStudentCompetency(e,t){return Se("/api/quiz/student-competency",{studentId:e}),j("/api/quiz/student-competency",{method:"POST",body:JSON.stringify({studentId:e,quizHistory:t})})},async evaluateExpression(e){return Se("/api/calculator/evaluate",{expression:e}),j("/api/calculator/evaluate",{method:"POST",body:JSON.stringify({expression:e})})},async evaluateExpressionSafe(e){return ss(()=>bt.evaluateExpression(e),{...qE,expression:e},"evaluateExpression")},async automationDiagnosticCompleted(e){return Se("/api/automation/diagnostic-completed",{lrn:e.lrn,results:e.results}),j("/api/automation/diagnostic-completed",{method:"POST",body:JSON.stringify(e)})},async automationQuizSubmitted(e){return Se("/api/automation/quiz-submitted",{lrn:e.lrn,quizId:e.quizId,subject:e.subject}),j("/api/automation/quiz-submitted",{method:"POST",body:JSON.stringify(e)})},async automationStudentEnrolled(e){return Se("/api/automation/student-enrolled",{lrn:e.lrn,name:e.name,email:e.email}),j("/api/automation/student-enrolled",{method:"POST",body:JSON.stringify(e)})},async automationDataImported(e){return Se("/api/automation/data-imported",{teacherId:e.teacherId,students:e.students}),j("/api/automation/data-imported",{method:"POST",body:JSON.stringify(e)})},async automationContentUpdated(e){return Se("/api/automation/content-updated",{adminId:e.adminId,action:e.action,contentType:e.contentType,contentId:e.contentId}),j("/api/automation/content-updated",{method:"POST",body:JSON.stringify(e)})},getInferenceMetrics:async()=>j("/api/ops/inference-metrics",{method:"GET"}),getModelConfig:async()=>j("/api/admin/model-config",{method:"GET"}),setModelProfile:async e=>j("/api/admin/model-config/profile",{method:"POST",body:JSON.stringify({profile:e})}),setModelOverride:async(e,t)=>j("/api/admin/model-config/override",{method:"POST",body:JSON.stringify({key:e,value:t})}),resetModelConfig:async()=>j("/api/admin/model-config/reset",{method:"DELETE"}),uploadModulePdf:async e=>{const t=ye.currentUser,n=t?await t.getIdToken():void 0,s=await fetch(`${Ss}/api/admin/upload-pdf`,{method:"POST",headers:n?{Authorization:`Bearer ${n}`}:{},body:e});if(!s.ok){const r=await s.json().catch(()=>({detail:"Upload failed"}));throw new Error(r.detail||`Upload failed (${s.status})`)}return s.json()},reingestModulePdf:async(e,t)=>{const n=ye.currentUser?await ye.currentUser.getIdToken():void 0;return j("/api/admin/reingest-pdf",{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({subjectId:e,storagePath:t})})},getRagHealth:async()=>j("/api/rag/health",{method:"GET"}),adminDeleteFile:async(e,t)=>j("/api/admin/delete-file",{method:"POST",body:JSON.stringify({fileId:e,collection:t})}),async generateInterventionPlan(e){return j("/api/class-records/intervention-plan",{method:"POST",body:JSON.stringify(e)})},async fetchClassRecords(e){const t=new URLSearchParams;e?.limit&&t.set("limit",String(e.limit)),e?.after&&t.set("after",e.after);const n=t.toString();return j(`/api/class-records${n?`?${n}`:""}`,{method:"GET"})},async fetchQuizBattleResults(e){const t=new URLSearchParams;e?.classId&&t.set("classId",e.classId),e?.limit&&t.set("limit",String(e.limit)),e?.after&&t.set("after",e.after);const n=t.toString();return j(`/api/quiz-battle/results${n?`?${n}`:""}`,{method:"GET"})},async fetchUploadStudents(e,t){const n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.after&&n.set("after",t.after);const s=n.toString();return j(`/api/class-records/${e}/students${s?`?${s}`:""}`,{method:"GET"})},async generateClassReport(e){return j(`/api/class-records/${e}/ai-report`,{method:"POST"})},async generateQuizFromModule(e){return j(`/api/teacher-materials/${e}/generate-quiz`,{method:"POST"})},async getStudentRecommendations(e){return j(`/api/student/${e}/recommendations`,{method:"GET"})}};async function ZE(e,t,n,s){Se("/api/rag/lesson",{topic:e,subject:t,quarter:n}),De("/api/rag/lesson","quarter",n,1,4);const r=await j("/api/rag/lesson",{method:"POST",body:JSON.stringify({topic:e,subject:t,quarter:n,lessonTitle:s?.lessonTitle,learningCompetency:s?.learningCompetency,moduleUnit:s?.moduleUnit,learnerLevel:s?.learnerLevel})}),o=(r.sources||[]).map(i=>({...i,sourceFile:i.source_file||i.sourceFile,content:i.content||i.content,contentDomain:i.content_domain||i.contentDomain,chunkType:i.chunk_type||i.chunkType}));return{explanation:r.explanation,sources:o,retrievalConfidence:r.retrievalConfidence,retrievalBand:r.retrievalBand,retrievalQuery:r.retrievalQuery,needsReview:r.needsReview}}async function KE(e,t,n,s){Se("/api/rag/generate-problem",{topic:e,subject:t,quarter:n,difficulty:s}),De("/api/rag/generate-problem","quarter",n,1,4);const r=await j("/api/rag/generate-problem",{method:"POST",body:JSON.stringify({topic:e,subject:t,quarter:n,difficulty:s})}),o=(r.sources||[]).map(i=>({...i,sourceFile:i.source_file||i.sourceFile}));return{problem:r.problem,solution:r.solution,competencyReference:r.competencyReference,sources:o}}async function QE(e,t){return!Array.isArray(e)||e.length===0?"":(await j("/api/rag/analysis-context",{method:"POST",body:JSON.stringify({weakTopics:e,subject:t})})).curriculumContext||""}async function XE(e){const t=e?`?grade_level=${encodeURIComponent(e)}`:"";return j(`/api/curriculum/subjects${t}`)}async function YE(e){try{return await j(`/api/curriculum/subjects/${e}`)}catch{return null}}async function JE(e){try{return await j(`/api/curriculum/subjects/${e}/topics`)}catch{return[]}}async function eC(e,t){try{return await j(`/api/curriculum/subjects/${e}/topics/${t}`)}catch{return null}}const tC=Object.freeze(Object.defineProperty({__proto__:null,ApiError:It,ApiNetworkError:jr,ApiTimeoutError:xn,ApiValidationError:Ve,apiFetch:j,apiService:bt,fetchAnalysisCurriculumContext:QE,generateGroundedProblem:KE,generateRagLesson:DE,generateRagProblem:OE,getCurriculumGroundedLesson:ZE,getCurriculumSubject:YE,getCurriculumSubjects:XE,getCurriculumTopic:eC,getCurriculumTopics:JE,getRagAnalysisContext:LE,getRagHealth:IE,warmupBackend:$E},Symbol.toStringTag,{value:"Module"})),Gh="competencyProfiles",GR=async e=>{const t=U(L,Gh,e),n=await me(t);return n.exists()?n.data():null},nC=async(e,t)=>{const{strengths:n,weaknesses:s,borderline:r}=t.proficiencyProfile,o=n.length>0?n[0]:null,i=s.length>0?s[0]:null,a=t.proficiencyProfile.suggestedStartingModule,c={uid:e,lastAssessmentDate:ae(),lastAssessmentType:t.assessmentType,overallScore:t.rawScore,competencies:Object.fromEntries(Object.entries(t.competencyScores).map(([u,d])=>[u,{score:d.score,correct:d.correct,attempted:d.attempted,lastAttemptedAt:ae()}])),primaryWeakness:i,primaryStrength:o,suggestedModule:a,updatedAt:ae()};await Ce(U(L,Gh,e),c,{merge:!0})},eo=async e=>{const t={userId:e,subjects:{},lessons:{},quizAttempts:[],totalLessonsCompleted:0,totalQuizzesCompleted:0,averageScore:0,updatedAt:new Date};return await Ce(U(L,"progress",e),t),t},sC=async e=>{try{const t=U(L,"progress",e),n=await me(t);if(n.exists()){const s=n.data();return{...s,updatedAt:s.updatedAt?.toDate()||new Date}}return await eo(e)}catch(t){return console.error("Error getting user progress:",t),null}},WR=(e,t)=>{const n=U(L,"progress",e);return en(n,s=>{if(!s.exists()){t(null);return}const r=s.data();t({...r,updatedAt:r.updatedAt?.toDate?.()||new Date})},s=>{console.error("Error subscribing to user progress:",s),t(null)})},HR=async(e,t,n)=>{const s=Math.max(0,Math.min(100,n)),r=U(L,"progress",e);await Ce(r,{[`lessons.${t}.lessonId`]:t,[`lessons.${t}.progressPercent`]:s,updatedAt:ae()},{merge:!0})},ZR=async(e,t,n,s,r)=>{const o=U(L,"progress",e),i=await me(o);if(!i.exists())return 0;const c=i.data().subjects?.[t]?.modulesProgress?.[n];if(!c)return 0;const u=Math.max(1,s+r),d=c.lessonsCompleted?.length||0,l=c.quizzesCompleted?.length||0,f=Math.round((d+l)/u*100);return await Ce(o,{[`subjects.${t}.modulesProgress.${n}.progress`]:f,[`subjects.${t}.modulesProgress.${n}.lastAccessedAt`]:ae(),updatedAt:ae()},{merge:!0}),f},KR=async(e,t,n,s,r,o=50,i,a)=>{try{const c=U(L,"progress",e);let u=await me(c);u.exists()||(await eo(e),u=await me(c));const d=u.data(),l={lessonId:s,completed:!0,completedAt:new Date,timeSpent:r,...i!==void 0&&{quizCompleted:i},...a!==void 0&&{quizScore:a}};d.subjects||(d.subjects={}),d.subjects[t]||(d.subjects[t]={subjectId:t,progress:0,completedModules:0,totalModules:0,modulesProgress:{}});const f=d.subjects[t];f.modulesProgress[n]||(f.modulesProgress[n]={moduleId:n,subjectId:t,progress:0,lessonsCompleted:[],quizzesCompleted:[],startedAt:new Date,lastAccessedAt:new Date});const p=f.modulesProgress[n],m=!p.lessonsCompleted.includes(s);m&&(p.lessonsCompleted.push(s),p.lastAccessedAt=new Date),await Ce(c,{[`lessons.${s}`]:l,[`subjects.${t}.modulesProgress.${n}`]:p,...m&&{totalLessonsCompleted:fs(1)},updatedAt:ae()},{merge:!0}),await Wh(e,o,"lesson_complete",`Completed lesson: ${s}`),await Va(e);try{const{emitPipelineEvent:g,getStudentContext:y}=await ee(async()=>{const{emitPipelineEvent:k,getStudentContext:S}=await import("./pipelineService-h2NDr2Mk.js");return{emitPipelineEvent:k,getStudentContext:S}},__vite__mapDeps([11,3,1,2,4,5,6,7,8,9,10])),v=y();v&&g({student_id:e,event_type:"lesson",event_data:{lesson_id:s,is_completed:!0,time_spent_seconds:r},occurred_at:new Date().toISOString(),class_id:v.classId,teacher_id:v.teacherId})}catch{}}catch(c){throw console.error("Error completing lesson:",c),c}},QR=async(e,t,n,s,r,o)=>{try{const i=U(L,"progress",e);let a=await me(i);a.exists()||(await eo(e),a=await me(i));const c=a.data(),u={quizId:t,attemptNumber:(c.quizAttempts?.filter(l=>l.quizId===t).length||0)+1,score:s,completedAt:new Date,timeSpent:o,answers:r},d=!c.quizAttempts?.some(l=>l.quizId===t);await dt(i,{quizAttempts:[...c.quizAttempts||[],u],...d&&{totalQuizzesCompleted:fs(1)},updatedAt:ae()}),await Va(e)}catch(i){throw console.error("Error recording practice quiz:",i),i}},XR=async(e,t,n,s,r,o,i,a)=>{try{const c=U(L,"progress",e);let u=await me(c);u.exists()||(await eo(e),u=await me(c));const d=u.data(),l={quizId:s,attemptNumber:(d.quizAttempts?.filter(y=>y.quizId===s).length||0)+1,score:r,completedAt:new Date,timeSpent:i,answers:o},f=a!==void 0?a:Math.floor(r/100*100);d.subjects||(d.subjects={}),d.subjects[t]||(d.subjects[t]={subjectId:t,progress:0,completedModules:0,totalModules:0,modulesProgress:{}});const p=d.subjects[t];p.modulesProgress[n]||(p.modulesProgress[n]={moduleId:n,subjectId:t,progress:0,lessonsCompleted:[],quizzesCompleted:[],startedAt:new Date,lastAccessedAt:new Date});const m=p.modulesProgress[n],g=!m.quizzesCompleted.includes(s);g&&(m.quizzesCompleted.push(s),m.lastAccessedAt=new Date),await dt(c,{quizAttempts:[...d.quizAttempts||[],l],[`subjects.${t}.modulesProgress.${n}`]:m,...g&&{totalQuizzesCompleted:fs(1)},updatedAt:ae()}),await Wh(e,f,"quiz_complete",`Completed quiz: ${s} (Score: ${r}%)`),await Va(e);try{const{emitPipelineEvent:y,getStudentContext:v}=await ee(async()=>{const{emitPipelineEvent:S,getStudentContext:w}=await import("./pipelineService-h2NDr2Mk.js");return{emitPipelineEvent:S,getStudentContext:w}},__vite__mapDeps([11,3,1,2,4,5,6,7,8,9,10])),k=v();k&&y({student_id:e,event_type:"quiz",event_data:{quiz_id:s,score:r,source:"module_quiz",total_questions:o.length,correct_answers:o.filter(S=>S.isCorrect).length},occurred_at:new Date().toISOString(),class_id:k.classId,teacher_id:k.teacherId})}catch{}}catch(c){throw console.error("Error completing quiz:",c),c}},Wh=async(e,t,n,s)=>{try{const r=U(L,"users",e);let o=1;try{const u=(await me(r)).data();u?.xpMultiplier&&typeof u.xpMultiplier=="number"&&(o=u.xpMultiplier)}catch{}const i=Math.round(t*o);await dt(r,{currentXP:fs(i),totalXP:fs(i),updatedAt:ae()});const a=U(et(L,"xpActivities"));await Ce(a,{activityId:a.id,userId:e,type:n,xpEarned:i,description:s,timestamp:ae()})}catch(r){console.error("Error awarding XP:",r)}},Va=async e=>{try{const t=U(L,"progress",e),n=await me(t);if(!n.exists())return;const s=n.data(),r=s.quizAttempts||[],o=r.length>0?Math.round(r.reduce((c,u)=>c+u.score,0)/r.length):0,i={},a=s.subjects||{};for(const[c,u]of Object.entries(a)){const d=u.modulesProgress||{},l=Object.values(d);if(l.length>0){const f=Math.round(l.reduce((p,m)=>p+(m.progress||0),0)/l.length);i[`subjects.${c}.progress`]=f}}await Ce(t,{averageScore:o,...i,updatedAt:ae()},{merge:!0}),await rC(e,o)}catch(t){console.error("Error recalculating progress aggregates:",t)}},rC=async(e,t)=>{try{const{isAtRiskByScore:n}=await ee(async()=>{const{isAtRiskByScore:i}=await import("./riskEngine-DpxF1Vjk.js");return{isAtRiskByScore:i}},[]);let s=n(t);if(!s)try{const i=U(L,"managedStudents",e),a=await me(i);if(a.exists()){const c=a.data()?.riskStatus;c&&["intervene","critical","at_risk"].includes(c)&&(s=!0)}}catch{}const r=s?"High":"Low",o=U(L,"users",e);await Ce(o,{overallRisk:r,updatedAt:ae()},{merge:!0})}catch(n){console.error("Error syncing overallRisk:",n)}},yr={notifications:{emailNotifications:!0,pushNotifications:!0,soundEnabled:!0,notificationTypes:{quizReminders:!0,newContent:!0,achievements:!0,streakAlerts:!0,weeklySummary:!0},quietHours:{start:"22:00",end:"08:00"}},pushPreferences:{pushEnabled:!0,achievement:!0,quiz_battle:!0,daily_reward:!0,assignment:!0,grade_posted:!0,streak_reminder:!0,leaderboard:!0,system:!0},appearance:{darkMode:!1,fontSize:16,compactView:!1,reduceAnimations:!1},privacy:{profileVisibility:"everyone",showActivityStatus:!0,dataSharing:!0},learning:{dailyXpGoal:100,preferredStudyTime:"evening",autoPlayLessons:!1,showHints:!0,quizDifficultyPreference:"adaptive",studyReminderTime:"18:00"},adminPanel:{siteName:"MathPulse AI",siteDescription:"AI-Powered Mathematics Learning Platform",defaultLanguage:"English",maintenanceMode:!1,enforceStrongPasswords:!0,sessionTimeoutMinutes:60,aiTutorEnabled:!0,aiAutoRecommendations:!0,aiRiskAlertsEnabled:!0,gradingScale:"percentage",passingGrade:75,parentSummaryEmails:!0,teacherDigestEmails:!0,weeklyPlatformReport:!0,autoBackupEnabled:!1,backupFrequency:"weekly"}},oC=300*1e3,iC=1800*1e3,$i=new zm({defaultOptions:{queries:{staleTime:oC,gcTime:iC,retry:1,refetchOnWindowFocus:!1}}}),aC=async()=>{await $i.cancelQueries(),$i.clear()},Pu={quizDefaults:{timeLimitMinutes:30,passingScore:75,maxAttempts:3},classPreferences:{autoEnroll:!1,classVisibility:"public"},studentAnalyticsVisibility:!0,notifyOnSubmission:!0,notifyOnStudentActivity:!1},Eu={maintenanceMode:!1,defaultGradeLevel:"Grade 11",defaultCurriculum:"STEM",maxClassSize:50,auditLogVisible:!0,aiConfig:{modelName:"deepseek-chat",temperature:.7,endpoint:"https://api.deepseek.com"}},cC="preferences",Ba=()=>JSON.parse(JSON.stringify(yr)),Hh=e=>{const t=Ba();return e?{...t,...e,notifications:{...t.notifications,...e.notifications,notificationTypes:{...t.notifications.notificationTypes,...e.notifications?.notificationTypes},quietHours:{...t.notifications.quietHours,...e.notifications?.quietHours}},pushPreferences:{...t.pushPreferences,...e.pushPreferences},appearance:{...t.appearance,...e.appearance},privacy:{...t.privacy,...e.privacy},learning:{...t.learning,...e.learning},adminPanel:{...t.adminPanel,...e.adminPanel}}:t},Ua=e=>U(L,"users",e,"settings",cC),Zh=async e=>{const t=Ua(e),n=await me(t);if(!n.exists()){const s=Ba();return await Ce(t,{...s,createdAt:ae(),updatedAt:ae()}),s}return Hh(n.data())},lC=async(e,t)=>{const n=await Zh(e),s=Hh({...n,...t});return await Ce(Ua(e),{...s,updatedAt:ae()},{merge:!0}),s},Kh="mathpulse_appearance",uC=e=>{const t=document.documentElement;t.style.setProperty("--font-size",`${e.appearance.fontSize}px`),t.dataset.density=e.appearance.compactView?"compact":"comfortable",e.appearance.reduceAnimations?t.classList.add("reduced-motion"):t.classList.remove("reduced-motion"),e.appearance.darkMode?t.classList.add("smart-dark"):t.classList.remove("smart-dark");try{localStorage.setItem(Kh,JSON.stringify(e.appearance))}catch{}},dC=()=>{try{const e=localStorage.getItem(Kh);if(!e)return;const t=JSON.parse(e),n=document.documentElement;n.style.setProperty("--font-size",`${t.fontSize}px`),n.dataset.density=t.compactView?"compact":"comfortable",t.reduceAnimations&&n.classList.add("reduced-motion"),t.darkMode&&n.classList.add("smart-dark")}catch{}},fC=async()=>{try{if(await aC(),zP(),localStorage.clear(),sessionStorage.clear(),"caches"in window){const e=await caches.keys();await Promise.all(e.map(t=>caches.delete(t)))}}catch(e){throw console.error("Failed clearing client cache:",e),new Error("Unable to clear cache on this device.")}},hC=async e=>{const t=U(L,"users",e),n=await me(t),s=await me(Ua(e)),r=["progress","xpActivities","achievements","notifications","tasks","chatSessions","chatMessages"],o=await Promise.all(r.map(async i=>{const a=Dt(et(L,i),Rt("userId","==",e)),c=await Fn(a);return{collectionName:i,items:c.docs.map(u=>({id:u.id,...u.data()}))}}));return{exportedAt:new Date().toISOString(),user:n.exists()?{id:n.id,...n.data()}:null,settings:s.exists()?s.data():Ba(),collections:o.reduce((i,a)=>(i[a.collectionName]=a.items,i),{})}},qa=async e=>{const t=ye.currentUser;if(!t||!t.email)throw new Error("No user logged in");const n=em.credential(t.email,e);await tm(t,n)},YR=async(e,t)=>{if(await qa(e),!ye.currentUser)throw new Error("Re-auth failed");await Yp(ye.currentUser,t)},JR=async(e,t)=>{if(await qa(e),!ye.currentUser)throw new Error("Re-auth failed");await Xp(ye.currentUser,t)},eM=async(e,t)=>{if(await qa(e),!ye.currentUser)throw new Error("Re-auth failed");await Jp(ye.currentUser);try{const{deleteDoc:n}=await ee(async()=>{const{deleteDoc:s}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{deleteDoc:s}},__vite__mapDeps([1,2]));await n(U(L,"users",t))}catch{}},Qh=e=>U(L,"users",e,"settings","teacherPreferences"),pC=async e=>{const t=await me(Qh(e));return t.exists()?{...Pu,...t.data()}:{...Pu}},tM=async(e,t)=>{const n=await pC(e),s={...n,...t,quizDefaults:{...n.quizDefaults,...t.quizDefaults},classPreferences:{...n.classPreferences,...t.classPreferences}};return await Ce(Qh(e),{...s,updatedAt:ae()},{merge:!0}),s},Xh=()=>U(L,"system","config"),mC=async()=>{const e=await me(Xh());return e.exists()?{...Eu,...e.data()}:{...Eu}},nM=async e=>{const t=await mC(),n={...t,...e,aiConfig:{...t.aiConfig,...e.aiConfig}};return await Ce(Xh(),{...n,updatedAt:ae()},{merge:!0}),n};function Yh(e){const t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Jh(e){const t=Yh(e);return t.setHours(0,0,0,0),t}function gC(e){const t=Yh(e);return t.setHours(23,59,59,999),t}function Kn(){const e=ye.currentUser?.uid??null;return e||console.warn("[notificationFirestoreService] Skipping Firestore call — user not authenticated"),e}const yC=e=>{const t=e.data(),n=t.createdAt,s=n instanceof jn?n.toDate():n instanceof Date?n:new Date;return{id:e.id,userId:t.userId,type:t.type,title:t.title,message:t.message,isRead:t.isRead,createdAt:s,metadata:t.metadata,actionUrl:t.actionUrl}},bC=async e=>{if(!Kn())throw new Error("Cannot create notification — not authenticated");try{const n=U(et(L,"notifications",e.userId,"items")),s={userId:e.userId,type:e.type,title:e.title,message:e.message,isRead:!1,createdAt:ae(),...e.metadata?{metadata:e.metadata}:{},...e.actionUrl?{actionUrl:e.actionUrl}:{}};return await Ce(n,s),n.id}catch(n){throw console.error("[notificationFirestoreService] Error creating notification:",n),n}},vC=async(e,t)=>{if(Kn())try{const n=U(L,"notifications",e,"items",t),s=dt(n,{isRead:!0}).catch(i=>console.warn("[firestore] markAsRead subcollection skipped:",i)),r=U(L,"notifications",t),o=dt(r,{isRead:!0,read:!0}).catch(i=>console.warn("[firestore] markAsRead top-level skipped:",i));await Promise.all([s,o])}catch(n){throw console.error("[notificationFirestoreService] Error marking as read:",n),n}},wC=async e=>{if(Kn())try{const t=Dt(et(L,"notifications",e,"items"),Rt("isRead","==",!1)),s=(await Fn(t)).docs.map(r=>dt(r.ref,{isRead:!0}));try{const r=Dt(et(L,"notifications"),Rt("userId","==",e),Rt("read","==",!1)),o=await Fn(r);for(const i of o.docs)s.push(dt(i.ref,{isRead:!0,read:!0}))}catch(r){console.warn("[notificationFirestoreService] Top-level markAllAsRead skipped:",r)}await Promise.all(s)}catch(t){throw console.error("[notificationFirestoreService] Error marking all as read:",t),t}},xC=async(e,t)=>{try{const n=U(L,"notifications",e,"items",t),s=br(n).catch(i=>console.warn("[firestore] deleteNotification subcollection skipped:",i)),r=U(L,"notifications",t),o=br(r).catch(i=>console.warn("[firestore] deleteNotification top-level skipped:",i));await Promise.all([s,o])}catch(n){throw console.error("[notificationFirestoreService] Error deleting notification:",n),n}},SC=(e,t)=>{const n=Kn();if(!n||n!==e)return console.warn("[notificationFirestoreService] subscribeToNotifications skipped — auth UID mismatch or not signed in"),t([]),()=>{};const s=Dt(et(L,"notifications",e,"items"),Sn("createdAt","desc")),r=Dt(et(L,"notifications"),Rt("userId","==",e),Sn("createdAt","desc"));let o=[],i=[],a=!1,c=!1;const u=()=>{const f=new Map;for(const m of i)f.set(m.id,m);for(const m of o)f.set(m.id,m);const p=Array.from(f.values()).sort((m,g)=>g.createdAt.getTime()-m.createdAt.getTime());t(p)},d=en(s,f=>{o=f.docs.map(p=>yC(p)),a=!0,c&&u()},()=>{a=!0,c&&u()}),l=en(r,f=>{i=f.docs.map(p=>{const m=p.data(),g=m.createdAt,y=g instanceof jn?g.toDate():g instanceof Date?g:new Date;return{id:p.id,userId:m.userId,type:m.type||"message",title:m.title,message:m.message,isRead:m.isRead??m.read??!1,createdAt:y,metadata:m.metadata,actionUrl:m.actionUrl||m.link}}),c=!0,a&&u()},()=>{c=!0,a&&u()});return()=>{d(),l()}},kC=async e=>{if(!Kn())return!1;try{const t=new Date,n=Jh(t),s=gC(t),r=Dt(et(L,"notifications",e,"items"),Rt("type","==","daily_checkin"),Rt("createdAt",">=",n),Rt("createdAt","<=",s),Sn("createdAt","asc"),ks(1));return!(await Fn(r)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking daily check-in:",t),!1}},TC=async e=>{if(!Kn())return!1;try{const n=Jh(new Date),s=Dt(et(L,"notifications",e,"items"),Rt("type","==","streak_reminder"),Rt("createdAt",">=",n),Sn("createdAt","asc"),ks(1));return!(await Fn(s)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking reminder:",t),!1}};async function ep(e){try{await bC(e)}catch(t){console.error("[NotificationService] Failed to create notification:",t)}}function _C(e){const t=h.useRef(!1);h.useEffect(()=>{if(!e||t.current)return;t.current=!0,(async()=>{try{if(await kC(e)||await TC(e))return;await ep({userId:e,type:"streak_reminder",title:"Don't forget your daily check-in!",message:"Check in today to keep your streak alive and earn bonus XP."})}catch(s){console.error("[useDailyCheckInReminder] Error:",s)}})()},[e])}const tp=h.createContext(null),qo=({children:e})=>{const{currentUser:t,userProfile:n}=Ms(),[s,r]=h.useState([]),[o,i]=h.useState(!0),a=t?.uid??null,c=h.useRef([]);_C(n?.role==="student"?a:null),h.useEffect(()=>{if(!a)return r([]),i(!1),()=>{};i(!0);const m=SC(a,g=>{r(g),i(!1)});return()=>m()},[a]),h.useEffect(()=>{c.current=s},[s]);const u=h.useMemo(()=>s.filter(m=>!m.isRead).length,[s]),d=h.useCallback(async m=>{a&&await vC(a,m)},[a]),l=h.useCallback(async()=>{if(!a)return;const m=c.current;console.log("[markAllAsRead] prev count:",m.filter(g=>!g.isRead).length,"notifications:",m.length),r(g=>g.map(y=>y.isRead?y:{...y,isRead:!0})),console.log("[markAllAsRead] optimistic update applied, new count should be 0");try{await wC(a),console.log("[markAllAsRead] Firestore update succeeded")}catch(g){console.error("[markAllAsRead] Firestore update failed:",g),r(m)}},[a]),f=h.useCallback(async m=>{a&&await xC(a,m)},[a]),p=h.useMemo(()=>({notifications:s,unreadCount:u,isLoading:o,markAsRead:d,markAllAsRead:l,deleteNotification:f}),[s,u,o,d,l,f]);return b.jsx(tp.Provider,{value:p,children:e})},sM=()=>{const e=h.useContext(tp);if(!e)throw new Error("useNotifications must be used within a NotificationProvider");return e},Cu="/firebase-messaging-sw.js";let Go=null,Au=!1,Wo=!1;async function Ga(){if(!Au){try{Wo=await Bp()}catch{Wo=!1}Au=!0}return Wo?(Go||(Go=Up(Ut)),Go):null}async function PC(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.getRegistration(Cu);return e||await navigator.serviceWorker.register(Cu,{scope:"/"})}catch(e){return console.warn("[pushNotificationService] SW registration failed:",e),null}}async function np(e){if(!e||typeof window>"u"||typeof Notification>"u")return null;const t=await Ga();if(!t)return console.warn("[pushNotificationService] FCM not supported in this browser."),null;let n;try{if(Notification.permission==="granted")n="granted";else{if(Notification.permission==="denied")return null;n=await Notification.requestPermission()}}catch(i){return console.warn("[pushNotificationService] permission prompt failed:",i),null}if(n!=="granted")return null;const s="BCydYLOb7oDjcaIwvBq8VUbNE7AzIBSdNbPXHDvSBC9B_2COzlK16MlCLJbDmNynf0yFkx_ZvTLPQYlhiu-C91Q".trim();if(!s)return console.warn("[pushNotificationService] VITE_FIREBASE_VAPID_KEY missing — cannot fetch FCM token."),null;const r=await PC();if(!r)return null;let o=null;try{o=await Vp(t,{vapidKey:s,serviceWorkerRegistration:r})}catch(i){return console.warn("[pushNotificationService] getToken failed:",i),null}if(!o)return null;try{const i=U(L,"users",e,"fcmTokens",o),a={token:o,userId:e,platform:"web",userAgent:typeof navigator<"u"?navigator.userAgent:"",createdAt:ae(),updatedAt:ae(),active:!0};await Ce(i,a,{merge:!0})}catch(i){console.warn("[pushNotificationService] persisting token failed:",i)}return o}function sp(e){let t,n=!1;return Ga().then(s=>{n||!s||(t=Fp(s,e))}),()=>{n=!0,t?.()}}async function rp(e,t){if(!(!e||!t)){try{const n=U(L,"users",e,"fcmTokens",t);await dt(n,{active:!1,updatedAt:ae()})}catch(n){console.warn("[pushNotificationService] marking token inactive failed:",n)}try{const n=await Ga();n&&await $p(n)}catch(n){console.warn("[pushNotificationService] deleteToken failed:",n)}}}const rM=Object.freeze(Object.defineProperty({__proto__:null,deregisterPushToken:rp,onForegroundMessage:sp,requestPushPermissionAndRegister:np},Symbol.toStringTag,{value:"Module"})),EC={achievement:"achievement_unlocked",quiz_battle:"system_alert",daily_reward:"daily_checkin",assignment:"new_assignment",grade_posted:"quiz_result",streak_reminder:"streak_reminder",leaderboard:"system_alert",system:"system_alert"};function CC(e){return e?EC[e]??"system_alert":"system_alert"}function AC(){const{currentUser:e}=Ms(),t=Gi(),n=h.useRef(null),s=h.useRef(null);return h.useEffect(()=>{const o=e?.uid??null;if(s.current=o,!o)return;let i,a=!1;return(async()=>{const c=await np(o);a||(n.current=c,c&&(i=sp(u=>{const d=u.notification??{},l=u.data??{},f=d.title||l.title||"MathPulse AI",p=d.body||l.body||"",m=l.notificationType;ep({userId:o,type:CC(m),title:f,message:p,actionUrl:l.url,metadata:{...l,source:"fcm_foreground",fcmType:m??null}})})))})(),()=>{a=!0,i?.()}},[e?.uid]),h.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const o=i=>{const a=i.data;if(!a||a.type!=="NOTIFICATION_CLICK")return;const c=a.url||"/";try{const u=c.startsWith("http")?new URL(c).pathname:c;t(u)}catch{window.location.href=c}};return navigator.serviceWorker.addEventListener("message",o),()=>navigator.serviceWorker.removeEventListener("message",o)},[t]),{unregister:async()=>{const o=s.current,i=n.current;!o||!i||(await rp(o,i),n.current=null)}}}const Ho=()=>(AC(),null),RC=(e,t)=>{const n=new Array(e.length+t.length);for(let s=0;s({classGroupId:e,validator:t}),op=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Nr="-",Ru=[],IC="arbitrary..",DC=e=>{const t=LC(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return OC(i);const a=i.split(Nr),c=a[0]===""&&a.length>1?1:0;return ip(a,c,t)},getConflictingClassGroupIds:(i,a)=>{if(a){const c=s[i],u=n[i];return c?u?RC(u,c):c:u||Ru}return n[i]||Ru}}},ip=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const u=ip(e,t+1,o);if(u)return u}const i=n.validators;if(i===null)return;const a=t===0?e.join(Nr):e.slice(t).join(Nr),c=i.length;for(let u=0;ue.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),s=t.slice(0,n);return s?IC+s:void 0})(),LC=e=>{const{theme:t,classGroups:n}=e;return zC(n,t)},zC=(e,t)=>{const n=op();for(const s in e){const r=e[s];Wa(r,n,s,t)}return n},Wa=(e,t,n,s)=>{const r=e.length;for(let o=0;o{if(typeof e=="string"){NC(e,t,n);return}if(typeof e=="function"){$C(e,t,n,s);return}FC(e,t,n,s)},NC=(e,t,n)=>{const s=e===""?t:ap(t,e);s.classGroupId=n},$C=(e,t,n,s)=>{if(VC(e)){Wa(e(s),t,n,s);return}t.validators===null&&(t.validators=[]),t.validators.push(MC(n,e))},FC=(e,t,n,s)=>{const r=Object.entries(e),o=r.length;for(let i=0;i{let n=e;const s=t.split(Nr),r=s.length;for(let o=0;o"isThemeGetter"in e&&e.isThemeGetter===!0,BC=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),s=Object.create(null);const r=(o,i)=>{n[o]=i,t++,t>e&&(t=0,s=n,n=Object.create(null))};return{get(o){let i=n[o];if(i!==void 0)return i;if((i=s[o])!==void 0)return r(o,i),i},set(o,i){o in n?n[o]=i:r(o,i)}}},Fi="!",Mu=":",UC=[],Iu=(e,t,n,s,r)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:s,isExternal:r}),qC=e=>{const{prefix:t,experimentalParseClassName:n}=e;let s=r=>{const o=[];let i=0,a=0,c=0,u;const d=r.length;for(let g=0;gc?u-c:void 0;return Iu(o,p,f,m)};if(t){const r=t+Mu,o=s;s=i=>i.startsWith(r)?o(i.slice(r.length)):Iu(UC,!1,i,void 0,!0)}if(n){const r=s;s=o=>n({className:o,parseClassName:r})}return s},GC=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,s)=>{t.set(n,1e6+s)}),n=>{const s=[];let r=[];for(let o=0;o0&&(r.sort(),s.push(...r),r=[]),s.push(i)):r.push(i)}return r.length>0&&(r.sort(),s.push(...r)),s}},WC=e=>({cache:BC(e.cacheSize),parseClassName:qC(e),sortModifiers:GC(e),...DC(e)}),HC=/\s+/,ZC=(e,t)=>{const{parseClassName:n,getClassGroupId:s,getConflictingClassGroupIds:r,sortModifiers:o}=t,i=[],a=e.trim().split(HC);let c="";for(let u=a.length-1;u>=0;u-=1){const d=a[u],{isExternal:l,modifiers:f,hasImportantModifier:p,baseClassName:m,maybePostfixModifierPosition:g}=n(d);if(l){c=d+(c.length>0?" "+c:c);continue}let y=!!g,v=s(y?m.substring(0,g):m);if(!v){if(!y){c=d+(c.length>0?" "+c:c);continue}if(v=s(m),!v){c=d+(c.length>0?" "+c:c);continue}y=!1}const k=f.length===0?"":f.length===1?f[0]:o(f).join(":"),S=p?k+Fi:k,w=S+v;if(i.indexOf(w)>-1)continue;i.push(w);const T=r(v,y);for(let _=0;_0?" "+c:c)}return c},KC=(...e)=>{let t=0,n,s,r="";for(;t{if(typeof e=="string")return e;let t,n="";for(let s=0;s{let n,s,r,o;const i=c=>{const u=t.reduce((d,l)=>l(d),e());return n=WC(u),s=n.cache.get,r=n.cache.set,o=a,a(c)},a=c=>{const u=s(c);if(u)return u;const d=ZC(c,n);return r(c,d),d};return o=i,(...c)=>o(KC(...c))},XC=[],Ie=e=>{const t=n=>n[e]||XC;return t.isThemeGetter=!0,t},lp=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,up=/^\((?:(\w[\w-]*):)?(.+)\)$/i,YC=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,JC=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,eA=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,tA=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,nA=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,sA=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Kt=e=>YC.test(e),se=e=>!!e&&!Number.isNaN(Number(e)),Qt=e=>!!e&&Number.isInteger(Number(e)),Zo=e=>e.endsWith("%")&&se(e.slice(0,-1)),Ft=e=>JC.test(e),dp=()=>!0,rA=e=>eA.test(e)&&!tA.test(e),Ha=()=>!1,oA=e=>nA.test(e),iA=e=>sA.test(e),aA=e=>!z(e)&&!$(e),cA=e=>an(e,pp,Ha),z=e=>lp.test(e),pn=e=>an(e,mp,rA),Du=e=>an(e,gA,se),lA=e=>an(e,yp,dp),uA=e=>an(e,gp,Ha),Ou=e=>an(e,fp,Ha),dA=e=>an(e,hp,iA),tr=e=>an(e,bp,oA),$=e=>up.test(e),os=e=>Pn(e,mp),fA=e=>Pn(e,gp),Lu=e=>Pn(e,fp),hA=e=>Pn(e,pp),pA=e=>Pn(e,hp),nr=e=>Pn(e,bp,!0),mA=e=>Pn(e,yp,!0),an=(e,t,n)=>{const s=lp.exec(e);return s?s[1]?t(s[1]):n(s[2]):!1},Pn=(e,t,n=!1)=>{const s=up.exec(e);return s?s[1]?t(s[1]):n:!1},fp=e=>e==="position"||e==="percentage",hp=e=>e==="image"||e==="url",pp=e=>e==="length"||e==="size"||e==="bg-size",mp=e=>e==="length",gA=e=>e==="number",gp=e=>e==="family-name",yp=e=>e==="number"||e==="weight",bp=e=>e==="shadow",yA=()=>{const e=Ie("color"),t=Ie("font"),n=Ie("text"),s=Ie("font-weight"),r=Ie("tracking"),o=Ie("leading"),i=Ie("breakpoint"),a=Ie("container"),c=Ie("spacing"),u=Ie("radius"),d=Ie("shadow"),l=Ie("inset-shadow"),f=Ie("text-shadow"),p=Ie("drop-shadow"),m=Ie("blur"),g=Ie("perspective"),y=Ie("aspect"),v=Ie("ease"),k=Ie("animate"),S=()=>["auto","avoid","all","avoid-page","page","left","right","column"],w=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...w(),$,z],_=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto","contain","none"],x=()=>[$,z,c],A=()=>[Kt,"full","auto",...x()],P=()=>[Qt,"none","subgrid",$,z],V=()=>["auto",{span:["full",Qt,$,z]},Qt,$,z],F=()=>[Qt,"auto",$,z],H=()=>["auto","min","max","fr",$,z],re=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],te=()=>["start","end","center","stretch","center-safe","end-safe"],B=()=>["auto",...x()],ie=()=>[Kt,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],oe=()=>[Kt,"screen","full","dvw","lvw","svw","min","max","fit",...x()],ce=()=>[Kt,"screen","full","lh","dvh","lvh","svh","min","max","fit",...x()],D=()=>[e,$,z],de=()=>[...w(),Lu,Ou,{position:[$,z]}],He=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",hA,cA,{size:[$,z]}],J=()=>[Zo,os,pn],G=()=>["","none","full",u,$,z],ne=()=>["",se,os,pn],xe=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ue=()=>[se,Zo,Lu,Ou],W=()=>["","none",m,$,z],O=()=>["none",se,$,z],le=()=>["none",se,$,z],Te=()=>[se,$,z],Y=()=>[Kt,"full",...x()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ft],breakpoint:[Ft],color:[dp],container:[Ft],"drop-shadow":[Ft],ease:["in","out","in-out"],font:[aA],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ft],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ft],shadow:[Ft],spacing:["px",se],text:[Ft],"text-shadow":[Ft],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Kt,z,$,y]}],container:["container"],columns:[{columns:[se,z,$,a]}],"break-after":[{"break-after":S()}],"break-before":[{"break-before":S()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:T()}],overflow:[{overflow:_()}],"overflow-x":[{"overflow-x":_()}],"overflow-y":[{"overflow-y":_()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:A()}],"inset-x":[{"inset-x":A()}],"inset-y":[{"inset-y":A()}],start:[{"inset-s":A(),start:A()}],end:[{"inset-e":A(),end:A()}],"inset-bs":[{"inset-bs":A()}],"inset-be":[{"inset-be":A()}],top:[{top:A()}],right:[{right:A()}],bottom:[{bottom:A()}],left:[{left:A()}],visibility:["visible","invisible","collapse"],z:[{z:[Qt,"auto",$,z]}],basis:[{basis:[Kt,"full","auto",a,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[se,Kt,"auto","initial","none",z]}],grow:[{grow:["",se,$,z]}],shrink:[{shrink:["",se,$,z]}],order:[{order:[Qt,"first","last","none",$,z]}],"grid-cols":[{"grid-cols":P()}],"col-start-end":[{col:V()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":P()}],"row-start-end":[{row:V()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":H()}],"auto-rows":[{"auto-rows":H()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...re(),"normal"]}],"justify-items":[{"justify-items":[...te(),"normal"]}],"justify-self":[{"justify-self":["auto",...te()]}],"align-content":[{content:["normal",...re()]}],"align-items":[{items:[...te(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...te(),{baseline:["","last"]}]}],"place-content":[{"place-content":re()}],"place-items":[{"place-items":[...te(),"baseline"]}],"place-self":[{"place-self":["auto",...te()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pbs:[{pbs:x()}],pbe:[{pbe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:B()}],mx:[{mx:B()}],my:[{my:B()}],ms:[{ms:B()}],me:[{me:B()}],mbs:[{mbs:B()}],mbe:[{mbe:B()}],mt:[{mt:B()}],mr:[{mr:B()}],mb:[{mb:B()}],ml:[{ml:B()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:ie()}],"inline-size":[{inline:["auto",...oe()]}],"min-inline-size":[{"min-inline":["auto",...oe()]}],"max-inline-size":[{"max-inline":["none",...oe()]}],"block-size":[{block:["auto",...ce()]}],"min-block-size":[{"min-block":["auto",...ce()]}],"max-block-size":[{"max-block":["none",...ce()]}],w:[{w:[a,"screen",...ie()]}],"min-w":[{"min-w":[a,"screen","none",...ie()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[i]},...ie()]}],h:[{h:["screen","lh",...ie()]}],"min-h":[{"min-h":["screen","lh","none",...ie()]}],"max-h":[{"max-h":["screen","lh",...ie()]}],"font-size":[{text:["base",n,os,pn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,mA,lA]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Zo,z]}],"font-family":[{font:[fA,uA,t]}],"font-features":[{"font-features":[z]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,z]}],"line-clamp":[{"line-clamp":[se,"none",$,Du]}],leading:[{leading:[o,...x()]}],"list-image":[{"list-image":["none",$,z]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,z]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:D()}],"text-color":[{text:D()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...xe(),"wavy"]}],"text-decoration-thickness":[{decoration:[se,"from-font","auto",$,pn]}],"text-decoration-color":[{decoration:D()}],"underline-offset":[{"underline-offset":[se,"auto",$,z]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:x()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,z]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,z]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:de()}],"bg-repeat":[{bg:He()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Qt,$,z],radial:["",$,z],conic:[Qt,$,z]},pA,dA]}],"bg-color":[{bg:D()}],"gradient-from-pos":[{from:J()}],"gradient-via-pos":[{via:J()}],"gradient-to-pos":[{to:J()}],"gradient-from":[{from:D()}],"gradient-via":[{via:D()}],"gradient-to":[{to:D()}],rounded:[{rounded:G()}],"rounded-s":[{"rounded-s":G()}],"rounded-e":[{"rounded-e":G()}],"rounded-t":[{"rounded-t":G()}],"rounded-r":[{"rounded-r":G()}],"rounded-b":[{"rounded-b":G()}],"rounded-l":[{"rounded-l":G()}],"rounded-ss":[{"rounded-ss":G()}],"rounded-se":[{"rounded-se":G()}],"rounded-ee":[{"rounded-ee":G()}],"rounded-es":[{"rounded-es":G()}],"rounded-tl":[{"rounded-tl":G()}],"rounded-tr":[{"rounded-tr":G()}],"rounded-br":[{"rounded-br":G()}],"rounded-bl":[{"rounded-bl":G()}],"border-w":[{border:ne()}],"border-w-x":[{"border-x":ne()}],"border-w-y":[{"border-y":ne()}],"border-w-s":[{"border-s":ne()}],"border-w-e":[{"border-e":ne()}],"border-w-bs":[{"border-bs":ne()}],"border-w-be":[{"border-be":ne()}],"border-w-t":[{"border-t":ne()}],"border-w-r":[{"border-r":ne()}],"border-w-b":[{"border-b":ne()}],"border-w-l":[{"border-l":ne()}],"divide-x":[{"divide-x":ne()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ne()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...xe(),"hidden","none"]}],"divide-style":[{divide:[...xe(),"hidden","none"]}],"border-color":[{border:D()}],"border-color-x":[{"border-x":D()}],"border-color-y":[{"border-y":D()}],"border-color-s":[{"border-s":D()}],"border-color-e":[{"border-e":D()}],"border-color-bs":[{"border-bs":D()}],"border-color-be":[{"border-be":D()}],"border-color-t":[{"border-t":D()}],"border-color-r":[{"border-r":D()}],"border-color-b":[{"border-b":D()}],"border-color-l":[{"border-l":D()}],"divide-color":[{divide:D()}],"outline-style":[{outline:[...xe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[se,$,z]}],"outline-w":[{outline:["",se,os,pn]}],"outline-color":[{outline:D()}],shadow:[{shadow:["","none",d,nr,tr]}],"shadow-color":[{shadow:D()}],"inset-shadow":[{"inset-shadow":["none",l,nr,tr]}],"inset-shadow-color":[{"inset-shadow":D()}],"ring-w":[{ring:ne()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:D()}],"ring-offset-w":[{"ring-offset":[se,pn]}],"ring-offset-color":[{"ring-offset":D()}],"inset-ring-w":[{"inset-ring":ne()}],"inset-ring-color":[{"inset-ring":D()}],"text-shadow":[{"text-shadow":["none",f,nr,tr]}],"text-shadow-color":[{"text-shadow":D()}],opacity:[{opacity:[se,$,z]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[se]}],"mask-image-linear-from-pos":[{"mask-linear-from":ue()}],"mask-image-linear-to-pos":[{"mask-linear-to":ue()}],"mask-image-linear-from-color":[{"mask-linear-from":D()}],"mask-image-linear-to-color":[{"mask-linear-to":D()}],"mask-image-t-from-pos":[{"mask-t-from":ue()}],"mask-image-t-to-pos":[{"mask-t-to":ue()}],"mask-image-t-from-color":[{"mask-t-from":D()}],"mask-image-t-to-color":[{"mask-t-to":D()}],"mask-image-r-from-pos":[{"mask-r-from":ue()}],"mask-image-r-to-pos":[{"mask-r-to":ue()}],"mask-image-r-from-color":[{"mask-r-from":D()}],"mask-image-r-to-color":[{"mask-r-to":D()}],"mask-image-b-from-pos":[{"mask-b-from":ue()}],"mask-image-b-to-pos":[{"mask-b-to":ue()}],"mask-image-b-from-color":[{"mask-b-from":D()}],"mask-image-b-to-color":[{"mask-b-to":D()}],"mask-image-l-from-pos":[{"mask-l-from":ue()}],"mask-image-l-to-pos":[{"mask-l-to":ue()}],"mask-image-l-from-color":[{"mask-l-from":D()}],"mask-image-l-to-color":[{"mask-l-to":D()}],"mask-image-x-from-pos":[{"mask-x-from":ue()}],"mask-image-x-to-pos":[{"mask-x-to":ue()}],"mask-image-x-from-color":[{"mask-x-from":D()}],"mask-image-x-to-color":[{"mask-x-to":D()}],"mask-image-y-from-pos":[{"mask-y-from":ue()}],"mask-image-y-to-pos":[{"mask-y-to":ue()}],"mask-image-y-from-color":[{"mask-y-from":D()}],"mask-image-y-to-color":[{"mask-y-to":D()}],"mask-image-radial":[{"mask-radial":[$,z]}],"mask-image-radial-from-pos":[{"mask-radial-from":ue()}],"mask-image-radial-to-pos":[{"mask-radial-to":ue()}],"mask-image-radial-from-color":[{"mask-radial-from":D()}],"mask-image-radial-to-color":[{"mask-radial-to":D()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":w()}],"mask-image-conic-pos":[{"mask-conic":[se]}],"mask-image-conic-from-pos":[{"mask-conic-from":ue()}],"mask-image-conic-to-pos":[{"mask-conic-to":ue()}],"mask-image-conic-from-color":[{"mask-conic-from":D()}],"mask-image-conic-to-color":[{"mask-conic-to":D()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:de()}],"mask-repeat":[{mask:He()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,z]}],filter:[{filter:["","none",$,z]}],blur:[{blur:W()}],brightness:[{brightness:[se,$,z]}],contrast:[{contrast:[se,$,z]}],"drop-shadow":[{"drop-shadow":["","none",p,nr,tr]}],"drop-shadow-color":[{"drop-shadow":D()}],grayscale:[{grayscale:["",se,$,z]}],"hue-rotate":[{"hue-rotate":[se,$,z]}],invert:[{invert:["",se,$,z]}],saturate:[{saturate:[se,$,z]}],sepia:[{sepia:["",se,$,z]}],"backdrop-filter":[{"backdrop-filter":["","none",$,z]}],"backdrop-blur":[{"backdrop-blur":W()}],"backdrop-brightness":[{"backdrop-brightness":[se,$,z]}],"backdrop-contrast":[{"backdrop-contrast":[se,$,z]}],"backdrop-grayscale":[{"backdrop-grayscale":["",se,$,z]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[se,$,z]}],"backdrop-invert":[{"backdrop-invert":["",se,$,z]}],"backdrop-opacity":[{"backdrop-opacity":[se,$,z]}],"backdrop-saturate":[{"backdrop-saturate":[se,$,z]}],"backdrop-sepia":[{"backdrop-sepia":["",se,$,z]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,z]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[se,"initial",$,z]}],ease:[{ease:["linear","initial",v,$,z]}],delay:[{delay:[se,$,z]}],animate:[{animate:["none",k,$,z]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,z]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:O()}],"rotate-x":[{"rotate-x":O()}],"rotate-y":[{"rotate-y":O()}],"rotate-z":[{"rotate-z":O()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:Te()}],"skew-x":[{"skew-x":Te()}],"skew-y":[{"skew-y":Te()}],transform:[{transform:[$,z,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Y()}],"translate-x":[{"translate-x":Y()}],"translate-y":[{"translate-y":Y()}],"translate-z":[{"translate-z":Y()}],"translate-none":["translate-none"],accent:[{accent:D()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:D()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,z]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mbs":[{"scroll-mbs":x()}],"scroll-mbe":[{"scroll-mbe":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pbs":[{"scroll-pbs":x()}],"scroll-pbe":[{"scroll-pbe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,z]}],fill:[{fill:["none",...D()]}],"stroke-w":[{stroke:[se,os,pn,Du]}],stroke:[{stroke:["none",...D()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},bA=QC(yA);function bn(...e){return bA(am(e))}function vA({className:e,...t}){return b.jsx(rm,{"data-slot":"avatar",className:bn("relative flex size-10 shrink-0 overflow-hidden rounded-full",e),...t})}function zu({className:e,...t}){return b.jsx(om,{"data-slot":"avatar-image",className:bn("aspect-square size-full",e),...t})}function wA({className:e,...t}){return b.jsx(im,{"data-slot":"avatar-fallback",className:bn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}function xA(e){return e==="male"?"/icons/male-student.png":e==="female"?"/icons/female-student.png":"/icons/neutral-student.png"}const SA=e=>{const t=(e||"").trim();return t?t.split(/\s+/).slice(0,2).map(n=>n[0]?.toUpperCase()).join(""):"U"},kA=({src:e,name:t,gender:n,className:s,fallbackClassName:r,imageClassName:o})=>{const i=SA(t),a=xA(n);return b.jsxs(vA,{className:bn("shrink-0",s),children:[e?b.jsx(zu,{src:e,alt:t||"User",className:bn("object-cover",o)}):b.jsx(zu,{src:a,alt:t||"User",className:bn("object-cover",o)}),b.jsx(wA,{className:bn("bg-gradient-to-br from-violet-500 to-indigo-600 text-white font-display font-bold text-xs select-none",r),children:i})]})},TA={Functions:"Functions and Graphs",BusinessMath:"Business and Financial Mathematics",Logic:"Logic and Reasoning"},oM={Functions:"gm-q2-functions-graphs",BusinessMath:"gm-q1-business-finance",Logic:"gm-q4-propositions-syllogisms-fallacies"},_A=e=>{const t=e.trim().toLowerCase();return t==="functions"||t.includes("function")?"Functions":t==="businessmath"||t.includes("business")?"BusinessMath":t==="logic"||t.includes("reason")?"Logic":null},PA=[{lessonId:"gm-q1-bf-1",lessonTitle:"Represent business transactions and financial goals using variables and equations.",moduleId:"gm-q1-business-finance",subjectId:"gen-math",subject:"General Mathematics",quarter:1,competencyCode:"GM11-BF-1",learningCompetency:"Represent business transactions and financial goals using variables and equations.",storagePath:"curriculum/general_math/GENERAL-MATHEMATICS-1.pdf",sourceFile:"GENERAL-MATHEMATICS-1.pdf"},{lessonId:"gm-q1-pss-1",lessonTitle:"Identify and describe arithmetic and geometric patterns in data.",moduleId:"gm-q1-patterns-sequences-series",subjectId:"gen-math",subject:"General Mathematics",quarter:1,competencyCode:"GM11-PSS-1",learningCompetency:"Identify and describe arithmetic and geometric patterns in data.",storagePath:"curriculum/general_math/GENERAL-MATHEMATICS-1.pdf",sourceFile:"GENERAL-MATHEMATICS-1.pdf"},{lessonId:"gm-q1-fass-1",lessonTitle:"Use arithmetic and geometric series to estimate cumulative financial outcomes.",moduleId:"gm-q1-financial-application-sequences-series",subjectId:"gen-math",subject:"General Mathematics",quarter:1,competencyCode:"GM11-FASS-1",learningCompetency:"Use arithmetic and geometric series to estimate cumulative financial outcomes.",storagePath:"curriculum/gen_math_sdo/SDO_Navotas_Gen.Math_SHS_1stSem.FV.pdf",sourceFile:"SDO_Navotas_Gen.Math_SHS_1stSem.FV.pdf"},{lessonId:"bm-q1-1",lessonTitle:"Translate verbal phrases to mathematical expressions; model business scenarios using linear equations and inequalities.",moduleId:"bm-q1-business-math",subjectId:"business-math",subject:"Business Mathematics",quarter:1,competencyCode:"ABM_BM11BS-Ia-b-1",learningCompetency:"Translate verbal phrases to mathematical expressions; model business scenarios using linear equations and inequalities.",storagePath:"curriculum/business_math/SDO_Navotas_Bus.Math_SHS_1stSem.FV.pdf",sourceFile:"SDO_Navotas_Bus.Math_SHS_1stSem.FV.pdf"},{lessonId:"stat-q1-1",lessonTitle:"Define and describe random variables and their types.",moduleId:"stat-q1-probability",subjectId:"stats-prob",subject:"Statistics and Probability",quarter:1,competencyCode:"SP_SHS11-Ia-1",learningCompetency:"Define and describe random variables and their types.",storagePath:"curriculum/stat_prob/SDO_Navotas_STAT_PROB_SHS_1stSem.FV.pdf",sourceFile:"SDO_Navotas_STAT_PROB_SHS_1stSem_FV.pdf"},{lessonId:"bc-q3-lf-1",lessonTitle:"Evaluate limits using limit theorems.",moduleId:"bc-q3-limits-of-functions",subjectId:"basic-calc",subject:"Basic Calculus",quarter:3,competencyCode:"BC12-LF-1",learningCompetency:"Evaluate limits using limit theorems.",storagePath:"curriculum/basic_calc/SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf",sourceFile:"SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf"},{lessonId:"bc-q3-d-1",lessonTitle:"Apply the limit definition of the derivative.",moduleId:"bc-q3-derivatives",subjectId:"basic-calc",subject:"Basic Calculus",quarter:3,competencyCode:"BC12-D-1",learningCompetency:"Apply the limit definition of the derivative.",storagePath:"curriculum/basic_calc/SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf",sourceFile:"SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf"},{lessonId:"bc-q3-i-1",lessonTitle:"Determine antiderivatives of functions.",moduleId:"bc-q3-integration",subjectId:"basic-calc",subject:"Basic Calculus",quarter:3,competencyCode:"BC12-I-1",learningCompetency:"Determine antiderivatives of functions.",storagePath:"curriculum/basic_calc/SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf",sourceFile:"SDO_Navotas_BasicCalc_SHS_Q3.FV.pdf"}],EA=Object.fromEntries(PA.map(e=>[e.competencyCode,{lessonId:e.lessonId,storagePath:e.storagePath,sourceFile:e.sourceFile}])),ju=[{id:"deped-strengthened-gm",title:"DepEd Strengthened SHS General Mathematics Guide",url:"https://www.deped.gov.ph/"},{id:"deped-approved-exemplars",title:"Approved SHS Lesson Exemplars and Activity Sheets",url:"https://www.deped.gov.ph/"}],Za={"gen-math":{id:"gen-math",label:"General Mathematics",color:"#1f4ea8",accent:"#3f7cff"},"business-math":{id:"business-math",label:"Business Mathematics",color:"#166534",accent:"#22c55e"},"stats-prob":{id:"stats-prob",label:"Statistics and Probability",color:"#6b21a8",accent:"#a855f7"}},CA={"Grade 11":["gen-math"]},AA="Foundational competency flow with guided examples, step-by-step vocabulary support, and scaffolded checkpoints.",nt=(e,t,n,s,r,o,i,a,c,u,d,l)=>({id:e,subjectId:t,subject:Za[t].label,quarter:n,moduleTitle:s,moduleDescription:r,contentDomain:o,competencyGroup:i,competencies:a,performanceStandard:c,realWorldTheme:u,grade_level_availability:d,recommended_grade_level:l,sources:[ju[0],ju[1]]}),RA=[nt("gm-q1-business-finance","gen-math","Q1","Business and Finance","Interpret business contexts using mathematical models for pricing, savings, and financial planning.","Business Mathematics","GM-Q1-BF",[{code:"GM11-BF-1",outcome:"Represent business transactions and financial goals using variables and equations."},{code:"GM11-BF-2",outcome:"Analyze financial options using ratio, percent change, and margin reasoning."},{code:"GM11-BF-3",outcome:"Justify practical decisions with mathematically sound comparisons."}],"Produces a finance decision brief that explains and defends a chosen option using quantitative evidence.","Household budgeting and MSME pricing",["Grade 11"],"Grade 11"),nt("gm-q1-patterns-sequences-series","gen-math","Q1","Patterns, Sequences, and Series","Investigate arithmetic and geometric patterns, then model recurring structures in real settings.","Patterns and Algebraic Thinking","GM-Q1-PSS",[{code:"GM11-PSS-1",outcome:"Identify and describe arithmetic and geometric patterns in data."},{code:"GM11-PSS-2",outcome:"Construct explicit and recursive rules for sequences."},{code:"GM11-PSS-3",outcome:"Solve contextual problems involving finite series."}],"Creates a pattern model with formula, table, and verbal interpretation for a real-life process.","Savings goals and production growth",["Grade 11"],"Grade 11"),nt("gm-q1-financial-application-sequences-series","gen-math","Q1","Financial Application of Sequences and Series","Apply sequence and series models in annuities, installment planning, and long-term savings behavior.","Financial Applications","GM-Q1-FASS",[{code:"GM11-FASS-1",outcome:"Use arithmetic and geometric series to estimate cumulative financial outcomes."},{code:"GM11-FASS-2",outcome:"Compare payment plans and saving schemes using sequence-based models."}],"Builds a comparative recommendation report for financial plans grounded in sequence and series computations.","Installment plans and savings projections",["Grade 11"],"Grade 11"),nt("gm-q2-measurement-conversion","gen-math","Q2","Measurement and Conversion","Convert and validate units in practical settings involving length, area, volume, and rate.","Measurement","GM-Q2-MC",[{code:"GM11-MC-1",outcome:"Perform unit conversions accurately across metric and mixed contexts."},{code:"GM11-MC-2",outcome:"Evaluate measurement precision and reasonableness in applied tasks."}],"Produces an accurate conversion workflow with checks for reasonableness and precision.","Construction estimates and food production",["Grade 11"],"Grade 11"),nt("gm-q2-functions-graphs","gen-math","Q2","Functions and Their Graphs","Model relationships using function notation, tables, and graphs to explain changing quantities.","Functions","GM-Q2-FG",[{code:"GM11-FG-1",outcome:"Represent real-life relationships as functions and interpret domain/range."},{code:"GM11-FG-2",outcome:"Analyze function behavior from tables, equations, and graphs."},{code:"GM11-FG-3",outcome:"Use graph interpretation to support contextual conclusions."}],"Submits a function modeling portfolio with equation selection and graph-based interpretation.","Transport fare, utility consumption, and growth trends",["Grade 11"],"Grade 11"),nt("gm-q2-piecewise-functions","gen-math","Q2","Piecewise Functions","Use piecewise definitions to model tiered pricing, conditional rates, and policy thresholds.","Functions","GM-Q2-PF",[{code:"GM11-PF-1",outcome:"Translate threshold-based scenarios into piecewise functions."},{code:"GM11-PF-2",outcome:"Evaluate and graph piecewise functions for decision-making."}],"Constructs and defends a piecewise model for a threshold-driven policy scenario.","Electricity billing tiers and shipping rates",["Grade 11"],"Grade 11"),nt("gm-q2-statistical-variables","gen-math","Q2","Statistical Variables","Differentiate variable types and build data representations suitable for statistical analysis.","Data and Statistics","GM-Q2-SV",[{code:"GM11-SV-1",outcome:"Classify variables and choose appropriate data representations."},{code:"GM11-SV-2",outcome:"Interpret variable distributions and detect potential data issues."}],"Prepares a data profile report with justified variable treatment and representation choices.","School survey dashboards",["Grade 11"],"Grade 11"),nt("gm-q3-basic-trigonometry","gen-math","Q3","Basic Trigonometry","Solve right-triangle and angle problems using trigonometric ratios in practical contexts.","Geometry and Trigonometry","GM-Q3-BT",[{code:"GM11-BT-1",outcome:"Apply trigonometric ratios to solve angle and distance problems."},{code:"GM11-BT-2",outcome:"Interpret trigonometric results in measurement contexts."}],"Creates a field-measurement solution set that justifies method and interpretation.","Building height and slope analysis",["Grade 11"],"Grade 11"),nt("gm-q3-practical-applications-measurement","gen-math","Q3","Practical Applications of Measurement","Integrate measurement methods to solve multi-step tasks in planning, costing, and logistics.","Measurement Applications","GM-Q3-PAM",[{code:"GM11-PAM-1",outcome:"Select and apply measurement methods in practical multi-step tasks."},{code:"GM11-PAM-2",outcome:"Estimate uncertainty and communicate justified approximations."}],"Delivers a practical measurement plan with justified estimates and assumptions.","Project costing and logistics planning",["Grade 11"],"Grade 11"),nt("gm-q3-transformational-geometry-volume-capacity","gen-math","Q3","Transformational Geometry / Volume and Capacity","Use geometric transformations and solid measurement to solve design and storage problems.","Geometry","GM-Q3-TGVC",[{code:"GM11-TGVC-1",outcome:"Analyze geometric transformations in patterned and engineered layouts."},{code:"GM11-TGVC-2",outcome:"Compute volume and capacity for practical container and space tasks."}],"Produces a geometry-based layout and capacity justification for a real constraint.","Packaging and facility layout",["Grade 11"],"Grade 11"),nt("gm-q3-random-variables-sampling","gen-math","Q3","Random Variables and Sampling","Model uncertainty and sampling behavior to support evidence-based conclusions.","Probability and Sampling","GM-Q3-RVS",[{code:"GM11-RVS-1",outcome:"Define random variables and compute basic expected outcomes."},{code:"GM11-RVS-2",outcome:"Explain sampling methods and sampling bias in practical studies."},{code:"GM11-RVS-3",outcome:"Interpret sampling outcomes in context."}],"Presents a sampling design and interpretation memo for a study question.","Consumer preference and public opinion studies",["Grade 11"],"Grade 11"),nt("gm-q4-compound-interest-annuities-loans","gen-math","Q4","Compound Interest, Annuities, and Loans","Evaluate long-term financial commitments using compound growth and annuity structures.","Financial Mathematics","GM-Q4-CIAL",[{code:"GM11-CIAL-1",outcome:"Compute and compare compound interest outcomes across periods and rates."},{code:"GM11-CIAL-2",outcome:"Model annuity and loan payment structures for planning decisions."},{code:"GM11-CIAL-3",outcome:"Assess affordability and sustainability of borrowing plans."}],"Builds a defensible personal finance plan covering savings and borrowing scenarios.","Education financing and long-term savings",["Grade 11"],"Grade 11"),nt("gm-q4-hypothesis-testing-regression","gen-math","Q4","Hypothesis Testing and Regression","Use inferential reasoning and regression modeling to evaluate data-driven claims.","Statistics","GM-Q4-HTR",[{code:"GM11-HTR-1",outcome:"Formulate and interpret hypotheses using context-appropriate tests."},{code:"GM11-HTR-2",outcome:"Develop and interpret regression models for trend analysis."}],"Produces an evidence report with hypothesis decision and regression-backed interpretation.","School performance and market trend analysis",["Grade 11"],"Grade 11"),nt("gm-q4-propositions-syllogisms-fallacies","gen-math","Q4","Logical Propositions, Syllogisms, and Fallacies","Evaluate arguments using formal logic, syllogistic forms, and fallacy detection.","Logic and Reasoning","GM-Q4-PSF",[{code:"GM11-PSF-1",outcome:"Translate statements into logical propositions and evaluate validity."},{code:"GM11-PSF-2",outcome:"Test syllogistic arguments and identify common fallacies."},{code:"GM11-PSF-3",outcome:"Construct sound arguments supported by formal reasoning."}],"Submits a logic audit that classifies validity and fallacies in real arguments.","Media literacy and policy argument review",["Grade 11"],"Grade 11")];function MA(e,t){return`${e.moduleDescription} ${AA}`}function IA(e,t){const n=t==="Grade 11"?"22 min":"18 min";return e.competencies.map((s,r)=>{const o=EA[s.code];return{id:o?.lessonId??`${e.id}-l${r+1}`,title:s.outcome,duration:n,completed:!1,locked:!1,description:`${s.code} · ${s.outcome}`,competencyCode:s.code,subjectId:e.subjectId,subject:e.subject,quarter:parseInt(e.quarter.replace("Q","")),learningCompetency:s.outcome,...o&&{storagePath:o.storagePath,sourceFile:o.sourceFile}}})}function DA(e){const t=[];let s=0;for(let r=0;ri.code),type:s===Math.ceil(e.competencies.length/2)?"module":"practice"})}return t}function OA(e,t){return t.map((n,s)=>({id:`${e.id}-q${s+1}`,title:n.title,questions:Math.max(8,n.competencyCodes.length*5),duration:n.type==="module"?"22 min":"15 min",completed:!1,locked:s>0,type:n.type}))}function LA(e){const t=(e||"").trim();if(!t)return"Grade 11";const n=t.match(/(\d{1,2})/);if(n){const s=parseInt(n[1],10);return s>=11&&s<=12?`Grade ${s}`:"Grade 11"}if(/^grade\s*\d{1,2}$/i.test(t)){const s=parseInt(t.replace(/grade\s*/i,""),10);if(s>=11&&s<=12)return`Grade ${s}`}return"Grade 11"}function zA(e){if(!Array.isArray(e)||e.length===0)return null;const t=new Set(["gen-math","business-math","stats-prob"]),n=e.map(s=>s.trim().toLowerCase()).map(s=>s==="gen-math"||s==="general-mathematics"||s==="general mathematics"?"gen-math":s==="business-math"||s==="business mathematics"||s==="bm"?"business-math":s==="stats-prob"||s==="statistics and probability"||s==="statistics"?"stats-prob":null).filter(s=>s!==null&&t.has(s));return n.length>0?n:null}function jA(e){return LA(e)}function NA(e,t){const n=zA(t),s=CA[e];return n?s.filter(r=>n.includes(r)):s}function $A(e,t){const n=NA(e,t);return RA.filter(s=>s.grade_level_availability.includes(e)).filter(s=>n.includes(s.subjectId)).map(s=>{const r=DA(s),o=IA(s,e),i=OA(s,r),a=Za[s.subjectId],c=o.some(l=>l.storagePath&&l.storagePath.length>0),u=s.isAvailable??c??!0,d=u?"available":"coming_soon";return{id:s.id,title:s.moduleTitle,description:MA(s),lessons:o,quizzes:i,progress:0,color:"bg-white",iconColor:"text-slate-700",accentColor:"bg-slate-700",subjectId:s.subjectId,subject:s.subject,subjectColor:a.color,subjectAccentColor:a.accent,grade_level_availability:s.grade_level_availability,recommended_grade_level:s.recommended_grade_level,active_grade_level:e,quarter:s.quarter,content_domain:s.contentDomain,competency_group:s.competencyGroup,competencies:s.competencies,performance_standard:s.performanceStandard,real_world_theme:s.realWorldTheme,lesson_count:o.length,quiz_count:i.length,is_visible_for_grade:s.grade_level_availability.includes(e),curriculum_aligned_label:"Curriculum-aligned",module_sources:s.sources,module_assessments:r,isAvailable:u,moduleStatus:d}})}const iM=Za,FA=()=>{const e=new Date,t=e.getMonth(),n=e.getFullYear();return t>=7?`${n}-${n+1}-1`:t>=5?`${n-1}-${n}-summer`:`${n-1}-${n}-2`},vp=async e=>{const{uid:t,score:n,subject:s,title:r}=e,o=s||r||"General";let i="";return await Op(L,async a=>{const c=U(L,"users",t,"gradeSummary","current"),u=await a.get(c);let d;if(!u.exists())d={overallGpa:n/100*4,averageScore:n,quizzesCompleted:1,subjectPerformance:{[o]:{totalScore:n,count:1,avgScore:n}},lastUpdated:jn.now()};else{const m=u.data(),g=(m.quizzesCompleted||0)+1,v=((m.averageScore||0)*(m.quizzesCompleted||0)+n)/g,k=m.subjectPerformance||{},S=k[o]||{totalScore:0,count:0},w=S.count+1,T=S.totalScore+n,_=T/w;d={overallGpa:v/100*4,averageScore:v,quizzesCompleted:g,subjectPerformance:{...k,[o]:{totalScore:T,count:w,avgScore:_}},lastUpdated:jn.now()}}a.set(c,d,{merge:!0});const l=et(L,"users",t,"assessments"),f=U(l);i=f.id;const p={title:e.title,subject:o,type:e.type,score:e.score,totalQuestions:e.totalQuestions,completedAt:jn.now(),risk:e.risk,intervention:e.intervention,xpEarned:e.xpEarned,badgeUnlocked:e.badgeUnlocked,semester:FA(),createdAt:ae()};a.set(f,p)}),i},VA=(e,t)=>{const n=U(L,"users",e,"gradeSummary","current");return en(n,s=>{s.exists()?t(s.data()):t(null)},s=>{console.error("[gradesService] subscribeToGradeSummary error:",s),t(null)})},BA=(e,t)=>{const n=Dt(et(L,"users",e,"assessments"),Sn("completedAt","desc"),ks(20));return en(n,s=>{const r=[];s.forEach(o=>{r.push({id:o.id,...o.data()})}),t(r)},s=>{console.error("[gradesService] subscribeToAssessments error:",s),t([])})},aM=Object.freeze(Object.defineProperty({__proto__:null,saveAssessmentResult:vp,subscribeToAssessments:BA,subscribeToGradeSummary:VA},Symbol.toStringTag,{value:"Module"}));function UA(e){const{assessmentId:t,overallScorePercent:n,overallRisk:s,intervention:r,proficiencyProfile:o}=e,i=GA(n),a=WA(n,s,o),c=HA(s,r),u=o?.strengths??[],d=o?.weaknesses??[];return{status:"ready",headline:i,summary:a,strengths:u,weaknesses:d,recommendation:c,latestAssessmentId:t,latestScorePercent:n,latestRiskLevel:wp(s),updatedAt:new Date}}async function qA(e,t){const n=U(L,"users",e,"dashboardSummary","heroBannerModal");await Ce(n,{...t,updatedAt:ae()})}async function cM(e){const t=U(L,"users",e,"dashboardSummary","heroBannerModal"),n=await me(t);if(!n.exists())return null;const s=n.data();return{status:s.status??"not_started",headline:s.headline??"",summary:s.summary??"",strengths:s.strengths??[],weaknesses:s.weaknesses??[],recommendation:s.recommendation??"",latestAssessmentId:s.latestAssessmentId??"",latestScorePercent:s.latestScorePercent??0,latestRiskLevel:s.latestRiskLevel??"",updatedAt:xp(s.updatedAt)}}function lM(e,t){const n=U(L,"users",e,"dashboardSummary","heroBannerModal");return en(n,s=>{if(!s.exists()){t(null);return}const r=s.data();t({status:r.status??"not_started",headline:r.headline??"",summary:r.summary??"",strengths:r.strengths??[],weaknesses:r.weaknesses??[],recommendation:r.recommendation??"",latestAssessmentId:r.latestAssessmentId??"",latestScorePercent:r.latestScorePercent??0,latestRiskLevel:r.latestRiskLevel??"",updatedAt:xp(r.updatedAt)})},s=>{console.warn("[heroBannerSummaryService] Subscription error:",s),t(null)})}function GA(e){return e>=80?"Outstanding performance! 🎉":e>=65?"Good job — keep it up!":e>=50?"You're making progress!":"Let's build your foundation"}function WA(e,t,n){const s=n?.strengths??[],r=n?.weaknesses??[];if(s.length>0&&r.length>0){const o=s[0],i=r[0];return`You show stronger understanding in ${o}, while ${i} needs more attention. Keep practicing to strengthen your weaker areas!`}return s.length>0?"Great work! You demonstrated strong understanding. Focus on maintaining your performance and expanding your skills.":r.length>0?"You have some areas to work on. With guided practice and focused review, you can build a stronger foundation in the topics that need attention.":e>=70?"You performed well overall! You have a solid foundation. Continue practicing to maintain and expand your skills.":e>=50?"You showed understanding in several areas. Keep practicing and review the topics where you lost points.":"The diagnostic shows there are foundational topics to work on. Don't worry — with consistent practice, you'll build confidence and improve!"}function HA(e,t,n){return t&&t.trim().length>0?t:(wp(e),e==="critical"||e==="high"?"We recommend starting with foundational lessons and guided practice to build confidence. Focus on one topic at a time, and don't hesitate to review earlier material.":e==="moderate"?"Start with guided review lessons to strengthen your foundation, then progressively tackle more challenging problems.":"Continue practicing regularly and review topics you find challenging. Your personalized learning path will guide you to the right lessons.")}function wp(e){switch(e){case"low":return"Low";case"moderate":return"Moderate";case"high":return"High";case"critical":return"Critical";default:return e.charAt(0).toUpperCase()+e.slice(1)}}function xp(e){return e?e instanceof Date?e:e instanceof jn?e.toDate():typeof e=="string"||typeof e=="number"?new Date(e):new Date:new Date}const ZA=h.lazy(()=>ee(()=>import("./LoginPage-Dp-x74N8.js"),__vite__mapDeps([14,3,15,7,8,16,17,18,19,20,1,2,4,5,6,9,10]))),KA=h.lazy(()=>ee(()=>import("./TeacherDashboard-CqJcvlfm.js"),__vite__mapDeps([21,3,15,7,8,16,22,23,24,25,1,2,4,5,6,9,10,26,27,28,29,30,31,32,33,17,34,35,36,37,38,39,40,19,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61]))),QA=h.lazy(()=>ee(()=>import("./AdminDashboard-CMvLZSCj.js"),__vite__mapDeps([62,3,63,34,25,39,7,23,48,47,44,64,22,15,8,24,1,2,4,5,6,9,10,65,42,27,16,53,50,29,30,31,32,33,17,57,46,20,26,36,19,41,18,28,49,52,66,67,68,40]))),Nu=h.lazy(()=>ee(()=>import("./Sidebar-BohFsvbI.js").then(e=>e.b),__vite__mapDeps([63,3,34,25,39,7,23,48,47,44,64]))),XA=h.lazy(()=>ee(()=>import("./HeroBanner-BW-D6-hj.js"),__vite__mapDeps([69,3,57,7,23,8,1,2,33,32,17,4,5,6,9,10]))),YA=h.lazy(()=>ee(()=>import("./RightSidebar-DRNR3ylv.js"),__vite__mapDeps([70,3,71,38,39,7,48,1,2,4,5,6,8,9,10]))),JA=h.lazy(()=>ee(()=>import("./XPNotification-BKiP3rYx.js"),__vite__mapDeps([72,3,17,1,2,4,5,6,7,8,9,10]))),eR=h.lazy(()=>ee(()=>import("./index-oMQKBL9u.js"),__vite__mapDeps([73,3,33,74,31,38,60,30,24,23,1,2,4,5,6,7,8,9,10])).then(e=>({default:e.NotificationBell})));h.lazy(()=>ee(()=>import("./SupplementalBanner-BaLhyCv2.js"),__vite__mapDeps([75,3,23,17,48,1,2,4,5,6,7,8,9,10])));const tR=h.lazy(()=>ee(()=>import("./SupplementalPillCarousel-EeBQ4OFw.js"),__vite__mapDeps([76,3,77,7,59,1,2,33,42,31,36,48,17,23,4,5,6,8,9,10]))),nR=h.lazy(()=>ee(()=>import("./LearningPath-BKjN0COS.js"),__vite__mapDeps([78,3,79,68,1,2,77,36,31,41,4,5,6,7,8,9,10]))),sR=h.lazy(()=>ee(()=>import("./CompetencyRadarChart-CYjxrfwY.js"),__vite__mapDeps([80,3,1,2,53,44,17,8,4,5,6,7,9,10])).then(e=>({default:e.CompetencyRadarChart}))),rR=h.lazy(()=>ee(()=>import("./ModulesPage-DdfzGaQY.js"),__vite__mapDeps([81,3,52,1,2,79,68,77,36,31,41,15,7,8,9,10,0,4,5,6,35,82,42,23,27,83,47,48,51,38,40,13,60,53,44,61,32,56,66,84,85,54,59,26,86,17]))),oR=h.lazy(()=>ee(()=>import("./AIChatPage-CEm6qhAI.js"),__vite__mapDeps([87,3,15,7,8,16,55,9,10,1,2,4,5,6,28,26,24,47,37]))),iR=h.lazy(()=>ee(()=>import("./GradesPage-BXZfrLBa.js"),__vite__mapDeps([88,3,15,7,8,53,44,54,1,2,46,32,33,86,4,5,6,9,10]))),aR=h.lazy(()=>ee(()=>import("./LeaderboardPage-C7BC2ZU8.js"),__vite__mapDeps([89,3,23,36,61,90,1,2,4,5,6,7,8,9,10]))),cR=h.lazy(()=>ee(()=>import("./QuizBattlePage-BgqU8ht-.js"),__vite__mapDeps([91,3,71,53,44,1,2,15,7,8,65,42,27,16,67,45,83,92,93,17,56,48,4,5,6,9,10]))),lR=h.lazy(()=>ee(()=>import("./AvatarShop-CU1RR7LT.js"),__vite__mapDeps([94,3,7,90,1,2,39,92,93,49,23,64,17,4,5,6,8,9,10]))),uR=h.lazy(()=>ee(()=>import("./FloatingAITutor-ZRTH3xRj.js"),__vite__mapDeps([95,3,1,2,96,43,23,37,4,5,6,7,8,9,10]))),dR=h.lazy(()=>ee(()=>import("./RewardsModal-Duh63-te.js"),__vite__mapDeps([97,3,1,2,23,4,5,6,7,8,9,10]))),Ko=h.lazy(()=>ee(()=>import("./ProfileModal-DG84pnuP.js"),__vite__mapDeps([98,3,15,7,8,16,65,42,27,99,4,2,5,23,43,28,50,18,40,49,1,6,9,10]))),fR=h.lazy(()=>ee(()=>import("./ConfirmModal-DPzAgSP6.js"),__vite__mapDeps([22,3,15,7,8,23,24,25,1,2,4,5,6,9,10]))),Qo=h.lazy(()=>ee(()=>import("./SettingsModal-YXgi6gjA.js"),__vite__mapDeps([100,3,65,7,42,27,15,8,16,67,22,23,24,25,1,2,4,5,6,9,10,99,43,28,50,31,46,40,85,44,74,36,19]))),hR=h.lazy(()=>ee(()=>import("./ScientificCalculator-DQTxoI7Z.js"),__vite__mapDeps([82,3,42,23,1,2,4,5,6,7,8,9,10]))),pR=h.lazy(()=>ee(()=>import("./InitialAssessmentModal-DdNBSpH9.js"),__vite__mapDeps([101,3,15,7,8,102,1,2,23,38,4,5,6,9,10]))),mR=h.lazy(()=>ee(()=>import("./AssessmentPage-CNGTAZUT.js"),__vite__mapDeps([103,3,15,7,8,102,96,23,36,38,48,1,2,4,5,6,9,10]))),gR=h.lazy(()=>ee(()=>import("./DiagnosticBreakdown-1Ae0p8Ht.js"),__vite__mapDeps([104,3,1,2,23,36,51,32,44,42,4,5,6,7,8,9,10]))),yR=()=>{const{isLoggedIn:e,userProfile:t,userRole:n,loading:s,refreshProfile:r}=Ms();Gi();const o=zt(),i=b.jsx("div",{className:"flex min-h-[320px] items-center justify-center text-sm font-semibold text-slate-500",children:"Loading content..."}),a=b.jsx("div",{className:"pb-4 text-sm font-semibold text-slate-500",children:"Loading dashboard content..."}),c=b.jsx("div",{className:"h-11 w-11 shrink-0 rounded-xl bg-[#edf1f7]","aria-hidden":"true"}),u=b.jsx("div",{className:"h-screen w-72 border-r border-[#dde3eb] bg-white/70","aria-hidden":"true"}),d=b.jsx("div",{className:"min-h-[240px] rounded-3xl border border-[#dde3eb] bg-white/70","aria-hidden":"true"}),[l,f]=h.useState("Dashboard"),p=h.useRef(!1),[m,g]=h.useState(null),y=h.useRef(null),v=h.useRef(null),[k,S]=h.useState(!1),[w,T]=h.useState(!1),[_,R]=h.useState(!1),[x,A]=h.useState(!1);h.useEffect(()=>{(async()=>{try{const M=await me(U(L,"settings","general"));M.exists()&&M.data()?.maintenanceMode===!0?(R(!0),e&&n!=="admin"&&await ou()):R(!1)}catch{}A(!0)})()},[e,n]);const P=t,[V,F]=h.useState(P?.level||1),[H,re]=h.useState(P?.currentXP||0),[te,B]=h.useState(P?.totalXP||0),ie=Math.floor(100*Math.pow(1.5,V-1));let oe=0;for(let E=1;E{const E=P?.learnerCurriculumAssignments?.subjects??P?.assignedSubjects??P?.curriculumAssignedSubjects??[];return Array.isArray(E)?E:[]},[P]),He=h.useMemo(()=>$A(D,de),[D,de]),X=h.useMemo(()=>Object.fromEntries(He.map(E=>[E.id,E.moduleStatus])),[He]),[J,G]=h.useState({collapsed:!1}),ne={Dashboard:"/",Modules:"/modules","AI Chat":"/chat",Assessment:"/assessment","Quiz Battle":"/battle",Leaderboard:"/leaderboard",Grades:"/grades","Avatar Studio":"/avatar"},xe={"/":"Dashboard","/modules":"Modules","/chat":"AI Chat","/assessment":"Assessment","/battle":"Quiz Battle","/leaderboard":"Leaderboard","/grades":"Grades","/avatar":"Avatar Studio"};h.useEffect(()=>{const E=xe[o.pathname]||"Dashboard";f(E)},[o.pathname]),h.useEffect(()=>{const E=()=>{const M=xe[window.location.pathname]||"Dashboard";f(M)};return window.addEventListener("popstate",E),()=>window.removeEventListener("popstate",E)},[]);const Z=(E,M)=>{if(l==="Avatar Studio"&&p.current&&E!=="Avatar Studio"){g(E);return}M?Ds(M):E==="Modules"&&l!=="Modules"&&Ds(null),E==="Quiz Battle"&&l!=="Quiz Battle"?(G({collapsed:k}),S(!0)):l==="Quiz Battle"&&E!=="Quiz Battle"&&S(J.collapsed),f(E);const q=ne[E];q&&window.location.pathname!==q&&window.history.pushState({},"",q),T(!1)},[ue,W]=h.useState(!1),[O,le]=h.useState({show:!1,xp:0,message:""}),[Te,Y]=h.useState(!1),[Ne,be]=h.useState(!1),[Ae,it]=h.useState(!1),[at,Qn]=h.useState(!1),[to,$e]=h.useState({}),[Gt,Ds]=h.useState(null),[Os,En]=h.useState(!1),[cn,kt]=h.useState(yr),[Xn,pt]=h.useState(""),[Wt,Nt]=h.useState(!1),[Ls,Ht]=h.useState(!1),[Zt,ln]=h.useState(null),[no,un]=h.useState(!1),[Tt,zs]=h.useState(!1),[so,js]=h.useState(0),[Cn,Q]=h.useState(!1),[Pe,Re]=h.useState(!1),[Fe,An]=h.useState(""),[Me,tt]=h.useState([]),[rt,Ue]=h.useState(P?.atRiskSubjects||[]),[Ze,dn]=h.useState(P?.priorityTopics||[]),[$t,ro]=h.useState(P?.gpa||"0");h.useEffect(()=>{e&&n==="student"&&t&&sC(t.uid).then(E=>{E&&E.averageScore>0&&ro(Math.round(E.averageScore).toString())}).catch(E=>console.error("Error loading progress for GPA:",E))},[e,n,t]);const[Yn,Ka]=h.useState(!1);h.useEffect(()=>{P&&n==="student"?(F(P.level||1),re(P.currentXP||0),B(P.totalXP||0),Ue(P.atRiskSubjects||[]),dn(P.priorityTopics||[]),Ka(!0)):n!=="student"&&Ka(!0)},[t,n]),h.useEffect(()=>{if(!e||n!=="student"){Nt(!1);return}let E=!1;const M=()=>{E||Nt(!0)},q=window.requestIdleCallback,pe=window.cancelIdleCallback,ho=window.setTimeout(M,800),po=window.requestAnimationFrame(()=>{q||M()}),mt=q?.(()=>{M()},{timeout:500});return()=>{E=!0,window.clearTimeout(ho),window.cancelAnimationFrame(po),mt!==void 0&&pe&&pe(mt)}},[e,n]),h.useEffect(()=>{$e({})},[t?.uid]);const oo=h.useMemo(()=>{const E=new Set;return rt.map(q=>_A(q)).filter(q=>q!==null).filter(q=>E.has(q)?!1:(E.add(q),!0))},[rt]),io=h.useMemo(()=>{const E=Ze.length>0?Ze:oo,M=new Set;return E.filter(q=>M.has(q)?!1:(M.add(q),!0))},[Ze,oo]),kp=()=>{Ht(!0)};h.useEffect(()=>{const E=()=>Ht(!0);return window.addEventListener("mathpulse:open-assessment",E),()=>window.removeEventListener("mathpulse:open-assessment",E)},[]),h.useEffect(()=>{if(!e||n!=="student"||!Yn||!t?.uid)return;let E=!1;return(async()=>{try{un(!!P?.assessmentDismissed),zs(!!P?.initialAssessmentCompleted);const q=await Xo(U(L,"diagnosticResults",t.uid)).catch(()=>me(U(L,"diagnosticResults",t.uid))),pe=await Xo(U(L,"competencyProfiles",t.uid)).catch(()=>me(U(L,"competencyProfiles",t.uid)));if(E)return;const ho=q.exists()&&q.data()?.status==="completed",po=pe.exists()&&pe.data()?.overallScore>0;if(!ho&&!po){ln(!1);const mt=setTimeout(()=>{!E&&!no&&!Tt&&(sessionStorage.getItem("mathpulse_iar_session_dismissed")==="true"||Ht(!0))},1e3);return()=>clearTimeout(mt)}else{if(ln(!0),q.exists()){const mt=q.data();mt?.riskProfile&&(Ue(mt.riskProfile.weak_domains||[]),dn(mt.riskProfile.critical_gaps||[]))}if(pe.exists()){const mt=pe.data();mt?.primaryWeakness&&Ue(Xa=>[...new Set([...Xa,mt.primaryWeakness])])}}}catch(q){console.error("[diagnostic] Firestore check failed:",q)}})(),()=>{E=!0}},[e,n,Yn,t?.uid,so]);const Tp=[...rt].sort().join("|"),Jn=t?.uid?`mathpulse_supplemental_dismissed_${t.uid}`:null;h.useEffect(()=>{if(!Jn){pt("");return}try{const E=localStorage.getItem(Jn)||"";pt(E)}catch{pt("")}},[Jn]);const _p=()=>{if(pt(""),!!Jn)try{localStorage.removeItem(Jn)}catch{}};rt.length>0,h.useEffect(()=>{(async()=>{if(!t?.uid){kt(yr);return}try{const M=await Zh(t.uid);kt(M)}catch(M){console.error("Error loading user settings:",M),kt(yr)}})()},[t?.uid]),h.useEffect(()=>{uC(cn)},[cn]);const Pp=(E,M)=>{Ht(!1),An(E),tt(M),Q(!0)},Qa=async E=>{if(Q(!1),ln(!0),Re(!0),E.xpEarned>0&&t?.uid)try{await No(t.uid,E.xpEarned,"manual","Diagnostic assessment completed"),ct.success(`Assessment complete! +${E.xpEarned} XP earned. ${E.badgeUnlocked.replace("_"," ")} badge unlocked!`)}catch{ct.success("Assessment complete!")}else ct.success("Assessment complete!");if(t?.uid&&E.competencyScores&&E.proficiencyProfile)try{await nC(t.uid,{uid:t.uid,assessmentId:`assessment-${Date.now()}`,completedAt:new Date,rawScore:E.overallScorePercent,totalQuestions:Object.values(E.competencyScores).reduce((M,q)=>M+q.attempted,0),correctAnswers:Object.values(E.competencyScores).reduce((M,q)=>M+q.correct,0),timeSpentSeconds:0,competencyScores:E.competencyScores,recommendations:E.proficiencyProfile.weaknesses.map(M=>`Focus on ${M}`),proficiencyProfile:E.proficiencyProfile,assessmentType:"initial"})}catch(M){console.error("[WARN] Failed to save competency profile:",M)}if(t?.uid)try{const M=UA({assessmentId:Fe?`assessment-${Fe}`:`assessment-${Date.now()}`,overallScorePercent:E.overallScorePercent,overallRisk:E.overallRisk,intervention:E.intervention,proficiencyProfile:E.proficiencyProfile});await qA(t.uid,M)}catch(M){console.error("[App] Failed to save hero banner summary:",M)}if(t?.uid){try{const M=await me(U(L,"diagnosticResults",t.uid));if(M.exists()){const q=M.data();q?.riskProfile&&(Ue(q.riskProfile.weak_domains||[]),dn(q.riskProfile.critical_gaps||[]))}_p()}catch(M){console.error("[diagnostic] Failed to refresh risk data:",M)}try{await dt(U(L,"users",t.uid),{initialAssessmentCompleted:!0,assessmentDismissed:!1,assessmentCompletedAt:ae()}),await No(t.uid,50,"initial_assessment","Initial assessment completed")}catch(M){console.error("[App] Failed to persist assessment completion:",M)}try{await vp({uid:t.uid,testId:Fe||"diagnostic",title:"Diagnostic Assessment",subject:"General Mathematics",type:"diagnostic",score:E.overallScorePercent,totalQuestions:Object.values(E.competencyScores||{}).reduce((M,q)=>M+q.attempted,0),risk:E.overallRisk,intervention:E.intervention,xpEarned:E.xpEarned,badgeUnlocked:E.badgeUnlocked})}catch(M){console.error("[App] Failed to persist grade result:",M)}}},Ep=()=>{f("AI Chat")},Cp=async(E,M)=>{if(t)try{const q=await No(t.uid,E,"manual",M);re(q.xp),q.leveledUp&&F(q.newLevel),B(pe=>pe+E),await r(),le({show:!0,xp:E,message:M})}catch(q){console.error("Error awarding XP:",q)}},ao=async()=>{try{await ou(),$e({}),f("Dashboard"),Y(!1)}catch(E){console.error("Error logging out:",E)}},Rn=async E=>{if(!t){it(!1),be(!1);return}const M={};["name","email","phone","photo","avatarLayers","gender","lrn","grade","section","school","enrollmentDate","major","gpa","department","subject","yearsOfExperience","qualification","position"].forEach(pe=>{E[pe]!==void 0&&(M[pe]=E[pe])});try{await U_(t.uid,M),$e(pe=>({...pe,...M})),it(!1),be(!1),ct.success("Profile updated successfully")}catch(pe){console.error("Error saving profile:",pe),ct.error("Failed to update profile")}},co=async E=>{if(t?.uid)try{const M=await lC(t.uid,E);kt(M),ct.success("Settings saved successfully")}catch(M){throw console.error("Error saving settings:",M),ct.error("Failed to save settings"),M}},lo=async()=>{if(!t?.uid)return;const E=await hC(t.uid),M=new Blob([JSON.stringify(E,null,2)],{type:"application/json"}),q=URL.createObjectURL(M),pe=document.createElement("a");pe.href=q,pe.download=`mathpulse-data-export-${t.uid}-${Date.now()}.json`,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe),URL.revokeObjectURL(q),ct.success("Data export downloaded")},uo=async()=>{await fC(),ct.success("Local cache cleared")},fo=async()=>{if(!t)throw new Error("No active profile found.");const E=n==="student"?P?.lrn||t.uid:void 0;n==="student"&&(await br(U(L,"diagnosticResults",t.uid)).catch(()=>{}),await br(U(L,"competencyProfiles",t.uid)).catch(()=>{}));const{resetTestingDataForRole:M}=await ee(async()=>{const{resetTestingDataForRole:pe}=await import("./testResetService-DiMJKnvV.js");return{resetTestingDataForRole:pe}},__vite__mapDeps([105,1,2,3,4,5,6,7,8,9,10])),q=await M({uid:t.uid,role:n,lrn:E});n==="student"&&(F(1),re(0),B(0),Ue([]),dn([]),ln(null),un(!1),zs(!1),ro("0"),f("Dashboard"),r(),js(pe=>pe+1)),ct.success(q.summary)},Ke=t?{uid:t.uid,name:t.name,email:t.email,phone:t.phone||"",photo:t.photo||"",avatarLayers:t.avatarLayers,role:t.role,...n==="student"&&P?{lrn:P.lrn,grade:P.grade,section:P.section,school:P.school,enrollmentDate:P.enrollmentDate,major:P.major,gpa:$t}:{},...to}:{uid:void 0,name:"User",email:"",phone:"",photo:"",avatarLayers:void 0,role:n},Ns=Ke.name.trim().split(/\s+/).find(E=>/\p{L}/u.test(E))||Ke.name.trim()||"User";if(h.useEffect(()=>{const E=M=>{if(!(M.target instanceof HTMLInputElement||M.target instanceof HTMLTextAreaElement)&&M.altKey)switch(M.key.toLowerCase()){case"d":M.preventDefault(),Z("Dashboard");break;case"m":M.preventDefault(),Z("Modules");break;case"c":M.preventDefault(),Z("AI Chat");break;case"g":M.preventDefault(),Z("Grades");break;case"b":M.preventDefault(),Z("Quiz Battle");break;case"s":M.preventDefault(),be(!0);break;case"p":M.preventDefault(),it(!0);break;case"k":M.preventDefault(),Qn(q=>!q);break}};if(e&&n==="student")return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e,n]),h.useEffect(()=>{const E=M=>{const q=M.detail;q?.tab&&e&&Z(q.tab)};return window.addEventListener("mathpulse:navigate",E),()=>window.removeEventListener("mathpulse:navigate",E)},[e]),s)return b.jsx(ns,{});if(_&&(!e||n!=="admin"))return b.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-[#f8fafc] to-[#eef2ff] p-6",children:b.jsxs("div",{className:"bg-white rounded-2xl shadow-xl border border-slate-200 p-8 max-w-md w-full text-center",children:[b.jsx("div",{className:"w-16 h-16 rounded-full bg-amber-100 flex items-center justify-center mx-auto mb-5",children:b.jsx(Ei,{className:"w-8 h-8 text-amber-600"})}),b.jsx("h1",{className:"text-xl font-bold text-[#1e293b] mb-2",children:"System Under Maintenance"}),b.jsx("p",{className:"text-sm text-[#64748b] leading-relaxed mb-4",children:"MathPulse AI is currently undergoing scheduled maintenance. All user sessions have been paused and your progress has been saved."}),b.jsx("p",{className:"text-xs text-[#94a3b8]",children:"Please check back shortly. We apologize for the inconvenience."})]})});if(!e)return b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading sign in..."}),children:b.jsx(ZA,{})});if(!(n!=="student"||Yn))return b.jsx(ns,{message:"Preparing your dashboard..."});if(n==="teacher")return b.jsx(qo,{children:b.jsxs(b.Fragment,{children:[b.jsx(Ho,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading teacher dashboard..."}),children:b.jsx(KA,{onLogout:ao,onOpenProfile:()=>it(!0),onOpenSettings:()=>be(!0)})}),Ae&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ko,{isOpen:Ae,onClose:()=>it(!1),profileData:Ke,onSave:Rn})}),Ne&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Qo,{isOpen:Ne,onClose:()=>be(!1),profileData:Ke,onSave:Rn,settingsData:cn,onSaveSettings:co,onApplySettingsPreview:kt,onExportData:lo,onClearCache:uo,onResetData:fo})}),b.jsx($o,{position:"top-right",richColors:!0,closeButton:!0})]})});if(n==="admin")return b.jsx(qo,{children:b.jsxs(b.Fragment,{children:[b.jsx(Ho,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading admin dashboard..."}),children:b.jsx(QA,{onLogout:ao,onOpenProfile:()=>it(!0),onOpenSettings:()=>be(!0)})}),Ae&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ko,{isOpen:Ae,onClose:()=>it(!1),profileData:Ke,onSave:Rn})}),Ne&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Qo,{isOpen:Ne,onClose:()=>be(!1),profileData:Ke,onSave:Rn,settingsData:cn,onSaveSettings:co,onApplySettingsPreview:kt,onExportData:lo,onClearCache:uo,onResetData:fo})}),b.jsx($o,{position:"top-right",richColors:!0,closeButton:!0})]})});const Ap=b.jsx(qo,{children:b.jsxs(b.Fragment,{children:[b.jsx(Ho,{}),b.jsx(ZP,{children:b.jsxs("div",{className:"flex h-screen w-full bg-[#f8faff] overflow-hidden",children:[b.jsx("div",{className:"hidden lg:block",children:b.jsx(h.Suspense,{fallback:u,children:b.jsx(Nu,{activeTab:l,setActiveTab:Z,userRole:n,onOpenSettings:()=>be(!0),onLogout:()=>Y(!0),sidebarCollapsed:k,setSidebarCollapsed:S,forceCollapsed:l==="Quiz Battle"})})}),w&&b.jsxs(b.Fragment,{children:[b.jsx("button",{"aria-label":"Close navigation",className:"fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-[1px] lg:hidden",onClick:()=>T(!1)}),b.jsx("div",{className:"fixed inset-y-0 left-0 z-50 p-3 lg:hidden",children:b.jsx(h.Suspense,{fallback:u,children:b.jsx(Nu,{mode:"mobile",onRequestClose:()=>T(!1),activeTab:l,setActiveTab:Z,userRole:n,onOpenSettings:()=>{be(!0),T(!1)},onLogout:()=>{Y(!0),T(!1)},sidebarCollapsed:!1})})})]}),b.jsxs("div",{className:"flex-1 min-h-0 flex flex-col min-w-0 bg-gradient-to-br from-indigo-200 via-fuchsia-50 to-orange-100 relative z-10 shadow-[rgba(124,58,237,0.05)_0px_0px_30px_inset]",children:[b.jsx("div",{className:"absolute inset-0 bg-math-pattern opacity-30 pointer-events-none mix-blend-multiply z-0"}),b.jsxs("header",{className:"bg-white/90 backdrop-blur-md border-b border-[#dde3eb] px-3 sm:px-6 py-2 sm:py-3 flex flex-row items-center justify-between gap-2 sm:gap-3 sticky top-0 z-30 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[b.jsx("button",{className:"lg:hidden p-2 rounded-xl bg-[#edf1f7] hover:bg-[#dde3eb] text-[#5a6578] hover:text-primary transition-colors",onClick:()=>T(!0),"aria-label":"Open navigation",children:b.jsx(Bx,{size:20})}),b.jsxs("div",{className:"min-w-0",children:[b.jsx("h1",{className:"text-base sm:text-xl font-display font-bold text-[#0a1628] leading-tight truncate",children:l==="Grades"?"Assessment":l==="Leaderboard"?"Leadership Board":l}),b.jsxs("p",{className:"hidden sm:block text-xs text-[#5a6578] font-body truncate",children:["Welcome back, ",Ke.name.split(" ")[0],"!"]})]}),b.jsxs("div",{className:"hidden md:flex items-center gap-2 ml-2",children:[b.jsxs("button",{onClick:()=>W(!0),className:"flex items-center gap-1.5 px-3 py-1.5 bg-rose-50 hover:bg-rose-100 border border-rose-200/60 rounded-lg transition-colors cursor-pointer group",title:"View Rewards & Progress",children:[b.jsx(mr,{className:"h-3.5 w-3.5 text-rose-500","aria-hidden":"true"}),b.jsxs("span",{className:"text-xs font-display font-bold text-rose-700",children:["Lv ",V]})]}),b.jsxs("button",{onClick:()=>W(!0),className:"flex items-center gap-2 px-3 py-1.5 bg-violet-50 hover:bg-violet-100 border border-violet-200/60 rounded-lg transition-colors cursor-pointer w-[180px] xl:w-[200px] justify-between",title:`${ce}/${ie} XP to next level`,children:[b.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b.jsx(Ci,{className:"h-3.5 w-3.5 text-violet-500","aria-hidden":"true"}),b.jsxs("span",{className:"text-xs font-display font-bold text-violet-700 whitespace-nowrap",children:[H," XP"]})]}),b.jsx("div",{className:"h-1.5 flex-1 min-w-0 bg-violet-100 rounded-full overflow-hidden",children:b.jsx("div",{className:"h-full bg-violet-500 rounded-full transition-all e-w",style:{"--w":`${Math.max(0,Math.min(100,ce/ie*100))}%`}})})]}),b.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-orange-50 border border-orange-200/60 rounded-lg",children:[b.jsx(gr,{className:"h-3.5 w-3.5 text-orange-500","aria-hidden":"true"}),b.jsx("span",{className:"text-xs font-display font-bold text-orange-700",children:"Daily Rewards"})]})]})]}),b.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 shrink-0",children:[b.jsx("button",{onClick:()=>Qn(E=>!E),className:"p-3 rounded-xl bg-[#edf1f7] hover:bg-[#dde3eb] text-[#5a6578] hover:text-primary transition-all group",title:"Scientific Calculator (Alt+K)",children:b.jsx(Px,{size:20,className:"group-hover:scale-110 transition-transform"})}),b.jsx(h.Suspense,{fallback:c,children:b.jsx(eR,{})}),b.jsxs("button",{onClick:()=>it(!0),className:"flex items-center gap-2.5 h-11 shrink-0 bg-[#edf1f7] hover:bg-[#dde3eb] p-1.5 pr-3 rounded-lg cursor-pointer transition-all group","aria-label":`Profile: ${Ke.name}`,children:[b.jsx(kA,{src:Ke.photo,name:Ke.name,className:"w-8 h-8 rounded-lg"}),b.jsx("div",{className:"hidden sm:block text-left min-w-0 flex-1",children:b.jsx("p",{className:"text-sm font-semibold text-[#0a1628] leading-none group-hover:text-primary transition-colors font-body truncate",children:Ns})})]})]})]}),b.jsx("main",{ref:v,className:`flex-1 min-h-0 ${l==="AI Chat"||l==="Modules"?"overflow-hidden p-0":"p-3 lg:p-4 overflow-y-auto pb-24 sm:pb-28"}`,children:b.jsx(Uf,{mode:"wait",children:b.jsx(Nn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.25,ease:[.22,1,.36,1]},className:l==="AI Chat"||l==="Modules"?"h-full min-h-0":"",children:l==="Dashboard"?b.jsx("div",{className:"px-4 sm:px-6 xl:px-10 py-6 sm:py-8",children:b.jsxs("div",{className:"grid grid-cols-12 gap-6 sm:gap-8 lg:gap-10",children:[b.jsxs("div",{className:"col-span-12 xl:col-span-9 flex flex-col gap-10 lg:gap-14 pt-0",children:[b.jsx(h.Suspense,{fallback:d,children:b.jsx(XA,{userName:Ns,userLevel:V,avatarLayers:Ke.avatarLayers,onContinueLearning:()=>Z("Modules"),showAssessmentTooltip:!Zt&&Zt!==null,onOpenAssessment:kp,studentId:t?.uid,assessmentCompleted:Zt===!0})}),Wt&&Zt&&oo.length>0&&b.jsxs("div",{className:"rounded-2xl border border-amber-300 bg-amber-50 px-5 py-4 shadow-sm dark:border-amber-400/40 dark:bg-amber-400/10",children:[b.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[b.jsxs("div",{children:[b.jsxs("p",{className:"inline-flex items-center gap-2 text-sm font-black text-amber-900 dark:text-amber-200",children:[b.jsx(Ei,{className:"h-4 w-4"}),"Assessment Focus Review"]}),b.jsx("p",{className:"mt-1 text-sm text-amber-900/85 dark:text-amber-100/90",children:"Your latest diagnostic flagged these topics for review. Modules are prioritized based on this focus order."})]}),b.jsxs("button",{type:"button",onClick:()=>Z("Modules"),className:"inline-flex items-center gap-1.5 rounded-xl bg-amber-600 px-3 py-2 text-xs font-bold text-white transition-colors hover:bg-amber-700",children:["Open Modules",b.jsx(bx,{className:"h-3.5 w-3.5"})]})]}),b.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:io.map((E,M)=>b.jsxs("span",{className:"rounded-full bg-white/90 px-3 py-1 text-xs font-semibold text-amber-900 shadow-sm dark:bg-amber-100/20 dark:text-amber-100",children:[M+1,". ",TA[E]]},E))})]}),Wt&&(P?.flaggedTopics?.length||rt.length>0)&&b.jsx(h.Suspense,{fallback:a,children:b.jsx(tR,{flaggedTopics:P?.flaggedTopics||[],atRiskSubjects:rt,moduleStatusMap:X,studentId:t?.uid,onTopicClick:E=>{Z("Modules",E)},onNavigateToPrerequisite:E=>{Z("Modules",E)}})}),Yn&&Wt&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(nR,{modules:He,onNavigateToModules:E=>Z("Modules",E),atRiskSubjects:rt,priorityTopics:io})})}),Yn&&Wt&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(sR,{})})})]}),b.jsx("div",{className:"col-span-12 xl:col-span-3 pt-2",children:Wt?b.jsx(h.Suspense,{fallback:d,children:b.jsx(YA,{currentUserId:t?.uid||"",onOpenRewards:()=>W(!0),onOpenLeaderboard:()=>f("Leaderboard"),onNavigateToModules:()=>f("Modules"),onNavigateToQuizBattle:()=>Z("Quiz Battle"),userLevel:V,userPhoto:Ke.photo,currentXP:ce,xpToNextLevel:ie,overallXP:H,userName:Ns})}):d})]})}):l==="Modules"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(rR,{onEarnXP:Cp,atRiskSubjects:rt,priorityTopics:io,initialModuleId:Gt,isInQuizMode:Os,setIsInQuizMode:En,hasCompletedDiagnostic:Zt??!1})}):l==="Leaderboard"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(aR,{currentUserPhoto:Ke.photo})}):l==="Quiz Battle"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(cR,{})}):l==="AI Chat"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(oR,{})}):l==="Grades"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(iR,{})}):l==="Avatar Studio"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(lR,{onSaveProfile:E=>{$e(M=>({...M,avatarLayers:E}))},onNavigateToModules:()=>Z("Modules"),unsavedChangesRef:p,pendingNavigation:m,onConfirmLeave:()=>{const E=m;g(null),E&&setTimeout(()=>Z(E),0)},onCancelNavigation:()=>g(null)})}):b.jsxs("div",{className:"flex-1 flex items-center justify-center text-[#a8a5b3] font-medium font-body",children:[l," Content Coming Soon"]})},l)})}),l!=="AI Chat"&&!Os&&b.jsx(h.Suspense,{fallback:null,children:b.jsx("div",{className:"fixed bottom-4 right-4 sm:bottom-8 sm:right-8 z-50",children:b.jsx(uR,{constraintsRef:y,onFullScreen:Ep})})}),b.jsx(h.Suspense,{fallback:null,children:b.jsx(JA,{xp:O.xp,message:O.message,show:O.show,onComplete:()=>le(E=>({...E,show:!1}))})}),ue&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(dR,{isOpen:ue,onClose:()=>W(!1),userLevel:V,currentXP:ce,xpToNextLevel:ie,totalXP:te,userId:t?.uid||""})}),Ae&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ko,{isOpen:Ae,onClose:()=>it(!1),profileData:Ke,onSave:Rn})}),Te&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(fR,{isOpen:Te,onClose:()=>Y(!1),onConfirm:ao,title:"Confirm Logout",message:"Are you sure you want to log out? Your progress is saved automatically.",confirmText:"Logout",cancelText:"Stay",type:"warning",icon:"logout"})}),Ne&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Qo,{isOpen:Ne,onClose:()=>be(!1),profileData:Ke,onSave:Rn,settingsData:cn,onSaveSettings:co,onApplySettingsPreview:kt,onExportData:lo,onClearCache:uo,onResetData:fo})}),at&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(hR,{isOpen:at,onClose:()=>Qn(!1)})}),Ls&&!Cn&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(pR,{isOpen:Ls&&!Cn,onClose:()=>Ht(!1),onDismiss:()=>{Ht(!1),un(!0)},userId:t?.uid||"",strand:P?.major||"STEM",gradeLevel:P?.grade||"Grade 11",onAssessmentStart:Pp,onAssessmentComplete:Qa})}),Cn&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(mR,{testId:Fe,questions:Me,userName:Ns,onComplete:Qa,onCancel:()=>{Q(!1),f("Dashboard")}})}),Pe&&t?.uid&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(gR,{userId:t.uid,mode:"fullscreen",onClose:()=>{Re(!1),f("Dashboard")}})})]})]})}),b.jsx($o,{position:"top-right",richColors:!0,closeButton:!0})]})});return b.jsx(G_,{children:Ap})},sr="mathpulse_chunk_reload_attempted",bR=[/Failed to fetch dynamically imported module/i,/Loading chunk \d+ failed/i,/Importing a module script failed/i,/error loading dynamically imported module/i];function $u(e){return e?.message?bR.some(t=>t.test(e.message)):!1}class vR extends h.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){if(console.error("[ErrorBoundary] Caught render error:",t.message,n.componentStack),$u(t))try{sessionStorage.getItem(sr)||(sessionStorage.setItem(sr,String(Date.now())),console.warn("[ErrorBoundary] Stale chunk detected — reloading to recover."),window.location.reload())}catch{}}handleReset=()=>{try{sessionStorage.removeItem(sr)}catch{}this.setState({hasError:!1,error:null})};render(){if(this.state.hasError){if($u(this.state.error)){let t=!1;try{t=!!sessionStorage.getItem(sr)}catch{}if(!t)return null}return this.props.fallback?this.props.fallback:b.jsx("div",{className:"flex min-h-screen flex-col items-center justify-center bg-slate-50 p-8 text-center",children:b.jsxs("div",{className:"max-w-md rounded-xl border border-slate-200 bg-white p-8 shadow-sm",children:[b.jsx("h2",{className:"mb-2 text-xl font-semibold text-slate-900",children:"Something went wrong"}),b.jsx("p",{className:"mb-6 text-sm text-slate-600",children:"The application encountered an unexpected error. Please try refreshing the page."}),this.state.error&&b.jsx("pre",{className:"mb-6 max-h-24 overflow-auto rounded bg-red-50 p-3 text-left text-xs text-red-700",children:this.state.error.message}),b.jsx("button",{onClick:this.handleReset,className:"rounded-lg bg-blue-600 px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Try again"}),b.jsx("button",{onClick:()=>window.location.reload(),className:"ml-3 rounded-lg border border-slate-300 bg-white px-6 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50",children:"Refresh page"})]})})}return this.props.children}}dC();try{sessionStorage.removeItem("mathpulse_chunk_reload_attempted")}catch{}typeof window<"u"&&(window.addEventListener("error",e=>{console.error("[global] Uncaught error:",e.error?.message??e.message)}),window.addEventListener("unhandledrejection",e=>{console.error("[global] Unhandled promise rejection:",e.reason?.message??e.reason),e.preventDefault()}));{const e=(...t)=>{};console.log=e,console.info=e,console.debug=e}const Sp=document.getElementById("root");if(!Sp)throw new Error("Root element not found");Mp.createRoot(Sp).render(b.jsx(vR,{children:b.jsx(sy,{children:b.jsx(jm,{client:$i,children:b.jsx(q_,{children:b.jsx(yR,{})})})})}));export{gr as $,Dl as A,Tx as B,Px as C,sS as D,sM as E,$l as F,Ll as G,Ol as H,RA as I,uS as J,ns as K,Fx as L,Bx as M,Sx as N,kA as O,QE as P,xn as Q,qx as R,jr as S,Nl as T,oS as U,zl as V,vA as W,zu as X,wA as Y,Ci as Z,ee as _,bx as a,mC as a$,IR as a0,Dx as a1,Ws as a2,lM as a3,cM as a4,VR as a5,mr as a6,Hx as a7,qo as a8,ep as a9,Yo as aA,Vu as aB,Mm as aC,vm as aD,Xe as aE,MR as aF,$R as aG,VA as aH,BA as aI,XE as aJ,BR as aK,FR as aL,fS as aM,sh as aN,La as aO,UR as aP,U_ as aQ,KP as aR,zx as aS,Ax as aT,Kx as aU,OR as aV,Pu as aW,Eu as aX,tM as aY,nM as aZ,pC as a_,gC as aa,_A as ab,oM as ac,WR as ad,QR as ae,KR as af,ZR as ag,HR as ah,XR as ai,No as aj,qR as ak,jA as al,$A as am,GR as an,iM as ao,LE as ap,TA as aq,$r as ar,km as as,gm as at,RR as au,Jo as av,wt as aw,qu as ax,pm as ay,mm as az,Oo as b,yr as b0,JR as b1,YR as b2,eM as b3,Ut as b4,eo as b5,uP as b6,pS as b7,tC as b8,rM as b9,aM as ba,zR as c,jR as d,he as e,Jh as f,L as g,Uf as h,Fl as i,ct as j,ye as k,ZE as l,Nn as m,bt as n,bn as o,It as p,Nx as q,jl as r,LR as s,Yh as t,Ms as u,xA as v,j as w,NR as x,Ei as y,sC as z}; diff --git a/assets/index-B23D5AFn.js b/assets/index-oMQKBL9u.js similarity index 92% rename from assets/index-B23D5AFn.js rename to assets/index-oMQKBL9u.js index fbacc7828e8a681570b5e026dd6272f1adc4f1af..973fa6af703531d859d8a5d82cc37fc94e037eb2 100644 --- a/assets/index-B23D5AFn.js +++ b/assets/index-oMQKBL9u.js @@ -1 +1 @@ -import{E as m,y as u,Z as p,b as h,$ as f,T as b,F as g}from"./index-BvEKrMkD.js";import{a8 as W,a9 as ee}from"./index-BvEKrMkD.js";import{j as e,r as c,b as v}from"./vendor-react-B4AQeu28.js";import{C as k}from"./circle-alert-fPu7cawt.js";import{M as y}from"./megaphone-DpNhcxX3.js";import{B as d}from"./bell-C57aSZcx.js";import{C as j}from"./circle-check-big-mtMsU82c.js";import{C as N}from"./clipboard-check-jJ306e7q.js";import{f as w,C as _}from"./formatDistanceToNow-5Jvf3U0l.js";import{T as C}from"./trash-2-B056YIHV.js";import{X as E}from"./x-BYtx1i07.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const R={achievement_unlocked:g,level_up:b,quiz_result:N,daily_checkin:j,streak_milestone:f,streak_reminder:d,teacher_announcement:y,new_assignment:h,xp_earned:p,system_alert:k,risk_alert:u},z=t=>{switch(t){case"achievement_unlocked":case"achievement":return"bg-rose-500/10 text-rose-600";case"xp_earned":return"bg-amber-500/10 text-amber-600";case"daily_checkin":case"checkin":return"bg-emerald-500/10 text-emerald-600";case"streak_milestone":case"streak_reminder":return"bg-orange-500/10 text-orange-600";case"teacher_announcement":return"bg-violet-500/10 text-violet-600";case"new_assignment":case"quiz_result":return"bg-sky-500/10 text-sky-600";case"level_up":return"bg-indigo-500/10 text-indigo-600";case"system_alert":return"bg-red-500/10 text-red-600";case"risk_alert":return"bg-amber-500/10 text-amber-700";default:return"bg-[#edf1f7] text-[#5a6578]"}},T=({notification:t})=>{const{markAsRead:r,deleteNotification:a}=m(),o=R[t.type]||d,i=z(t.type),n=()=>{if(t.isRead||r(t.id),t.type==="streak_reminder"||t.type==="daily_checkin"){window.dispatchEvent(new CustomEvent("mathpulse:navigate",{detail:{tab:"Modules"}}));return}t.actionUrl&&(window.location.href=t.actionUrl)},l=w(t.createdAt,{addSuffix:!0});return e.jsx("div",{role:"button",tabIndex:0,onClick:n,onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())},className:`group text-left p-4 border-b border-[#dde3eb] cursor-pointer transition-colors hover:bg-[#edf1f7]/50 ${t.isRead?"":"bg-sky-50/40"}`,children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${i}`,children:e.jsx(o,{size:18})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] line-clamp-1 font-body",children:t.title}),!t.isRead&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-sky-600 flex-shrink-0 mt-1.5"})]}),e.jsx("p",{className:"text-xs text-[#5a6578] mb-2 line-clamp-2 font-body",children:t.message}),e.jsx("p",{className:"text-xs text-slate-500",children:l})]}),e.jsx("button",{onClick:s=>{s.stopPropagation(),a(t.id)},className:"opacity-0 group-hover:opacity-100 transition-opacity text-slate-400 hover:text-red-500","aria-label":"Delete notification",children:e.jsx(C,{size:14})})]})})},A=({onClose:t})=>{const{notifications:r,unreadCount:a,isLoading:o,markAllAsRead:i}=m(),n=c.useRef(null);c.useEffect(()=>{const s=x=>{n.current&&!n.current.contains(x.target)&&t()};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[t]);const l=e.jsxs("div",{ref:n,className:"fixed right-4 top-20 w-80 bg-[#f7f9fc] rounded-xl shadow-2xl border border-[#dde3eb] max-h-96 overflow-y-auto z-[9999] overflow-hidden",style:{right:"1rem",top:"5rem"},children:[e.jsxs("div",{className:"p-4 border-b border-[#dde3eb] flex items-center justify-between bg-gradient-to-r from-sky-600 to-sky-500",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-bold text-white text-sm",children:"Notifications"}),e.jsx("p",{className:"text-xs text-sky-100 mt-0.5",children:a>0?`${a} unread`:"No new alerts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[a>0&&e.jsxs("button",{onClick:i,className:"text-xs text-sky-200 hover:text-white font-bold transition-colors flex items-center gap-1",children:[e.jsx(_,{size:14}),"Mark all read"]}),e.jsx("button",{onClick:t,className:"text-sky-200 hover:text-white transition-colors",title:"Close",children:e.jsx(E,{size:16})})]})]}),e.jsx("div",{className:"max-h-80 overflow-y-auto",children:o?e.jsx("div",{className:"p-4 space-y-3",children:[1,2,3].map(s=>e.jsx("div",{className:"animate-pulse bg-[#dde3eb] rounded h-12"},s))}):r.length===0?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(d,{size:48,className:"text-[#d1cec6] mx-auto mb-3"}),e.jsx("p",{className:"text-[#5a6578] text-sm font-body",children:"You're all caught up!"})]}):r.map(s=>e.jsx(T,{notification:s},s.id))})]});return v.createPortal(l,document.body)},J=()=>{const{unreadCount:t}=m(),[r,a]=c.useState(!1),o=c.useRef(null);c.useEffect(()=>{const n=l=>{o.current&&!o.current.contains(l.target)&&a(!1)};return r&&document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n)}},[r]);const i=t>99?"99+":t.toString();return e.jsxs("div",{ref:o,className:"relative",children:[e.jsxs("button",{onClick:()=>a(!r),className:"relative p-3 bg-[#edf1f7] rounded-xl text-[#5a6578] hover:bg-[#dde3eb] transition-colors","aria-label":"Notifications","aria-expanded":r,"aria-haspopup":"true",children:[e.jsx(d,{size:20}),t>0&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full min-w-[18px] h-[18px] flex items-center justify-center px-1",children:i})]}),r&&e.jsx(A,{onClose:()=>a(!1)})]})};export{J as NotificationBell,W as NotificationProvider,ee as notify,m as useNotifications}; +import{E as m,y as u,Z as p,b as h,$ as f,T as b,F as g}from"./index-BdLfAeGL.js";import{a8 as W,a9 as ee}from"./index-BdLfAeGL.js";import{j as e,r as c,b as v}from"./vendor-react-B4AQeu28.js";import{C as k}from"./circle-alert-ByVTnT3r.js";import{M as y}from"./megaphone-Cd4AJY3E.js";import{B as d}from"./bell-C5_RRTsA.js";import{C as j}from"./circle-check-big-B54zXy3k.js";import{C as N}from"./clipboard-check-hgJTQlzs.js";import{f as w,C as _}from"./formatDistanceToNow-DQ9IJwBi.js";import{T as C}from"./trash-2-f-pq6QuO.js";import{X as E}from"./x-BLhsirCD.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const R={achievement_unlocked:g,level_up:b,quiz_result:N,daily_checkin:j,streak_milestone:f,streak_reminder:d,teacher_announcement:y,new_assignment:h,xp_earned:p,system_alert:k,risk_alert:u},z=t=>{switch(t){case"achievement_unlocked":case"achievement":return"bg-rose-500/10 text-rose-600";case"xp_earned":return"bg-amber-500/10 text-amber-600";case"daily_checkin":case"checkin":return"bg-emerald-500/10 text-emerald-600";case"streak_milestone":case"streak_reminder":return"bg-orange-500/10 text-orange-600";case"teacher_announcement":return"bg-violet-500/10 text-violet-600";case"new_assignment":case"quiz_result":return"bg-sky-500/10 text-sky-600";case"level_up":return"bg-indigo-500/10 text-indigo-600";case"system_alert":return"bg-red-500/10 text-red-600";case"risk_alert":return"bg-amber-500/10 text-amber-700";default:return"bg-[#edf1f7] text-[#5a6578]"}},T=({notification:t})=>{const{markAsRead:r,deleteNotification:a}=m(),o=R[t.type]||d,i=z(t.type),n=()=>{if(t.isRead||r(t.id),t.type==="streak_reminder"||t.type==="daily_checkin"){window.dispatchEvent(new CustomEvent("mathpulse:navigate",{detail:{tab:"Modules"}}));return}t.actionUrl&&(window.location.href=t.actionUrl)},l=w(t.createdAt,{addSuffix:!0});return e.jsx("div",{role:"button",tabIndex:0,onClick:n,onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())},className:`group text-left p-4 border-b border-[#dde3eb] cursor-pointer transition-colors hover:bg-[#edf1f7]/50 ${t.isRead?"":"bg-sky-50/40"}`,children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${i}`,children:e.jsx(o,{size:18})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:"text-sm font-bold text-[#0a1628] line-clamp-1 font-body",children:t.title}),!t.isRead&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-sky-600 flex-shrink-0 mt-1.5"})]}),e.jsx("p",{className:"text-xs text-[#5a6578] mb-2 line-clamp-2 font-body",children:t.message}),e.jsx("p",{className:"text-xs text-slate-500",children:l})]}),e.jsx("button",{onClick:s=>{s.stopPropagation(),a(t.id)},className:"opacity-0 group-hover:opacity-100 transition-opacity text-slate-400 hover:text-red-500","aria-label":"Delete notification",children:e.jsx(C,{size:14})})]})})},A=({onClose:t})=>{const{notifications:r,unreadCount:a,isLoading:o,markAllAsRead:i}=m(),n=c.useRef(null);c.useEffect(()=>{const s=x=>{n.current&&!n.current.contains(x.target)&&t()};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[t]);const l=e.jsxs("div",{ref:n,className:"fixed right-4 top-20 w-80 bg-[#f7f9fc] rounded-xl shadow-2xl border border-[#dde3eb] max-h-96 overflow-y-auto z-[9999] overflow-hidden",style:{right:"1rem",top:"5rem"},children:[e.jsxs("div",{className:"p-4 border-b border-[#dde3eb] flex items-center justify-between bg-gradient-to-r from-sky-600 to-sky-500",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-bold text-white text-sm",children:"Notifications"}),e.jsx("p",{className:"text-xs text-sky-100 mt-0.5",children:a>0?`${a} unread`:"No new alerts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[a>0&&e.jsxs("button",{onClick:i,className:"text-xs text-sky-200 hover:text-white font-bold transition-colors flex items-center gap-1",children:[e.jsx(_,{size:14}),"Mark all read"]}),e.jsx("button",{onClick:t,className:"text-sky-200 hover:text-white transition-colors",title:"Close",children:e.jsx(E,{size:16})})]})]}),e.jsx("div",{className:"max-h-80 overflow-y-auto",children:o?e.jsx("div",{className:"p-4 space-y-3",children:[1,2,3].map(s=>e.jsx("div",{className:"animate-pulse bg-[#dde3eb] rounded h-12"},s))}):r.length===0?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(d,{size:48,className:"text-[#d1cec6] mx-auto mb-3"}),e.jsx("p",{className:"text-[#5a6578] text-sm font-body",children:"You're all caught up!"})]}):r.map(s=>e.jsx(T,{notification:s},s.id))})]});return v.createPortal(l,document.body)},J=()=>{const{unreadCount:t}=m(),[r,a]=c.useState(!1),o=c.useRef(null);c.useEffect(()=>{const n=l=>{o.current&&!o.current.contains(l.target)&&a(!1)};return r&&document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n)}},[r]);const i=t>99?"99+":t.toString();return e.jsxs("div",{ref:o,className:"relative",children:[e.jsxs("button",{onClick:()=>a(!r),className:"relative p-3 bg-[#edf1f7] rounded-xl text-[#5a6578] hover:bg-[#dde3eb] transition-colors","aria-label":"Notifications","aria-expanded":r,"aria-haspopup":"true",children:[e.jsx(d,{size:20}),t>0&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full min-w-[18px] h-[18px] flex items-center justify-center px-1",children:i})]}),r&&e.jsx(A,{onClose:()=>a(!1)})]})};export{J as NotificationBell,W as NotificationProvider,ee as notify,m as useNotifications}; diff --git a/assets/index.es-CkGqZuf8.js b/assets/index.es-CAwVNbbg.js similarity index 99% rename from assets/index.es-CkGqZuf8.js rename to assets/index.es-CAwVNbbg.js index 94839ddb00ff9c87ec6ed4d44cfffbca2cad3f55..87dbe6181007dda853a65d18d1def79bee3187e5 100644 --- a/assets/index.es-CkGqZuf8.js +++ b/assets/index.es-CAwVNbbg.js @@ -1,4 +1,4 @@ -import{e as Va,g as il}from"./vendor-react-B4AQeu28.js";import{_ as La}from"./jspdf.es.min-CpWaCVL9.js";import"./index-BvEKrMkD.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";var fn={},cn={},cr,vn;function Q(){if(vn)return cr;vn=1;var n=function(e){return e&&e.Math===Math&&e};return cr=n(typeof globalThis=="object"&&globalThis)||n(typeof window=="object"&&window)||n(typeof self=="object"&&self)||n(typeof Va=="object"&&Va)||n(typeof cr=="object"&&cr)||(function(){return this})()||Function("return this")(),cr}var Zr={},Jr,gn;function Z(){return gn||(gn=1,Jr=function(n){try{return!!n()}catch{return!0}}),Jr}var et,dn;function we(){if(dn)return et;dn=1;var n=Z();return et=!n(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),et}var rt,pn;function Ar(){if(pn)return rt;pn=1;var n=Z();return rt=!n(function(){var e=function(){}.bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),rt}var tt,yn;function se(){if(yn)return tt;yn=1;var n=Ar(),e=Function.prototype.call;return tt=n?e.bind(e):function(){return e.apply(e,arguments)},tt}var it={},mn;function Yl(){if(mn)return it;mn=1;var n={}.propertyIsEnumerable,e=Object.getOwnPropertyDescriptor,r=e&&!n.call({1:2},1);return it.f=r?function(i){var a=e(this,i);return!!a&&a.enumerable}:n,it}var at,bn;function Ua(){return bn||(bn=1,at=function(n,e){return{enumerable:!(n&1),configurable:!(n&2),writable:!(n&4),value:e}}),at}var nt,xn;function J(){if(xn)return nt;xn=1;var n=Ar(),e=Function.prototype,r=e.call,t=n&&e.bind.bind(r,r);return nt=n?t:function(i){return function(){return r.apply(i,arguments)}},nt}var st,On;function er(){if(On)return st;On=1;var n=J(),e=n({}.toString),r=n("".slice);return st=function(t){return r(e(t),8,-1)},st}var ot,Tn;function al(){if(Tn)return ot;Tn=1;var n=J(),e=Z(),r=er(),t=Object,i=n("".split);return ot=e(function(){return!t("z").propertyIsEnumerable(0)})?function(a){return r(a)==="String"?i(a,""):t(a)}:t,ot}var ut,Sn;function Ir(){return Sn||(Sn=1,ut=function(n){return n==null}),ut}var lt,En;function Pe(){if(En)return lt;En=1;var n=Ir(),e=TypeError;return lt=function(r){if(n(r))throw new e("Can't call method on "+r);return r},lt}var ht,Rn;function dr(){if(Rn)return ht;Rn=1;var n=al(),e=Pe();return ht=function(r){return n(e(r))},ht}var ft,Cn;function re(){if(Cn)return ft;Cn=1;var n=typeof document=="object"&&document.all;return ft=typeof n>"u"&&n!==void 0?function(e){return typeof e=="function"||e===n}:function(e){return typeof e=="function"},ft}var ct,wn;function ye(){if(wn)return ct;wn=1;var n=re();return ct=function(e){return typeof e=="object"?e!==null:n(e)},ct}var vt,Pn;function rr(){if(Pn)return vt;Pn=1;var n=Q(),e=re(),r=function(t){return e(t)?t:void 0};return vt=function(t,i){return arguments.length<2?r(n[t]):n[t]&&n[t][i]},vt}var gt,An;function Nr(){if(An)return gt;An=1;var n=J();return gt=n({}.isPrototypeOf),gt}var dt,In;function pr(){if(In)return dt;In=1;var n=Q(),e=n.navigator,r=e&&e.userAgent;return dt=r?String(r):"",dt}var pt,Nn;function Ga(){if(Nn)return pt;Nn=1;var n=Q(),e=pr(),r=n.process,t=n.Deno,i=r&&r.versions||t&&t.version,a=i&&i.v8,s,o;return a&&(s=a.split("."),o=s[0]>0&&s[0]<4?1:+(s[0]+s[1])),!o&&e&&(s=e.match(/Edge\/(\d+)/),(!s||s[1]>=74)&&(s=e.match(/Chrome\/(\d+)/),s&&(o=+s[1]))),pt=o,pt}var yt,_n;function nl(){if(_n)return yt;_n=1;var n=Ga(),e=Z(),r=Q(),t=r.String;return yt=!!Object.getOwnPropertySymbols&&!e(function(){var i=Symbol("symbol detection");return!t(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&n&&n<41}),yt}var mt,Mn;function sl(){if(Mn)return mt;Mn=1;var n=nl();return mt=n&&!Symbol.sham&&typeof Symbol.iterator=="symbol",mt}var bt,qn;function ol(){if(qn)return bt;qn=1;var n=rr(),e=re(),r=Nr(),t=sl(),i=Object;return bt=t?function(a){return typeof a=="symbol"}:function(a){var s=n("Symbol");return e(s)&&r(s.prototype,i(a))},bt}var xt,Dn;function _r(){if(Dn)return xt;Dn=1;var n=String;return xt=function(e){try{return n(e)}catch{return"Object"}},xt}var Ot,Vn;function Fe(){if(Vn)return Ot;Vn=1;var n=re(),e=_r(),r=TypeError;return Ot=function(t){if(n(t))return t;throw new r(e(t)+" is not a function")},Ot}var Tt,Ln;function nr(){if(Ln)return Tt;Ln=1;var n=Fe(),e=Ir();return Tt=function(r,t){var i=r[t];return e(i)?void 0:n(i)},Tt}var St,kn;function Xl(){if(kn)return St;kn=1;var n=se(),e=re(),r=ye(),t=TypeError;return St=function(i,a){var s,o;if(a==="string"&&e(s=i.toString)&&!r(o=n(s,i))||e(s=i.valueOf)&&!r(o=n(s,i))||a!=="string"&&e(s=i.toString)&&!r(o=n(s,i)))return o;throw new t("Can't convert object to primitive value")},St}var Et={exports:{}},Rt,jn;function Me(){return jn||(jn=1,Rt=!1),Rt}var Ct,Bn;function $a(){if(Bn)return Ct;Bn=1;var n=Q(),e=Object.defineProperty;return Ct=function(r,t){try{e(n,r,{value:t,configurable:!0,writable:!0})}catch{n[r]=t}return t},Ct}var Fn;function za(){if(Fn)return Et.exports;Fn=1;var n=Me(),e=Q(),r=$a(),t="__core-js_shared__",i=Et.exports=e[t]||r(t,{});return(i.versions||(i.versions=[])).push({version:"3.49.0",mode:n?"pure":"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"}),Et.exports}var wt,Un;function Ha(){if(Un)return wt;Un=1;var n=za();return wt=function(e,r){return n[e]||(n[e]=r||{})},wt}var Pt,Gn;function Mr(){if(Gn)return Pt;Gn=1;var n=Pe(),e=Object;return Pt=function(r){return e(n(r))},Pt}var At,$n;function Ae(){if($n)return At;$n=1;var n=J(),e=Mr(),r=n({}.hasOwnProperty);return At=Object.hasOwn||function(i,a){return r(e(i),a)},At}var It,zn;function ul(){if(zn)return It;zn=1;var n=J(),e=0,r=Math.random(),t=n(1.1.toString);return It=function(i){return"Symbol("+(i===void 0?"":i)+")_"+t(++e+r,36)},It}var Nt,Hn;function ne(){if(Hn)return Nt;Hn=1;var n=Q(),e=Ha(),r=Ae(),t=ul(),i=nl(),a=sl(),s=n.Symbol,o=e("wks"),u=a?s.for||s:s&&s.withoutSetter||t;return Nt=function(l){return r(o,l)||(o[l]=i&&r(s,l)?s[l]:u("Symbol."+l)),o[l]},Nt}var _t,Wn;function Kl(){if(Wn)return _t;Wn=1;var n=se(),e=ye(),r=ol(),t=nr(),i=Xl(),a=ne(),s=TypeError,o=a("toPrimitive");return _t=function(u,l){if(!e(u)||r(u))return u;var h=t(u,o),c;if(h){if(l===void 0&&(l="default"),c=n(h,u,l),!e(c)||r(c))return c;throw new s("Can't convert object to primitive value")}return l===void 0&&(l="number"),i(u,l)},_t}var Mt,Yn;function ll(){if(Yn)return Mt;Yn=1;var n=Kl(),e=ol();return Mt=function(r){var t=n(r,"string");return e(t)?t:t+""},Mt}var qt,Xn;function qr(){if(Xn)return qt;Xn=1;var n=Q(),e=ye(),r=n.document,t=e(r)&&e(r.createElement);return qt=function(i){return t?r.createElement(i):{}},qt}var Dt,Kn;function hl(){if(Kn)return Dt;Kn=1;var n=we(),e=Z(),r=qr();return Dt=!n&&!e(function(){return Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a!==7}),Dt}var Qn;function Dr(){if(Qn)return Zr;Qn=1;var n=we(),e=se(),r=Yl(),t=Ua(),i=dr(),a=ll(),s=Ae(),o=hl(),u=Object.getOwnPropertyDescriptor;return Zr.f=n?u:function(h,c){if(h=i(h),c=a(c),o)try{return u(h,c)}catch{}if(s(h,c))return t(!e(r.f,h,c),h[c])},Zr}var Vt={},Lt,Zn;function fl(){if(Zn)return Lt;Zn=1;var n=we(),e=Z();return Lt=n&&e(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Lt}var kt,Jn;function he(){if(Jn)return kt;Jn=1;var n=ye(),e=String,r=TypeError;return kt=function(t){if(n(t))return t;throw new r(e(t)+" is not an object")},kt}var es;function Ye(){if(es)return Vt;es=1;var n=we(),e=hl(),r=fl(),t=he(),i=ll(),a=TypeError,s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,u="enumerable",l="configurable",h="writable";return Vt.f=n?r?function(v,f,g){if(t(v),f=i(f),t(g),typeof v=="function"&&f==="prototype"&&"value"in g&&h in g&&!g[h]){var d=o(v,f);d&&d[h]&&(v[f]=g.value,g={configurable:l in g?g[l]:d[l],enumerable:u in g?g[u]:d[u],writable:!1})}return s(v,f,g)}:s:function(v,f,g){if(t(v),f=i(f),t(g),e)try{return s(v,f,g)}catch{}if("get"in g||"set"in g)throw new a("Accessors not supported");return"value"in g&&(v[f]=g.value),v},Vt}var jt,rs;function yr(){if(rs)return jt;rs=1;var n=we(),e=Ye(),r=Ua();return jt=n?function(t,i,a){return e.f(t,i,r(1,a))}:function(t,i,a){return t[i]=a,t},jt}var Bt={exports:{}},Ft,ts;function Vr(){if(ts)return Ft;ts=1;var n=we(),e=Ae(),r=Function.prototype,t=n&&Object.getOwnPropertyDescriptor,i=e(r,"name"),a=i&&function(){}.name==="something",s=i&&(!n||n&&t(r,"name").configurable);return Ft={EXISTS:i,PROPER:a,CONFIGURABLE:s},Ft}var Ut,is;function Wa(){if(is)return Ut;is=1;var n=J(),e=re(),r=za(),t=n(Function.toString);return e(r.inspectSource)||(r.inspectSource=function(i){return t(i)}),Ut=r.inspectSource,Ut}var Gt,as;function Ql(){if(as)return Gt;as=1;var n=Q(),e=re(),r=n.WeakMap;return Gt=e(r)&&/native code/.test(String(r)),Gt}var $t,ns;function Ya(){if(ns)return $t;ns=1;var n=Ha(),e=ul(),r=n("keys");return $t=function(t){return r[t]||(r[t]=e(t))},$t}var zt,ss;function Xa(){return ss||(ss=1,zt={}),zt}var Ht,os;function Lr(){if(os)return Ht;os=1;var n=Ql(),e=Q(),r=ye(),t=yr(),i=Ae(),a=za(),s=Ya(),o=Xa(),u="Object already initialized",l=e.TypeError,h=e.WeakMap,c,v,f,g=function(m){return f(m)?v(m):c(m,{})},d=function(m){return function(b){var x;if(!r(b)||(x=v(b)).type!==m)throw new l("Incompatible receiver, "+m+" required");return x}};if(n||a.state){var p=a.state||(a.state=new h);p.get=p.get,p.has=p.has,p.set=p.set,c=function(m,b){if(p.has(m))throw new l(u);return b.facade=m,p.set(m,b),b},v=function(m){return p.get(m)||{}},f=function(m){return p.has(m)}}else{var y=s("state");o[y]=!0,c=function(m,b){if(i(m,y))throw new l(u);return b.facade=m,t(m,y,b),b},v=function(m){return i(m,y)?m[y]:{}},f=function(m){return i(m,y)}}return Ht={set:c,get:v,has:f,enforce:g,getterFor:d},Ht}var us;function cl(){if(us)return Bt.exports;us=1;var n=J(),e=Z(),r=re(),t=Ae(),i=we(),a=Vr().CONFIGURABLE,s=Wa(),o=Lr(),u=o.enforce,l=o.get,h=String,c=Object.defineProperty,v=n("".slice),f=n("".replace),g=n([].join),d=i&&!e(function(){return c(function(){},"length",{value:8}).length!==8}),p=String(String).split("String"),y=Bt.exports=function(m,b,x){v(h(b),0,7)==="Symbol("&&(b="["+f(h(b),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),x&&x.getter&&(b="get "+b),x&&x.setter&&(b="set "+b),(!t(m,"name")||a&&m.name!==b)&&(i?c(m,"name",{value:b,configurable:!0}):m.name=b),d&&x&&t(x,"arity")&&m.length!==x.arity&&c(m,"length",{value:x.arity});try{x&&t(x,"constructor")&&x.constructor?i&&c(m,"prototype",{writable:!1}):m.prototype&&(m.prototype=void 0)}catch{}var S=u(m);return t(S,"source")||(S.source=g(p,typeof b=="string"?b:"")),m};return Function.prototype.toString=y(function(){return r(this)&&l(this).source||s(this)},"toString"),Bt.exports}var Wt,ls;function tr(){if(ls)return Wt;ls=1;var n=re(),e=Ye(),r=cl(),t=$a();return Wt=function(i,a,s,o){o||(o={});var u=o.enumerable,l=o.name!==void 0?o.name:a;if(n(s)&&r(s,l,o),o.global)u?i[a]=s:t(a,s);else{try{o.unsafe?i[a]&&(u=!0):delete i[a]}catch{}u?i[a]=s:e.f(i,a,{value:s,enumerable:!1,configurable:!o.nonConfigurable,writable:!o.nonWritable})}return i},Wt}var Yt={},Xt,hs;function Zl(){if(hs)return Xt;hs=1;var n=Math.ceil,e=Math.floor;return Xt=Math.trunc||function(t){var i=+t;return(i>0?e:n)(i)},Xt}var Kt,fs;function kr(){if(fs)return Kt;fs=1;var n=Zl();return Kt=function(e){var r=+e;return r!==r||r===0?0:n(r)},Kt}var Qt,cs;function Jl(){if(cs)return Qt;cs=1;var n=kr(),e=Math.max,r=Math.min;return Qt=function(t,i){var a=n(t);return a<0?e(a+i,0):r(a,i)},Qt}var Zt,vs;function sr(){if(vs)return Zt;vs=1;var n=kr(),e=Math.min;return Zt=function(r){var t=n(r);return t>0?e(t,9007199254740991):0},Zt}var Jt,gs;function Ka(){if(gs)return Jt;gs=1;var n=sr();return Jt=function(e){return n(e.length)},Jt}var ei,ds;function vl(){if(ds)return ei;ds=1;var n=dr(),e=Jl(),r=Ka(),t=function(i){return function(a,s,o){var u=n(a),l=r(u);if(l===0)return!i&&-1;var h=e(o,l),c;if(i&&s!==s){for(;l>h;)if(c=u[h++],c!==c)return!0}else for(;l>h;h++)if((i||h in u)&&u[h]===s)return i||h||0;return!i&&-1}};return ei={includes:t(!0),indexOf:t(!1)},ei}var ri,ps;function gl(){if(ps)return ri;ps=1;var n=J(),e=Ae(),r=dr(),t=vl().indexOf,i=Xa(),a=n([].push);return ri=function(s,o){var u=r(s),l=0,h=[],c;for(c in u)!e(i,c)&&e(u,c)&&a(h,c);for(;o.length>l;)e(u,c=o[l++])&&(~t(h,c)||a(h,c));return h},ri}var ti,ys;function Qa(){return ys||(ys=1,ti=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]),ti}var ms;function eh(){if(ms)return Yt;ms=1;var n=gl(),e=Qa(),r=e.concat("length","prototype");return Yt.f=Object.getOwnPropertyNames||function(i){return n(i,r)},Yt}var ii={},bs;function rh(){return bs||(bs=1,ii.f=Object.getOwnPropertySymbols),ii}var ai,xs;function th(){if(xs)return ai;xs=1;var n=rr(),e=J(),r=eh(),t=rh(),i=he(),a=e([].concat);return ai=n("Reflect","ownKeys")||function(o){var u=r.f(i(o)),l=t.f;return l?a(u,l(o)):u},ai}var ni,Os;function ih(){if(Os)return ni;Os=1;var n=Ae(),e=th(),r=Dr(),t=Ye();return ni=function(i,a,s){for(var o=e(a),u=t.f,l=r.f,h=0;hR;R++)if(A=w(f[R]),A&&s(v,A))return A;return new c(!1)}E=o(f,T)}for(D=m?f.next:E.next;!(I=e(D,E)).done;){var V=I.value;try{A=w(V)}catch(B){if(E)l(E,"throw",B);else throw B}if(typeof A=="object"&&A&&s(v,A))return A}return new c(!1)},Wi}var Yi,co;function Rh(){if(co)return Yi;co=1;var n=ne(),e=n("iterator"),r=!1;try{var t=0,i={next:function(){return{done:!!t++}},return:function(){r=!0}};i[e]=function(){return this},Array.from(i,function(){throw 2})}catch{}return Yi=function(a,s){try{if(!s&&!r)return!1}catch{return!1}var o=!1;try{var u={};u[e]=function(){return{next:function(){return{done:o=!0}}}},a(u)}catch{}return o},Yi}var Xi,vo;function Cl(){if(vo)return Xi;vo=1;var n=mr(),e=Rh(),r=br().CONSTRUCTOR;return Xi=r||!e(function(t){n.all(t).then(void 0,function(){})}),Xi}var go;function Ch(){if(go)return no;go=1;var n=fe(),e=se(),r=Fe(),t=xr(),i=en(),a=Rl(),s=Cl();return n({target:"Promise",stat:!0,forced:s},{all:function(u){var l=this,h=t.f(l),c=h.resolve,v=h.reject,f=i(function(){var g=r(l.resolve),d=[],p=0,y=1;a(u,function(m){var b=p++,x=!1;y++,e(g,l,m).then(function(S){x||(x=!0,d[b]=S,--y||c(d))},v)}),--y||c(d)});return f.error&&v(f.value),h.promise}}),no}var po={},yo;function wh(){if(yo)return po;yo=1;var n=fe(),e=Me(),r=br().CONSTRUCTOR,t=mr(),i=rr(),a=re(),s=tr(),o=t&&t.prototype;if(n({target:"Promise",proto:!0,forced:r,real:!0},{catch:function(l){return this.then(void 0,l)}}),!e&&a(t)){var u=i("Promise").prototype.catch;o.catch!==u&&s(o,"catch",u,{unsafe:!0})}return po}var mo={},bo;function Ph(){if(bo)return mo;bo=1;var n=fe(),e=se(),r=Fe(),t=xr(),i=en(),a=Rl(),s=Cl();return n({target:"Promise",stat:!0,forced:s},{race:function(u){var l=this,h=t.f(l),c=h.reject,v=i(function(){var f=r(l.resolve);a(u,function(g){e(f,l,g).then(h.resolve,c)})});return v.error&&c(v.value),h.promise}}),mo}var xo={},Oo;function Ah(){if(Oo)return xo;Oo=1;var n=fe(),e=xr(),r=br().CONSTRUCTOR;return n({target:"Promise",stat:!0,forced:r},{reject:function(i){var a=e.f(this),s=a.reject;return s(i),a.promise}}),xo}var To={},Ki,So;function Ih(){if(So)return Ki;So=1;var n=he(),e=ye(),r=xr();return Ki=function(t,i){if(n(t),e(i)&&i.constructor===t)return i;var a=r.f(t),s=a.resolve;return s(i),a.promise},Ki}var Eo;function Nh(){if(Eo)return To;Eo=1;var n=fe(),e=rr(),r=Me(),t=mr(),i=br().CONSTRUCTOR,a=Ih(),s=e("Promise"),o=r&&!i;return n({target:"Promise",stat:!0,forced:r||i},{resolve:function(l){return a(o&&this===s?t:this,l)}}),To}var Ro;function _h(){return Ro||(Ro=1,Oh(),Ch(),wh(),Ph(),Ah(),Nh()),fn}_h();function Co(n,e,r,t,i,a,s){try{var o=n[a](s),u=o.value}catch(l){return void r(l)}o.done?e(u):Promise.resolve(u).then(t,i)}function Be(n){return function(){var e=this,r=arguments;return new Promise(function(t,i){var a=n.apply(e,r);function s(u){Co(a,t,i,s,o,"next",u)}function o(u){Co(a,t,i,s,o,"throw",u)}s(void 0)})}}var wo={},Po={},Qi,Ao;function qe(){if(Ao)return Qi;Ao=1;var n=Za(),e=String;return Qi=function(r){if(n(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return e(r)},Qi}var Zi,Io;function wl(){if(Io)return Zi;Io=1;var n=he();return Zi=function(){var e=n(this),r="";return e.hasIndices&&(r+="d"),e.global&&(r+="g"),e.ignoreCase&&(r+="i"),e.multiline&&(r+="m"),e.dotAll&&(r+="s"),e.unicode&&(r+="u"),e.unicodeSets&&(r+="v"),e.sticky&&(r+="y"),r},Zi}var Ji,No;function Pl(){if(No)return Ji;No=1;var n=Z(),e=Q(),r=e.RegExp,t=n(function(){var s=r("a","y");return s.lastIndex=2,s.exec("abcd")!==null}),i=t||n(function(){return!r("a","y").sticky}),a=t||n(function(){var s=r("^r","gy");return s.lastIndex=2,s.exec("str")!==null});return Ji={BROKEN_CARET:a,MISSED_STICKY:i,UNSUPPORTED_Y:t},Ji}var ea={},ra,_o;function Mh(){if(_o)return ra;_o=1;var n=gl(),e=Qa();return ra=Object.keys||function(t){return n(t,e)},ra}var Mo;function qh(){if(Mo)return ea;Mo=1;var n=we(),e=fl(),r=Ye(),t=he(),i=dr(),a=Mh();return ea.f=n&&!e?Object.defineProperties:function(o,u){t(o);for(var l=i(u),h=a(u),c=h.length,v=0,f;c>v;)r.f(o,f=h[v++],l[f]);return o},ea}var ta,qo;function Ur(){if(qo)return ta;qo=1;var n=he(),e=qh(),r=Qa(),t=Xa(),i=xl(),a=qr(),s=Ya(),o=">",u="<",l="prototype",h="script",c=s("IE_PROTO"),v=function(){},f=function(m){return u+h+o+m+u+"/"+h+o},g=function(m){m.write(f("")),m.close();var b=m.parentWindow.Object;return m=null,b},d=function(){var m=a("iframe"),b="java"+h+":",x;return m.style.display="none",i.appendChild(m),m.src=String(b),x=m.contentWindow.document,x.open(),x.write(f("document.F=Object")),x.close(),x.F},p,y=function(){try{p=new ActiveXObject("htmlfile")}catch{}y=typeof document<"u"?document.domain&&p?g(p):d():g(p);for(var m=r.length;m--;)delete y[l][r[m]];return y()};return t[c]=!0,ta=Object.create||function(b,x){var S;return b!==null?(v[l]=n(b),S=new v,v[l]=null,S[c]=b):S=y(),x===void 0?S:e.f(S,x)},ta}var ia,Do;function Dh(){if(Do)return ia;Do=1;var n=Z(),e=Q(),r=e.RegExp;return ia=n(function(){var t=r(".","s");return!(t.dotAll&&t.test(` +import{e as Va,g as il}from"./vendor-react-B4AQeu28.js";import{_ as La}from"./jspdf.es.min-CwsrHLQV.js";import"./index-BdLfAeGL.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";var fn={},cn={},cr,vn;function Q(){if(vn)return cr;vn=1;var n=function(e){return e&&e.Math===Math&&e};return cr=n(typeof globalThis=="object"&&globalThis)||n(typeof window=="object"&&window)||n(typeof self=="object"&&self)||n(typeof Va=="object"&&Va)||n(typeof cr=="object"&&cr)||(function(){return this})()||Function("return this")(),cr}var Zr={},Jr,gn;function Z(){return gn||(gn=1,Jr=function(n){try{return!!n()}catch{return!0}}),Jr}var et,dn;function we(){if(dn)return et;dn=1;var n=Z();return et=!n(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),et}var rt,pn;function Ar(){if(pn)return rt;pn=1;var n=Z();return rt=!n(function(){var e=function(){}.bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),rt}var tt,yn;function se(){if(yn)return tt;yn=1;var n=Ar(),e=Function.prototype.call;return tt=n?e.bind(e):function(){return e.apply(e,arguments)},tt}var it={},mn;function Yl(){if(mn)return it;mn=1;var n={}.propertyIsEnumerable,e=Object.getOwnPropertyDescriptor,r=e&&!n.call({1:2},1);return it.f=r?function(i){var a=e(this,i);return!!a&&a.enumerable}:n,it}var at,bn;function Ua(){return bn||(bn=1,at=function(n,e){return{enumerable:!(n&1),configurable:!(n&2),writable:!(n&4),value:e}}),at}var nt,xn;function J(){if(xn)return nt;xn=1;var n=Ar(),e=Function.prototype,r=e.call,t=n&&e.bind.bind(r,r);return nt=n?t:function(i){return function(){return r.apply(i,arguments)}},nt}var st,On;function er(){if(On)return st;On=1;var n=J(),e=n({}.toString),r=n("".slice);return st=function(t){return r(e(t),8,-1)},st}var ot,Tn;function al(){if(Tn)return ot;Tn=1;var n=J(),e=Z(),r=er(),t=Object,i=n("".split);return ot=e(function(){return!t("z").propertyIsEnumerable(0)})?function(a){return r(a)==="String"?i(a,""):t(a)}:t,ot}var ut,Sn;function Ir(){return Sn||(Sn=1,ut=function(n){return n==null}),ut}var lt,En;function Pe(){if(En)return lt;En=1;var n=Ir(),e=TypeError;return lt=function(r){if(n(r))throw new e("Can't call method on "+r);return r},lt}var ht,Rn;function dr(){if(Rn)return ht;Rn=1;var n=al(),e=Pe();return ht=function(r){return n(e(r))},ht}var ft,Cn;function re(){if(Cn)return ft;Cn=1;var n=typeof document=="object"&&document.all;return ft=typeof n>"u"&&n!==void 0?function(e){return typeof e=="function"||e===n}:function(e){return typeof e=="function"},ft}var ct,wn;function ye(){if(wn)return ct;wn=1;var n=re();return ct=function(e){return typeof e=="object"?e!==null:n(e)},ct}var vt,Pn;function rr(){if(Pn)return vt;Pn=1;var n=Q(),e=re(),r=function(t){return e(t)?t:void 0};return vt=function(t,i){return arguments.length<2?r(n[t]):n[t]&&n[t][i]},vt}var gt,An;function Nr(){if(An)return gt;An=1;var n=J();return gt=n({}.isPrototypeOf),gt}var dt,In;function pr(){if(In)return dt;In=1;var n=Q(),e=n.navigator,r=e&&e.userAgent;return dt=r?String(r):"",dt}var pt,Nn;function Ga(){if(Nn)return pt;Nn=1;var n=Q(),e=pr(),r=n.process,t=n.Deno,i=r&&r.versions||t&&t.version,a=i&&i.v8,s,o;return a&&(s=a.split("."),o=s[0]>0&&s[0]<4?1:+(s[0]+s[1])),!o&&e&&(s=e.match(/Edge\/(\d+)/),(!s||s[1]>=74)&&(s=e.match(/Chrome\/(\d+)/),s&&(o=+s[1]))),pt=o,pt}var yt,_n;function nl(){if(_n)return yt;_n=1;var n=Ga(),e=Z(),r=Q(),t=r.String;return yt=!!Object.getOwnPropertySymbols&&!e(function(){var i=Symbol("symbol detection");return!t(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&n&&n<41}),yt}var mt,Mn;function sl(){if(Mn)return mt;Mn=1;var n=nl();return mt=n&&!Symbol.sham&&typeof Symbol.iterator=="symbol",mt}var bt,qn;function ol(){if(qn)return bt;qn=1;var n=rr(),e=re(),r=Nr(),t=sl(),i=Object;return bt=t?function(a){return typeof a=="symbol"}:function(a){var s=n("Symbol");return e(s)&&r(s.prototype,i(a))},bt}var xt,Dn;function _r(){if(Dn)return xt;Dn=1;var n=String;return xt=function(e){try{return n(e)}catch{return"Object"}},xt}var Ot,Vn;function Fe(){if(Vn)return Ot;Vn=1;var n=re(),e=_r(),r=TypeError;return Ot=function(t){if(n(t))return t;throw new r(e(t)+" is not a function")},Ot}var Tt,Ln;function nr(){if(Ln)return Tt;Ln=1;var n=Fe(),e=Ir();return Tt=function(r,t){var i=r[t];return e(i)?void 0:n(i)},Tt}var St,kn;function Xl(){if(kn)return St;kn=1;var n=se(),e=re(),r=ye(),t=TypeError;return St=function(i,a){var s,o;if(a==="string"&&e(s=i.toString)&&!r(o=n(s,i))||e(s=i.valueOf)&&!r(o=n(s,i))||a!=="string"&&e(s=i.toString)&&!r(o=n(s,i)))return o;throw new t("Can't convert object to primitive value")},St}var Et={exports:{}},Rt,jn;function Me(){return jn||(jn=1,Rt=!1),Rt}var Ct,Bn;function $a(){if(Bn)return Ct;Bn=1;var n=Q(),e=Object.defineProperty;return Ct=function(r,t){try{e(n,r,{value:t,configurable:!0,writable:!0})}catch{n[r]=t}return t},Ct}var Fn;function za(){if(Fn)return Et.exports;Fn=1;var n=Me(),e=Q(),r=$a(),t="__core-js_shared__",i=Et.exports=e[t]||r(t,{});return(i.versions||(i.versions=[])).push({version:"3.49.0",mode:n?"pure":"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"}),Et.exports}var wt,Un;function Ha(){if(Un)return wt;Un=1;var n=za();return wt=function(e,r){return n[e]||(n[e]=r||{})},wt}var Pt,Gn;function Mr(){if(Gn)return Pt;Gn=1;var n=Pe(),e=Object;return Pt=function(r){return e(n(r))},Pt}var At,$n;function Ae(){if($n)return At;$n=1;var n=J(),e=Mr(),r=n({}.hasOwnProperty);return At=Object.hasOwn||function(i,a){return r(e(i),a)},At}var It,zn;function ul(){if(zn)return It;zn=1;var n=J(),e=0,r=Math.random(),t=n(1.1.toString);return It=function(i){return"Symbol("+(i===void 0?"":i)+")_"+t(++e+r,36)},It}var Nt,Hn;function ne(){if(Hn)return Nt;Hn=1;var n=Q(),e=Ha(),r=Ae(),t=ul(),i=nl(),a=sl(),s=n.Symbol,o=e("wks"),u=a?s.for||s:s&&s.withoutSetter||t;return Nt=function(l){return r(o,l)||(o[l]=i&&r(s,l)?s[l]:u("Symbol."+l)),o[l]},Nt}var _t,Wn;function Kl(){if(Wn)return _t;Wn=1;var n=se(),e=ye(),r=ol(),t=nr(),i=Xl(),a=ne(),s=TypeError,o=a("toPrimitive");return _t=function(u,l){if(!e(u)||r(u))return u;var h=t(u,o),c;if(h){if(l===void 0&&(l="default"),c=n(h,u,l),!e(c)||r(c))return c;throw new s("Can't convert object to primitive value")}return l===void 0&&(l="number"),i(u,l)},_t}var Mt,Yn;function ll(){if(Yn)return Mt;Yn=1;var n=Kl(),e=ol();return Mt=function(r){var t=n(r,"string");return e(t)?t:t+""},Mt}var qt,Xn;function qr(){if(Xn)return qt;Xn=1;var n=Q(),e=ye(),r=n.document,t=e(r)&&e(r.createElement);return qt=function(i){return t?r.createElement(i):{}},qt}var Dt,Kn;function hl(){if(Kn)return Dt;Kn=1;var n=we(),e=Z(),r=qr();return Dt=!n&&!e(function(){return Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a!==7}),Dt}var Qn;function Dr(){if(Qn)return Zr;Qn=1;var n=we(),e=se(),r=Yl(),t=Ua(),i=dr(),a=ll(),s=Ae(),o=hl(),u=Object.getOwnPropertyDescriptor;return Zr.f=n?u:function(h,c){if(h=i(h),c=a(c),o)try{return u(h,c)}catch{}if(s(h,c))return t(!e(r.f,h,c),h[c])},Zr}var Vt={},Lt,Zn;function fl(){if(Zn)return Lt;Zn=1;var n=we(),e=Z();return Lt=n&&e(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Lt}var kt,Jn;function he(){if(Jn)return kt;Jn=1;var n=ye(),e=String,r=TypeError;return kt=function(t){if(n(t))return t;throw new r(e(t)+" is not an object")},kt}var es;function Ye(){if(es)return Vt;es=1;var n=we(),e=hl(),r=fl(),t=he(),i=ll(),a=TypeError,s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,u="enumerable",l="configurable",h="writable";return Vt.f=n?r?function(v,f,g){if(t(v),f=i(f),t(g),typeof v=="function"&&f==="prototype"&&"value"in g&&h in g&&!g[h]){var d=o(v,f);d&&d[h]&&(v[f]=g.value,g={configurable:l in g?g[l]:d[l],enumerable:u in g?g[u]:d[u],writable:!1})}return s(v,f,g)}:s:function(v,f,g){if(t(v),f=i(f),t(g),e)try{return s(v,f,g)}catch{}if("get"in g||"set"in g)throw new a("Accessors not supported");return"value"in g&&(v[f]=g.value),v},Vt}var jt,rs;function yr(){if(rs)return jt;rs=1;var n=we(),e=Ye(),r=Ua();return jt=n?function(t,i,a){return e.f(t,i,r(1,a))}:function(t,i,a){return t[i]=a,t},jt}var Bt={exports:{}},Ft,ts;function Vr(){if(ts)return Ft;ts=1;var n=we(),e=Ae(),r=Function.prototype,t=n&&Object.getOwnPropertyDescriptor,i=e(r,"name"),a=i&&function(){}.name==="something",s=i&&(!n||n&&t(r,"name").configurable);return Ft={EXISTS:i,PROPER:a,CONFIGURABLE:s},Ft}var Ut,is;function Wa(){if(is)return Ut;is=1;var n=J(),e=re(),r=za(),t=n(Function.toString);return e(r.inspectSource)||(r.inspectSource=function(i){return t(i)}),Ut=r.inspectSource,Ut}var Gt,as;function Ql(){if(as)return Gt;as=1;var n=Q(),e=re(),r=n.WeakMap;return Gt=e(r)&&/native code/.test(String(r)),Gt}var $t,ns;function Ya(){if(ns)return $t;ns=1;var n=Ha(),e=ul(),r=n("keys");return $t=function(t){return r[t]||(r[t]=e(t))},$t}var zt,ss;function Xa(){return ss||(ss=1,zt={}),zt}var Ht,os;function Lr(){if(os)return Ht;os=1;var n=Ql(),e=Q(),r=ye(),t=yr(),i=Ae(),a=za(),s=Ya(),o=Xa(),u="Object already initialized",l=e.TypeError,h=e.WeakMap,c,v,f,g=function(m){return f(m)?v(m):c(m,{})},d=function(m){return function(b){var x;if(!r(b)||(x=v(b)).type!==m)throw new l("Incompatible receiver, "+m+" required");return x}};if(n||a.state){var p=a.state||(a.state=new h);p.get=p.get,p.has=p.has,p.set=p.set,c=function(m,b){if(p.has(m))throw new l(u);return b.facade=m,p.set(m,b),b},v=function(m){return p.get(m)||{}},f=function(m){return p.has(m)}}else{var y=s("state");o[y]=!0,c=function(m,b){if(i(m,y))throw new l(u);return b.facade=m,t(m,y,b),b},v=function(m){return i(m,y)?m[y]:{}},f=function(m){return i(m,y)}}return Ht={set:c,get:v,has:f,enforce:g,getterFor:d},Ht}var us;function cl(){if(us)return Bt.exports;us=1;var n=J(),e=Z(),r=re(),t=Ae(),i=we(),a=Vr().CONFIGURABLE,s=Wa(),o=Lr(),u=o.enforce,l=o.get,h=String,c=Object.defineProperty,v=n("".slice),f=n("".replace),g=n([].join),d=i&&!e(function(){return c(function(){},"length",{value:8}).length!==8}),p=String(String).split("String"),y=Bt.exports=function(m,b,x){v(h(b),0,7)==="Symbol("&&(b="["+f(h(b),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),x&&x.getter&&(b="get "+b),x&&x.setter&&(b="set "+b),(!t(m,"name")||a&&m.name!==b)&&(i?c(m,"name",{value:b,configurable:!0}):m.name=b),d&&x&&t(x,"arity")&&m.length!==x.arity&&c(m,"length",{value:x.arity});try{x&&t(x,"constructor")&&x.constructor?i&&c(m,"prototype",{writable:!1}):m.prototype&&(m.prototype=void 0)}catch{}var S=u(m);return t(S,"source")||(S.source=g(p,typeof b=="string"?b:"")),m};return Function.prototype.toString=y(function(){return r(this)&&l(this).source||s(this)},"toString"),Bt.exports}var Wt,ls;function tr(){if(ls)return Wt;ls=1;var n=re(),e=Ye(),r=cl(),t=$a();return Wt=function(i,a,s,o){o||(o={});var u=o.enumerable,l=o.name!==void 0?o.name:a;if(n(s)&&r(s,l,o),o.global)u?i[a]=s:t(a,s);else{try{o.unsafe?i[a]&&(u=!0):delete i[a]}catch{}u?i[a]=s:e.f(i,a,{value:s,enumerable:!1,configurable:!o.nonConfigurable,writable:!o.nonWritable})}return i},Wt}var Yt={},Xt,hs;function Zl(){if(hs)return Xt;hs=1;var n=Math.ceil,e=Math.floor;return Xt=Math.trunc||function(t){var i=+t;return(i>0?e:n)(i)},Xt}var Kt,fs;function kr(){if(fs)return Kt;fs=1;var n=Zl();return Kt=function(e){var r=+e;return r!==r||r===0?0:n(r)},Kt}var Qt,cs;function Jl(){if(cs)return Qt;cs=1;var n=kr(),e=Math.max,r=Math.min;return Qt=function(t,i){var a=n(t);return a<0?e(a+i,0):r(a,i)},Qt}var Zt,vs;function sr(){if(vs)return Zt;vs=1;var n=kr(),e=Math.min;return Zt=function(r){var t=n(r);return t>0?e(t,9007199254740991):0},Zt}var Jt,gs;function Ka(){if(gs)return Jt;gs=1;var n=sr();return Jt=function(e){return n(e.length)},Jt}var ei,ds;function vl(){if(ds)return ei;ds=1;var n=dr(),e=Jl(),r=Ka(),t=function(i){return function(a,s,o){var u=n(a),l=r(u);if(l===0)return!i&&-1;var h=e(o,l),c;if(i&&s!==s){for(;l>h;)if(c=u[h++],c!==c)return!0}else for(;l>h;h++)if((i||h in u)&&u[h]===s)return i||h||0;return!i&&-1}};return ei={includes:t(!0),indexOf:t(!1)},ei}var ri,ps;function gl(){if(ps)return ri;ps=1;var n=J(),e=Ae(),r=dr(),t=vl().indexOf,i=Xa(),a=n([].push);return ri=function(s,o){var u=r(s),l=0,h=[],c;for(c in u)!e(i,c)&&e(u,c)&&a(h,c);for(;o.length>l;)e(u,c=o[l++])&&(~t(h,c)||a(h,c));return h},ri}var ti,ys;function Qa(){return ys||(ys=1,ti=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]),ti}var ms;function eh(){if(ms)return Yt;ms=1;var n=gl(),e=Qa(),r=e.concat("length","prototype");return Yt.f=Object.getOwnPropertyNames||function(i){return n(i,r)},Yt}var ii={},bs;function rh(){return bs||(bs=1,ii.f=Object.getOwnPropertySymbols),ii}var ai,xs;function th(){if(xs)return ai;xs=1;var n=rr(),e=J(),r=eh(),t=rh(),i=he(),a=e([].concat);return ai=n("Reflect","ownKeys")||function(o){var u=r.f(i(o)),l=t.f;return l?a(u,l(o)):u},ai}var ni,Os;function ih(){if(Os)return ni;Os=1;var n=Ae(),e=th(),r=Dr(),t=Ye();return ni=function(i,a,s){for(var o=e(a),u=t.f,l=r.f,h=0;hR;R++)if(A=w(f[R]),A&&s(v,A))return A;return new c(!1)}E=o(f,T)}for(D=m?f.next:E.next;!(I=e(D,E)).done;){var V=I.value;try{A=w(V)}catch(B){if(E)l(E,"throw",B);else throw B}if(typeof A=="object"&&A&&s(v,A))return A}return new c(!1)},Wi}var Yi,co;function Rh(){if(co)return Yi;co=1;var n=ne(),e=n("iterator"),r=!1;try{var t=0,i={next:function(){return{done:!!t++}},return:function(){r=!0}};i[e]=function(){return this},Array.from(i,function(){throw 2})}catch{}return Yi=function(a,s){try{if(!s&&!r)return!1}catch{return!1}var o=!1;try{var u={};u[e]=function(){return{next:function(){return{done:o=!0}}}},a(u)}catch{}return o},Yi}var Xi,vo;function Cl(){if(vo)return Xi;vo=1;var n=mr(),e=Rh(),r=br().CONSTRUCTOR;return Xi=r||!e(function(t){n.all(t).then(void 0,function(){})}),Xi}var go;function Ch(){if(go)return no;go=1;var n=fe(),e=se(),r=Fe(),t=xr(),i=en(),a=Rl(),s=Cl();return n({target:"Promise",stat:!0,forced:s},{all:function(u){var l=this,h=t.f(l),c=h.resolve,v=h.reject,f=i(function(){var g=r(l.resolve),d=[],p=0,y=1;a(u,function(m){var b=p++,x=!1;y++,e(g,l,m).then(function(S){x||(x=!0,d[b]=S,--y||c(d))},v)}),--y||c(d)});return f.error&&v(f.value),h.promise}}),no}var po={},yo;function wh(){if(yo)return po;yo=1;var n=fe(),e=Me(),r=br().CONSTRUCTOR,t=mr(),i=rr(),a=re(),s=tr(),o=t&&t.prototype;if(n({target:"Promise",proto:!0,forced:r,real:!0},{catch:function(l){return this.then(void 0,l)}}),!e&&a(t)){var u=i("Promise").prototype.catch;o.catch!==u&&s(o,"catch",u,{unsafe:!0})}return po}var mo={},bo;function Ph(){if(bo)return mo;bo=1;var n=fe(),e=se(),r=Fe(),t=xr(),i=en(),a=Rl(),s=Cl();return n({target:"Promise",stat:!0,forced:s},{race:function(u){var l=this,h=t.f(l),c=h.reject,v=i(function(){var f=r(l.resolve);a(u,function(g){e(f,l,g).then(h.resolve,c)})});return v.error&&c(v.value),h.promise}}),mo}var xo={},Oo;function Ah(){if(Oo)return xo;Oo=1;var n=fe(),e=xr(),r=br().CONSTRUCTOR;return n({target:"Promise",stat:!0,forced:r},{reject:function(i){var a=e.f(this),s=a.reject;return s(i),a.promise}}),xo}var To={},Ki,So;function Ih(){if(So)return Ki;So=1;var n=he(),e=ye(),r=xr();return Ki=function(t,i){if(n(t),e(i)&&i.constructor===t)return i;var a=r.f(t),s=a.resolve;return s(i),a.promise},Ki}var Eo;function Nh(){if(Eo)return To;Eo=1;var n=fe(),e=rr(),r=Me(),t=mr(),i=br().CONSTRUCTOR,a=Ih(),s=e("Promise"),o=r&&!i;return n({target:"Promise",stat:!0,forced:r||i},{resolve:function(l){return a(o&&this===s?t:this,l)}}),To}var Ro;function _h(){return Ro||(Ro=1,Oh(),Ch(),wh(),Ph(),Ah(),Nh()),fn}_h();function Co(n,e,r,t,i,a,s){try{var o=n[a](s),u=o.value}catch(l){return void r(l)}o.done?e(u):Promise.resolve(u).then(t,i)}function Be(n){return function(){var e=this,r=arguments;return new Promise(function(t,i){var a=n.apply(e,r);function s(u){Co(a,t,i,s,o,"next",u)}function o(u){Co(a,t,i,s,o,"throw",u)}s(void 0)})}}var wo={},Po={},Qi,Ao;function qe(){if(Ao)return Qi;Ao=1;var n=Za(),e=String;return Qi=function(r){if(n(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return e(r)},Qi}var Zi,Io;function wl(){if(Io)return Zi;Io=1;var n=he();return Zi=function(){var e=n(this),r="";return e.hasIndices&&(r+="d"),e.global&&(r+="g"),e.ignoreCase&&(r+="i"),e.multiline&&(r+="m"),e.dotAll&&(r+="s"),e.unicode&&(r+="u"),e.unicodeSets&&(r+="v"),e.sticky&&(r+="y"),r},Zi}var Ji,No;function Pl(){if(No)return Ji;No=1;var n=Z(),e=Q(),r=e.RegExp,t=n(function(){var s=r("a","y");return s.lastIndex=2,s.exec("abcd")!==null}),i=t||n(function(){return!r("a","y").sticky}),a=t||n(function(){var s=r("^r","gy");return s.lastIndex=2,s.exec("str")!==null});return Ji={BROKEN_CARET:a,MISSED_STICKY:i,UNSUPPORTED_Y:t},Ji}var ea={},ra,_o;function Mh(){if(_o)return ra;_o=1;var n=gl(),e=Qa();return ra=Object.keys||function(t){return n(t,e)},ra}var Mo;function qh(){if(Mo)return ea;Mo=1;var n=we(),e=fl(),r=Ye(),t=he(),i=dr(),a=Mh();return ea.f=n&&!e?Object.defineProperties:function(o,u){t(o);for(var l=i(u),h=a(u),c=h.length,v=0,f;c>v;)r.f(o,f=h[v++],l[f]);return o},ea}var ta,qo;function Ur(){if(qo)return ta;qo=1;var n=he(),e=qh(),r=Qa(),t=Xa(),i=xl(),a=qr(),s=Ya(),o=">",u="<",l="prototype",h="script",c=s("IE_PROTO"),v=function(){},f=function(m){return u+h+o+m+u+"/"+h+o},g=function(m){m.write(f("")),m.close();var b=m.parentWindow.Object;return m=null,b},d=function(){var m=a("iframe"),b="java"+h+":",x;return m.style.display="none",i.appendChild(m),m.src=String(b),x=m.contentWindow.document,x.open(),x.write(f("document.F=Object")),x.close(),x.F},p,y=function(){try{p=new ActiveXObject("htmlfile")}catch{}y=typeof document<"u"?document.domain&&p?g(p):d():g(p);for(var m=r.length;m--;)delete y[l][r[m]];return y()};return t[c]=!0,ta=Object.create||function(b,x){var S;return b!==null?(v[l]=n(b),S=new v,v[l]=null,S[c]=b):S=y(),x===void 0?S:e.f(S,x)},ta}var ia,Do;function Dh(){if(Do)return ia;Do=1;var n=Z(),e=Q(),r=e.RegExp;return ia=n(function(){var t=r(".","s");return!(t.dotAll&&t.test(` `)&&t.flags==="s")}),ia}var aa,Vo;function Vh(){if(Vo)return aa;Vo=1;var n=Z(),e=Q(),r=e.RegExp;return aa=n(function(){var t=r("(?b)","g");return t.exec("b").groups.a!=="b"||"b".replace(t,"$c")!=="bc"}),aa}var na,Lo;function rn(){if(Lo)return na;Lo=1;var n=se(),e=J(),r=qe(),t=wl(),i=Pl(),a=Ha(),s=Ur(),o=Lr().get,u=Dh(),l=Vh(),h=a("native-string-replace",String.prototype.replace),c=RegExp.prototype.exec,v=c,f=e("".charAt),g=e("".indexOf),d=e("".replace),p=e("".slice),y=(function(){var E=/a/,T=/b*/g;return n(c,E,"a"),n(c,T,"a"),E.lastIndex!==0||T.lastIndex!==0})(),m=i.BROKEN_CARET,b=/()??/.exec("")[1]!==void 0,x=y||b||m||u||l,S=function(E,T){for(var R=E.groups=s(null),P=0;P0&&f(A,R.lastIndex-1);R.lastIndex>0&&(!R.multiline||R.multiline&&U!==` `&&U!=="\r"&&U!=="\u2028"&&U!=="\u2029")&&(j="(?: (?:"+j+"))",q=" "+q,_++),k=new RegExp("^(?:"+j+")",N)}b&&(k=new RegExp("^"+j+"$(?!\\s)",N)),y&&(w=R.lastIndex);var L=n(c,B?k:R,q);return B?L?(L.input=A,L[0]=p(L[0],_),L.index=R.lastIndex,R.lastIndex+=L[0].length):R.lastIndex=0:y&&L&&(R.lastIndex=R.global?L.index+L[0].length:w),b&&L&&L.length>1&&n(h,L[0],k,function(){for(var $=1;$=f?u?"":void 0:(g=a(c,v),g<55296||g>56319||v+1===f||(d=a(c,v+1))<56320||d>57343?u?i(c,v):g:u?s(c,v,v+2):(g-55296<<10)+(d-56320)+65536)}};return oa={codeAt:o(!1),charAt:o(!0)},oa}var ua,Fo;function an(){if(Fo)return ua;Fo=1;var n=kh().charAt;return ua=function(e,r,t){return r+(t&&n(e,r).length||1)},ua}var la,Uo;function jh(){if(Uo)return la;Uo=1;var n=Q(),e=Z(),r=n.RegExp,t=!e(function(){var i=!0;try{r(".","d")}catch{i=!1}var a={},s="",o=i?"dgimsy":"gimsy",u=function(v,f){Object.defineProperty(a,v,{get:function(){return s+=f,!0}})},l={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};i&&(l.hasIndices="d");for(var h in l)u(h,l[h]);var c=Object.getOwnPropertyDescriptor(r.prototype,"flags").get.call(a);return c!==o||s!==o});return la={correct:t},la}var ha,Go;function Gr(){if(Go)return ha;Go=1;var n=se(),e=Ae(),r=Nr(),t=jh(),i=wl(),a=RegExp.prototype;return ha=t.correct?function(s){return s.flags}:function(s){return!t.correct&&r(a,s)&&!e(s,"flags")?n(i,s):s.flags},ha}var fa,$o;function nn(){if($o)return fa;$o=1;var n=se(),e=he(),r=re(),t=er(),i=rn(),a=TypeError;return fa=function(s,o){var u=s.exec;if(r(u)){var l=n(u,s,o);return l!==null&&e(l),l}if(t(s)==="RegExp")return n(i,s,o);throw new a("RegExp#exec called on incompatible receiver")},fa}var zo;function Bh(){if(zo)return wo;zo=1;var n=se(),e=J(),r=tn(),t=he(),i=ye(),a=sr(),s=qe(),o=Pe(),u=nr(),l=an(),h=Gr(),c=nn(),v=e("".indexOf);return r("match",function(f,g,d){return[function(y){var m=o(this),b=i(y)?u(y,f):void 0;return b?n(b,y,m):new RegExp(y)[f](s(m))},function(p){var y=t(this),m=s(p),b=d(g,y,m);if(b.done)return b.value;var x=s(h(y));if(!~v(x,"g"))return c(y,m);var S=!!~v(x,"u")||!!~v(x,"v");y.lastIndex=0;for(var E=[],T=0,R;(R=c(y,m))!==null;){var P=s(R[0]);E[T]=P,P===""&&(y.lastIndex=l(m,a(y.lastIndex),S)),T++}return T===0?null:E}]}),wo}Bh();var Ho={},ca,Wo;function Fh(){if(Wo)return ca;Wo=1;var n=J(),e=Mr(),r=Math.floor,t=n("".charAt),i=n("".replace),a=n("".slice),s=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,o=/\$([$&'`]|\d{1,2})/g;return ca=function(u,l,h,c,v,f){var g=h+u.length,d=c.length,p=o;return v!==void 0&&(v=e(v),p=s),i(f,p,function(y,m){var b;switch(t(m,0)){case"$":return"$";case"&":return u;case"`":return a(l,0,h);case"'":return a(l,g);case"<":b=v[a(m,1,-1)];break;default:var x=+m;if(x===0)return y;if(x>d){var S=r(x/10);return S===0?y:S<=d?c[S-1]===void 0?t(m,1):c[S-1]+t(m,1):y}b=c[x-1]}return b===void 0?"":b})},ca}var Yo;function Uh(){if(Yo)return Ho;Yo=1;var n=bl(),e=se(),r=J(),t=tn(),i=Z(),a=he(),s=re(),o=ye(),u=kr(),l=sr(),h=qe(),c=Pe(),v=an(),f=nr(),g=Fh(),d=Gr(),p=nn(),y=ne(),m=y("replace"),b=Math.max,x=Math.min,S=r([].concat),E=r([].push),T=r("".indexOf),R=r("".slice),P=function(k){return k===void 0?k:String(k)},A=(function(){return"a".replace(/./,"$0")==="$0"})(),D=(function(){return/./[m]?/./[m]("a","$0")==="":!1})(),I=!i(function(){var k=/./;return k.exec=function(){var w=[];return w.groups={a:"7"},w},"".replace(k,"$")!=="7"});return t("replace",function(k,w,V){var B=D?"$":"$0";return[function(j,_){var q=c(this),U=o(j)?f(j,m):void 0;return U?e(U,j,q,_):e(w,h(q),j,_)},function(N,j){var _=a(this),q=h(N),U=s(j);U||(j=h(j));var L=h(d(_));if(typeof j=="string"&&!~T(j,B)&&!~T(j,"$<")&&!~T(L,"y")){var $=V(w,_,q,j);if($.done)return $.value}var X=!!~T(L,"g"),ae;X&&(ae=!!~T(L,"u")||!!~T(L,"v"),_.lastIndex=0);for(var oe=[],ue;ue=p(_,q),!(ue===null||(E(oe,ue),!X));){var Ue=h(ue[0]);Ue===""&&(_.lastIndex=v(q,l(_.lastIndex),ae))}for(var Ge="",ce=0,Ne=0;Ne=ce&&(Ge+=R(q,ce,be)+xe,ce=be+_e.length)}return Ge+R(q,ce)}]},!I||!A||D),Ho}Uh();var Xo={},va,Ko;function Gh(){if(Ko)return va;Ko=1;var n=ye(),e=er(),r=ne(),t=r("match");return va=function(i){var a;return n(i)&&((a=i[t])!==void 0?!!a:e(i)==="RegExp")},va}var ga,Qo;function sn(){if(Qo)return ga;Qo=1;var n=Gh(),e=TypeError;return ga=function(r){if(n(r))throw new e("The method doesn't accept regular expressions");return r},ga}var da,Zo;function on(){if(Zo)return da;Zo=1;var n=ne(),e=n("match");return da=function(r){var t=/./;try{"/./"[r](t)}catch{try{return t[e]=!1,"/./"[r](t)}catch{}}return!1},da}var Jo;function $h(){if(Jo)return Xo;Jo=1;var n=fe(),e=Fr(),r=Dr().f,t=sr(),i=qe(),a=sn(),s=Pe(),o=on(),u=Me(),l=e("".slice),h=Math.min,c=o("startsWith"),v=!u&&!c&&!!(function(){var f=r(String.prototype,"startsWith");return f&&!f.writable})();return n({target:"String",proto:!0,forced:!v&&!c},{startsWith:function(g){var d=i(s(this));a(g);var p=i(g),y=t(h(arguments.length>1?arguments[1]:void 0,d.length));return l(d,y,y+p.length)===p}}),Xo}$h();var pa,eu;function zh(){if(eu)return pa;eu=1;var n=ne(),e=Ur(),r=Ye().f,t=n("unscopables"),i=Array.prototype;return i[t]===void 0&&r(i,t,{configurable:!0,value:e(null)}),pa=function(a){i[t][a]=!0},pa}var ya,ru;function Hh(){if(ru)return ya;ru=1;var n=Z();return ya=!n(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),ya}var ma,tu;function Al(){if(tu)return ma;tu=1;var n=Ae(),e=re(),r=Mr(),t=Ya(),i=Hh(),a=t("IE_PROTO"),s=Object,o=s.prototype;return ma=i?s.getPrototypeOf:function(u){var l=r(u);if(n(l,a))return l[a];var h=l.constructor;return e(h)&&l instanceof h?h.prototype:l instanceof s?o:null},ma}var ba,iu;function Il(){if(iu)return ba;iu=1;var n=Z(),e=re(),r=ye(),t=Ur(),i=Al(),a=tr(),s=ne(),o=Me(),u=s("iterator"),l=!1,h,c,v;[].keys&&(v=[].keys(),"next"in v?(c=i(i(v)),c!==Object.prototype&&(h=c)):l=!0);var f=!r(h)||n(function(){var g={};return h[u].call(g)!==g});return f?h={}:o&&(h=t(h)),e(h[u])||a(h,u,function(){return this}),ba={IteratorPrototype:h,BUGGY_SAFARI_ITERATORS:l},ba}var xa,au;function Wh(){if(au)return xa;au=1;var n=Il().IteratorPrototype,e=Ur(),r=Ua(),t=Br(),i=Or(),a=function(){return this};return xa=function(s,o,u,l){var h=o+" Iterator";return s.prototype=e(n,{next:r(+!l,u)}),t(s,h,!1,!0),i[h]=a,s},xa}var Oa,nu;function Yh(){if(nu)return Oa;nu=1;var n=fe(),e=se(),r=Me(),t=Vr(),i=re(),a=Wh(),s=Al(),o=yl(),u=Br(),l=yr(),h=tr(),c=ne(),v=Or(),f=Il(),g=t.PROPER,d=t.CONFIGURABLE,p=f.IteratorPrototype,y=f.BUGGY_SAFARI_ITERATORS,m=c("iterator"),b="keys",x="values",S="entries",E=function(){return this};return Oa=function(T,R,P,A,D,I,k){a(P,R,A);var w=function(X){if(X===D&&_)return _;if(!y&&X&&X in N)return N[X];switch(X){case b:return function(){return new P(this,X)};case x:return function(){return new P(this,X)};case S:return function(){return new P(this,X)}}return function(){return new P(this)}},V=R+" Iterator",B=!1,N=T.prototype,j=N[m]||N["@@iterator"]||D&&N[D],_=!y&&j||w(D),q=R==="Array"&&N.entries||j,U,L,$;if(q&&(U=s(q.call(new T)),U!==Object.prototype&&U.next&&(!r&&s(U)!==p&&(o?o(U,p):i(U[m])||h(U,m,E)),u(U,V,!0,!0),r&&(v[V]=E))),g&&D===x&&j&&j.name!==x&&(!r&&d?l(N,"name",x):(B=!0,_=function(){return e(j,this)})),D)if(L={values:w(x),keys:I?_:w(b),entries:w(S)},k)for($ in L)(y||B||!($ in N))&&h(N,$,L[$]);else n({target:R,proto:!0,forced:y||B},L);return(!r||k)&&N[m]!==_&&h(N,m,_,{name:D}),v[R]=_,L},Oa}var Ta,su;function Xh(){return su||(su=1,Ta=function(n,e){return{value:n,done:e}}),Ta}var Sa,ou;function Nl(){if(ou)return Sa;ou=1;var n=dr(),e=zh(),r=Or(),t=Lr(),i=Ye().f,a=Yh(),s=Xh(),o=Me(),u=we(),l="Array Iterator",h=t.set,c=t.getterFor(l);Sa=a(Array,"Array",function(f,g){h(this,{type:l,target:n(f),index:0,kind:g})},function(){var f=c(this),g=f.target,d=f.index++;if(!g||d>=g.length)return f.target=null,s(void 0,!0);switch(f.kind){case"keys":return s(d,!1);case"values":return s(g[d],!1)}return s([d,g[d]],!1)},"values");var v=r.Arguments=r.Array;if(e("keys"),e("values"),e("entries"),!o&&u&&v.name!=="values")try{i(v,"name",{value:"values"})}catch{}return Sa}Nl();var uu={},Ea,lu;function Kh(){return lu||(lu=1,Ea={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}),Ea}var Ra,hu;function Qh(){if(hu)return Ra;hu=1;var n=qr(),e=n("span").classList,r=e&&e.constructor&&e.constructor.prototype;return Ra=r===Object.prototype?void 0:r,Ra}var fu;function Zh(){if(fu)return uu;fu=1;var n=Q(),e=Kh(),r=Qh(),t=Nl(),i=yr(),a=Br(),s=ne(),o=s("iterator"),u=t.values,l=function(c,v){if(c){if(c[o]!==u)try{i(c,o,u)}catch{c[o]=u}if(a(c,v,!0),e[v]){for(var f in t)if(c[f]!==t[f])try{i(c,f,t[f])}catch{c[f]=t[f]}}}};for(var h in e)l(n[h]&&n[h].prototype,h);return l(r,"DOMTokenList"),uu}Zh();function Jh(n,e){if(La(n)!="object"||!n)return n;var r=n[Symbol.toPrimitive];if(r!==void 0){var t=r.call(n,e);if(La(t)!="object")return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function ef(n){var e=Jh(n,"string");return La(e)=="symbol"?e:e+""}function un(n,e,r){return(e=ef(e))in n?Object.defineProperty(n,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):n[e]=r,n}var cu={},Ca,vu;function rf(){if(vu)return Ca;vu=1;var n=Fe(),e=Mr(),r=al(),t=Ka(),i=TypeError,a="Reduce of empty array with no initial value",s=function(o){return function(u,l,h,c){var v=e(u),f=r(v),g=t(v);if(n(l),g===0&&h<2)throw new i(a);var d=o?g-1:0,p=o?-1:1;if(h<2)for(;;){if(d in f){c=f[d],d+=p;break}if(d+=p,o?d<0:g<=d)throw new i(a)}for(;o?d>=0:g>d;d+=p)d in f&&(c=l(c,f[d],d,v));return c}};return Ca={left:s(!1),right:s(!0)},Ca}var wa,gu;function _l(){if(gu)return wa;gu=1;var n=Z();return wa=function(e,r){var t=[][e];return!!t&&n(function(){t.call(null,r||function(){return 1},1)})},wa}var du;function tf(){if(du)return cu;du=1;var n=fe(),e=rf().left,r=_l(),t=Ga(),i=jr(),a=!i&&t>79&&t<83,s=a||!r("reduce");return n({target:"Array",proto:!0,forced:s},{reduce:function(u){var l=arguments.length;return e(this,u,l,l>1?arguments[1]:void 0)}}),cu}tf();var pu={},yu;function af(){if(yu)return pu;yu=1;var n=fe(),e=Fr(),r=Dr().f,t=sr(),i=qe(),a=sn(),s=Pe(),o=on(),u=Me(),l=e("".slice),h=Math.min,c=o("endsWith"),v=!u&&!c&&!!(function(){var f=r(String.prototype,"endsWith");return f&&!f.writable})();return n({target:"String",proto:!0,forced:!v&&!c},{endsWith:function(g){var d=i(s(this));a(g);var p=i(g),y=arguments.length>1?arguments[1]:void 0,m=d.length,b=y===void 0?m:h(t(y),m);return l(d,b-p.length,b)===p}}),pu}af();var mu={},bu;function nf(){if(bu)return mu;bu=1;var n=se(),e=J(),r=tn(),t=he(),i=ye(),a=Pe(),s=ml(),o=an(),u=sr(),l=qe(),h=nr(),c=Gr(),v=nn(),f=Pl(),g=Z(),d=f.UNSUPPORTED_Y,p=4294967295,y=Math.min,m=e([].push),b=e("".slice),x=e("".indexOf),S=!g(function(){var T=/(?:)/,R=T.exec;T.exec=function(){return R.apply(this,arguments)};var P="ab".split(T);return P.length!==2||P[0]!=="a"||P[1]!=="b"}),E="abbc".split(/(b)*/)[1]==="c"||"test".split(/(?:)/,-1).length!==4||"ab".split(/(?:ab)*/).length!==2||".".split(/(.?)(.?)/).length!==4||".".split(/()()/).length>1||"".split(/.?/).length;return r("split",function(T,R,P){var A="0".split(void 0,0).length?function(D,I){return D===void 0&&I===0?[]:n(R,this,D,I)}:R;return[function(I,k){var w=a(this),V=i(I)?h(I,T):void 0;return V?n(V,I,w,k):n(A,l(w),I,k)},function(D,I){var k=t(this),w=l(D);if(!E){var V=P(A,k,w,I,A!==R);if(V.done)return V.value}var B=s(k,RegExp),N=l(c(k)),j=!!~x(N,"u")||!!~x(N,"v");d?~x(N,"g")||(N+="g"):~x(N,"y")||(N+="y");var _=new B(d?"^(?:"+k.source+")":k,N),q=I===void 0?p:I>>>0;if(q===0)return[];if(w.length===0)return v(_,w)===null?[w]:[];for(var U=0,L=0,$=[];L"u"?Va:window,r=["moz","webkit"],t="AnimationFrame",i=e["request"+t],a=e["cancel"+t]||e["cancelRequest"+t],s=0;!i&&s3&&(this.alpha=o[3]),this.ok=!0}}this.r=this.r<0||isNaN(this.r)?0:this.r>255?255:this.r,this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g,this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b,this.alpha=this.alpha<0?0:this.alpha>1||isNaN(this.alpha)?1:this.alpha,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toRGBA=function(){return"rgba("+this.r+", "+this.g+", "+this.b+", "+this.alpha+")"},this.toHex=function(){var u=this.r.toString(16),l=this.g.toString(16),h=this.b.toString(16);return u.length==1&&(u="0"+u),l.length==1&&(l="0"+l),h.length==1&&(h="0"+h),"#"+u+l+h},this.getHelpXML=function(){for(var u=new Array,l=0;l "+d.toRGB()+" -> "+d.toHex());g.appendChild(p),g.appendChild(y),f.appendChild(g)}catch{}return f}}),_a}var gf=vf();const ka=il(gf);var Pu={},Au;function df(){if(Au)return Pu;Au=1;var n=fe(),e=Fr(),r=vl().indexOf,t=_l(),i=e([].indexOf),a=!!i&&1/i([1],1,-0)<0,s=a||!t("indexOf");return n({target:"Array",proto:!0,forced:s},{indexOf:function(u){var l=arguments.length>1?arguments[1]:void 0;return a?i(this,u,l)||0:r(this,u,l)}}),Pu}df();var Iu={},Nu;function pf(){if(Nu)return Iu;Nu=1;var n=fe(),e=J(),r=sn(),t=Pe(),i=qe(),a=on(),s=e("".indexOf);return n({target:"String",proto:!0,forced:!a("includes")},{includes:function(u){return!!~s(i(t(this)),i(r(u)),arguments.length>1?arguments[1]:void 0)}}),Iu}pf();var _u={},Ma,Mu;function yf(){if(Mu)return Ma;Mu=1;var n=er();return Ma=Array.isArray||function(r){return n(r)==="Array"},Ma}var qu;function mf(){if(qu)return _u;qu=1;var n=fe(),e=J(),r=yf(),t=e([].reverse),i=[1,2];return n({target:"Array",proto:!0,forced:String(i)===String(i.reverse())},{reverse:function(){return r(this)&&(this.length=this.length),t(this)}}),_u}mf();/*! ***************************************************************************** diff --git a/assets/info-CMvRmbQw.js b/assets/info-D1mJ7S8g.js similarity index 89% rename from assets/info-CMvRmbQw.js rename to assets/info-D1mJ7S8g.js index 43ee8ec86799a221da60c50ac0ef23fbf3e426a0..37e543cf924273f2c833904aa28b49cd4f80f8ac 100644 --- a/assets/info-CMvRmbQw.js +++ b/assets/info-D1mJ7S8g.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/input-B3TmduBc.js b/assets/input-CHfZS1wQ.js similarity index 92% rename from assets/input-B3TmduBc.js rename to assets/input-CHfZS1wQ.js index a38fefae078a91afd11852085785cdb3fa78f528..648c4e3033259ca2d18ef2a0335e21706d280b7a 100644 --- a/assets/input-B3TmduBc.js +++ b/assets/input-CHfZS1wQ.js @@ -1 +1 @@ -import{j as t}from"./vendor-react-B4AQeu28.js";import{o as n}from"./index-BvEKrMkD.js";function a({className:e,type:i,...r}){return t.jsx("input",{type:i,"data-slot":"input",className:n("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...r})}export{a as I}; +import{j as t}from"./vendor-react-B4AQeu28.js";import{o as n}from"./index-BdLfAeGL.js";function a({className:e,type:i,...r}){return t.jsx("input",{type:i,"data-slot":"input",className:n("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...r})}export{a as I}; diff --git a/assets/jspdf.es.min-CpWaCVL9.js b/assets/jspdf.es.min-CwsrHLQV.js similarity index 99% rename from assets/jspdf.es.min-CpWaCVL9.js rename to assets/jspdf.es.min-CwsrHLQV.js index 1f32f7e28d99f271357643e19661d9800865ccfb..876a0c1b7324ab4f644d5053cbf27f9e3bdb37c6 100644 --- a/assets/jspdf.es.min-CpWaCVL9.js +++ b/assets/jspdf.es.min-CwsrHLQV.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index.es-CkGqZuf8.js","assets/vendor-react-B4AQeu28.js","assets/index-BvEKrMkD.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{_ as mo}from"./index-BvEKrMkD.js";function xe(n){"@babel/helpers - typeof";return xe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xe(n)}var Qn=Uint8Array,Mn=Uint16Array,Ko=Int32Array,Xo=new Qn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),$o=new Qn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Bl=new Qn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Yu=function(n,t){for(var e=new Mn(31),i=0;i<31;++i)e[i]=t+=1<>1|(Ee&21845)<<1;Jr=(Jr&52428)>>2|(Jr&13107)<<2,Jr=(Jr&61680)>>4|(Jr&3855)<<4,Do[Ee]=((Jr&65280)>>8|(Jr&255)<<8)>>1}var Ia=(function(n,t,e){for(var i=n.length,o=0,a=new Mn(t);o>h]=d}else for(l=new Mn(i),o=0;o>15-n[o]);return l}),Li=new Qn(288);for(var Ee=0;Ee<144;++Ee)Li[Ee]=8;for(var Ee=144;Ee<256;++Ee)Li[Ee]=9;for(var Ee=256;Ee<280;++Ee)Li[Ee]=7;for(var Ee=280;Ee<288;++Ee)Li[Ee]=8;var Is=new Qn(32);for(var Ee=0;Ee<32;++Ee)Is[Ee]=5;var Nh=Ia(Li,9,0),Lh=Ia(Is,5,0),Ku=function(n){return(n+7)/8|0},Sh=function(n,t,e){return(e==null||e>n.length)&&(e=n.length),new Qn(n.subarray(t,e))},Cr=function(n,t,e){e<<=t&7;var i=t/8|0;n[i]|=e,n[i+1]|=e>>8},ka=function(n,t,e){e<<=t&7;var i=t/8|0;n[i]|=e,n[i+1]|=e>>8,n[i+2]|=e>>16},vo=function(n,t){for(var e=[],i=0;ik&&(k=a[i].s);var p=new Mn(k+1),j=qo(e[m-1],p,0);if(j>t){var i=0,O=0,M=j-t,S=1<t)O+=S-(1<>=M;O>0;){var G=a[i].s;p[G]=0&&O;--i){var q=a[i].s;p[q]==t&&(--p[q],++O)}j=t}return{t:new Qn(p),l:j}},qo=function(n,t,e){return n.s==-1?Math.max(qo(n.l,t,e+1),qo(n.r,t,e+1)):t[n.s]=e},Rl=function(n){for(var t=n.length;t&&!n[--t];);for(var e=new Mn(++t),i=0,o=n[0],a=1,c=function(h){e[i++]=h},l=1;l<=t;++l)if(n[l]==o&&l!=t)++a;else{if(!o&&a>2){for(;a>138;a-=138)c(32754);a>2&&(c(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(c(o),--a;a>6;a-=6)c(8304);a>2&&(c(a-3<<5|8208),a=0)}for(;a--;)c(o);a=1,o=n[l]}return{c:e.subarray(0,i),n:t}},Pa=function(n,t){for(var e=0,i=0;i>8,n[o+2]=n[o]^255,n[o+3]=n[o+1]^255;for(var a=0;a4&&!tt[Bl[E-1]];--E);var z=d+5<<3,U=Pa(o,Li)+Pa(a,Is)+c,rt=Pa(o,k)+Pa(a,O)+c+14+3*E+Pa(dt,tt)+2*dt[16]+3*dt[17]+7*dt[18];if(h>=0&&z<=U&&z<=rt)return Xu(t,m,n.subarray(h,h+d));var ot,ft,nt,ct;if(Cr(t,m,1+(rt15&&(Cr(t,m,B[X]>>5&127),m+=B[X]>>12)}}else ot=Nh,ft=Li,nt=Lh,ct=Is;for(var X=0;X255){var T=H>>18&31;ka(t,m,ot[T+257]),m+=ft[T+257],T>7&&(Cr(t,m,H>>23&31),m+=Xo[T]);var J=H&31;ka(t,m,nt[J]),m+=ct[J],J>3&&(ka(t,m,H>>5&8191),m+=$o[J])}else ka(t,m,ot[H]),m+=ft[H]}return ka(t,m,ot[256]),m+ft[256]},kh=new Ko([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),$u=new Qn(0),Ph=function(n,t,e,i,o,a){var c=a.z||n.length,l=new Qn(i+c+5*(1+Math.ceil(c/7e3))+o),h=l.subarray(i,l.length-o),d=a.l,m=(a.r||0)&7;if(t){m&&(h[0]=a.r>>3);for(var _=kh[t-1],k=_>>13,p=_&8191,j=(1<7e3||tt>24576)&&(ot>423||!d)){m=Tl(n,h,0,q,it,vt,X,tt,E,R-E,m),tt=dt=X=0,E=R;for(var ft=0;ft<286;++ft)it[ft]=0;for(var ft=0;ft<30;++ft)vt[ft]=0}var nt=2,ct=0,At=p,wt=U-rt&32767;if(ot>2&&z==G(R-wt))for(var x=Math.min(k,ot)-1,B=Math.min(32767,R),T=Math.min(258,ot);wt<=B&&--At&&U!=rt;){if(n[R+nt]==n[R+nt-wt]){for(var H=0;Hnt){if(nt=H,ct=wt,H>x)break;for(var J=Math.min(wt,H-2),Z=0,ft=0;ftZ&&(Z=gt,rt=at)}}}U=rt,rt=O[U],wt+=U-rt&32767}if(ct){q[tt++]=268435456|To[nt]<<18|Ml[ct];var _t=To[nt]&31,kt=Ml[ct]&31;X+=Xo[_t]+$o[kt],++it[257+_t],++vt[kt],N=R+nt,++dt}else q[tt++]=n[R],++it[n[R]]}}for(R=Math.max(R,N);R=c&&(h[m/8|0]=d,St=c),m=Xu(h,m+1,n.subarray(R,St))}a.i=c}return Sh(l,0,i+Ku(m)+o)},Zu=function(){var n=1,t=0;return{p:function(e){for(var i=n,o=t,a=e.length|0,c=0;c!=a;){for(var l=Math.min(c+2655,a);c>16),o=(o&65535)+15*(o>>16)}n=i,t=o},d:function(){return n%=65521,t%=65521,(n&255)<<24|(n&65280)<<8|(t&255)<<8|t>>8}}},Ih=function(n,t,e,i,o){if(!o&&(o={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),c=new Qn(a.length+n.length);c.set(a),c.set(n,a.length),n=c,o.w=a.length}return Ph(n,t.level==null?6:t.level,t.mem==null?o.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+t.mem,e,i,o)},Qu=function(n,t,e){for(;e;++t)n[t]=e,e>>>=8},Ch=function(n,t){var e=t.level,i=e==0?0:e<6?1:e==9?3:2;if(n[0]=120,n[1]=i<<6|(t.dictionary&&32),n[1]|=31-(n[0]<<8|n[1])%31,t.dictionary){var o=Zu();o.p(t.dictionary),Qu(n,2,o.d())}};function Uo(n,t){t||(t={});var e=Zu();e.p(n);var i=Ih(n,t,t.dictionary?6:2,4);return Ch(i,t),Qu(i,i.length-4,e.d()),i}var Fh=typeof TextDecoder<"u"&&new TextDecoder,Eh=0;try{Fh.decode($u,{stream:!0}),Eh=1}catch{}function Oh(n){if(Array.isArray(n))return n}function jh(n,t){var e=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(e!=null){var i,o,a,c,l=[],h=!0,d=!1;try{if(a=(e=e.call(n)).next,t!==0)for(;!(h=(i=a.call(e)).done)&&(l.push(i.value),l.length!==t);h=!0);}catch(m){d=!0,o=m}finally{try{if(!h&&e.return!=null&&(c=e.return(),Object(c)!==c))return}finally{if(d)throw o}}return l}}function Dl(n,t){(t==null||t>n.length)&&(t=n.length);for(var e=0,i=Array(t);ei.map(i=>d[i]); +import{_ as mo}from"./index-BdLfAeGL.js";function xe(n){"@babel/helpers - typeof";return xe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xe(n)}var Qn=Uint8Array,Mn=Uint16Array,Ko=Int32Array,Xo=new Qn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),$o=new Qn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Bl=new Qn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Yu=function(n,t){for(var e=new Mn(31),i=0;i<31;++i)e[i]=t+=1<>1|(Ee&21845)<<1;Jr=(Jr&52428)>>2|(Jr&13107)<<2,Jr=(Jr&61680)>>4|(Jr&3855)<<4,Do[Ee]=((Jr&65280)>>8|(Jr&255)<<8)>>1}var Ia=(function(n,t,e){for(var i=n.length,o=0,a=new Mn(t);o>h]=d}else for(l=new Mn(i),o=0;o>15-n[o]);return l}),Li=new Qn(288);for(var Ee=0;Ee<144;++Ee)Li[Ee]=8;for(var Ee=144;Ee<256;++Ee)Li[Ee]=9;for(var Ee=256;Ee<280;++Ee)Li[Ee]=7;for(var Ee=280;Ee<288;++Ee)Li[Ee]=8;var Is=new Qn(32);for(var Ee=0;Ee<32;++Ee)Is[Ee]=5;var Nh=Ia(Li,9,0),Lh=Ia(Is,5,0),Ku=function(n){return(n+7)/8|0},Sh=function(n,t,e){return(e==null||e>n.length)&&(e=n.length),new Qn(n.subarray(t,e))},Cr=function(n,t,e){e<<=t&7;var i=t/8|0;n[i]|=e,n[i+1]|=e>>8},ka=function(n,t,e){e<<=t&7;var i=t/8|0;n[i]|=e,n[i+1]|=e>>8,n[i+2]|=e>>16},vo=function(n,t){for(var e=[],i=0;ik&&(k=a[i].s);var p=new Mn(k+1),j=qo(e[m-1],p,0);if(j>t){var i=0,O=0,M=j-t,S=1<t)O+=S-(1<>=M;O>0;){var G=a[i].s;p[G]=0&&O;--i){var q=a[i].s;p[q]==t&&(--p[q],++O)}j=t}return{t:new Qn(p),l:j}},qo=function(n,t,e){return n.s==-1?Math.max(qo(n.l,t,e+1),qo(n.r,t,e+1)):t[n.s]=e},Rl=function(n){for(var t=n.length;t&&!n[--t];);for(var e=new Mn(++t),i=0,o=n[0],a=1,c=function(h){e[i++]=h},l=1;l<=t;++l)if(n[l]==o&&l!=t)++a;else{if(!o&&a>2){for(;a>138;a-=138)c(32754);a>2&&(c(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(c(o),--a;a>6;a-=6)c(8304);a>2&&(c(a-3<<5|8208),a=0)}for(;a--;)c(o);a=1,o=n[l]}return{c:e.subarray(0,i),n:t}},Pa=function(n,t){for(var e=0,i=0;i>8,n[o+2]=n[o]^255,n[o+3]=n[o+1]^255;for(var a=0;a4&&!tt[Bl[E-1]];--E);var z=d+5<<3,U=Pa(o,Li)+Pa(a,Is)+c,rt=Pa(o,k)+Pa(a,O)+c+14+3*E+Pa(dt,tt)+2*dt[16]+3*dt[17]+7*dt[18];if(h>=0&&z<=U&&z<=rt)return Xu(t,m,n.subarray(h,h+d));var ot,ft,nt,ct;if(Cr(t,m,1+(rt15&&(Cr(t,m,B[X]>>5&127),m+=B[X]>>12)}}else ot=Nh,ft=Li,nt=Lh,ct=Is;for(var X=0;X255){var T=H>>18&31;ka(t,m,ot[T+257]),m+=ft[T+257],T>7&&(Cr(t,m,H>>23&31),m+=Xo[T]);var J=H&31;ka(t,m,nt[J]),m+=ct[J],J>3&&(ka(t,m,H>>5&8191),m+=$o[J])}else ka(t,m,ot[H]),m+=ft[H]}return ka(t,m,ot[256]),m+ft[256]},kh=new Ko([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),$u=new Qn(0),Ph=function(n,t,e,i,o,a){var c=a.z||n.length,l=new Qn(i+c+5*(1+Math.ceil(c/7e3))+o),h=l.subarray(i,l.length-o),d=a.l,m=(a.r||0)&7;if(t){m&&(h[0]=a.r>>3);for(var _=kh[t-1],k=_>>13,p=_&8191,j=(1<7e3||tt>24576)&&(ot>423||!d)){m=Tl(n,h,0,q,it,vt,X,tt,E,R-E,m),tt=dt=X=0,E=R;for(var ft=0;ft<286;++ft)it[ft]=0;for(var ft=0;ft<30;++ft)vt[ft]=0}var nt=2,ct=0,At=p,wt=U-rt&32767;if(ot>2&&z==G(R-wt))for(var x=Math.min(k,ot)-1,B=Math.min(32767,R),T=Math.min(258,ot);wt<=B&&--At&&U!=rt;){if(n[R+nt]==n[R+nt-wt]){for(var H=0;Hnt){if(nt=H,ct=wt,H>x)break;for(var J=Math.min(wt,H-2),Z=0,ft=0;ftZ&&(Z=gt,rt=at)}}}U=rt,rt=O[U],wt+=U-rt&32767}if(ct){q[tt++]=268435456|To[nt]<<18|Ml[ct];var _t=To[nt]&31,kt=Ml[ct]&31;X+=Xo[_t]+$o[kt],++it[257+_t],++vt[kt],N=R+nt,++dt}else q[tt++]=n[R],++it[n[R]]}}for(R=Math.max(R,N);R=c&&(h[m/8|0]=d,St=c),m=Xu(h,m+1,n.subarray(R,St))}a.i=c}return Sh(l,0,i+Ku(m)+o)},Zu=function(){var n=1,t=0;return{p:function(e){for(var i=n,o=t,a=e.length|0,c=0;c!=a;){for(var l=Math.min(c+2655,a);c>16),o=(o&65535)+15*(o>>16)}n=i,t=o},d:function(){return n%=65521,t%=65521,(n&255)<<24|(n&65280)<<8|(t&255)<<8|t>>8}}},Ih=function(n,t,e,i,o){if(!o&&(o={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),c=new Qn(a.length+n.length);c.set(a),c.set(n,a.length),n=c,o.w=a.length}return Ph(n,t.level==null?6:t.level,t.mem==null?o.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+t.mem,e,i,o)},Qu=function(n,t,e){for(;e;++t)n[t]=e,e>>>=8},Ch=function(n,t){var e=t.level,i=e==0?0:e<6?1:e==9?3:2;if(n[0]=120,n[1]=i<<6|(t.dictionary&&32),n[1]|=31-(n[0]<<8|n[1])%31,t.dictionary){var o=Zu();o.p(t.dictionary),Qu(n,2,o.d())}};function Uo(n,t){t||(t={});var e=Zu();e.p(n);var i=Ih(n,t,t.dictionary?6:2,4);return Ch(i,t),Qu(i,i.length-4,e.d()),i}var Fh=typeof TextDecoder<"u"&&new TextDecoder,Eh=0;try{Fh.decode($u,{stream:!0}),Eh=1}catch{}function Oh(n){if(Array.isArray(n))return n}function jh(n,t){var e=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(e!=null){var i,o,a,c,l=[],h=!0,d=!1;try{if(a=(e=e.call(n)).next,t!==0)for(;!(h=(i=a.call(e)).done)&&(l.push(i.value),l.length!==t);h=!0);}catch(m){d=!0,o=m}finally{try{if(!h&&e.return!=null&&(c=e.return(),Object(c)!==c))return}finally{if(d)throw o}}return l}}function Dl(n,t){(t==null||t>n.length)&&(t=n.length);for(var e=0,i=Array(t);e{const n=new Uint8Array(4),t=new Uint32Array(n.buffer);return!((t[0]=1)&n[0])})(),bo={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};class Zo{buffer;byteLength;byteOffset;length;offset;lastWrittenByte;littleEndian;_data;_mark;_marks;constructor(t=Dh,e={}){let i=!1;typeof t=="number"?t=new ArrayBuffer(t):(i=!0,this.lastWrittenByte=t.byteLength);const o=e.offset?e.offset>>>0:0,a=t.byteLength-o;let c=o;(ArrayBuffer.isView(t)||t instanceof Zo)&&(t.byteLength!==t.buffer.byteLength&&(c=t.byteOffset+o),t=t.buffer),i?this.lastWrittenByte=a:this.lastWrittenByte=0,this.buffer=t,this.length=a,this.byteLength=a,this.byteOffset=c,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,c,a),this._mark=0,this._marks=[]}available(t=1){return this.offset+t<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(t=1){return this.offset+=t,this}back(t=1){return this.offset-=t,this}seek(t){return this.offset=t,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const t=this._marks.pop();if(t===void 0)throw new Error("Mark stack empty");return this.seek(t),this}rewind(){return this.offset=0,this}ensureAvailable(t=1){if(!this.available(t)){const i=(this.offset+t)*2,o=new Uint8Array(i);o.set(new Uint8Array(this.buffer)),this.buffer=o.buffer,this.length=i,this.byteLength=i,this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(t=1){return this.readArray(t,"uint8")}readArray(t,e){const i=bo[e].BYTES_PER_ELEMENT*t,o=this.byteOffset+this.offset,a=this.buffer.slice(o,o+i);if(this.littleEndian===qh&&e!=="uint8"&&e!=="int8"){const l=new Uint8Array(this.buffer.slice(o,o+i));l.reverse();const h=new bo[e](l.buffer);return this.offset+=i,h.reverse(),h}const c=new bo[e](a);return this.offset+=i,c}readInt16(){const t=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}readUint16(){const t=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,t}readInt32(){const t=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}readUint32(){const t=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat32(){const t=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat64(){const t=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}readBigInt64(){const t=this._data.getBigInt64(this.offset,this.littleEndian);return this.offset+=8,t}readBigUint64(){const t=this._data.getBigUint64(this.offset,this.littleEndian);return this.offset+=8,t}readChar(){return String.fromCharCode(this.readInt8())}readChars(t=1){let e="";for(let i=0;ithis.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}function ra(n){let t=n.length;for(;--t>=0;)n[t]=0}const Uh=3,zh=258,tf=29,Hh=256,Wh=Hh+1+tf,ef=30,Vh=512,Gh=new Array((Wh+2)*2);ra(Gh);const Yh=new Array(ef*2);ra(Yh);const Jh=new Array(Vh);ra(Jh);const Kh=new Array(zh-Uh+1);ra(Kh);const Xh=new Array(tf);ra(Xh);const $h=new Array(ef);ra($h);const Zh=(n,t,e,i)=>{let o=n&65535|0,a=n>>>16&65535|0,c=0;for(;e!==0;){c=e>2e3?2e3:e,e-=c;do o=o+t[i++]|0,a=a+o|0;while(--c);o%=65521,a%=65521}return o|a<<16|0};var zo=Zh;const Qh=()=>{let n,t=[];for(var e=0;e<256;e++){n=e;for(var i=0;i<8;i++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n}return t},tc=new Uint32Array(Qh()),ec=(n,t,e,i)=>{const o=tc,a=i+e;n^=-1;for(let c=i;c>>8^o[(n^t[c])&255];return n^-1};var cr=ec,Ho={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},nf={Z_NO_FLUSH:0,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFLATED:8};const nc=(n,t)=>Object.prototype.hasOwnProperty.call(n,t);var rc=function(n){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const e=t.shift();if(e){if(typeof e!="object")throw new TypeError(e+"must be non-object");for(const i in e)nc(e,i)&&(n[i]=e[i])}}return n},ic=n=>{let t=0;for(let i=0,o=n.length;i=252?6:n>=248?5:n>=240?4:n>=224?3:n>=192?2:1;Ba[254]=Ba[254]=1;var ac=n=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(n);let t,e,i,o,a,c=n.length,l=0;for(o=0;o>>6,t[a++]=128|e&63):e<65536?(t[a++]=224|e>>>12,t[a++]=128|e>>>6&63,t[a++]=128|e&63):(t[a++]=240|e>>>18,t[a++]=128|e>>>12&63,t[a++]=128|e>>>6&63,t[a++]=128|e&63);return t};const sc=(n,t)=>{if(t<65534&&n.subarray&&af)return String.fromCharCode.apply(null,n.length===t?n:n.subarray(0,t));let e="";for(let i=0;i{const e=t||n.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(n.subarray(0,t));let i,o;const a=new Array(e*2);for(o=0,i=0;i4){a[o++]=65533,i+=l-1;continue}for(c&=l===2?31:l===3?15:7;l>1&&i1){a[o++]=65533;continue}c<65536?a[o++]=c:(c-=65536,a[o++]=55296|c>>10&1023,a[o++]=56320|c&1023)}return sc(a,o)},lc=(n,t)=>{t=t||n.length,t>n.length&&(t=n.length);let e=t-1;for(;e>=0&&(n[e]&192)===128;)e--;return e<0||e===0?t:e+Ba[n[e]]>t?e:t},Wo={string2buf:ac,buf2string:oc,utf8border:lc};function uc(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var fc=uc;const ws=16209,hc=16191;var cc=function(t,e){let i,o,a,c,l,h,d,m,_,k,p,j,O,M,S,V,G,q,it,vt,dt,X,R,tt;const N=t.state;i=t.next_in,R=t.input,o=i+(t.avail_in-5),a=t.next_out,tt=t.output,c=a-(e-t.avail_out),l=a+(t.avail_out-257),h=N.dmax,d=N.wsize,m=N.whave,_=N.wnext,k=N.window,p=N.hold,j=N.bits,O=N.lencode,M=N.distcode,S=(1<>>24,p>>>=q,j-=q,q=G>>>16&255,q===0)tt[a++]=G&65535;else if(q&16){it=G&65535,q&=15,q&&(j>>=q,j-=q),j<15&&(p+=R[i++]<>>24,p>>>=q,j-=q,q=G>>>16&255,q&16){if(vt=G&65535,q&=15,jh){t.msg="invalid distance too far back",N.mode=ws;break t}if(p>>>=q,j-=q,q=a-c,vt>q){if(q=vt-q,q>m&&N.sane){t.msg="invalid distance too far back",N.mode=ws;break t}if(dt=0,X=k,_===0){if(dt+=d-q,q2;)tt[a++]=X[dt++],tt[a++]=X[dt++],tt[a++]=X[dt++],it-=3;it&&(tt[a++]=X[dt++],it>1&&(tt[a++]=X[dt++]))}else{dt=a-vt;do tt[a++]=tt[dt++],tt[a++]=tt[dt++],tt[a++]=tt[dt++],it-=3;while(it>2);it&&(tt[a++]=tt[dt++],it>1&&(tt[a++]=tt[dt++]))}}else if((q&64)===0){G=M[(G&65535)+(p&(1<>3,i-=it,j-=it<<3,p&=(1<{const h=l.bits;let d=0,m=0,_=0,k=0,p=0,j=0,O=0,M=0,S=0,V=0,G,q,it,vt,dt,X=null,R;const tt=new Uint16Array(Zi+1),N=new Uint16Array(Zi+1);let E=null,z,U,rt;for(d=0;d<=Zi;d++)tt[d]=0;for(m=0;m=1&&tt[k]===0;k--);if(p>k&&(p=k),k===0)return o[a++]=1<<24|64<<16|0,o[a++]=1<<24|64<<16|0,l.bits=1,0;for(_=1;_0&&(n===Wl||k!==1))return-1;for(N[1]=0,d=1;dzl||n===Vl&&S>Hl)return 1;for(;;){z=d-O,c[m]+1=R?(U=E[c[m]-R],rt=X[c[m]-R]):(U=96,rt=0),G=1<>O)+q]=z<<24|U<<16|rt|0;while(q!==0);for(G=1<>=1;if(G!==0?(V&=G-1,V+=G):V=0,m++,--tt[d]===0){if(d===k)break;d=t[e+c[m]]}if(d>p&&(V&vt)!==it){for(O===0&&(O=p),dt+=_,j=d-O,M=1<zl||n===Vl&&S>Hl)return 1;it=V&vt,o[it]=p<<24|j<<16|dt-a|0}}return V!==0&&(o[dt+V]=d-O<<24|64<<16|0),l.bits=p,0};var Ca=vc;const bc=0,sf=1,of=2,{Z_FINISH:Gl,Z_BLOCK:wc,Z_TREES:ys,Z_OK:Si,Z_STREAM_END:yc,Z_NEED_DICT:xc,Z_STREAM_ERROR:Wn,Z_DATA_ERROR:lf,Z_MEM_ERROR:uf,Z_BUF_ERROR:_c,Z_DEFLATED:Yl}=nf,Es=16180,Jl=16181,Kl=16182,Xl=16183,$l=16184,Zl=16185,Ql=16186,tu=16187,eu=16188,nu=16189,Cs=16190,Fr=16191,yo=16192,ru=16193,xo=16194,iu=16195,au=16196,su=16197,ou=16198,xs=16199,_s=16200,lu=16201,uu=16202,fu=16203,hu=16204,cu=16205,_o=16206,du=16207,pu=16208,Be=16209,ff=16210,hf=16211,Ac=852,Nc=592,Lc=15,Sc=Lc,gu=n=>(n>>>24&255)+(n>>>8&65280)+((n&65280)<<8)+((n&255)<<24);function kc(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Pi=n=>{if(!n)return 1;const t=n.state;return!t||t.strm!==n||t.modehf?1:0},cf=n=>{if(Pi(n))return Wn;const t=n.state;return n.total_in=n.total_out=t.total=0,n.msg="",t.wrap&&(n.adler=t.wrap&1),t.mode=Es,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(Ac),t.distcode=t.distdyn=new Int32Array(Nc),t.sane=1,t.back=-1,Si},df=n=>{if(Pi(n))return Wn;const t=n.state;return t.wsize=0,t.whave=0,t.wnext=0,cf(n)},pf=(n,t)=>{let e;if(Pi(n))return Wn;const i=n.state;return t<0?(e=0,t=-t):(e=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?Wn:(i.window!==null&&i.wbits!==t&&(i.window=null),i.wrap=e,i.wbits=t,df(n))},gf=(n,t)=>{if(!n)return Wn;const e=new kc;n.state=e,e.strm=n,e.window=null,e.mode=Es;const i=pf(n,t);return i!==Si&&(n.state=null),i},Pc=n=>gf(n,Sc);let mu=!0,Ao,No;const Ic=n=>{if(mu){Ao=new Int32Array(512),No=new Int32Array(32);let t=0;for(;t<144;)n.lens[t++]=8;for(;t<256;)n.lens[t++]=9;for(;t<280;)n.lens[t++]=7;for(;t<288;)n.lens[t++]=8;for(Ca(sf,n.lens,0,288,Ao,0,n.work,{bits:9}),t=0;t<32;)n.lens[t++]=5;Ca(of,n.lens,0,32,No,0,n.work,{bits:5}),mu=!1}n.lencode=Ao,n.lenbits=9,n.distcode=No,n.distbits=5},mf=(n,t,e,i)=>{let o;const a=n.state;return a.window===null&&(a.wsize=1<=a.wsize?(a.window.set(t.subarray(e-a.wsize,e),0),a.wnext=0,a.whave=a.wsize):(o=a.wsize-a.wnext,o>i&&(o=i),a.window.set(t.subarray(e-i,e-i+o),a.wnext),i-=o,i?(a.window.set(t.subarray(e-i,e),0),a.wnext=i,a.whave=a.wsize):(a.wnext+=o,a.wnext===a.wsize&&(a.wnext=0),a.whave{let e,i,o,a,c,l,h,d,m,_,k,p,j,O,M=0,S,V,G,q,it,vt,dt,X;const R=new Uint8Array(4);let tt,N;const E=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Pi(n)||!n.output||!n.input&&n.avail_in!==0)return Wn;e=n.state,e.mode===Fr&&(e.mode=yo),c=n.next_out,o=n.output,h=n.avail_out,a=n.next_in,i=n.input,l=n.avail_in,d=e.hold,m=e.bits,_=l,k=h,X=Si;t:for(;;)switch(e.mode){case Es:if(e.wrap===0){e.mode=yo;break}for(;m<16;){if(l===0)break t;l--,d+=i[a++]<>>8&255,e.check=cr(e.check,R,2,0),d=0,m=0,e.mode=Jl;break}if(e.head&&(e.head.done=!1),!(e.wrap&1)||(((d&255)<<8)+(d>>8))%31){n.msg="incorrect header check",e.mode=Be;break}if((d&15)!==Yl){n.msg="unknown compression method",e.mode=Be;break}if(d>>>=4,m-=4,dt=(d&15)+8,e.wbits===0&&(e.wbits=dt),dt>15||dt>e.wbits){n.msg="invalid window size",e.mode=Be;break}e.dmax=1<>8&1),e.flags&512&&e.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,e.check=cr(e.check,R,2,0)),d=0,m=0,e.mode=Kl;case Kl:for(;m<32;){if(l===0)break t;l--,d+=i[a++]<>>8&255,R[2]=d>>>16&255,R[3]=d>>>24&255,e.check=cr(e.check,R,4,0)),d=0,m=0,e.mode=Xl;case Xl:for(;m<16;){if(l===0)break t;l--,d+=i[a++]<>8),e.flags&512&&e.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,e.check=cr(e.check,R,2,0)),d=0,m=0,e.mode=$l;case $l:if(e.flags&1024){for(;m<16;){if(l===0)break t;l--,d+=i[a++]<>>8&255,e.check=cr(e.check,R,2,0)),d=0,m=0}else e.head&&(e.head.extra=null);e.mode=Zl;case Zl:if(e.flags&1024&&(p=e.length,p>l&&(p=l),p&&(e.head&&(dt=e.head.extra_len-e.length,e.head.extra||(e.head.extra=new Uint8Array(e.head.extra_len)),e.head.extra.set(i.subarray(a,a+p),dt)),e.flags&512&&e.wrap&4&&(e.check=cr(e.check,i,p,a)),l-=p,a+=p,e.length-=p),e.length))break t;e.length=0,e.mode=Ql;case Ql:if(e.flags&2048){if(l===0)break t;p=0;do dt=i[a+p++],e.head&&dt&&e.length<65536&&(e.head.name+=String.fromCharCode(dt));while(dt&&p>9&1,e.head.done=!0),n.adler=e.check=0,e.mode=Fr;break;case nu:for(;m<32;){if(l===0)break t;l--,d+=i[a++]<>>=m&7,m-=m&7,e.mode=_o;break}for(;m<3;){if(l===0)break t;l--,d+=i[a++]<>>=1,m-=1,d&3){case 0:e.mode=ru;break;case 1:if(Ic(e),e.mode=xs,t===ys){d>>>=2,m-=2;break t}break;case 2:e.mode=au;break;case 3:n.msg="invalid block type",e.mode=Be}d>>>=2,m-=2;break;case ru:for(d>>>=m&7,m-=m&7;m<32;){if(l===0)break t;l--,d+=i[a++]<>>16^65535)){n.msg="invalid stored block lengths",e.mode=Be;break}if(e.length=d&65535,d=0,m=0,e.mode=xo,t===ys)break t;case xo:e.mode=iu;case iu:if(p=e.length,p){if(p>l&&(p=l),p>h&&(p=h),p===0)break t;o.set(i.subarray(a,a+p),c),l-=p,a+=p,h-=p,c+=p,e.length-=p;break}e.mode=Fr;break;case au:for(;m<14;){if(l===0)break t;l--,d+=i[a++]<>>=5,m-=5,e.ndist=(d&31)+1,d>>>=5,m-=5,e.ncode=(d&15)+4,d>>>=4,m-=4,e.nlen>286||e.ndist>30){n.msg="too many length or distance symbols",e.mode=Be;break}e.have=0,e.mode=su;case su:for(;e.have>>=3,m-=3}for(;e.have<19;)e.lens[E[e.have++]]=0;if(e.lencode=e.lendyn,e.lenbits=7,tt={bits:e.lenbits},X=Ca(bc,e.lens,0,19,e.lencode,0,e.work,tt),e.lenbits=tt.bits,X){n.msg="invalid code lengths set",e.mode=Be;break}e.have=0,e.mode=ou;case ou:for(;e.have>>24,V=M>>>16&255,G=M&65535,!(S<=m);){if(l===0)break t;l--,d+=i[a++]<>>=S,m-=S,e.lens[e.have++]=G;else{if(G===16){for(N=S+2;m>>=S,m-=S,e.have===0){n.msg="invalid bit length repeat",e.mode=Be;break}dt=e.lens[e.have-1],p=3+(d&3),d>>>=2,m-=2}else if(G===17){for(N=S+3;m>>=S,m-=S,dt=0,p=3+(d&7),d>>>=3,m-=3}else{for(N=S+7;m>>=S,m-=S,dt=0,p=11+(d&127),d>>>=7,m-=7}if(e.have+p>e.nlen+e.ndist){n.msg="invalid bit length repeat",e.mode=Be;break}for(;p--;)e.lens[e.have++]=dt}}if(e.mode===Be)break;if(e.lens[256]===0){n.msg="invalid code -- missing end-of-block",e.mode=Be;break}if(e.lenbits=9,tt={bits:e.lenbits},X=Ca(sf,e.lens,0,e.nlen,e.lencode,0,e.work,tt),e.lenbits=tt.bits,X){n.msg="invalid literal/lengths set",e.mode=Be;break}if(e.distbits=6,e.distcode=e.distdyn,tt={bits:e.distbits},X=Ca(of,e.lens,e.nlen,e.ndist,e.distcode,0,e.work,tt),e.distbits=tt.bits,X){n.msg="invalid distances set",e.mode=Be;break}if(e.mode=xs,t===ys)break t;case xs:e.mode=_s;case _s:if(l>=6&&h>=258){n.next_out=c,n.avail_out=h,n.next_in=a,n.avail_in=l,e.hold=d,e.bits=m,cc(n,k),c=n.next_out,o=n.output,h=n.avail_out,a=n.next_in,i=n.input,l=n.avail_in,d=e.hold,m=e.bits,e.mode===Fr&&(e.back=-1);break}for(e.back=0;M=e.lencode[d&(1<>>24,V=M>>>16&255,G=M&65535,!(S<=m);){if(l===0)break t;l--,d+=i[a++]<>q)],S=M>>>24,V=M>>>16&255,G=M&65535,!(q+S<=m);){if(l===0)break t;l--,d+=i[a++]<>>=q,m-=q,e.back+=q}if(d>>>=S,m-=S,e.back+=S,e.length=G,V===0){e.mode=cu;break}if(V&32){e.back=-1,e.mode=Fr;break}if(V&64){n.msg="invalid literal/length code",e.mode=Be;break}e.extra=V&15,e.mode=lu;case lu:if(e.extra){for(N=e.extra;m>>=e.extra,m-=e.extra,e.back+=e.extra}e.was=e.length,e.mode=uu;case uu:for(;M=e.distcode[d&(1<>>24,V=M>>>16&255,G=M&65535,!(S<=m);){if(l===0)break t;l--,d+=i[a++]<>q)],S=M>>>24,V=M>>>16&255,G=M&65535,!(q+S<=m);){if(l===0)break t;l--,d+=i[a++]<>>=q,m-=q,e.back+=q}if(d>>>=S,m-=S,e.back+=S,V&64){n.msg="invalid distance code",e.mode=Be;break}e.offset=G,e.extra=V&15,e.mode=fu;case fu:if(e.extra){for(N=e.extra;m>>=e.extra,m-=e.extra,e.back+=e.extra}if(e.offset>e.dmax){n.msg="invalid distance too far back",e.mode=Be;break}e.mode=hu;case hu:if(h===0)break t;if(p=k-h,e.offset>p){if(p=e.offset-p,p>e.whave&&e.sane){n.msg="invalid distance too far back",e.mode=Be;break}p>e.wnext?(p-=e.wnext,j=e.wsize-p):j=e.wnext-p,p>e.length&&(p=e.length),O=e.window}else O=o,j=c-e.offset,p=e.length;p>h&&(p=h),h-=p,e.length-=p;do o[c++]=O[j++];while(--p);e.length===0&&(e.mode=_s);break;case cu:if(h===0)break t;o[c++]=e.length,h--,e.mode=_s;break;case _o:if(e.wrap){for(;m<32;){if(l===0)break t;l--,d|=i[a++]<{if(Pi(n))return Wn;let t=n.state;return t.window&&(t.window=null),n.state=null,Si},Ec=(n,t)=>{if(Pi(n))return Wn;const e=n.state;return(e.wrap&2)===0?Wn:(e.head=t,t.done=!1,Si)},Oc=(n,t)=>{const e=t.length;let i,o,a;return Pi(n)||(i=n.state,i.wrap!==0&&i.mode!==Cs)?Wn:i.mode===Cs&&(o=1,o=zo(o,t,e,0),o!==i.check)?lf:(a=mf(n,t,e,e),a?(i.mode=ff,uf):(i.havedict=1,Si))};var jc=df,Bc=pf,Mc=cf,Rc=Pc,Tc=gf,Dc=Cc,qc=Fc,Uc=Ec,zc=Oc,Hc="pako inflate (from Nodeca project)",Er={inflateReset:jc,inflateReset2:Bc,inflateResetKeep:Mc,inflateInit:Rc,inflateInit2:Tc,inflate:Dc,inflateEnd:qc,inflateGetHeader:Uc,inflateSetDictionary:zc,inflateInfo:Hc};function Wc(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var Vc=Wc;const vf=Object.prototype.toString,{Z_NO_FLUSH:Gc,Z_FINISH:Yc,Z_OK:Ma,Z_STREAM_END:Lo,Z_NEED_DICT:So,Z_STREAM_ERROR:Jc,Z_DATA_ERROR:vu,Z_MEM_ERROR:Kc}=nf;function Ta(n){this.options=rf.assign({chunkSize:1024*64,windowBits:15,to:""},n||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(n&&n.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15)===0&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new fc,this.strm.avail_out=0;let e=Er.inflateInit2(this.strm,t.windowBits);if(e!==Ma)throw new Error(Ho[e]);if(this.header=new Vc,Er.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=Wo.string2buf(t.dictionary):vf.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(e=Er.inflateSetDictionary(this.strm,t.dictionary),e!==Ma)))throw new Error(Ho[e])}Ta.prototype.push=function(n,t){const e=this.strm,i=this.options.chunkSize,o=this.options.dictionary;let a,c,l;if(this.ended)return!1;for(t===~~t?c=t:c=t===!0?Yc:Gc,vf.call(n)==="[object ArrayBuffer]"?e.input=new Uint8Array(n):e.input=n,e.next_in=0,e.avail_in=e.input.length;;){for(e.avail_out===0&&(e.output=new Uint8Array(i),e.next_out=0,e.avail_out=i),a=Er.inflate(e,c),a===So&&o&&(a=Er.inflateSetDictionary(e,o),a===Ma?a=Er.inflate(e,c):a===vu&&(a=So));e.avail_in>0&&a===Lo&&e.state.wrap>0&&n[e.next_in]!==0;)Er.inflateReset(e),a=Er.inflate(e,c);switch(a){case Jc:case vu:case So:case Kc:return this.onEnd(a),this.ended=!0,!1}if(l=e.avail_out,e.next_out&&(e.avail_out===0||a===Lo))if(this.options.to==="string"){let h=Wo.utf8border(e.output,e.next_out),d=e.next_out-h,m=Wo.buf2string(e.output,h);e.next_out=d,e.avail_out=i-d,d&&e.output.set(e.output.subarray(h,h+d),0),this.onData(m)}else this.onData(e.output.length===e.next_out?e.output:e.output.subarray(0,e.next_out));if(!(a===Ma&&l===0)){if(a===Lo)return a=Er.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,!0;if(e.avail_in===0)break}}return!0};Ta.prototype.onData=function(n){this.chunks.push(n)};Ta.prototype.onEnd=function(n){n===Ma&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=rf.flattenChunks(this.chunks)),this.chunks=[],this.err=n,this.msg=this.strm.msg};function Xc(n,t){const e=new Ta(t);if(e.push(n),e.err)throw e.msg||Ho[e.err];return e.result}var $c=Ta,Zc=Xc,Qc={Inflate:$c,inflate:Zc};const{Inflate:t1,inflate:e1}=Qc;var bu=t1,n1=e1;const bf=[];for(let n=0;n<256;n++){let t=n;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t=t>>>1;bf[n]=t}const wu=4294967295;function r1(n,t,e){let i=n;for(let o=0;o>>8;return i}function i1(n,t){return(r1(wu,n,t)^wu)>>>0}function yu(n,t,e){const i=n.readUint32(),o=i1(new Uint8Array(n.buffer,n.byteOffset+n.offset-t-4,t),t);if(o!==i)throw new Error(`CRC mismatch for chunk ${e}. Expected ${i}, found ${o}`)}function wf(n,t,e){for(let i=0;i>1)&255}else{for(;a>1)&255;for(;a>1)&255}}function Af(n,t,e,i,o){let a=0;if(e.length===0){for(;a=e||vt>=i))for(let dt=0;dt>8&255}const c1=new Uint16Array([255]),d1=new Uint8Array(c1.buffer),p1=d1[0]===255,g1=new Uint8Array(0);function xu(n){const{data:t,width:e,height:i,channels:o,depth:a}=n,c=Math.ceil(a/8)*o,l=Math.ceil(a/8*o*e),h=new Uint8Array(i*l);let d=g1,m=0,_,k;for(let p=0;p>8&255}const ks=Uint8Array.of(137,80,78,71,13,10,26,10);function _u(n){if(!v1(n.readBytes(ks.length)))throw new Error("wrong PNG signature")}function v1(n){if(n.length79)throw new Error("keyword length must be between 1 and 79")}const x1=/^[\u0000-\u00FF]*$/;function _1(n){if(!x1.test(n))throw new Error("invalid latin1 text")}function A1(n,t,e){const i=Lf(t);n[i]=N1(t,e-i.length-1)}function Lf(n){for(n.mark();n.readByte()!==w1;);const t=n.offset;n.reset();const e=Nf.decode(n.readBytes(t-n.offset-1));return n.skip(1),y1(e),e}function N1(n,t){return Nf.decode(n.readBytes(t))}const Bn={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},ko={UNKNOWN:-1,DEFLATE:0},Au={UNKNOWN:-1,ADAPTIVE:0},Po={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},As={NONE:0,BACKGROUND:1,PREVIOUS:2},Io={SOURCE:0,OVER:1};class L1 extends Zo{_checkCrc;_inflator;_png;_apng;_end;_hasPalette;_palette;_hasTransparency;_transparency;_compressionMethod;_filterMethod;_interlaceMethod;_colorType;_isAnimated;_numberOfFrames;_numberOfPlays;_frames;_writingDataChunks;constructor(t,e={}){super(t);const{checkCrc:i=!1}=e;this._checkCrc=i,this._inflator=new bu,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]},this._end=!1,this._hasPalette=!1,this._palette=[],this._hasTransparency=!1,this._transparency=new Uint16Array(0),this._compressionMethod=ko.UNKNOWN,this._filterMethod=Au.UNKNOWN,this._interlaceMethod=Po.UNKNOWN,this._colorType=Bn.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(_u(this);!this._end;){const t=this.readUint32(),e=this.readChars(4);this.decodeChunk(t,e)}return this.decodeImage(),this._png}decodeApng(){for(_u(this);!this._end;){const t=this.readUint32(),e=this.readChars(4);this.decodeApngChunk(t,e)}return this.decodeApngImage(),this._apng}decodeChunk(t,e){const i=this.offset;switch(e){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(t);break;case"IDAT":this.decodeIDAT(t);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(t);break;case"iCCP":this.decodeiCCP(t);break;case b1:A1(this._png.text,this,t);break;case"pHYs":this.decodepHYs();break;default:this.skip(t);break}if(this.offset-i!==t)throw new Error(`Length mismatch while decoding chunk ${e}`);this._checkCrc?yu(this,t+4,e):this.skip(4)}decodeApngChunk(t,e){const i=this.offset;switch(e!=="fdAT"&&e!=="IDAT"&&this._writingDataChunks&&this.pushDataToFrame(),e){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(t);break;default:this.decodeChunk(t,e),this.offset=i+t;break}if(this.offset-i!==t)throw new Error(`Length mismatch while decoding chunk ${e}`);this._checkCrc?yu(this,t+4,e):this.skip(4)}decodeIHDR(){const t=this._png;t.width=this.readUint32(),t.height=this.readUint32(),t.depth=S1(this.readUint8());const e=this.readUint8();this._colorType=e;let i;switch(e){case Bn.GREYSCALE:i=1;break;case Bn.TRUECOLOUR:i=3;break;case Bn.INDEXED_COLOUR:i=1;break;case Bn.GREYSCALE_ALPHA:i=2;break;case Bn.TRUECOLOUR_ALPHA:i=4;break;case Bn.UNKNOWN:default:throw new Error(`Unknown color type: ${e}`)}if(this._png.channels=i,this._compressionMethod=this.readUint8(),this._compressionMethod!==ko.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32(),this._numberOfPlays=this.readUint32(),this._isAnimated=!0}decodeFCTL(){const t={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(t)}decodePLTE(t){if(t%3!==0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${t}`);const e=t/3;this._hasPalette=!0;const i=[];this._palette=i;for(let o=0;othis._png.width*this._png.height)throw new Error(`tRNS chunk contains more alpha values than there are pixels (${t/2} vs ${this._png.width*this._png.height})`);this._hasTransparency=!0,this._transparency=new Uint16Array(t/2);for(let e=0;ethis._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${t} vs ${this._palette.length})`);let e=0;for(;e{const l=((a+e.yOffset)*this._png.width+e.xOffset+c)*this._png.channels,h=(a*e.width+c)*this._png.channels;return{index:l,frameIndex:h}};switch(e.blendOp){case Io.SOURCE:for(let a=0;a=200&&t.status<=299}function Ns(n){try{n.dispatchEvent(new MouseEvent("click"))}catch{var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),n.dispatchEvent(t)}}var wi=Kt.saveAs||((typeof window>"u"?"undefined":xe(window))!=="object"||window!==Kt?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(n,t,e){var i=Kt.URL||Kt.webkitURL,o=document.createElement("a");t=t||n.name||"download",o.download=t,o.rel="noopener",typeof n=="string"?(o.href=n,o.origin!==location.origin?Lu(o.href)?Fo(n,t,e):Ns(o,o.target="_blank"):Ns(o)):(o.href=i.createObjectURL(n),setTimeout(function(){i.revokeObjectURL(o.href)},4e4),setTimeout(function(){Ns(o)},0))}:"msSaveOrOpenBlob"in navigator?function(n,t,e){if(t=t||n.name||"download",typeof n=="string")if(Lu(n))Fo(n,t,e);else{var i=document.createElement("a");i.href=n,i.target="_blank",setTimeout(function(){Ns(i)})}else navigator.msSaveOrOpenBlob((function(o,a){return a===void 0?a={autoBom:!1}:xe(a)!=="object"&&(Le.warn("Deprecated: Expected third argument to be a object"),a={autoBom:!a}),a.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(o.type)?new Blob(["\uFEFF",o],{type:o.type}):o})(n,e),t)}:function(n,t,e,i){if((i=i||open("","_blank"))&&(i.document.title=i.document.body.innerText="downloading..."),typeof n=="string")return Fo(n,t,e);var o=n.type==="application/octet-stream",a=/constructor/i.test(Kt.HTMLElement)||Kt.safari,c=/CriOS\/[\d]+/.test(navigator.userAgent);if((c||o&&a)&&(typeof FileReader>"u"?"undefined":xe(FileReader))==="object"){var l=new FileReader;l.onloadend=function(){var m=l.result;m=c?m:m.replace(/^data:[^;]*;/,"data:attachment/file;"),i?i.location.href=m:location=m,i=null},l.readAsDataURL(n)}else{var h=Kt.URL||Kt.webkitURL,d=h.createObjectURL(n);i?i.location=d:location.href=d,i=null,setTimeout(function(){h.revokeObjectURL(d)},4e4)}});/** * A class to parse color values * @author Stoyan Stefanov @@ -138,7 +138,7 @@ T* `):u.join(` Tj endobj\r `},e.outline.count_r=function(i,o){for(var a=0;a1){U=!0,ot=void 0;var J=R*tt;ft=new Uint8Array(J);for(var Z=new DataView(N.buffer),at=0;at536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[n]()}catch(e){Le.log("bit decode error:"+e)}},Zn.prototype.bit1=function(){var n,t=Math.ceil(this.width/8),e=t%4;for(n=this.height-1;n>=0;n--){for(var i=this.bottom_up?n:this.height-1-n,o=0;o>7-l&1];this.data[c+4*l]=h.blue,this.data[c+4*l+1]=h.green,this.data[c+4*l+2]=h.red,this.data[c+4*l+3]=255}e!==0&&(this.pos+=4-e)}},Zn.prototype.bit4=function(){for(var n=Math.ceil(this.width/2),t=n%4,e=this.height-1;e>=0;e--){for(var i=this.bottom_up?e:this.height-1-e,o=0;o>4,h=15&a,d=this.palette[l];if(this.data[c]=d.blue,this.data[c+1]=d.green,this.data[c+2]=d.red,this.data[c+3]=255,2*o+1>=this.width)break;d=this.palette[h],this.data[c+4]=d.blue,this.data[c+4+1]=d.green,this.data[c+4+2]=d.red,this.data[c+4+3]=255}t!==0&&(this.pos+=4-t)}},Zn.prototype.bit8=function(){for(var n=this.width%4,t=this.height-1;t>=0;t--){for(var e=this.bottom_up?t:this.height-1-t,i=0;i=0;e--){for(var i=this.bottom_up?e:this.height-1-e,o=0;o>5&t)/t*255|0,h=(a>>10&t)/t*255|0,d=a>>15?255:0,m=i*this.width*4+4*o;this.data[m]=h,this.data[m+1]=l,this.data[m+2]=c,this.data[m+3]=d}this.pos+=n}},Zn.prototype.bit16=function(){for(var n=this.width%3,t=parseInt("11111",2),e=parseInt("111111",2),i=this.height-1;i>=0;i--){for(var o=this.bottom_up?i:this.height-1-i,a=0;a>5&e)/e*255|0,d=(c>>11)/t*255|0,m=o*this.width*4+4*a;this.data[m]=d,this.data[m+1]=h,this.data[m+2]=l,this.data[m+3]=255}this.pos+=n}},Zn.prototype.bit24=function(){for(var n=this.height-1;n>=0;n--){for(var t=this.bottom_up?n:this.height-1-n,e=0;e=0;n--)for(var t=this.bottom_up?n:this.height-1-n,e=0;ei&&(o.push(n.slice(h,a)),l=0,h=a),l+=t[a],a++;return h!==a&&o.push(n.slice(h,a)),o},Ru=function(n,t,e){e||(e={});var i,o,a,c,l,h,d,m=[],_=[m],k=e.textIndent||0,p=0,j=0,O=n.split(" "),M=Ss.apply(this,[" ",e])[0];if(h=e.lineIndent===-1?O[0].length+2:e.lineIndent||0){var S=Array(h).join(" "),V=[];O.map(function(q){(q=q.split(/\s*\n/)).length>1?V=V.concat(q.map(function(it,vt){return(vt&&it.length?` `:"")+it})):V.push(q[0])}),O=V,h=Bu.apply(this,[S,e])}for(a=0,c=O.length;at||G){if(j>t){for(l=Mu.apply(this,[i,o,t-(k+p),t]),m.push(l.shift()),m=[l.pop()];l.length;)_.push([l.shift()]);j=o.slice(i.length-(m[0]?m[0].length:0)).reduce(function(q,it){return q+it},0)}else m=[i];_.push(m),k=j+h,p=M}else m.push(i),k+=p+j,p=M}return d=h?function(q,it){return(it?S:"")+q.join(" ")}:function(q){return q.join(" ")},_.map(d)},ta.splitTextToSize=function(n,t,e){var i,o=(e=e||{}).fontSize||this.internal.getFontSize(),a=function(m){if(m.widths&&m.kerning)return{widths:m.widths,kerning:m.kerning};var _=this.internal.getFont(m.fontName,m.fontStyle),k="Unicode";return _.metadata[k]?{widths:_.metadata[k].widths||{0:1},kerning:_.metadata[k].kerning||{}}:{font:_.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()}}.call(this,e);i=Array.isArray(n)?n:String(n).split(/\r?\n/);var c=1*this.internal.scaleFactor*t/o;a.textIndent=e.textIndent?1*e.textIndent*this.internal.scaleFactor/o:0,a.lineIndent=e.lineIndent;var l,h,d=[];for(l=0,h=i.length;limport("./index.es-CkGqZuf8.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12]))).catch(function(k){return Promise.reject(new Error("Could not load canvg: "+k))}).then(function(k){return k.default?k.default:k}).then(function(k){return k.fromString(d,n,m)},function(){return Promise.reject(new Error("Could not load canvg."))}).then(function(k){return k.render(m)}).then(function(){_.addImage(h.toDataURL("image/jpeg",1),t,e,i,o,c,l)})},Mt.API.putTotalPages=function(n){var t,e=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(t=new RegExp(n,"g"),e=this.internal.getNumberOfPages()):(t=new RegExp(this.pdfEscape16(n,this.internal.getFont()),"g"),e=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var i=1;i<=this.internal.getNumberOfPages();i++)for(var o=0;o1){for(m=0;mt||G){if(j>t){for(l=Mu.apply(this,[i,o,t-(k+p),t]),m.push(l.shift()),m=[l.pop()];l.length;)_.push([l.shift()]);j=o.slice(i.length-(m[0]?m[0].length:0)).reduce(function(q,it){return q+it},0)}else m=[i];_.push(m),k=j+h,p=M}else m.push(i),k+=p+j,p=M}return d=h?function(q,it){return(it?S:"")+q.join(" ")}:function(q){return q.join(" ")},_.map(d)},ta.splitTextToSize=function(n,t,e){var i,o=(e=e||{}).fontSize||this.internal.getFontSize(),a=function(m){if(m.widths&&m.kerning)return{widths:m.widths,kerning:m.kerning};var _=this.internal.getFont(m.fontName,m.fontStyle),k="Unicode";return _.metadata[k]?{widths:_.metadata[k].widths||{0:1},kerning:_.metadata[k].kerning||{}}:{font:_.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()}}.call(this,e);i=Array.isArray(n)?n:String(n).split(/\r?\n/);var c=1*this.internal.scaleFactor*t/o;a.textIndent=e.textIndent?1*e.textIndent*this.internal.scaleFactor/o:0,a.lineIndent=e.lineIndent;var l,h,d=[];for(l=0,h=i.length;limport("./index.es-CAwVNbbg.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12]))).catch(function(k){return Promise.reject(new Error("Could not load canvg: "+k))}).then(function(k){return k.default?k.default:k}).then(function(k){return k.fromString(d,n,m)},function(){return Promise.reject(new Error("Could not load canvg."))}).then(function(k){return k.render(m)}).then(function(){_.addImage(h.toDataURL("image/jpeg",1),t,e,i,o,c,l)})},Mt.API.putTotalPages=function(n){var t,e=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(t=new RegExp(n,"g"),e=this.internal.getNumberOfPages()):(t=new RegExp(this.pdfEscape16(n,this.internal.getFont()),"g"),e=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var i=1;i<=this.internal.getNumberOfPages();i++)for(var o=0;o1){for(m=0;m{try{const t=o.currentUser;if(!t)return;const i=await t.getIdToken(!1);await fetch(`${r}/api/pipeline/event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(e)})}catch(t){console.warn("[pipeline] event emit failed (non-blocking):",t)}})()}let n=null;function y(e,t){n={classId:e,teacherId:t}}function S(){return n}export{g as emitPipelineEvent,S as getStudentContext,y as setStudentContext}; +import{k as o}from"./index-BdLfAeGL.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const r="https://deign86-mathpulse-api-v3test.hf.space";function g(e){(async()=>{try{const t=o.currentUser;if(!t)return;const i=await t.getIdToken(!1);await fetch(`${r}/api/pipeline/event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(e)})}catch(t){console.warn("[pipeline] event emit failed (non-blocking):",t)}})()}let n=null;function y(e,t){n={classId:e,teacherId:t}}function S(){return n}export{g as emitPipelineEvent,S as getStudentContext,y as setStudentContext}; diff --git a/assets/plus-IoQaIojF.js b/assets/plus-Z9YkmuN1.js similarity index 87% rename from assets/plus-IoQaIojF.js rename to assets/plus-Z9YkmuN1.js index 6f45e9328749ae83c2a04e291578e5a72bb6443d..c92ef8de15175b4bf61d7d08eab541a1b9934ce8 100644 --- a/assets/plus-IoQaIojF.js +++ b/assets/plus-Z9YkmuN1.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/quizService-D6WAd8P5.js b/assets/quizService-DxWImmI3.js similarity index 97% rename from assets/quizService-D6WAd8P5.js rename to assets/quizService-DxWImmI3.js index ec5e2fede02226bfe40a63e6c8016852ae895867..4aa3c28351dce84a8e99947f50b92c3e34d2be05 100644 --- a/assets/quizService-D6WAd8P5.js +++ b/assets/quizService-DxWImmI3.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-BVFD1ZML.js","assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{e as y,h as I,m as L,k as q,g as c,_ as Q}from"./index-BvEKrMkD.js";import{r as T,j as s}from"./vendor-react-B4AQeu28.js";import{query as N,collection as f,where as b,orderBy as E,getDocs as j,doc as u,setDoc as x,updateDoc as v,serverTimestamp as h,deleteDoc as M}from"./vendor-firebase-firestore-CNv3xXal.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-h2NDr2Mk.js","assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{e as y,h as I,m as L,k as q,g as c,_ as Q}from"./index-BdLfAeGL.js";import{r as T,j as s}from"./vendor-react-B4AQeu28.js";import{query as N,collection as f,where as b,orderBy as E,getDocs as j,doc as u,setDoc as x,updateDoc as v,serverTimestamp as h,deleteDoc as M}from"./vendor-firebase-firestore-CNv3xXal.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -34,4 +34,4 @@ import{e as y,h as I,m as L,k as q,g as c,_ as Q}from"./index-BvEKrMkD.js";impor * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const R=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],se=y("video",R);function F(){return s.jsxs("div",{className:"rounded-2xl bg-slate-900 shadow-lg",children:[s.jsx("div",{className:"w-full rounded-t-2xl bg-slate-800 animate-pulse",style:{position:"relative",paddingBottom:"56.25%",height:0}}),s.jsxs("div",{className:"px-4 py-3 bg-slate-800 rounded-b-2xl space-y-2",children:[s.jsx("div",{className:"h-4 bg-slate-700 rounded w-3/4 animate-pulse"}),s.jsx("div",{className:"h-3 bg-slate-700 rounded w-1/2 animate-pulse"})]})]})}const ae=({videos:e,topic:t})=>{const[a,o]=T.useState(0);if(!e||e.length===0)return s.jsx(F,{});const i=e[a],r=e.filter((n,d)=>d!==a);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(I,{mode:"wait",children:s.jsxs(L.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"rounded-2xl bg-slate-900 shadow-lg",style:{overflow:"visible"},children:[s.jsx("div",{className:"w-full rounded-t-xl",style:{position:"relative",paddingBottom:"40%",height:0,overflow:"hidden"},children:s.jsx("iframe",{src:`https://www.youtube.com/embed/${i.videoId}?rel=0&modestbranding=1`,title:i.title,allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",border:"none"}})}),s.jsxs("div",{className:"px-4 py-3 bg-slate-800 rounded-b-2xl",children:[s.jsx("p",{className:"text-slate-200 text-sm font-medium truncate",children:i.title}),s.jsx("p",{className:"text-slate-400 text-xs mt-0.5",children:i.channelTitle})]})]},i.videoId)}),r.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-slate-500 font-medium uppercase tracking-wide",children:"More videos"}),s.jsx("div",{className:"grid grid-cols-2 gap-3",children:r.slice(0,2).map(n=>{const d=e.findIndex(p=>p.videoId===n.videoId);return s.jsxs("button",{onClick:()=>o(d),className:"group text-left rounded-xl overflow-hidden border border-slate-200 hover:border-rose-300 hover:shadow-md transition-all duration-200 bg-white",children:[s.jsxs("div",{className:"relative aspect-video",children:[s.jsx("img",{src:n.thumbnailUrl,alt:n.title,loading:"lazy",className:"w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:s.jsx("div",{className:"w-8 h-8 rounded-full bg-white/90 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity shadow-sm",children:s.jsx(O,{size:14,className:"text-rose-500 ml-0.5"})})})]}),s.jsxs("div",{className:"p-2.5",children:[s.jsx("p",{className:"text-slate-700 text-xs font-medium line-clamp-2 leading-snug",children:n.title}),s.jsx("p",{className:"text-slate-400 text-[10px] mt-0.5 truncate",children:n.channelTitle})]})]},n.videoId)})})]})]})},J="https://deign86-mathpulse-api-v3test.hf.space";async function _(e,t,a=!1){const o={"Content-Type":"application/json",...t?.headers||{}},i=q.currentUser;if(i)try{const n=await i.getIdToken(a);n&&(o.Authorization=`Bearer ${n}`)}catch(n){throw console.error("[lessonService] Failed to get Firebase ID token:",n),new Error("Authentication failed. Please sign in again.")}const r=await fetch(`${J}${e}`,{...t,headers:o});if(r.status===401&&i&&!a)return _(e,t,!0);if(!r.ok){let n;try{n=await r.json()}catch{n=await r.text()}const d=new Error(typeof n=="object"?JSON.stringify(n):n);throw d.status=r.status,d.body=n,d}return r.json()}async function ie(e){return _("/api/rag/lesson",{method:"POST",body:JSON.stringify(e)})}async function U(e){return _("/api/lessons/videos/search",{method:"POST",body:JSON.stringify(e)})}async function ne(e){return(await U({topic:e})).videos}const G=e=>{if(!(e instanceof Error))return!1;const t=e.code,a=(e.message||"").toLowerCase();return t==="failed-precondition"&&a.includes("requires an index")},A=e=>{if(!e)return 0;if(e instanceof Date)return e.getTime();if(typeof e=="number")return e;if(typeof e=="string"){const t=Date.parse(e);return Number.isNaN(t)?0:t}if(typeof e=="object"){const t=e;if(typeof t.toMillis=="function")return t.toMillis();if(typeof t.seconds=="number")return t.seconds*1e3}return 0};async function oe(e,t,a){const o=a?.documentId?u(c,"generatedQuizzes",a.documentId):u(f(c,"generatedQuizzes")),i={...e,teacherId:t,createdAt:h(),status:"draft"};return a?.documentId?await x(o,i,{merge:!0}):await x(o,i),o.id}async function re(e){await v(u(c,"generatedQuizzes",e),{status:"published",publishedAt:h()})}async function ce(e){await M(u(c,"generatedQuizzes",e))}async function de(e,t,a){await v(u(c,"generatedQuizzes",e),{status:"assigned","metadata.assignedTo":t,assignedBy:a,assignedAt:h()});const o=u(f(c,"quizAssignments"));await x(o,{quizId:e,lrn:t,teacherId:a,status:"pending",assignedAt:h(),dueDate:null});const i=u(f(c,"notifications"));await x(i,{userId:t,type:"quiz_assigned",title:"New Quiz Assigned",message:"Your teacher has assigned you a new quiz. Complete it to earn XP!",quizId:e,read:!1,createdAt:h()})}async function le(e){try{const t=N(f(c,"generatedQuizzes"),b("teacherId","==",e),E("createdAt","desc"));return(await j(t)).docs.map(o=>({id:o.id,...o.data()}))}catch(t){if(!G(t))throw t;const a=N(f(c,"generatedQuizzes"),b("teacherId","==",e));return(await j(a)).docs.map(i=>({id:i.id,...i.data()})).sort((i,r)=>A(r.createdAt)-A(i.createdAt))}}async function ue(e,t,a,o,i,r,n,d,p,w){const k=u(f(c,"quizSubmissions"));if(await x(k,{submissionId:k.id,lrn:e,quizId:t,generatedQuizId:a??null,subject:o,source:i,score:r,xpEarned:n,totalTime:d,answers:p,correctCount:p.filter(l=>l.correct).length,totalQuestions:p.length,questionBreakdown:p.map((l,m)=>({questionId:l.questionId,topic:w[m]?.topic??o,difficulty:w[m]?.difficulty??"medium",bloomLevel:w[m]?.bloomLevel??"understand",correct:l.correct,timeSpent:l.timeSpent})),submittedAt:h()}),a){const l=N(f(c,"quizAssignments"),b("quizId","==",a),b("lrn","==",e)),m=await j(l);for(const g of m.docs)await v(g.ref,{status:"completed",completedAt:h(),score:r});try{await v(u(c,"generatedQuizzes",a),{status:"completed"})}catch{}}try{const{emitPipelineEvent:l,getStudentContext:m}=await Q(async()=>{const{emitPipelineEvent:z,getStudentContext:S}=await import("./pipelineService-BVFD1ZML.js");return{emitPipelineEvent:z,getStudentContext:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),g=m();g&&l({student_id:e,event_type:"quiz",event_data:{quiz_id:t,topic:w[0]?.topic??o,score:r,total_questions:p.length,correct_answers:p.filter(z=>z.correct).length,source:i},occurred_at:new Date().toISOString(),class_id:g.classId,teacher_id:g.teacherId})}catch{}}export{Z as A,K as E,W as L,ee as M,te as P,ae as V,se as a,le as b,de as c,ce as d,O as e,ne as f,ue as g,ie as h,re as p,oe as s}; + */const R=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],se=y("video",R);function F(){return s.jsxs("div",{className:"rounded-2xl bg-slate-900 shadow-lg",children:[s.jsx("div",{className:"w-full rounded-t-2xl bg-slate-800 animate-pulse",style:{position:"relative",paddingBottom:"56.25%",height:0}}),s.jsxs("div",{className:"px-4 py-3 bg-slate-800 rounded-b-2xl space-y-2",children:[s.jsx("div",{className:"h-4 bg-slate-700 rounded w-3/4 animate-pulse"}),s.jsx("div",{className:"h-3 bg-slate-700 rounded w-1/2 animate-pulse"})]})]})}const ae=({videos:e,topic:t})=>{const[a,o]=T.useState(0);if(!e||e.length===0)return s.jsx(F,{});const i=e[a],r=e.filter((n,d)=>d!==a);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(I,{mode:"wait",children:s.jsxs(L.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"rounded-2xl bg-slate-900 shadow-lg",style:{overflow:"visible"},children:[s.jsx("div",{className:"w-full rounded-t-xl",style:{position:"relative",paddingBottom:"40%",height:0,overflow:"hidden"},children:s.jsx("iframe",{src:`https://www.youtube.com/embed/${i.videoId}?rel=0&modestbranding=1`,title:i.title,allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",border:"none"}})}),s.jsxs("div",{className:"px-4 py-3 bg-slate-800 rounded-b-2xl",children:[s.jsx("p",{className:"text-slate-200 text-sm font-medium truncate",children:i.title}),s.jsx("p",{className:"text-slate-400 text-xs mt-0.5",children:i.channelTitle})]})]},i.videoId)}),r.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-slate-500 font-medium uppercase tracking-wide",children:"More videos"}),s.jsx("div",{className:"grid grid-cols-2 gap-3",children:r.slice(0,2).map(n=>{const d=e.findIndex(p=>p.videoId===n.videoId);return s.jsxs("button",{onClick:()=>o(d),className:"group text-left rounded-xl overflow-hidden border border-slate-200 hover:border-rose-300 hover:shadow-md transition-all duration-200 bg-white",children:[s.jsxs("div",{className:"relative aspect-video",children:[s.jsx("img",{src:n.thumbnailUrl,alt:n.title,loading:"lazy",className:"w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:s.jsx("div",{className:"w-8 h-8 rounded-full bg-white/90 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity shadow-sm",children:s.jsx(O,{size:14,className:"text-rose-500 ml-0.5"})})})]}),s.jsxs("div",{className:"p-2.5",children:[s.jsx("p",{className:"text-slate-700 text-xs font-medium line-clamp-2 leading-snug",children:n.title}),s.jsx("p",{className:"text-slate-400 text-[10px] mt-0.5 truncate",children:n.channelTitle})]})]},n.videoId)})})]})]})},J="https://deign86-mathpulse-api-v3test.hf.space";async function _(e,t,a=!1){const o={"Content-Type":"application/json",...t?.headers||{}},i=q.currentUser;if(i)try{const n=await i.getIdToken(a);n&&(o.Authorization=`Bearer ${n}`)}catch(n){throw console.error("[lessonService] Failed to get Firebase ID token:",n),new Error("Authentication failed. Please sign in again.")}const r=await fetch(`${J}${e}`,{...t,headers:o});if(r.status===401&&i&&!a)return _(e,t,!0);if(!r.ok){let n;try{n=await r.json()}catch{n=await r.text()}const d=new Error(typeof n=="object"?JSON.stringify(n):n);throw d.status=r.status,d.body=n,d}return r.json()}async function ie(e){return _("/api/rag/lesson",{method:"POST",body:JSON.stringify(e)})}async function U(e){return _("/api/lessons/videos/search",{method:"POST",body:JSON.stringify(e)})}async function ne(e){return(await U({topic:e})).videos}const G=e=>{if(!(e instanceof Error))return!1;const t=e.code,a=(e.message||"").toLowerCase();return t==="failed-precondition"&&a.includes("requires an index")},A=e=>{if(!e)return 0;if(e instanceof Date)return e.getTime();if(typeof e=="number")return e;if(typeof e=="string"){const t=Date.parse(e);return Number.isNaN(t)?0:t}if(typeof e=="object"){const t=e;if(typeof t.toMillis=="function")return t.toMillis();if(typeof t.seconds=="number")return t.seconds*1e3}return 0};async function oe(e,t,a){const o=a?.documentId?u(c,"generatedQuizzes",a.documentId):u(f(c,"generatedQuizzes")),i={...e,teacherId:t,createdAt:h(),status:"draft"};return a?.documentId?await x(o,i,{merge:!0}):await x(o,i),o.id}async function re(e){await v(u(c,"generatedQuizzes",e),{status:"published",publishedAt:h()})}async function ce(e){await M(u(c,"generatedQuizzes",e))}async function de(e,t,a){await v(u(c,"generatedQuizzes",e),{status:"assigned","metadata.assignedTo":t,assignedBy:a,assignedAt:h()});const o=u(f(c,"quizAssignments"));await x(o,{quizId:e,lrn:t,teacherId:a,status:"pending",assignedAt:h(),dueDate:null});const i=u(f(c,"notifications"));await x(i,{userId:t,type:"quiz_assigned",title:"New Quiz Assigned",message:"Your teacher has assigned you a new quiz. Complete it to earn XP!",quizId:e,read:!1,createdAt:h()})}async function le(e){try{const t=N(f(c,"generatedQuizzes"),b("teacherId","==",e),E("createdAt","desc"));return(await j(t)).docs.map(o=>({id:o.id,...o.data()}))}catch(t){if(!G(t))throw t;const a=N(f(c,"generatedQuizzes"),b("teacherId","==",e));return(await j(a)).docs.map(i=>({id:i.id,...i.data()})).sort((i,r)=>A(r.createdAt)-A(i.createdAt))}}async function ue(e,t,a,o,i,r,n,d,p,w){const k=u(f(c,"quizSubmissions"));if(await x(k,{submissionId:k.id,lrn:e,quizId:t,generatedQuizId:a??null,subject:o,source:i,score:r,xpEarned:n,totalTime:d,answers:p,correctCount:p.filter(l=>l.correct).length,totalQuestions:p.length,questionBreakdown:p.map((l,m)=>({questionId:l.questionId,topic:w[m]?.topic??o,difficulty:w[m]?.difficulty??"medium",bloomLevel:w[m]?.bloomLevel??"understand",correct:l.correct,timeSpent:l.timeSpent})),submittedAt:h()}),a){const l=N(f(c,"quizAssignments"),b("quizId","==",a),b("lrn","==",e)),m=await j(l);for(const g of m.docs)await v(g.ref,{status:"completed",completedAt:h(),score:r});try{await v(u(c,"generatedQuizzes",a),{status:"completed"})}catch{}}try{const{emitPipelineEvent:l,getStudentContext:m}=await Q(async()=>{const{emitPipelineEvent:z,getStudentContext:S}=await import("./pipelineService-h2NDr2Mk.js");return{emitPipelineEvent:z,getStudentContext:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),g=m();g&&l({student_id:e,event_type:"quiz",event_data:{quiz_id:t,topic:w[0]?.topic??o,score:r,total_questions:p.length,correct_answers:p.filter(z=>z.correct).length,source:i},occurred_at:new Date().toISOString(),class_id:g.classId,teacher_id:g.teacherId})}catch{}}export{Z as A,K as E,W as L,ee as M,te as P,ae as V,se as a,le as b,de as c,ce as d,O as e,ne as f,ue as g,ie as h,re as p,oe as s}; diff --git a/assets/save-DAHVTL2X.js b/assets/save-CUEUjfb0.js similarity index 91% rename from assets/save-DAHVTL2X.js rename to assets/save-CUEUjfb0.js index 1f30c0c14139b65ebe5258836e622e324a3538c7..5b163fd23ba60783b2e9bc90d39db3e2b3d7193e 100644 --- a/assets/save-DAHVTL2X.js +++ b/assets/save-CUEUjfb0.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BvEKrMkD.js";/** +import{e as a}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/search-CHZcTJmD.js b/assets/search-gQ2OCqgd.js similarity index 88% rename from assets/search-CHZcTJmD.js rename to assets/search-gQ2OCqgd.js index 0fc1075813eb7f7de7fd00100926c185b0d7edd0..62f023e7dbc11ae7b400d64521a71eef521f249b 100644 --- a/assets/search-CHZcTJmD.js +++ b/assets/search-gQ2OCqgd.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/select-CU8TeDXy.js b/assets/select-C3tB_0M-.js similarity index 96% rename from assets/select-CU8TeDXy.js rename to assets/select-C3tB_0M-.js index ba024c57dc2c23f2bbc074d6db31b72ab8462e6e..d4fee4252f5ea5c91b2760fac0a9cdc6162974b0 100644 --- a/assets/select-CU8TeDXy.js +++ b/assets/select-C3tB_0M-.js @@ -1 +1 @@ -import{j as e}from"./vendor-react-B4AQeu28.js";import{t as n,u as i,v as d,V as c,w as u,x as m,y as p,z as f,B as x,E as g,G as v,H as h}from"./vendor-radix-C5nwdvGr.js";import{o as r}from"./index-BvEKrMkD.js";import{C as l,a as b}from"./chevron-up-CDr90bpM.js";import{C as j}from"./check-BmWAQELM.js";function k({...t}){return e.jsx(n,{"data-slot":"select",...t})}function I({...t}){return e.jsx(c,{"data-slot":"select-value",...t})}function B({className:t,size:a="default",children:s,...o}){return e.jsxs(i,{"data-slot":"select-trigger","data-size":a,className:r("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full items-center justify-between gap-2 rounded-md border bg-input-background px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:min-w-0 *:data-[slot=select-value]:flex-1 *:data-[slot=select-value]:truncate *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...o,children:[s,e.jsx(d,{asChild:!0,children:e.jsx(l,{className:"size-4"})})]})}function V({className:t,children:a,position:s="popper",...o}){return e.jsx(u,{children:e.jsxs(m,{"data-slot":"select-content",className:r("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,...o,children:[e.jsx(w,{}),e.jsx(p,{className:r("p-1",s==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:a}),e.jsx(z,{})]})})}function D({className:t,children:a,...s}){return e.jsxs(f,{"data-slot":"select-item",className:r("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...s,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(x,{children:e.jsx(j,{className:"size-4"})})}),e.jsx(g,{children:a})]})}function w({className:t,...a}){return e.jsx(v,{"data-slot":"select-scroll-up-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(b,{className:"size-4"})})}function z({className:t,...a}){return e.jsx(h,{"data-slot":"select-scroll-down-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l,{className:"size-4"})})}export{k as S,B as a,I as b,V as c,D as d}; +import{j as e}from"./vendor-react-B4AQeu28.js";import{t as n,u as i,v as d,V as c,w as u,x as m,y as p,z as f,B as x,E as g,G as v,H as h}from"./vendor-radix-C5nwdvGr.js";import{o as r}from"./index-BdLfAeGL.js";import{C as l,a as b}from"./chevron-up-uSn_SWll.js";import{C as j}from"./check-DbVe23hB.js";function k({...t}){return e.jsx(n,{"data-slot":"select",...t})}function I({...t}){return e.jsx(c,{"data-slot":"select-value",...t})}function B({className:t,size:a="default",children:s,...o}){return e.jsxs(i,{"data-slot":"select-trigger","data-size":a,className:r("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full items-center justify-between gap-2 rounded-md border bg-input-background px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:min-w-0 *:data-[slot=select-value]:flex-1 *:data-[slot=select-value]:truncate *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...o,children:[s,e.jsx(d,{asChild:!0,children:e.jsx(l,{className:"size-4"})})]})}function V({className:t,children:a,position:s="popper",...o}){return e.jsx(u,{children:e.jsxs(m,{"data-slot":"select-content",className:r("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,...o,children:[e.jsx(w,{}),e.jsx(p,{className:r("p-1",s==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:a}),e.jsx(z,{})]})})}function D({className:t,children:a,...s}){return e.jsxs(f,{"data-slot":"select-item",className:r("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...s,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(x,{children:e.jsx(j,{className:"size-4"})})}),e.jsx(g,{children:a})]})}function w({className:t,...a}){return e.jsx(v,{"data-slot":"select-scroll-up-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(b,{className:"size-4"})})}function z({className:t,...a}){return e.jsx(h,{"data-slot":"select-scroll-down-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l,{className:"size-4"})})}export{k as S,B as a,I as b,V as c,D as d}; diff --git a/assets/send-BivcIdIA.js b/assets/send-CxDLfaHq.js similarity index 90% rename from assets/send-BivcIdIA.js rename to assets/send-CxDLfaHq.js index ab7fcdcaa8b31d3ed408879de9e0b70c32dc747c..d52a4684d34a4ddc2b4dd19f2e22d53a29b5416b 100644 --- a/assets/send-BivcIdIA.js +++ b/assets/send-CxDLfaHq.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BvEKrMkD.js";/** +import{e as a}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/shield-check-X3NwQ434.js b/assets/shield-check-DqqR-L0T.js similarity index 92% rename from assets/shield-check-X3NwQ434.js rename to assets/shield-check-DqqR-L0T.js index da89828c61cea4d17063c8f2e8cb84f045c6dede..6b455803cae36afd1d4bf1c810d72510d7173dff 100644 --- a/assets/shield-check-X3NwQ434.js +++ b/assets/shield-check-DqqR-L0T.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/shirt-DFiZ2C4J.js b/assets/shirt-iZ6vtR5i.js similarity index 90% rename from assets/shirt-DFiZ2C4J.js rename to assets/shirt-iZ6vtR5i.js index bf4645fa1864e4ea7acc95fa31b99e076685a8e8..8876f29ff97fbbffd32e201b64656a4a337a37ef 100644 --- a/assets/shirt-DFiZ2C4J.js +++ b/assets/shirt-iZ6vtR5i.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BvEKrMkD.js";/** +import{e as a}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/skeleton-CU_hcmX-.js b/assets/skeleton-SSuNGBG3.js similarity index 89% rename from assets/skeleton-CU_hcmX-.js rename to assets/skeleton-SSuNGBG3.js index 347d2ef0fe980f64b3de28667dda0e9a396214bb..be572a1ebd47cf140392714c66d33d01e33ea681 100644 --- a/assets/skeleton-CU_hcmX-.js +++ b/assets/skeleton-SSuNGBG3.js @@ -1,4 +1,4 @@ -import{e as o,o as c}from"./index-BvEKrMkD.js";import{j as a}from"./vendor-react-B4AQeu28.js";/** +import{e as o,o as c}from"./index-BdLfAeGL.js";import{j as a}from"./vendor-react-B4AQeu28.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/sparkles-av0wSNZT.js b/assets/sparkles-DnAkO9TX.js similarity index 93% rename from assets/sparkles-av0wSNZT.js rename to assets/sparkles-DnAkO9TX.js index b09584d7c3e4991735a7c7d9c12f6dee4e60506d..69368e0b55e94b3a4e13ab307f09ca47fcc523e3 100644 --- a/assets/sparkles-av0wSNZT.js +++ b/assets/sparkles-DnAkO9TX.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BvEKrMkD.js";/** +import{e as a}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/subjects-ChEJ6J55.js b/assets/subjects-Dw9HR29l.js similarity index 98% rename from assets/subjects-ChEJ6J55.js rename to assets/subjects-Dw9HR29l.js index a3977eb075f6f87588f3859ddddf37970fc408af..eaf233b5fa4813a7298e05489a0eb873ff628ba8 100644 --- a/assets/subjects-ChEJ6J55.js +++ b/assets/subjects-Dw9HR29l.js @@ -1 +1 @@ -import{C as a}from"./index-BvEKrMkD.js";import{C as o}from"./chart-column-DKW3TTRX.js";const t=[{id:"gen-math",code:"GEN MATH",name:"General Mathematics",gradeLevel:"Grade 11",semester:"1st Semester",color:"from-blue-500 to-cyan-500",pdfAvailable:!0,topics:[{id:"gen-math-001",name:"Patterns and Real-Life Relationships",unit:"Patterns, Relations, and Functions"},{id:"gen-math-002",name:"Functions as Mathematical Models",unit:"Patterns, Relations, and Functions"},{id:"gen-math-003",name:"Function Notation and Evaluation",unit:"Patterns, Relations, and Functions"},{id:"gen-math-004",name:"Domain and Range of Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-005",name:"Operations on Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-006",name:"Composite Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-007",name:"Inverse Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-008",name:"Graphs of Rational Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-009",name:"Graphs of Exponential Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-010",name:"Graphs of Logarithmic Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-011",name:"Simple and Compound Interest",unit:"Financial Mathematics"},{id:"gen-math-012",name:"Simple and General Annuities",unit:"Financial Mathematics"},{id:"gen-math-013",name:"Present and Future Value",unit:"Financial Mathematics"},{id:"gen-math-014",name:"Loans, Amortization, and Sinking Funds",unit:"Financial Mathematics"},{id:"gen-math-015",name:"Stocks, Bonds, and Market Indices",unit:"Financial Mathematics"},{id:"gen-math-016",name:"Business Decision-Making with Mathematical Models",unit:"Financial Mathematics"},{id:"gen-math-017",name:"Propositions and Logical Connectives",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-018",name:"Truth Values and Truth Tables",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-019",name:"Logical Equivalence and Implication",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-020",name:"Quantifiers and Negation",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-021",name:"Validity of Arguments",unit:"Logic and Mathematical Reasoning"}]},{id:"stats-prob",code:"STAT&PROB",name:"Statistics and Probability",gradeLevel:"Grade 11",semester:"2nd Semester",color:"from-sky-500 to-cyan-500",pdfAvailable:!0,topics:[{id:"stat-001",name:"Random Variables",unit:"Random Variables"},{id:"stat-002",name:"Discrete Probability Distributions",unit:"Random Variables"},{id:"stat-003",name:"Mean and Variance of Discrete RV",unit:"Random Variables"},{id:"stat-004",name:"Normal Distribution",unit:"Normal Distribution"},{id:"stat-005",name:"Standard Normal Distribution and Z-scores",unit:"Normal Distribution"},{id:"stat-006",name:"Areas Under the Normal Curve",unit:"Normal Distribution"},{id:"stat-007",name:"Sampling Distributions",unit:"Sampling and Estimation"},{id:"stat-008",name:"Central Limit Theorem",unit:"Sampling and Estimation"},{id:"stat-009",name:"Point Estimation",unit:"Sampling and Estimation"},{id:"stat-010",name:"Confidence Intervals",unit:"Sampling and Estimation"},{id:"stat-011",name:"Hypothesis Testing Concepts",unit:"Hypothesis Testing"},{id:"stat-012",name:"T-test",unit:"Hypothesis Testing"},{id:"stat-013",name:"Z-test",unit:"Hypothesis Testing"},{id:"stat-014",name:"Correlation and Regression",unit:"Correlation and Regression"}]}],c=["Grade 11"];[...t];const s={"Grade 11":["gen-math","stats-prob"]};function l(i){if(!i)return null;const e=i.trim().toLowerCase();return e==="grade 11"||e==="11"||e.includes("11")?"Grade 11":null}function m(i){const e=l(i);return e?s[e]:t.map(n=>n.id)}const u=[{id:"gen-math",title:"General Mathematics",description:"Functions, business math, and logic for Grade 11 Senior High School students.",icon:a,color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,totalModules:3,completedModules:0,rating:4.9,reviewCount:204,pdfAvailable:!0,modules:[{id:"gm-1",title:"Functions and Their Graphs",description:"Evaluate, compose, and represent functions including rational, exponential, and logarithmic types.",color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,lessons:[{id:"gm-1-l1",title:"Patterns and Real-Life Relationships",duration:"15 min",completed:!1,locked:!1},{id:"gm-1-l2",title:"Functions as Mathematical Models",duration:"16 min",completed:!1,locked:!1},{id:"gm-1-l3",title:"Operations on Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l4",title:"Composite Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l5",title:"Function Notation and Evaluation",duration:"16 min",completed:!1,locked:!1},{id:"gm-1-l6",title:"Domain and Range of Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l7",title:"Inverse Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l8",title:"Graphs of Rational Functions",duration:"20 min",completed:!1,locked:!1},{id:"gm-1-l9",title:"Graphs of Exponential Functions",duration:"20 min",completed:!1,locked:!1},{id:"gm-1-l10",title:"Graphs of Logarithmic Functions",duration:"22 min",completed:!1,locked:!1}],quizzes:[{id:"gm-1-q1",title:"Practice Quiz: Functions",questions:10,duration:"15 min",completed:!1,locked:!1,type:"practice"},{id:"gm-1-q2",title:"Module Quiz: Functions and Graphs",questions:15,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"gm-2",title:"Business Mathematics",description:"Simple and compound interest, annuities, stocks, and bonds.",color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,lessons:[{id:"gm-2-l1",title:"Simple and Compound Interest",duration:"18 min",completed:!1,locked:!1},{id:"gm-2-l2",title:"Simple and General Annuities",duration:"20 min",completed:!1,locked:!1},{id:"gm-2-l3",title:"Present and Future Value",duration:"18 min",completed:!1,locked:!1},{id:"gm-2-l4",title:"Loans, Amortization, and Sinking Funds",duration:"20 min",completed:!1,locked:!1},{id:"gm-2-l5",title:"Stocks, Bonds, and Market Indices",duration:"18 min",completed:!1,locked:!1},{id:"gm-2-l6",title:"Business Decision-Making with Mathematical Models",duration:"20 min",completed:!1,locked:!1}],quizzes:[{id:"gm-2-q1",title:"Practice Quiz: Interest",questions:12,duration:"18 min",completed:!1,locked:!1,type:"practice"},{id:"gm-2-q2",title:"Module Quiz: Business Math",questions:15,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"gm-3",title:"Logic",description:"Propositions, truth tables, logical equivalence, and valid arguments.",color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,lessons:[{id:"gm-3-l1",title:"Propositions and Connectives",duration:"15 min",completed:!1,locked:!1},{id:"gm-3-l2",title:"Truth Values and Truth Tables",duration:"18 min",completed:!1,locked:!1},{id:"gm-3-l3",title:"Logical Equivalence and Implication",duration:"18 min",completed:!1,locked:!1},{id:"gm-3-l4",title:"Quantifiers and Negation",duration:"18 min",completed:!1,locked:!1},{id:"gm-3-l5",title:"Validity of Arguments",duration:"22 min",completed:!1,locked:!1}],quizzes:[{id:"gm-3-q1",title:"Practice Quiz: Logic",questions:10,duration:"15 min",completed:!1,locked:!1,type:"practice"},{id:"gm-3-q2",title:"Module Quiz: Logic",questions:12,duration:"18 min",completed:!1,locked:!0,type:"module"}]}]},{id:"stats-prob",title:"Statistics and Probability",description:"Random variables, distributions, sampling, and hypothesis testing for Grade 11 students.",icon:o,color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,totalModules:4,completedModules:0,rating:4.8,reviewCount:160,pdfAvailable:!0,modules:[{id:"sp-1",title:"Random Variables and Probability Distributions",description:"Discrete random variables, probability distributions, mean, and variance.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-1-l1",title:"Random Variables",duration:"16 min",completed:!1,locked:!1},{id:"sp-1-l2",title:"Discrete Probability Distributions",duration:"18 min",completed:!1,locked:!1},{id:"sp-1-l3",title:"Mean and Variance of Discrete RV",duration:"20 min",completed:!1,locked:!1}],quizzes:[{id:"sp-1-q1",title:"Practice Quiz: Random Variables",questions:10,duration:"15 min",completed:!1,locked:!1,type:"practice"},{id:"sp-1-q2",title:"Module Quiz: Probability Distributions",questions:15,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"sp-2",title:"Normal Distribution",description:"The normal curve, standard normal distribution, z-scores, and areas under the curve.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-2-l1",title:"Normal Distribution",duration:"16 min",completed:!1,locked:!1},{id:"sp-2-l2",title:"Standard Normal Distribution and Z-scores",duration:"18 min",completed:!1,locked:!1},{id:"sp-2-l3",title:"Areas Under the Normal Curve",duration:"18 min",completed:!1,locked:!1}],quizzes:[{id:"sp-2-q1",title:"Practice Quiz: Normal Distribution",questions:12,duration:"18 min",completed:!1,locked:!1,type:"practice"},{id:"sp-2-q2",title:"Module Quiz: Z-Scores & Normal Curve",questions:14,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"sp-3",title:"Sampling and Estimation",description:"Sampling distributions, central limit theorem, point estimation, and confidence intervals.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-3-l1",title:"Sampling Distributions",duration:"18 min",completed:!1,locked:!1},{id:"sp-3-l2",title:"Central Limit Theorem",duration:"20 min",completed:!1,locked:!1},{id:"sp-3-l3",title:"Point Estimation",duration:"16 min",completed:!1,locked:!1},{id:"sp-3-l4",title:"Confidence Intervals",duration:"20 min",completed:!1,locked:!1}],quizzes:[{id:"sp-3-q1",title:"Practice Quiz: Sampling",questions:12,duration:"18 min",completed:!1,locked:!1,type:"practice"},{id:"sp-3-q2",title:"Module Quiz: Estimation",questions:16,duration:"24 min",completed:!1,locked:!1,type:"module"}]},{id:"sp-4",title:"Hypothesis Testing",description:"Hypothesis testing concepts, t-test, z-test, and correlation.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-4-l1",title:"Hypothesis Testing Concepts",duration:"20 min",completed:!1,locked:!1},{id:"sp-4-l2",title:"T-test",duration:"22 min",completed:!1,locked:!1},{id:"sp-4-l3",title:"Z-test",duration:"22 min",completed:!1,locked:!1},{id:"sp-4-l4",title:"Correlation and Regression",duration:"24 min",completed:!1,locked:!1}],quizzes:[{id:"sp-4-q1",title:"Practice Quiz: Hypothesis Testing",questions:14,duration:"22 min",completed:!1,locked:!1,type:"practice"},{id:"sp-4-q2",title:"Module Quiz: Hypothesis Testing",questions:18,duration:"28 min",completed:!1,locked:!0,type:"module"}]}]}];export{c as G,t as S,m as g,u as s}; +import{C as a}from"./index-BdLfAeGL.js";import{C as o}from"./chart-column-Dl7iJ2BC.js";const t=[{id:"gen-math",code:"GEN MATH",name:"General Mathematics",gradeLevel:"Grade 11",semester:"1st Semester",color:"from-blue-500 to-cyan-500",pdfAvailable:!0,topics:[{id:"gen-math-001",name:"Patterns and Real-Life Relationships",unit:"Patterns, Relations, and Functions"},{id:"gen-math-002",name:"Functions as Mathematical Models",unit:"Patterns, Relations, and Functions"},{id:"gen-math-003",name:"Function Notation and Evaluation",unit:"Patterns, Relations, and Functions"},{id:"gen-math-004",name:"Domain and Range of Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-005",name:"Operations on Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-006",name:"Composite Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-007",name:"Inverse Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-008",name:"Graphs of Rational Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-009",name:"Graphs of Exponential Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-010",name:"Graphs of Logarithmic Functions",unit:"Patterns, Relations, and Functions"},{id:"gen-math-011",name:"Simple and Compound Interest",unit:"Financial Mathematics"},{id:"gen-math-012",name:"Simple and General Annuities",unit:"Financial Mathematics"},{id:"gen-math-013",name:"Present and Future Value",unit:"Financial Mathematics"},{id:"gen-math-014",name:"Loans, Amortization, and Sinking Funds",unit:"Financial Mathematics"},{id:"gen-math-015",name:"Stocks, Bonds, and Market Indices",unit:"Financial Mathematics"},{id:"gen-math-016",name:"Business Decision-Making with Mathematical Models",unit:"Financial Mathematics"},{id:"gen-math-017",name:"Propositions and Logical Connectives",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-018",name:"Truth Values and Truth Tables",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-019",name:"Logical Equivalence and Implication",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-020",name:"Quantifiers and Negation",unit:"Logic and Mathematical Reasoning"},{id:"gen-math-021",name:"Validity of Arguments",unit:"Logic and Mathematical Reasoning"}]},{id:"stats-prob",code:"STAT&PROB",name:"Statistics and Probability",gradeLevel:"Grade 11",semester:"2nd Semester",color:"from-sky-500 to-cyan-500",pdfAvailable:!0,topics:[{id:"stat-001",name:"Random Variables",unit:"Random Variables"},{id:"stat-002",name:"Discrete Probability Distributions",unit:"Random Variables"},{id:"stat-003",name:"Mean and Variance of Discrete RV",unit:"Random Variables"},{id:"stat-004",name:"Normal Distribution",unit:"Normal Distribution"},{id:"stat-005",name:"Standard Normal Distribution and Z-scores",unit:"Normal Distribution"},{id:"stat-006",name:"Areas Under the Normal Curve",unit:"Normal Distribution"},{id:"stat-007",name:"Sampling Distributions",unit:"Sampling and Estimation"},{id:"stat-008",name:"Central Limit Theorem",unit:"Sampling and Estimation"},{id:"stat-009",name:"Point Estimation",unit:"Sampling and Estimation"},{id:"stat-010",name:"Confidence Intervals",unit:"Sampling and Estimation"},{id:"stat-011",name:"Hypothesis Testing Concepts",unit:"Hypothesis Testing"},{id:"stat-012",name:"T-test",unit:"Hypothesis Testing"},{id:"stat-013",name:"Z-test",unit:"Hypothesis Testing"},{id:"stat-014",name:"Correlation and Regression",unit:"Correlation and Regression"}]}],c=["Grade 11"];[...t];const s={"Grade 11":["gen-math","stats-prob"]};function l(i){if(!i)return null;const e=i.trim().toLowerCase();return e==="grade 11"||e==="11"||e.includes("11")?"Grade 11":null}function m(i){const e=l(i);return e?s[e]:t.map(n=>n.id)}const u=[{id:"gen-math",title:"General Mathematics",description:"Functions, business math, and logic for Grade 11 Senior High School students.",icon:a,color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,totalModules:3,completedModules:0,rating:4.9,reviewCount:204,pdfAvailable:!0,modules:[{id:"gm-1",title:"Functions and Their Graphs",description:"Evaluate, compose, and represent functions including rational, exponential, and logarithmic types.",color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,lessons:[{id:"gm-1-l1",title:"Patterns and Real-Life Relationships",duration:"15 min",completed:!1,locked:!1},{id:"gm-1-l2",title:"Functions as Mathematical Models",duration:"16 min",completed:!1,locked:!1},{id:"gm-1-l3",title:"Operations on Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l4",title:"Composite Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l5",title:"Function Notation and Evaluation",duration:"16 min",completed:!1,locked:!1},{id:"gm-1-l6",title:"Domain and Range of Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l7",title:"Inverse Functions",duration:"18 min",completed:!1,locked:!1},{id:"gm-1-l8",title:"Graphs of Rational Functions",duration:"20 min",completed:!1,locked:!1},{id:"gm-1-l9",title:"Graphs of Exponential Functions",duration:"20 min",completed:!1,locked:!1},{id:"gm-1-l10",title:"Graphs of Logarithmic Functions",duration:"22 min",completed:!1,locked:!1}],quizzes:[{id:"gm-1-q1",title:"Practice Quiz: Functions",questions:10,duration:"15 min",completed:!1,locked:!1,type:"practice"},{id:"gm-1-q2",title:"Module Quiz: Functions and Graphs",questions:15,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"gm-2",title:"Business Mathematics",description:"Simple and compound interest, annuities, stocks, and bonds.",color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,lessons:[{id:"gm-2-l1",title:"Simple and Compound Interest",duration:"18 min",completed:!1,locked:!1},{id:"gm-2-l2",title:"Simple and General Annuities",duration:"20 min",completed:!1,locked:!1},{id:"gm-2-l3",title:"Present and Future Value",duration:"18 min",completed:!1,locked:!1},{id:"gm-2-l4",title:"Loans, Amortization, and Sinking Funds",duration:"20 min",completed:!1,locked:!1},{id:"gm-2-l5",title:"Stocks, Bonds, and Market Indices",duration:"18 min",completed:!1,locked:!1},{id:"gm-2-l6",title:"Business Decision-Making with Mathematical Models",duration:"20 min",completed:!1,locked:!1}],quizzes:[{id:"gm-2-q1",title:"Practice Quiz: Interest",questions:12,duration:"18 min",completed:!1,locked:!1,type:"practice"},{id:"gm-2-q2",title:"Module Quiz: Business Math",questions:15,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"gm-3",title:"Logic",description:"Propositions, truth tables, logical equivalence, and valid arguments.",color:"bg-indigo-50",iconColor:"text-indigo-600",accentColor:"bg-indigo-600",progress:0,lessons:[{id:"gm-3-l1",title:"Propositions and Connectives",duration:"15 min",completed:!1,locked:!1},{id:"gm-3-l2",title:"Truth Values and Truth Tables",duration:"18 min",completed:!1,locked:!1},{id:"gm-3-l3",title:"Logical Equivalence and Implication",duration:"18 min",completed:!1,locked:!1},{id:"gm-3-l4",title:"Quantifiers and Negation",duration:"18 min",completed:!1,locked:!1},{id:"gm-3-l5",title:"Validity of Arguments",duration:"22 min",completed:!1,locked:!1}],quizzes:[{id:"gm-3-q1",title:"Practice Quiz: Logic",questions:10,duration:"15 min",completed:!1,locked:!1,type:"practice"},{id:"gm-3-q2",title:"Module Quiz: Logic",questions:12,duration:"18 min",completed:!1,locked:!0,type:"module"}]}]},{id:"stats-prob",title:"Statistics and Probability",description:"Random variables, distributions, sampling, and hypothesis testing for Grade 11 students.",icon:o,color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,totalModules:4,completedModules:0,rating:4.8,reviewCount:160,pdfAvailable:!0,modules:[{id:"sp-1",title:"Random Variables and Probability Distributions",description:"Discrete random variables, probability distributions, mean, and variance.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-1-l1",title:"Random Variables",duration:"16 min",completed:!1,locked:!1},{id:"sp-1-l2",title:"Discrete Probability Distributions",duration:"18 min",completed:!1,locked:!1},{id:"sp-1-l3",title:"Mean and Variance of Discrete RV",duration:"20 min",completed:!1,locked:!1}],quizzes:[{id:"sp-1-q1",title:"Practice Quiz: Random Variables",questions:10,duration:"15 min",completed:!1,locked:!1,type:"practice"},{id:"sp-1-q2",title:"Module Quiz: Probability Distributions",questions:15,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"sp-2",title:"Normal Distribution",description:"The normal curve, standard normal distribution, z-scores, and areas under the curve.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-2-l1",title:"Normal Distribution",duration:"16 min",completed:!1,locked:!1},{id:"sp-2-l2",title:"Standard Normal Distribution and Z-scores",duration:"18 min",completed:!1,locked:!1},{id:"sp-2-l3",title:"Areas Under the Normal Curve",duration:"18 min",completed:!1,locked:!1}],quizzes:[{id:"sp-2-q1",title:"Practice Quiz: Normal Distribution",questions:12,duration:"18 min",completed:!1,locked:!1,type:"practice"},{id:"sp-2-q2",title:"Module Quiz: Z-Scores & Normal Curve",questions:14,duration:"20 min",completed:!1,locked:!1,type:"module"}]},{id:"sp-3",title:"Sampling and Estimation",description:"Sampling distributions, central limit theorem, point estimation, and confidence intervals.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-3-l1",title:"Sampling Distributions",duration:"18 min",completed:!1,locked:!1},{id:"sp-3-l2",title:"Central Limit Theorem",duration:"20 min",completed:!1,locked:!1},{id:"sp-3-l3",title:"Point Estimation",duration:"16 min",completed:!1,locked:!1},{id:"sp-3-l4",title:"Confidence Intervals",duration:"20 min",completed:!1,locked:!1}],quizzes:[{id:"sp-3-q1",title:"Practice Quiz: Sampling",questions:12,duration:"18 min",completed:!1,locked:!1,type:"practice"},{id:"sp-3-q2",title:"Module Quiz: Estimation",questions:16,duration:"24 min",completed:!1,locked:!1,type:"module"}]},{id:"sp-4",title:"Hypothesis Testing",description:"Hypothesis testing concepts, t-test, z-test, and correlation.",color:"bg-sky-50",iconColor:"text-sky-600",accentColor:"bg-sky-500",progress:0,lessons:[{id:"sp-4-l1",title:"Hypothesis Testing Concepts",duration:"20 min",completed:!1,locked:!1},{id:"sp-4-l2",title:"T-test",duration:"22 min",completed:!1,locked:!1},{id:"sp-4-l3",title:"Z-test",duration:"22 min",completed:!1,locked:!1},{id:"sp-4-l4",title:"Correlation and Regression",duration:"24 min",completed:!1,locked:!1}],quizzes:[{id:"sp-4-q1",title:"Practice Quiz: Hypothesis Testing",questions:14,duration:"22 min",completed:!1,locked:!1,type:"practice"},{id:"sp-4-q2",title:"Module Quiz: Hypothesis Testing",questions:18,duration:"28 min",completed:!1,locked:!0,type:"module"}]}]}];export{c as G,t as S,m as g,u as s}; diff --git a/assets/switch-kakgyvwt.js b/assets/switch-BZ2ceCBk.js similarity index 86% rename from assets/switch-kakgyvwt.js rename to assets/switch-BZ2ceCBk.js index e444d465428323ea60222be6bc02aebf9d5d4de8..898a9f8829edc3cc7cdd9a36a102de4b4790a067 100644 --- a/assets/switch-kakgyvwt.js +++ b/assets/switch-BZ2ceCBk.js @@ -1 +1 @@ -import{j as e}from"./vendor-react-B4AQeu28.js";import{m as s,n}from"./vendor-radix-C5nwdvGr.js";import{o as t}from"./index-BvEKrMkD.js";function c({className:a,...r}){return e.jsx(s,{"data-slot":"switch",className:t("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",a),...r,children:e.jsx(n,{"data-slot":"switch-thumb",className:t("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}export{c as S}; +import{j as e}from"./vendor-react-B4AQeu28.js";import{m as s,n}from"./vendor-radix-C5nwdvGr.js";import{o as t}from"./index-BdLfAeGL.js";function c({className:a,...r}){return e.jsx(s,{"data-slot":"switch",className:t("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",a),...r,children:e.jsx(n,{"data-slot":"switch-thumb",className:t("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}export{c as S}; diff --git a/assets/testResetService-DUw6qLIU.js b/assets/testResetService-DiMJKnvV.js similarity index 99% rename from assets/testResetService-DUw6qLIU.js rename to assets/testResetService-DiMJKnvV.js index 03b6ea2779950578db52364afe29cd14fd2a0996..a384629154687869adb8cf851bbd3e13cc3f2b79 100644 --- a/assets/testResetService-DUw6qLIU.js +++ b/assets/testResetService-DiMJKnvV.js @@ -1 +1 @@ -import{getDoc as R,doc as d,setDoc as p,serverTimestamp as h,deleteField as c,deleteDoc as l,getDocs as y,query as I,where as v,collection as f,writeBatch as g}from"./vendor-firebase-firestore-CNv3xXal.js";import{b5 as k,g as i,k as $}from"./index-BvEKrMkD.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const T=400,C="https://deign86-mathpulse-api-v3test.hf.space";async function B(e){const t=$.currentUser;if(!t)throw new Error("Authentication is required to reset testing data.");const r=await t.getIdToken(),s=await fetch(`${C}/api/testing/reset-data`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({role:e.role,...e.lrn?{lrn:e.lrn}:{}})}),o=await s.json().catch(()=>({}));if(!s.ok){const S=typeof o?.detail=="string"?o.detail:"";throw new Error(S||`Reset request failed with status ${s.status}.`)}const n=typeof o?.role=="string"?o.role:e.role,w=Number(o?.deletedDocs??0),m=Number(o?.updatedDocs??0),A=typeof o?.summary=="string"?o.summary:`${n} reset complete: ${w} records deleted, ${m} records reset.`;return{role:n,deletedDocs:w,updatedDocs:m,summary:A}}async function D(e){const t=await y(e);if(t.empty)return 0;let r=g(i),s=0,o=0;for(const n of t.docs)r.delete(n.ref),s+=1,o+=1,s>=T&&(await r.commit(),r=g(i),s=0);return s>0&&await r.commit(),o}async function b(e,t,r){return D(I(f(i,e),v(t,"==",r)))}async function a(e,t,r){try{return await b(e,t,r)}catch{return 0}}async function u(e,t){try{const r=f(i,e,t);return await D(r)}catch{return 0}}async function q(e,t){const r=t||e;let s=0,o=0;await k(e),o+=1;const n=await R(d(i,"users",e));let w={};if(n.exists()){const m=n.data();w={...m.photo?{photo:m.photo}:{},...m.avatarLayers?{avatarLayers:m.avatarLayers}:{},...m.ownedAvatarItems?{ownedAvatarItems:m.ownedAvatarItems}:{}}}return await p(d(i,"users",e),{...w,level:1,currentXP:0,totalXP:0,streak:0,streakHistory:[],quizzesCompleted:0,averageScore:0,atRiskSubjects:[],hasTakenDiagnostic:!1,iarAssessmentState:"not_started",learningPathState:"unlocked",remediationState:"not_required",subjectBadges:{},riskClassifications:{},overallRisk:"Low",assessmentDismissed:!1,initialAssessmentCompleted:!1,hasCompletedInitialAssessment:!1,assessmentResults:null,assessmentCompletedAt:null,initialAssessmentCompletedAt:c(),diagnosticCompleted:!1,lastAssessmentDate:c(),assessmentAttemptCount:0,initialProficiencyLevel:c(),iarQuestionSetVersion:c(),iarTopicClassifications:c(),topicScores:c(),priorityTopics:c(),recommendedPace:c(),g12ReadinessIndicators:c(),riskFlags:c(),iarMode:c(),lastAssessmentType:c(),startingQuarterG11:c(),recommendedNextTopicGroupId:c(),recommendationRationale:c(),recommendationReasonCode:c(),grade12TransitionGate:c(),currentCurriculumVersionSetId:c(),unlockCriteriaVersion:c(),updatedAt:h()},{merge:!0}),o+=1,s+=await a("notifications","userId",e),s+=await a("chatSessions","userId",e),s+=await a("chatMessages","userId",e),await l(d(i,"diagnosticResults",e)).then(()=>{s+=1}).catch(()=>{}),await l(d(i,"competencyProfiles",e)).then(()=>{s+=1}).catch(()=>{}),await l(d(i,"assessments",e)).then(()=>{s+=1}).catch(()=>{}),s+=await u(`assessmentResults/${e}`,"attempts"),s+=await u(`assessments/${e}`,"attempts"),s+=await u(`studentProgress/${e}`,"diagnostics"),s+=await u(`assessmentQuestionHistory/${e}`,"questions"),s+=await u(`practice_results/${e}`,"sessions"),await l(d(i,"users",e,"gradeSummary","current")).then(()=>{s+=1}).catch(()=>{}),s+=await u(`users/${e}`,"assessments"),r!==e&&(s+=await a("notifications","userId",r),await l(d(i,"diagnosticResults",r)).then(()=>{s+=1}).catch(()=>{})),s+=await a("xpActivities","userId",e),s+=await a("quizBattleHistory","studentId",e),await l(d(i,"studentBattleStats",e)).then(()=>{s+=1}).catch(()=>{}),await l(d(i,"studentBattleLeaderboard",e)).then(()=>{s+=1}).catch(()=>{}),s+=await a("quizResults","studentId",e),s+=await a("quizResults","lrn",e),s+=await a("quizSubmissions","lrn",e),s+=await u(`users/${e}`,"moduleProgress"),s+=await u(`users/${e}`,"dailyRewards"),await l(d(i,"users",e,"dashboardSummary","heroBannerModal")).then(()=>{s+=1}).catch(()=>{}),await p(d(i,"achievements",e),{userId:e,achievements:[],totalAchievements:0,updatedAt:h()},{merge:!0}).catch(()=>{}),{deletedDocs:s,updatedDocs:o}}async function P(e){let t=0,r=0;const o=(await y(I(f(i,"classrooms"),v("teacherId","==",e)))).docs.map(n=>n.id);t+=await a("notifications","userId",e),t+=await a("chatSessions","userId",e),t+=await a("chatMessages","userId",e),t+=await a("announcements","teacherId",e),t+=await a("classSectionOwnership","ownerTeacherId",e),t+=await a("managedStudents","teacherId",e),t+=await a("classrooms","teacherId",e),t+=await a("normalizedClassRecords","teacherId",e),t+=await a("classRecordImports","teacherId",e),t+=await a("courseMaterials","teacherId",e),t+=await a("riskRefreshEvents","teacherId",e),t+=await a("riskRefreshJobs","teacherId",e),t+=await a("importGroundedFeedbackEvents","teacherId",e),t+=await a("accessAuditLogs","actorUid",e),t+=await a("accessAuditLogs","teacherId",e);for(const n of o)t+=await a("managedStudents","classroomId",n),t+=await a("activities","classroomId",n),t+=await a("announcements","classroomId",n),await l(d(i,"classrooms",n)).then(()=>{t+=1}).catch(()=>{});return await l(d(i,"riskRefreshStats",e)).then(()=>{t+=1}).catch(()=>{}),await p(d(i,"users",e),{testingResetAt:h(),updatedAt:h()},{merge:!0}).catch(()=>{}),r+=1,{deletedDocs:t,updatedDocs:r}}async function L(e){let t=0,r=0;return t+=await a("notifications","userId",e),t+=await a("chatSessions","userId",e),t+=await a("chatMessages","userId",e),t+=await a("curriculumContent","updatedBy",e),t+=await a("curriculumContent","deletedBy",e),await p(d(i,"users",e),{testingResetAt:h(),updatedAt:h()},{merge:!0}).catch(()=>{}),r+=1,{deletedDocs:t,updatedDocs:r}}async function N(e){const{uid:t,role:r,lrn:s}=e;if(!t)throw new Error("Missing user id for reset.");let o;r==="student"?o=await q(t,s):r==="teacher"?o=await P(t):o=await L(t);let n=null;try{n=await B(e)}catch(w){console.warn("[testReset] Backend sync failed (non-fatal):",w)}return{role:r,deletedDocs:o.deletedDocs+(n?.deletedDocs??0),updatedDocs:o.updatedDocs+(n?.updatedDocs??0),summary:`${r} reset complete: ${o.deletedDocs} local records deleted, ${o.updatedDocs} local records updated.${n?` Backend: ${n.summary}`:""}`}}export{N as resetTestingDataForRole}; +import{getDoc as R,doc as d,setDoc as p,serverTimestamp as h,deleteField as c,deleteDoc as l,getDocs as y,query as I,where as v,collection as f,writeBatch as g}from"./vendor-firebase-firestore-CNv3xXal.js";import{b5 as k,g as i,k as $}from"./index-BdLfAeGL.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const T=400,C="https://deign86-mathpulse-api-v3test.hf.space";async function B(e){const t=$.currentUser;if(!t)throw new Error("Authentication is required to reset testing data.");const r=await t.getIdToken(),s=await fetch(`${C}/api/testing/reset-data`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({role:e.role,...e.lrn?{lrn:e.lrn}:{}})}),o=await s.json().catch(()=>({}));if(!s.ok){const S=typeof o?.detail=="string"?o.detail:"";throw new Error(S||`Reset request failed with status ${s.status}.`)}const n=typeof o?.role=="string"?o.role:e.role,w=Number(o?.deletedDocs??0),m=Number(o?.updatedDocs??0),A=typeof o?.summary=="string"?o.summary:`${n} reset complete: ${w} records deleted, ${m} records reset.`;return{role:n,deletedDocs:w,updatedDocs:m,summary:A}}async function D(e){const t=await y(e);if(t.empty)return 0;let r=g(i),s=0,o=0;for(const n of t.docs)r.delete(n.ref),s+=1,o+=1,s>=T&&(await r.commit(),r=g(i),s=0);return s>0&&await r.commit(),o}async function b(e,t,r){return D(I(f(i,e),v(t,"==",r)))}async function a(e,t,r){try{return await b(e,t,r)}catch{return 0}}async function u(e,t){try{const r=f(i,e,t);return await D(r)}catch{return 0}}async function q(e,t){const r=t||e;let s=0,o=0;await k(e),o+=1;const n=await R(d(i,"users",e));let w={};if(n.exists()){const m=n.data();w={...m.photo?{photo:m.photo}:{},...m.avatarLayers?{avatarLayers:m.avatarLayers}:{},...m.ownedAvatarItems?{ownedAvatarItems:m.ownedAvatarItems}:{}}}return await p(d(i,"users",e),{...w,level:1,currentXP:0,totalXP:0,streak:0,streakHistory:[],quizzesCompleted:0,averageScore:0,atRiskSubjects:[],hasTakenDiagnostic:!1,iarAssessmentState:"not_started",learningPathState:"unlocked",remediationState:"not_required",subjectBadges:{},riskClassifications:{},overallRisk:"Low",assessmentDismissed:!1,initialAssessmentCompleted:!1,hasCompletedInitialAssessment:!1,assessmentResults:null,assessmentCompletedAt:null,initialAssessmentCompletedAt:c(),diagnosticCompleted:!1,lastAssessmentDate:c(),assessmentAttemptCount:0,initialProficiencyLevel:c(),iarQuestionSetVersion:c(),iarTopicClassifications:c(),topicScores:c(),priorityTopics:c(),recommendedPace:c(),g12ReadinessIndicators:c(),riskFlags:c(),iarMode:c(),lastAssessmentType:c(),startingQuarterG11:c(),recommendedNextTopicGroupId:c(),recommendationRationale:c(),recommendationReasonCode:c(),grade12TransitionGate:c(),currentCurriculumVersionSetId:c(),unlockCriteriaVersion:c(),updatedAt:h()},{merge:!0}),o+=1,s+=await a("notifications","userId",e),s+=await a("chatSessions","userId",e),s+=await a("chatMessages","userId",e),await l(d(i,"diagnosticResults",e)).then(()=>{s+=1}).catch(()=>{}),await l(d(i,"competencyProfiles",e)).then(()=>{s+=1}).catch(()=>{}),await l(d(i,"assessments",e)).then(()=>{s+=1}).catch(()=>{}),s+=await u(`assessmentResults/${e}`,"attempts"),s+=await u(`assessments/${e}`,"attempts"),s+=await u(`studentProgress/${e}`,"diagnostics"),s+=await u(`assessmentQuestionHistory/${e}`,"questions"),s+=await u(`practice_results/${e}`,"sessions"),await l(d(i,"users",e,"gradeSummary","current")).then(()=>{s+=1}).catch(()=>{}),s+=await u(`users/${e}`,"assessments"),r!==e&&(s+=await a("notifications","userId",r),await l(d(i,"diagnosticResults",r)).then(()=>{s+=1}).catch(()=>{})),s+=await a("xpActivities","userId",e),s+=await a("quizBattleHistory","studentId",e),await l(d(i,"studentBattleStats",e)).then(()=>{s+=1}).catch(()=>{}),await l(d(i,"studentBattleLeaderboard",e)).then(()=>{s+=1}).catch(()=>{}),s+=await a("quizResults","studentId",e),s+=await a("quizResults","lrn",e),s+=await a("quizSubmissions","lrn",e),s+=await u(`users/${e}`,"moduleProgress"),s+=await u(`users/${e}`,"dailyRewards"),await l(d(i,"users",e,"dashboardSummary","heroBannerModal")).then(()=>{s+=1}).catch(()=>{}),await p(d(i,"achievements",e),{userId:e,achievements:[],totalAchievements:0,updatedAt:h()},{merge:!0}).catch(()=>{}),{deletedDocs:s,updatedDocs:o}}async function P(e){let t=0,r=0;const o=(await y(I(f(i,"classrooms"),v("teacherId","==",e)))).docs.map(n=>n.id);t+=await a("notifications","userId",e),t+=await a("chatSessions","userId",e),t+=await a("chatMessages","userId",e),t+=await a("announcements","teacherId",e),t+=await a("classSectionOwnership","ownerTeacherId",e),t+=await a("managedStudents","teacherId",e),t+=await a("classrooms","teacherId",e),t+=await a("normalizedClassRecords","teacherId",e),t+=await a("classRecordImports","teacherId",e),t+=await a("courseMaterials","teacherId",e),t+=await a("riskRefreshEvents","teacherId",e),t+=await a("riskRefreshJobs","teacherId",e),t+=await a("importGroundedFeedbackEvents","teacherId",e),t+=await a("accessAuditLogs","actorUid",e),t+=await a("accessAuditLogs","teacherId",e);for(const n of o)t+=await a("managedStudents","classroomId",n),t+=await a("activities","classroomId",n),t+=await a("announcements","classroomId",n),await l(d(i,"classrooms",n)).then(()=>{t+=1}).catch(()=>{});return await l(d(i,"riskRefreshStats",e)).then(()=>{t+=1}).catch(()=>{}),await p(d(i,"users",e),{testingResetAt:h(),updatedAt:h()},{merge:!0}).catch(()=>{}),r+=1,{deletedDocs:t,updatedDocs:r}}async function L(e){let t=0,r=0;return t+=await a("notifications","userId",e),t+=await a("chatSessions","userId",e),t+=await a("chatMessages","userId",e),t+=await a("curriculumContent","updatedBy",e),t+=await a("curriculumContent","deletedBy",e),await p(d(i,"users",e),{testingResetAt:h(),updatedAt:h()},{merge:!0}).catch(()=>{}),r+=1,{deletedDocs:t,updatedDocs:r}}async function N(e){const{uid:t,role:r,lrn:s}=e;if(!t)throw new Error("Missing user id for reset.");let o;r==="student"?o=await q(t,s):r==="teacher"?o=await P(t):o=await L(t);let n=null;try{n=await B(e)}catch(w){console.warn("[testReset] Backend sync failed (non-fatal):",w)}return{role:r,deletedDocs:o.deletedDocs+(n?.deletedDocs??0),updatedDocs:o.updatedDocs+(n?.updatedDocs??0),summary:`${r} reset complete: ${o.deletedDocs} local records deleted, ${o.updatedDocs} local records updated.${n?` Backend: ${n.summary}`:""}`}}export{N as resetTestingDataForRole}; diff --git a/assets/tooltip-DDXcKYaB.js b/assets/tooltip-Blvwukwg.js similarity index 94% rename from assets/tooltip-DDXcKYaB.js rename to assets/tooltip-Blvwukwg.js index 20075b0e7cd37ceb2b12a977ab4d7a2e4ee53d94..9afb3a717d2db0bb87806c368e16a3c4ddbc0a7b 100644 --- a/assets/tooltip-DDXcKYaB.js +++ b/assets/tooltip-Blvwukwg.js @@ -1 +1 @@ -import{j as o}from"./vendor-react-B4AQeu28.js";import{h as e,i as s,j as n,k as d,A as l,l as m}from"./vendor-radix-C5nwdvGr.js";import{o as p}from"./index-BvEKrMkD.js";function f({delayDuration:t=0,...a}){return o.jsx(m,{"data-slot":"tooltip-provider",delayDuration:t,...a})}function g({...t}){return o.jsx(f,{children:o.jsx(e,{"data-slot":"tooltip",...t})})}function j({...t}){return o.jsx(s,{"data-slot":"tooltip-trigger",...t})}function T({className:t,sideOffset:a=0,children:r,...i}){return o.jsx(n,{children:o.jsxs(d,{"data-slot":"tooltip-content",sideOffset:a,className:p("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...i,children:[r,o.jsx(l,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}export{g as T,j as a,T as b}; +import{j as o}from"./vendor-react-B4AQeu28.js";import{h as e,i as s,j as n,k as d,A as l,l as m}from"./vendor-radix-C5nwdvGr.js";import{o as p}from"./index-BdLfAeGL.js";function f({delayDuration:t=0,...a}){return o.jsx(m,{"data-slot":"tooltip-provider",delayDuration:t,...a})}function g({...t}){return o.jsx(f,{children:o.jsx(e,{"data-slot":"tooltip",...t})})}function j({...t}){return o.jsx(s,{"data-slot":"tooltip-trigger",...t})}function T({className:t,sideOffset:a=0,children:r,...i}){return o.jsx(n,{children:o.jsxs(d,{"data-slot":"tooltip-content",sideOffset:a,className:p("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...i,children:[r,o.jsx(l,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}export{g as T,j as a,T as b}; diff --git a/assets/trackingService-SBoVE94r.js b/assets/trackingService-DJ3_U-Mf.js similarity index 90% rename from assets/trackingService-SBoVE94r.js rename to assets/trackingService-DJ3_U-Mf.js index 72c92bbcc9c1b0b73af599f408ad87b93876afae..d14ad34089fd44dc2299fbc1568a4d0652c864d8 100644 --- a/assets/trackingService-SBoVE94r.js +++ b/assets/trackingService-DJ3_U-Mf.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-BVFD1ZML.js","assets/index-BvEKrMkD.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); -import{g as s,_ as v}from"./index-BvEKrMkD.js";import{collection as a,addDoc as n,serverTimestamp as c}from"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const m="moduleActivities",x=async(e,o,i)=>{try{const t=a(s,m);await n(t,{userId:e,activityType:"chat_session",metadata:{sessionId:o,messageCount:i},timestamp:c()})}catch(t){throw console.error("Error logging chat session:",t),t}},L=async(e,o,i)=>{try{const t=a(s,m);await n(t,{userId:e,activityType:"lesson_view",moduleId:o,topicId:i,timestamp:c()});try{const{emitPipelineEvent:p,getStudentContext:_}=await v(async()=>{const{emitPipelineEvent:l,getStudentContext:d}=await import("./pipelineService-BVFD1ZML.js");return{emitPipelineEvent:l,getStudentContext:d}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),r=_();r&&p({student_id:e,event_type:"session",event_data:{event:"lesson_view",module_id:o,topic_id:i},occurred_at:new Date().toISOString(),class_id:r.classId,teacher_id:r.teacherId})}catch{}}catch(t){throw console.error("Error logging lesson view:",t),t}};export{x as logChatSession,L as logLessonView}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pipelineService-h2NDr2Mk.js","assets/index-BdLfAeGL.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-C5nwdvGr.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-Z9-hiUOE.css"])))=>i.map(i=>d[i]); +import{g as s,_ as v}from"./index-BdLfAeGL.js";import{collection as a,addDoc as n,serverTimestamp as c}from"./vendor-firebase-firestore-CNv3xXal.js";import"./vendor-react-B4AQeu28.js";import"./vendor-firebase-core-D7GXCeNu.js";import"./vendor-firebase-auth-T_wvTOvf.js";import"./vendor-firebase-storage-Bi7H_66d.js";import"./vendor-firebase-analytics-rHarj5hR.js";import"./vendor-radix-C5nwdvGr.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const m="moduleActivities",x=async(e,o,i)=>{try{const t=a(s,m);await n(t,{userId:e,activityType:"chat_session",metadata:{sessionId:o,messageCount:i},timestamp:c()})}catch(t){throw console.error("Error logging chat session:",t),t}},L=async(e,o,i)=>{try{const t=a(s,m);await n(t,{userId:e,activityType:"lesson_view",moduleId:o,topicId:i,timestamp:c()});try{const{emitPipelineEvent:p,getStudentContext:_}=await v(async()=>{const{emitPipelineEvent:l,getStudentContext:d}=await import("./pipelineService-h2NDr2Mk.js");return{emitPipelineEvent:l,getStudentContext:d}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),r=_();r&&p({student_id:e,event_type:"session",event_data:{event:"lesson_view",module_id:o,topic_id:i},occurred_at:new Date().toISOString(),class_id:r.classId,teacher_id:r.teacherId})}catch{}}catch(t){throw console.error("Error logging lesson view:",t),t}};export{x as logChatSession,L as logLessonView}; diff --git a/assets/trash-2-B056YIHV.js b/assets/trash-2-f-pq6QuO.js similarity index 92% rename from assets/trash-2-B056YIHV.js rename to assets/trash-2-f-pq6QuO.js index 6ed6bfec3f941da3bb2fa868065087624554befb..003abf9a73f465fff6ccf61b81c042685958fbd0 100644 --- a/assets/trash-2-B056YIHV.js +++ b/assets/trash-2-f-pq6QuO.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/upload-COEzjD21.js b/assets/upload-CbDKucU9.js similarity index 89% rename from assets/upload-COEzjD21.js rename to assets/upload-CbDKucU9.js index 1823cebfbf21c92537957e36600ca01a53eef8d1..a796bc0711d9bf94fbe470a0b59a5f403eb40f2b 100644 --- a/assets/upload-COEzjD21.js +++ b/assets/upload-CbDKucU9.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BvEKrMkD.js";/** +import{e as o}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/useCurriculum-CSvqmu2B.js b/assets/useCurriculum-DZL96a-v.js similarity index 93% rename from assets/useCurriculum-CSvqmu2B.js rename to assets/useCurriculum-DZL96a-v.js index 37ac4511114fed7a411fe8aa5b641faba6e119f5..f687f954559f47f037d56f46487fe8b94860f02d 100644 --- a/assets/useCurriculum-CSvqmu2B.js +++ b/assets/useCurriculum-DZL96a-v.js @@ -1 +1 @@ -import{r}from"./vendor-react-B4AQeu28.js";import{aJ as g}from"./index-BvEKrMkD.js";import{S as f}from"./subjects-ChEJ6J55.js";const m=e=>({id:e.id,code:e.code,name:e.name,gradeLevel:e.gradeLevel,semester:e.semester,color:e.color,pdfAvailable:e.pdfAvailable,topics:e.topics.map(s=>({id:s.id,name:s.name,unit:s.unit}))});function k(e){const[s,c]=r.useState([]),[d,n]=r.useState(!0),[p,l]=r.useState(null),[C,i]=r.useState("static"),u=r.useCallback(async()=>{n(!0),l(null);try{const t=await g(e);if(t&&t.length>0)c(t),i("firestore");else{const a=f.filter(o=>!e||o.gradeLevel===e);c(a.map(m)),i("static")}}catch(t){console.warn("[useCurriculum] API failed, using static:",t);const a=f.filter(o=>!e||o.gradeLevel===e);c(a.map(m)),i("static"),l(t instanceof Error?t.message:"Failed to load curriculum")}finally{n(!1)}},[e]);r.useEffect(()=>{u()},[u]);const S=r.useCallback(t=>s.find(a=>a.id===t),[s]),b=r.useCallback(t=>s.find(o=>o.id===t)?.topics||[],[s]);return{subjects:s,isLoading:d,error:p,getSubject:S,getTopics:b,refetch:u}}export{k as u}; +import{r}from"./vendor-react-B4AQeu28.js";import{aJ as g}from"./index-BdLfAeGL.js";import{S as f}from"./subjects-Dw9HR29l.js";const m=e=>({id:e.id,code:e.code,name:e.name,gradeLevel:e.gradeLevel,semester:e.semester,color:e.color,pdfAvailable:e.pdfAvailable,topics:e.topics.map(s=>({id:s.id,name:s.name,unit:s.unit}))});function k(e){const[s,c]=r.useState([]),[d,n]=r.useState(!0),[p,l]=r.useState(null),[C,i]=r.useState("static"),u=r.useCallback(async()=>{n(!0),l(null);try{const t=await g(e);if(t&&t.length>0)c(t),i("firestore");else{const a=f.filter(o=>!e||o.gradeLevel===e);c(a.map(m)),i("static")}}catch(t){console.warn("[useCurriculum] API failed, using static:",t);const a=f.filter(o=>!e||o.gradeLevel===e);c(a.map(m)),i("static"),l(t instanceof Error?t.message:"Failed to load curriculum")}finally{n(!1)}},[e]);r.useEffect(()=>{u()},[u]);const S=r.useCallback(t=>s.find(a=>a.id===t),[s]),b=r.useCallback(t=>s.find(o=>o.id===t)?.topics||[],[s]);return{subjects:s,isLoading:d,error:p,getSubject:S,getTopics:b,refetch:u}}export{k as u}; diff --git a/assets/useFeatureAccess-BTg5PL53.js b/assets/useFeatureAccess-BGJy4XRW.js similarity index 91% rename from assets/useFeatureAccess-BTg5PL53.js rename to assets/useFeatureAccess-BGJy4XRW.js index 236b5e024367f88848f957a5ac74dce9f0915bc5..abc4eaa7cf4b38a204c9c3dfd3c0bee4f905751a 100644 --- a/assets/useFeatureAccess-BTg5PL53.js +++ b/assets/useFeatureAccess-BGJy4XRW.js @@ -1 +1 @@ -import{r as c}from"./vendor-react-B4AQeu28.js";import{doc as n,onSnapshot as l}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as d}from"./index-BvEKrMkD.js";const t={leaderboard:!0,cosmeticShop:!0,bonusChallenges:!0,optionalModules:!0,lockedFeatures:[],loading:!0};function h(r){const[u,s]=c.useState(t);return c.useEffect(()=>{if(!r){s(t);return}const a=n(d,"users",r);return l(a,o=>{if(!o.exists()){s(t);return}const e=o.data()?.lockedFeatures||[];s({leaderboard:!e.includes("leaderboard"),cosmeticShop:!e.includes("cosmetic_shop"),bonusChallenges:!e.includes("bonus_challenges"),optionalModules:!e.includes("optional_modules"),lockedFeatures:e,loading:!1})},o=>{console.error("[useFeatureAccess] snapshot error:",o),s(t)})},[r]),u}export{h as u}; +import{r as c}from"./vendor-react-B4AQeu28.js";import{doc as n,onSnapshot as l}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as d}from"./index-BdLfAeGL.js";const t={leaderboard:!0,cosmeticShop:!0,bonusChallenges:!0,optionalModules:!0,lockedFeatures:[],loading:!0};function h(r){const[u,s]=c.useState(t);return c.useEffect(()=>{if(!r){s(t);return}const a=n(d,"users",r);return l(a,o=>{if(!o.exists()){s(t);return}const e=o.data()?.lockedFeatures||[];s({leaderboard:!e.includes("leaderboard"),cosmeticShop:!e.includes("cosmetic_shop"),bonusChallenges:!e.includes("bonus_challenges"),optionalModules:!e.includes("optional_modules"),lockedFeatures:e,loading:!1})},o=>{console.error("[useFeatureAccess] snapshot error:",o),s(t)})},[r]),u}export{h as u}; diff --git a/assets/useQuery-a95tRwQa.js b/assets/useQuery-fA8_Syr9.js similarity index 99% rename from assets/useQuery-a95tRwQa.js rename to assets/useQuery-fA8_Syr9.js index 34cea6c8912f79b356490d6d1a04507c39d28d2f..7038df4a8c8b91d55c8270df2fbd3a4180dccd37 100644 --- a/assets/useQuery-a95tRwQa.js +++ b/assets/useQuery-fA8_Syr9.js @@ -1 +1 @@ -import{ar as G,as as N,at as u,au as Q,av as g,aw as M,ax as x,ay as B,az as J,aA as C,aB as X,aC as Y,aD as A,aE as W,aF as V,a0 as Z}from"./index-BvEKrMkD.js";import{r as d}from"./vendor-react-B4AQeu28.js";var $=class extends G{constructor(t,e){super(),this.options=e,this.#s=t,this.#r=null,this.#i=N(),this.bindMethods(),this.setOptions(e)}#s;#t=void 0;#p=void 0;#e=void 0;#n;#u;#i;#r;#v;#l;#d;#o;#h;#a;#f=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),j(this.#t,this.options)?this.#c():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#S(),this.#t.removeObserver(this)}setOptions(t){const e=this.options,s=this.#t;if(this.options=this.#s.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof u(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#O(),this.#t.setOptions(this.options),e._defaulted&&!Q(this.options,e)&&this.#s.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const i=this.hasListeners();i&&H(this.#t,s,this.options,e)&&this.#c(),this.updateResult(),i&&(this.#t!==s||u(this.options.enabled,this.#t)!==u(e.enabled,this.#t)||g(this.options.staleTime,this.#t)!==g(e.staleTime,this.#t))&&this.#R();const r=this.#b();i&&(this.#t!==s||u(this.options.enabled,this.#t)!==u(e.enabled,this.#t)||r!==this.#a)&&this.#m(r)}getOptimisticResult(t){const e=this.#s.getQueryCache().build(this.#s,t),s=this.createResult(e,t);return tt(this,s)&&(this.#e=s,this.#u=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#e}trackResult(t,e){return new Proxy(t,{get:(s,i)=>(this.trackProp(i),e?.(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#i.status==="pending"&&this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,i))})}trackProp(t){this.#f.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const e=this.#s.defaultQueryOptions(t),s=this.#s.getQueryCache().build(this.#s,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#c({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#e))}#c(t){this.#O();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(M)),e}#R(){this.#y();const t=g(this.options.staleTime,this.#t);if(x.isServer()||this.#e.isStale||!B(t))return;const s=J(this.#e.dataUpdatedAt,t)+1;this.#o=C.setTimeout(()=>{this.#e.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#m(t){this.#S(),this.#a=t,!(x.isServer()||u(this.options.enabled,this.#t)===!1||!B(this.#a)||this.#a===0)&&(this.#h=C.setInterval(()=>{(this.options.refetchIntervalInBackground||X.isFocused())&&this.#c()},this.#a))}#g(){this.#R(),this.#m(this.#b())}#y(){this.#o!==void 0&&(C.clearTimeout(this.#o),this.#o=void 0)}#S(){this.#h!==void 0&&(C.clearInterval(this.#h),this.#h=void 0)}createResult(t,e){const s=this.#t,i=this.options,r=this.#e,l=this.#n,a=this.#u,R=t!==s?t.state:this.#p,{state:h}=t;let n={...h},b=!1,o;if(e._optimisticResults){const c=this.hasListeners(),m=!c&&j(t,e),S=c&&H(t,s,e,i);(m||S)&&(n={...n,...Y(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(n.fetchStatus="idle")}let{error:y,errorUpdatedAt:F,status:v}=n;o=n.data;let D=!1;if(e.placeholderData!==void 0&&o===void 0&&v==="pending"){let c;r?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(c=r.data,D=!0):c=typeof e.placeholderData=="function"?e.placeholderData(this.#d?.state.data,this.#d):e.placeholderData,c!==void 0&&(v="success",o=A(r?.data,c,e),b=!0)}if(e.select&&o!==void 0&&!D)if(r&&o===l?.data&&e.select===this.#v)o=this.#l;else try{this.#v=e.select,o=e.select(o),o=A(r?.data,o,e),this.#l=o,this.#r=null}catch(c){this.#r=c}this.#r&&(y=this.#r,o=this.#l,F=Date.now(),v="error");const I=n.fetchStatus==="fetching",T=v==="pending",w=v==="error",U=T&&I,k=o!==void 0,p={status:v,fetchStatus:n.fetchStatus,isPending:T,isSuccess:v==="success",isError:w,isInitialLoading:U,isLoading:U,data:o,dataUpdatedAt:n.dataUpdatedAt,error:y,errorUpdatedAt:F,failureCount:n.fetchFailureCount,failureReason:n.fetchFailureReason,errorUpdateCount:n.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:n.dataUpdateCount>R.dataUpdateCount||n.errorUpdateCount>R.errorUpdateCount,isFetching:I,isRefetching:I&&!T,isLoadingError:w&&!k,isPaused:n.fetchStatus==="paused",isPlaceholderData:b,isRefetchError:w&&k,isStale:P(t,e),refetch:this.refetch,promise:this.#i,isEnabled:u(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const c=p.data!==void 0,m=p.status==="error"&&!c,S=E=>{m?E.reject(p.error):c&&E.resolve(p.data)},L=()=>{const E=this.#i=p.promise=N();S(E)},O=this.#i;switch(O.status){case"pending":t.queryHash===s.queryHash&&S(O);break;case"fulfilled":(m||p.data!==O.value)&&L();break;case"rejected":(!m||p.error!==O.reason)&&L();break}}return p}updateResult(){const t=this.#e,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#u=this.options,this.#n.data!==void 0&&(this.#d=this.#t),Q(e,t))return;this.#e=e;const s=()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,r=typeof i=="function"?i():i;if(r==="all"||!r&&!this.#f.size)return!0;const l=new Set(r??this.#f);return this.options.throwOnError&&l.add("error"),Object.keys(this.#e).some(a=>{const f=a;return this.#e[f]!==t[f]&&l.has(f)})};this.#E({listeners:s()})}#O(){const t=this.#s.getQueryCache().build(this.#s,this.options);if(t===this.#t)return;const e=this.#t;this.#t=t,this.#p=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#E(t){W.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#e)}),this.#s.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function q(t,e){return u(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&u(e.retryOnMount,t)===!1)}function j(t,e){return q(t,e)||t.state.data!==void 0&&_(t,e,e.refetchOnMount)}function _(t,e,s){if(u(e.enabled,t)!==!1&&g(e.staleTime,t)!=="static"){const i=typeof s=="function"?s(t):s;return i==="always"||i!==!1&&P(t,e)}return!1}function H(t,e,s,i){return(t!==e||u(i.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&P(t,s)}function P(t,e){return u(e.enabled,t)!==!1&&t.isStaleByTime(g(e.staleTime,t))}function tt(t,e){return!Q(t.getCurrentResult(),e)}var K=d.createContext(!1),et=()=>d.useContext(K);K.Provider;function st(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var it=d.createContext(st()),rt=()=>d.useContext(it),at=(t,e,s)=>{const i=s?.state.error&&typeof t.throwOnError=="function"?V(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||i)&&(e.isReset()||(t.retryOnMount=!1))},nt=t=>{d.useEffect(()=>{t.clearReset()},[t])},ot=({result:t,errorResetBoundary:e,throwOnError:s,query:i,suspense:r})=>t.isError&&!e.isReset()&&!t.isFetching&&i&&(r&&t.data===void 0||V(s,[t.error,i])),ht=t=>{if(t.suspense){const s=r=>r==="static"?r:Math.max(r??1e3,1e3),i=t.staleTime;t.staleTime=typeof i=="function"?(...r)=>s(i(...r)):s(i),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},ct=(t,e)=>t.isLoading&&t.isFetching&&!e,ut=(t,e)=>t?.suspense&&e.isPending,z=(t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()});function lt(t,e,s){const i=et(),r=rt(),l=Z(),a=l.defaultQueryOptions(t);l.getDefaultOptions().queries?._experimental_beforeQuery?.(a);const f=l.getQueryCache().get(a.queryHash);a._optimisticResults=i?"isRestoring":"optimistic",ht(a),at(a,r,f),nt(r);const R=!l.getQueryCache().get(a.queryHash),[h]=d.useState(()=>new e(l,a)),n=h.getOptimisticResult(a),b=!i&&t.subscribed!==!1;if(d.useSyncExternalStore(d.useCallback(o=>{const y=b?h.subscribe(W.batchCalls(o)):M;return h.updateResult(),y},[h,b]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),d.useEffect(()=>{h.setOptions(a)},[a,h]),ut(a,n))throw z(a,h,r);if(ot({result:n,errorResetBoundary:r,throwOnError:a.throwOnError,query:f,suspense:a.suspense}))throw n.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(a,n),a.experimental_prefetchInRender&&!x.isServer()&&ct(n,i)&&(R?z(a,h,r):f?.promise)?.catch(M).finally(()=>{h.updateResult()}),a.notifyOnChangeProps?n:h.trackResult(n)}function vt(t,e){return lt(t,$)}export{vt as u}; +import{ar as G,as as N,at as u,au as Q,av as g,aw as M,ax as x,ay as B,az as J,aA as C,aB as X,aC as Y,aD as A,aE as W,aF as V,a0 as Z}from"./index-BdLfAeGL.js";import{r as d}from"./vendor-react-B4AQeu28.js";var $=class extends G{constructor(t,e){super(),this.options=e,this.#s=t,this.#r=null,this.#i=N(),this.bindMethods(),this.setOptions(e)}#s;#t=void 0;#p=void 0;#e=void 0;#n;#u;#i;#r;#v;#l;#d;#o;#h;#a;#f=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),j(this.#t,this.options)?this.#c():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#S(),this.#t.removeObserver(this)}setOptions(t){const e=this.options,s=this.#t;if(this.options=this.#s.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof u(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#O(),this.#t.setOptions(this.options),e._defaulted&&!Q(this.options,e)&&this.#s.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const i=this.hasListeners();i&&H(this.#t,s,this.options,e)&&this.#c(),this.updateResult(),i&&(this.#t!==s||u(this.options.enabled,this.#t)!==u(e.enabled,this.#t)||g(this.options.staleTime,this.#t)!==g(e.staleTime,this.#t))&&this.#R();const r=this.#b();i&&(this.#t!==s||u(this.options.enabled,this.#t)!==u(e.enabled,this.#t)||r!==this.#a)&&this.#m(r)}getOptimisticResult(t){const e=this.#s.getQueryCache().build(this.#s,t),s=this.createResult(e,t);return tt(this,s)&&(this.#e=s,this.#u=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#e}trackResult(t,e){return new Proxy(t,{get:(s,i)=>(this.trackProp(i),e?.(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#i.status==="pending"&&this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,i))})}trackProp(t){this.#f.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const e=this.#s.defaultQueryOptions(t),s=this.#s.getQueryCache().build(this.#s,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#c({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#e))}#c(t){this.#O();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(M)),e}#R(){this.#y();const t=g(this.options.staleTime,this.#t);if(x.isServer()||this.#e.isStale||!B(t))return;const s=J(this.#e.dataUpdatedAt,t)+1;this.#o=C.setTimeout(()=>{this.#e.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#m(t){this.#S(),this.#a=t,!(x.isServer()||u(this.options.enabled,this.#t)===!1||!B(this.#a)||this.#a===0)&&(this.#h=C.setInterval(()=>{(this.options.refetchIntervalInBackground||X.isFocused())&&this.#c()},this.#a))}#g(){this.#R(),this.#m(this.#b())}#y(){this.#o!==void 0&&(C.clearTimeout(this.#o),this.#o=void 0)}#S(){this.#h!==void 0&&(C.clearInterval(this.#h),this.#h=void 0)}createResult(t,e){const s=this.#t,i=this.options,r=this.#e,l=this.#n,a=this.#u,R=t!==s?t.state:this.#p,{state:h}=t;let n={...h},b=!1,o;if(e._optimisticResults){const c=this.hasListeners(),m=!c&&j(t,e),S=c&&H(t,s,e,i);(m||S)&&(n={...n,...Y(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(n.fetchStatus="idle")}let{error:y,errorUpdatedAt:F,status:v}=n;o=n.data;let D=!1;if(e.placeholderData!==void 0&&o===void 0&&v==="pending"){let c;r?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(c=r.data,D=!0):c=typeof e.placeholderData=="function"?e.placeholderData(this.#d?.state.data,this.#d):e.placeholderData,c!==void 0&&(v="success",o=A(r?.data,c,e),b=!0)}if(e.select&&o!==void 0&&!D)if(r&&o===l?.data&&e.select===this.#v)o=this.#l;else try{this.#v=e.select,o=e.select(o),o=A(r?.data,o,e),this.#l=o,this.#r=null}catch(c){this.#r=c}this.#r&&(y=this.#r,o=this.#l,F=Date.now(),v="error");const I=n.fetchStatus==="fetching",T=v==="pending",w=v==="error",U=T&&I,k=o!==void 0,p={status:v,fetchStatus:n.fetchStatus,isPending:T,isSuccess:v==="success",isError:w,isInitialLoading:U,isLoading:U,data:o,dataUpdatedAt:n.dataUpdatedAt,error:y,errorUpdatedAt:F,failureCount:n.fetchFailureCount,failureReason:n.fetchFailureReason,errorUpdateCount:n.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:n.dataUpdateCount>R.dataUpdateCount||n.errorUpdateCount>R.errorUpdateCount,isFetching:I,isRefetching:I&&!T,isLoadingError:w&&!k,isPaused:n.fetchStatus==="paused",isPlaceholderData:b,isRefetchError:w&&k,isStale:P(t,e),refetch:this.refetch,promise:this.#i,isEnabled:u(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const c=p.data!==void 0,m=p.status==="error"&&!c,S=E=>{m?E.reject(p.error):c&&E.resolve(p.data)},L=()=>{const E=this.#i=p.promise=N();S(E)},O=this.#i;switch(O.status){case"pending":t.queryHash===s.queryHash&&S(O);break;case"fulfilled":(m||p.data!==O.value)&&L();break;case"rejected":(!m||p.error!==O.reason)&&L();break}}return p}updateResult(){const t=this.#e,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#u=this.options,this.#n.data!==void 0&&(this.#d=this.#t),Q(e,t))return;this.#e=e;const s=()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,r=typeof i=="function"?i():i;if(r==="all"||!r&&!this.#f.size)return!0;const l=new Set(r??this.#f);return this.options.throwOnError&&l.add("error"),Object.keys(this.#e).some(a=>{const f=a;return this.#e[f]!==t[f]&&l.has(f)})};this.#E({listeners:s()})}#O(){const t=this.#s.getQueryCache().build(this.#s,this.options);if(t===this.#t)return;const e=this.#t;this.#t=t,this.#p=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#E(t){W.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#e)}),this.#s.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function q(t,e){return u(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&u(e.retryOnMount,t)===!1)}function j(t,e){return q(t,e)||t.state.data!==void 0&&_(t,e,e.refetchOnMount)}function _(t,e,s){if(u(e.enabled,t)!==!1&&g(e.staleTime,t)!=="static"){const i=typeof s=="function"?s(t):s;return i==="always"||i!==!1&&P(t,e)}return!1}function H(t,e,s,i){return(t!==e||u(i.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&P(t,s)}function P(t,e){return u(e.enabled,t)!==!1&&t.isStaleByTime(g(e.staleTime,t))}function tt(t,e){return!Q(t.getCurrentResult(),e)}var K=d.createContext(!1),et=()=>d.useContext(K);K.Provider;function st(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var it=d.createContext(st()),rt=()=>d.useContext(it),at=(t,e,s)=>{const i=s?.state.error&&typeof t.throwOnError=="function"?V(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||i)&&(e.isReset()||(t.retryOnMount=!1))},nt=t=>{d.useEffect(()=>{t.clearReset()},[t])},ot=({result:t,errorResetBoundary:e,throwOnError:s,query:i,suspense:r})=>t.isError&&!e.isReset()&&!t.isFetching&&i&&(r&&t.data===void 0||V(s,[t.error,i])),ht=t=>{if(t.suspense){const s=r=>r==="static"?r:Math.max(r??1e3,1e3),i=t.staleTime;t.staleTime=typeof i=="function"?(...r)=>s(i(...r)):s(i),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},ct=(t,e)=>t.isLoading&&t.isFetching&&!e,ut=(t,e)=>t?.suspense&&e.isPending,z=(t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()});function lt(t,e,s){const i=et(),r=rt(),l=Z(),a=l.defaultQueryOptions(t);l.getDefaultOptions().queries?._experimental_beforeQuery?.(a);const f=l.getQueryCache().get(a.queryHash);a._optimisticResults=i?"isRestoring":"optimistic",ht(a),at(a,r,f),nt(r);const R=!l.getQueryCache().get(a.queryHash),[h]=d.useState(()=>new e(l,a)),n=h.getOptimisticResult(a),b=!i&&t.subscribed!==!1;if(d.useSyncExternalStore(d.useCallback(o=>{const y=b?h.subscribe(W.batchCalls(o)):M;return h.updateResult(),y},[h,b]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),d.useEffect(()=>{h.setOptions(a)},[a,h]),ut(a,n))throw z(a,h,r);if(ot({result:n,errorResetBoundary:r,throwOnError:a.throwOnError,query:f,suspense:a.suspense}))throw n.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(a,n),a.experimental_prefetchInRender&&!x.isServer()&&ct(n,i)&&(R?z(a,h,r):f?.promise)?.catch(M).finally(()=>{h.updateResult()}),a.notifyOnChangeProps?n:h.trackResult(n)}function vt(t,e){return lt(t,$)}export{vt as u}; diff --git a/assets/useSubjectAvailability-C0TzAHAR.js b/assets/useSubjectAvailability-BUrciGBC.js similarity index 97% rename from assets/useSubjectAvailability-C0TzAHAR.js rename to assets/useSubjectAvailability-BUrciGBC.js index cbf4e07d723dfa29613ab993abe1f0aaecf697d8..380189db3303cfa0fd945bb84294ca91d19fcfc2 100644 --- a/assets/useSubjectAvailability-C0TzAHAR.js +++ b/assets/useSubjectAvailability-BUrciGBC.js @@ -1 +1 @@ -import{r as u}from"./vendor-react-B4AQeu28.js";import{g as j}from"./index-BvEKrMkD.js";import{doc as y,getDoc as w,setDoc as A,serverTimestamp as p,onSnapshot as P}from"./vendor-firebase-firestore-CNv3xXal.js";const v="subjects",h="platformConfig";function g(){return{"gen-math":{available:!0,pdfPath:null,lastUpdated:new Date},"stats-prob":{available:!0,pdfPath:null,lastUpdated:new Date},"pre-calc":{available:!1,pdfPath:null,lastUpdated:new Date},"basic-calc":{available:!1,pdfPath:null,lastUpdated:new Date}}}function D(t){const r=t.subjects||{},a={};for(const[e,s]of Object.entries(r))a[e]={available:!!s.available,pdfPath:s.pdfPath?String(s.pdfPath):null,lastUpdated:s.lastUpdated?s.lastUpdated.toDate?.()||new Date:new Date};return{subjects:a,updatedAt:t.updatedAt?t.updatedAt.toDate?.()||new Date:new Date,updatedBy:String(t.updatedBy||"")}}async function x(){try{const t=y(j,h,v),r=await w(t);return r.exists()?D(r.data()):{subjects:g(),updatedAt:new Date,updatedBy:""}}catch(t){return console.error("[platformConfigService] getSubjectAvailability error:",t),{subjects:g(),updatedAt:new Date,updatedBy:""}}}function U(t){const r=y(j,h,v);return P(r,a=>{a.exists()?t(D(a.data())):t({subjects:g(),updatedAt:new Date,updatedBy:""})},a=>{console.error("[platformConfigService] subscribe error:",a),t({subjects:g(),updatedAt:new Date,updatedBy:""})})}async function O(t,r,a){try{const e=y(j,h,v),s=await w(e),o=s.exists()?s.data().subjects||{}:{};await A(e,{subjects:{...o,[t]:{available:r,pdfPath:o[t]?.pdfPath??null,lastUpdated:p()}},updatedAt:p(),updatedBy:a},{merge:!0})}catch(e){throw console.error("[platformConfigService] toggleSubjectAvailability error:",e),e}}async function L(t,r,a){try{const e=y(j,h,v),s=await w(e),o=s.exists()?s.data().subjects||{}:{};await A(e,{subjects:{...o,[t]:{available:o[t]?.available??!0,pdfPath:r,lastUpdated:p()}},updatedAt:p(),updatedBy:a},{merge:!0})}catch(e){throw console.error("[platformConfigService] updateSubjectPdfPath error:",e),e}}let c=null,l=!0,b=null,f=[];function S(){f.forEach(t=>t())}function R(){const[t,r]=u.useState(c),[a,e]=u.useState(l),[s,o]=u.useState(b);u.useEffect(()=>{const n=()=>{r(c),e(l),o(b)};if(f.push(n),!c&&l){x().then(d=>{c=d,l=!1,S()}).catch(d=>{console.error("[useSubjectAvailability] initial fetch error:",d),b="Failed to load subject availability",l=!1,S()});const i=U(d=>{c=d,l=!1,b=null,S()});f.push(i)}return()=>{const i=f.indexOf(n);i>-1&&f.splice(i,1)}},[]);const m=u.useCallback(n=>(t||c)?.subjects[n]?.available??!0,[t]),C=u.useCallback(n=>(t||c)?.subjects[n],[t]);return{availability:(t||c)?.subjects??{},config:t||c,loading:a||l,error:s||b,isSubjectAvailable:m,getSubjectEntry:C}}export{L as a,O as t,R as u}; +import{r as u}from"./vendor-react-B4AQeu28.js";import{g as j}from"./index-BdLfAeGL.js";import{doc as y,getDoc as w,setDoc as A,serverTimestamp as p,onSnapshot as P}from"./vendor-firebase-firestore-CNv3xXal.js";const v="subjects",h="platformConfig";function g(){return{"gen-math":{available:!0,pdfPath:null,lastUpdated:new Date},"stats-prob":{available:!0,pdfPath:null,lastUpdated:new Date},"pre-calc":{available:!1,pdfPath:null,lastUpdated:new Date},"basic-calc":{available:!1,pdfPath:null,lastUpdated:new Date}}}function D(t){const r=t.subjects||{},a={};for(const[e,s]of Object.entries(r))a[e]={available:!!s.available,pdfPath:s.pdfPath?String(s.pdfPath):null,lastUpdated:s.lastUpdated?s.lastUpdated.toDate?.()||new Date:new Date};return{subjects:a,updatedAt:t.updatedAt?t.updatedAt.toDate?.()||new Date:new Date,updatedBy:String(t.updatedBy||"")}}async function x(){try{const t=y(j,h,v),r=await w(t);return r.exists()?D(r.data()):{subjects:g(),updatedAt:new Date,updatedBy:""}}catch(t){return console.error("[platformConfigService] getSubjectAvailability error:",t),{subjects:g(),updatedAt:new Date,updatedBy:""}}}function U(t){const r=y(j,h,v);return P(r,a=>{a.exists()?t(D(a.data())):t({subjects:g(),updatedAt:new Date,updatedBy:""})},a=>{console.error("[platformConfigService] subscribe error:",a),t({subjects:g(),updatedAt:new Date,updatedBy:""})})}async function O(t,r,a){try{const e=y(j,h,v),s=await w(e),o=s.exists()?s.data().subjects||{}:{};await A(e,{subjects:{...o,[t]:{available:r,pdfPath:o[t]?.pdfPath??null,lastUpdated:p()}},updatedAt:p(),updatedBy:a},{merge:!0})}catch(e){throw console.error("[platformConfigService] toggleSubjectAvailability error:",e),e}}async function L(t,r,a){try{const e=y(j,h,v),s=await w(e),o=s.exists()?s.data().subjects||{}:{};await A(e,{subjects:{...o,[t]:{available:o[t]?.available??!0,pdfPath:r,lastUpdated:p()}},updatedAt:p(),updatedBy:a},{merge:!0})}catch(e){throw console.error("[platformConfigService] updateSubjectPdfPath error:",e),e}}let c=null,l=!0,b=null,f=[];function S(){f.forEach(t=>t())}function R(){const[t,r]=u.useState(c),[a,e]=u.useState(l),[s,o]=u.useState(b);u.useEffect(()=>{const n=()=>{r(c),e(l),o(b)};if(f.push(n),!c&&l){x().then(d=>{c=d,l=!1,S()}).catch(d=>{console.error("[useSubjectAvailability] initial fetch error:",d),b="Failed to load subject availability",l=!1,S()});const i=U(d=>{c=d,l=!1,b=null,S()});f.push(i)}return()=>{const i=f.indexOf(n);i>-1&&f.splice(i,1)}},[]);const m=u.useCallback(n=>(t||c)?.subjects[n]?.available??!0,[t]),C=u.useCallback(n=>(t||c)?.subjects[n],[t]);return{availability:(t||c)?.subjects??{},config:t||c,loading:a||l,error:s||b,isSubjectAvailable:m,getSubjectEntry:C}}export{L as a,O as t,R as u}; diff --git a/assets/volume-x-C2kyFHU5.js b/assets/volume-x-BfFSlkII.js similarity index 97% rename from assets/volume-x-C2kyFHU5.js rename to assets/volume-x-BfFSlkII.js index eb7e21aec02f4eea5291e2933675d32c14008aa9..bb8c8113f052b7d5511f2c8d93e755a82492e27f 100644 --- a/assets/volume-x-C2kyFHU5.js +++ b/assets/volume-x-BfFSlkII.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BvEKrMkD.js";/** +import{e as a}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/x-BYtx1i07.js b/assets/x-BLhsirCD.js similarity index 87% rename from assets/x-BYtx1i07.js rename to assets/x-BLhsirCD.js index dbec7670291aac493152615ff35056de424737d0..e06deae8abf98a681cbdadb5c04ee26026209f82 100644 --- a/assets/x-BYtx1i07.js +++ b/assets/x-BLhsirCD.js @@ -1,4 +1,4 @@ -import{e}from"./index-BvEKrMkD.js";/** +import{e}from"./index-BdLfAeGL.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/index.html b/index.html index 9307964442469ba835b9bf7058ac1c9c2760b0be..8dea755ff9348318c3c37a7e8b9e7b1250c178b5 100644 --- a/index.html +++ b/index.html @@ -33,7 +33,7 @@ #pp-static-loader .pp-spinner{width:1rem;height:1rem;border-radius:999px;border:2px solid #0284c7;border-top-color:transparent;animation:pp-spin 1.5s linear infinite} #pp-static-loader .pp-msg{margin:0;font-size:.875rem;font-weight:600;color:#64748b} - +