diff --git a/assets/AIChatPage-6rPaXTro.js b/assets/AIChatPage-BP31m_mb.js similarity index 94% rename from assets/AIChatPage-6rPaXTro.js rename to assets/AIChatPage-BP31m_mb.js index 3291c5a616118bdb859bcd0c04a6403eac1745af..b65b9b45372f67b0d691f34d953a4c503569cac9 100644 --- a/assets/AIChatPage-6rPaXTro.js +++ b/assets/AIChatPage-BP31m_mb.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BYG24j30.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); -import{aE as B,u as z,_ as F,h as S,m as C,J as D}from"./index-BYG24j30.js";import{r as o,j as e}from"./vendor-react-B4AQeu28.js";import{B as O}from"./button-LR_FKM7p.js";import{I}from"./input-CtjqQUbX.js";import H from"./ChatMarkdown-Dn0t_isr.js";import{P as Y}from"./plus-C5IM0tm0.js";import{S as G}from"./search-qXpo6Bz-.js";import{T as Q}from"./trash-2-Bz07bxtW.js";import{C as W}from"./chevron-left-CIE_NDv7.js";import{S as q}from"./send-Cs_bBaZx.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";function J(r){return r?r instanceof Date?r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):typeof r=="object"&&"toDate"in r?r.toDate().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):String(r):""}const he=()=>{const{sessions:r,activeSessionId:a,isLoading:l,loadingSessionId:A,setActiveSessionId:n,createNewSession:b,sendMessage:L,deleteSession:T,getActiveSession:_}=B(),{userProfile:c}=z(),[m,P]=o.useState(""),[i,g]=o.useState(""),[y,j]=o.useState(!1),x=o.useRef(null),h=o.useRef(!0),u=o.useRef(!1),d=_(),p=d?.messages||[],E=p.some(t=>t.sender==="ai"&&t.id.startsWith("stream-")),v=l&&a===A&&!E,w=(t="auto")=>{const s=x.current;s&&s.scrollTo({top:s.scrollHeight,behavior:t})},M=()=>{const t=x.current;return t?t.scrollHeight-t.scrollTop-t.clientHeight<=120:!0},R=()=>{h.current=M()};o.useEffect(()=>{F(async()=>{const{warmupBackend:t}=await import("./index-BYG24j30.js").then(s=>s.b6);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)})},[]),o.useEffect(()=>{if(!h.current)return;const t=window.requestAnimationFrame(()=>w("auto"));return()=>window.cancelAnimationFrame(t)},[p,v]),o.useEffect(()=>{h.current=!0,w("auto")},[a]);const N=async()=>{if(!(!i.trim()||l||y||u.current)){u.current=!0,j(!0);try{let t=a;t||(t=b(),n(t));const s=i.trim();g(""),await L(t,s)}finally{u.current=!1,j(!1)}}},k=()=>{const t=b();n(t)},$=(t,s)=>{s.stopPropagation(),T(t)},f=r.filter(t=>t.title.toLowerCase().includes(m.toLowerCase())||t.preview.toLowerCase().includes(m.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:`${a?"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:k,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(Y,{size:14}),"New Chat"]})]}),e.jsxs("div",{className:"relative mt-3",children:[e.jsx(G,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500",size:14}),e.jsx(I,{type:"text",placeholder:"Search conversations...",value:m,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:[f.length," Conversations"]})}),e.jsx(S,{children:f.map(t=>e.jsxs(C.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 ${a===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 ${a===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 ${a===t.id?"bg-sky-100 text-sky-600":"bg-[#dde3eb] text-[#5a6578]"}`,children:[t.messageCount," msgs"]})]})]},t.id))}),f.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:`${a?"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:a?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(W,{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:x,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(S,{children:p.map(t=>e.jsxs(C.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(H,{children:t.text}),e.jsx("p",{className:`text-[10px] mt-1.5 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:J(t.timestamp)})]}),t.sender==="user"&&e.jsx(D,{src:c?.photo,name:c?.name,gender:c?.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(I,{type:"text",value:i,onChange:t=>g(t.target.value),onKeyPress:t=>t.key==="Enter"&&N(),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:N,disabled:!i.trim()||l||y,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(q,{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:k,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{he as default}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CR5aYAL9.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); +import{aE as B,u as z,_ as F,h as S,m as C,J as D}from"./index-CR5aYAL9.js";import{r as o,j as e}from"./vendor-react-B4AQeu28.js";import{B as O}from"./button-CbtAHv27.js";import{I}from"./input-DgZjxAsx.js";import H from"./ChatMarkdown-kQBhTXf0.js";import{P as Y}from"./plus-Cp5Q-YTc.js";import{S as G}from"./search-1a4wCp_r.js";import{T as Q}from"./trash-2-BtGasoad.js";import{C as W}from"./chevron-left-Buq4JTY_.js";import{S as q}from"./send-B1wbvsc_.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";function J(r){return r?r instanceof Date?r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):typeof r=="object"&&"toDate"in r?r.toDate().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):String(r):""}const he=()=>{const{sessions:r,activeSessionId:a,isLoading:l,loadingSessionId:A,setActiveSessionId:n,createNewSession:b,sendMessage:L,deleteSession:T,getActiveSession:_}=B(),{userProfile:c}=z(),[m,P]=o.useState(""),[i,g]=o.useState(""),[y,j]=o.useState(!1),x=o.useRef(null),h=o.useRef(!0),u=o.useRef(!1),d=_(),p=d?.messages||[],E=p.some(t=>t.sender==="ai"&&t.id.startsWith("stream-")),v=l&&a===A&&!E,w=(t="auto")=>{const s=x.current;s&&s.scrollTo({top:s.scrollHeight,behavior:t})},M=()=>{const t=x.current;return t?t.scrollHeight-t.scrollTop-t.clientHeight<=120:!0},R=()=>{h.current=M()};o.useEffect(()=>{F(async()=>{const{warmupBackend:t}=await import("./index-CR5aYAL9.js").then(s=>s.b6);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)})},[]),o.useEffect(()=>{if(!h.current)return;const t=window.requestAnimationFrame(()=>w("auto"));return()=>window.cancelAnimationFrame(t)},[p,v]),o.useEffect(()=>{h.current=!0,w("auto")},[a]);const N=async()=>{if(!(!i.trim()||l||y||u.current)){u.current=!0,j(!0);try{let t=a;t||(t=b(),n(t));const s=i.trim();g(""),await L(t,s)}finally{u.current=!1,j(!1)}}},k=()=>{const t=b();n(t)},$=(t,s)=>{s.stopPropagation(),T(t)},f=r.filter(t=>t.title.toLowerCase().includes(m.toLowerCase())||t.preview.toLowerCase().includes(m.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:`${a?"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:k,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(Y,{size:14}),"New Chat"]})]}),e.jsxs("div",{className:"relative mt-3",children:[e.jsx(G,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500",size:14}),e.jsx(I,{type:"text",placeholder:"Search conversations...",value:m,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:[f.length," Conversations"]})}),e.jsx(S,{children:f.map(t=>e.jsxs(C.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 ${a===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 ${a===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 ${a===t.id?"bg-sky-100 text-sky-600":"bg-[#dde3eb] text-[#5a6578]"}`,children:[t.messageCount," msgs"]})]})]},t.id))}),f.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:`${a?"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:a?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(W,{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:x,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(S,{children:p.map(t=>e.jsxs(C.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(H,{children:t.text}),e.jsx("p",{className:`text-[10px] mt-1.5 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:J(t.timestamp)})]}),t.sender==="user"&&e.jsx(D,{src:c?.photo,name:c?.name,gender:c?.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(I,{type:"text",value:i,onChange:t=>g(t.target.value),onKeyPress:t=>t.key==="Enter"&&N(),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:N,disabled:!i.trim()||l||y,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(q,{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:k,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{he as default}; diff --git a/assets/AdminDashboard-BGOkExie.js b/assets/AdminDashboard-DY4v_Yug.js similarity index 98% rename from assets/AdminDashboard-BGOkExie.js rename to assets/AdminDashboard-DY4v_Yug.js index 1f521d35084c7f547c4fcc7bc56bbd4eae9b3f60..2e45d287c007c4ab29de2ab9d7078a73deee724f 100644 --- a/assets/AdminDashboard-BGOkExie.js +++ b/assets/AdminDashboard-DY4v_Yug.js @@ -1,4 +1,4 @@ -import{j as e,r as l,d as ys}from"./vendor-react-B4AQeu28.js";import{C as at,S as Bs}from"./Sidebar-DAee_vGE.js";import lt from"./ConfirmModal-BDSADafu.js";import{e as ve,n as Me,g as O,l as ke,j as N,h as Lt,m as re,p as V,R as Pe,N as Ut,r as ks,O as It,P as Ft,o as rt,u as ns,L as it,S as Ss,x as nt,v as De,U as Ie,G as rs,i as _t,Q as Gs,V as qs,W as Hs,q as Ot,A as Ws,Z as Fe,X as Bt,B as Gt,T as ct,b as qe,F as qt,Y as Ht,$ as Wt,D as Vt,M as Xt,J as Qt}from"./index-BYG24j30.js";import{B as k}from"./button-LR_FKM7p.js";import{S as Z,a as ee,b as Le,c as se,d as w}from"./select-DM5m46Pk.js";import{I as xe}from"./input-CtjqQUbX.js";import{S as as}from"./subjects-CnMsFeDX.js";import{getDocs as H,query as Re,collection as B,orderBy as He,deleteDoc as Kt,doc as Yt,limit as is,where as Cs,addDoc as Jt,serverTimestamp as Zt}from"./vendor-firebase-firestore-CNv3xXal.js";import{U as Je}from"./upload-z5a73neo.js";import{D as fe}from"./LogoutActionButton-U0Q7JjxX.js";import{F as Se,A as _e,I as ot,N as ea}from"./NotificationDropdown-vpdHjkTB.js";import{T as je}from"./trash-2-Bz07bxtW.js";import{S as Vs}from"./sparkles-DiaNugT9.js";import{S as Xs,D as dt,a as xt,b as mt,c as pt,e as sa}from"./dialog-H4V35jbm.js";import{D as Ds}from"./download-DRtqT_j8.js";import{S as As}from"./shield-check-CoyMgFec.js";import{S as ht}from"./search-qXpo6Bz-.js";import{C as zs}from"./clock-CGFFx3Yv.js";import{E as ut,a as ta}from"./eye-Cjs8eHiG.js";import{C as gt}from"./chevron-left-CIE_NDv7.js";import{C as bt}from"./chevron-right-CF79oTk8.js";import{C as ze}from"./circle-alert-D1BZWAsh.js";import{C as aa,a as la}from"./vendor-radix-BPuEd8FG.js";import{C as ra}from"./check-C-Jb6xS0.js";import{M as ia}from"./mail-B8qfL-UK.js";import{P as Qs}from"./plus-C5IM0tm0.js";import{S as ft}from"./save-DidAD_jg.js";import{C as na}from"./chart-column-BOgIfbES.js";import{u as ca}from"./useQuery-C5wg1Gx-.js";import{X as Ps}from"./x-DU8WEZ6X.js";import{D as oa}from"./dollar-sign-CFYvEMYD.js";import{S as da}from"./switch-CqM6p44O.js";import{u as xa,t as ma,a as pa}from"./useSubjectAvailability-CNwO6mr3.js";import{C as ha}from"./circle-help-BYya03qM.js";import{B as ua}from"./bell-CJfHcVLS.js";import{R as Ks,B as ga,C as ba,X as fa,Y as ja,T as va,a as Ys,P as wa,d as Na,b as Js}from"./vendor-charts-CAmziV1y.js";import{C as vs}from"./circle-check-_6J4FrSd.js";import"./tooltip-B8dZx5CM.js";import"./shirt-DhJu64M2.js";import"./log-out-7LnFvNg-.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"./chevron-up-vEHTl-in.js";import"./formatDistanceToNow-C9WeR9GV.js";/** +import{j as e,r as l,d as ys}from"./vendor-react-B4AQeu28.js";import{C as at,S as Bs}from"./Sidebar-DPdujCJv.js";import lt from"./ConfirmModal-BVHZuXaM.js";import{e as ve,n as Me,g as O,l as ke,j as N,h as Lt,m as re,p as V,R as Pe,N as Ut,r as ks,O as It,P as Ft,o as rt,u as ns,L as it,S as Ss,x as nt,v as De,U as Ie,G as rs,i as _t,Q as Gs,V as qs,W as Hs,q as Ot,A as Ws,Z as Fe,X as Bt,B as Gt,T as ct,b as qe,F as qt,Y as Ht,$ as Wt,D as Vt,M as Xt,J as Qt}from"./index-CR5aYAL9.js";import{B as k}from"./button-CbtAHv27.js";import{S as Z,a as ee,b as Le,c as se,d as w}from"./select-DMAe8pN9.js";import{I as xe}from"./input-DgZjxAsx.js";import{S as as}from"./subjects-CruSaBwq.js";import{getDocs as H,query as Re,collection as B,orderBy as He,deleteDoc as Kt,doc as Yt,limit as is,where as Cs,addDoc as Jt,serverTimestamp as Zt}from"./vendor-firebase-firestore-CNv3xXal.js";import{U as Je}from"./upload-Dv-dcZHV.js";import{D as fe}from"./LogoutActionButton-tEi5DIaj.js";import{F as Se,A as _e,I as ot,N as ea}from"./NotificationDropdown-DBksmA1S.js";import{T as je}from"./trash-2-BtGasoad.js";import{S as Vs}from"./sparkles-Df420Y_c.js";import{S as Xs,D as dt,a as xt,b as mt,c as pt,e as sa}from"./dialog-BhXeykx9.js";import{D as Ds}from"./download-teQqHQmt.js";import{S as As}from"./shield-check-CuuwgPnV.js";import{S as ht}from"./search-1a4wCp_r.js";import{C as zs}from"./clock-BF2L28Gg.js";import{E as ut,a as ta}from"./eye-BuiZU-wn.js";import{C as gt}from"./chevron-left-Buq4JTY_.js";import{C as bt}from"./chevron-right-d9v3XH9Z.js";import{C as ze}from"./circle-alert-CSWToxPb.js";import{C as aa,a as la}from"./vendor-radix-BPuEd8FG.js";import{C as ra}from"./check-MAu_C8ty.js";import{M as ia}from"./mail-sfPSTvMi.js";import{P as Qs}from"./plus-Cp5Q-YTc.js";import{S as ft}from"./save-BpEMiY1d.js";import{C as na}from"./chart-column-nZ0JrvMi.js";import{u as ca}from"./useQuery-CFyiy_x4.js";import{X as Ps}from"./x-DiyyYv8Q.js";import{D as oa}from"./dollar-sign-a1mi5_q1.js";import{S as da}from"./switch-DI6PCkYC.js";import{u as xa,t as ma,a as pa}from"./useSubjectAvailability-SVKjmUD3.js";import{C as ha}from"./circle-help-CS95sLmI.js";import{B as ua}from"./bell-DVzATilo.js";import{R as Ks,B as ga,C as ba,X as fa,Y as ja,T as va,a as Ys,P as wa,d as Na,b as Js}from"./vendor-charts-CAmziV1y.js";import{C as vs}from"./circle-check--_-gyncR.js";import"./tooltip-COrnGY4E.js";import"./shirt-DT9OZcT1.js";import"./log-out-BT_ShBSM.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"./chevron-up-BrrK8Cng.js";import"./formatDistanceToNow-B4dD00jc.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/AssessmentPage-BRsvq8VI.js b/assets/AssessmentPage-DhcG3TWJ.js similarity index 96% rename from assets/AssessmentPage-BRsvq8VI.js rename to assets/AssessmentPage-DhcG3TWJ.js index 25097b36986a05a6cab65d7d9546be83f141f785..e8633abfd75d3ceab8fc001df319a0176620ffda 100644 --- a/assets/AssessmentPage-BRsvq8VI.js +++ b/assets/AssessmentPage-DhcG3TWJ.js @@ -1,4 +1,4 @@ -import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as Q}from"./button-LR_FKM7p.js";import{s as Y}from"./diagnosticService-DGOeuGMt.js";import{e as J,m as i,Z as O,h as U,T as Z,E as G,q as H}from"./index-BYG24j30.js";import{M as W}from"./maximize-2-7OlWKBmu.js";import{X}from"./x-DU8WEZ6X.js";import{C as K}from"./clock-CGFFx3Yv.js";import{C as V}from"./circle-check-big-uJgj_456.js";import{C as ee}from"./chevron-right-CF79oTk8.js";import"./vendor-radix-BPuEd8FG.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";/** +import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as Q}from"./button-CbtAHv27.js";import{s as Y}from"./diagnosticService-C3w1VDru.js";import{e as J,m as i,Z as O,h as U,T as Z,E as G,q as H}from"./index-CR5aYAL9.js";import{M as W}from"./maximize-2-DtyTSFtD.js";import{X}from"./x-DiyyYv8Q.js";import{C as K}from"./clock-BF2L28Gg.js";import{C as V}from"./circle-check-big-CWD8eO1a.js";import{C as ee}from"./chevron-right-d9v3XH9Z.js";import"./vendor-radix-BPuEd8FG.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";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/AvatarShop-CiwigxhN.js b/assets/AvatarShop-1g2VJnfQ.js similarity index 97% rename from assets/AvatarShop-CiwigxhN.js rename to assets/AvatarShop-1g2VJnfQ.js index b55eba2eba38931f7ba31d31978adac6771d0157..3f7c3bcc95eccd5e3e8aa04eb50c83e439e07006 100644 --- a/assets/AvatarShop-CiwigxhN.js +++ b/assets/AvatarShop-1g2VJnfQ.js @@ -1,4 +1,4 @@ -import{r as i,j as e}from"./vendor-react-B4AQeu28.js";import{e as se,L as ae,g as re,f as oe}from"./vendor-radix-BPuEd8FG.js";import{e as S,u as le,L as w,a4 as R,m as y,h as ie,j as c,aM as ne,aN as ce}from"./index-BYG24j30.js";import{u as de}from"./useFeatureAccess-BqmsqlKE.js";import{T as me,a as ue,b as xe}from"./tooltip-B8dZx5CM.js";import{C as pe}from"./CompositeAvatar-Col05lJc.js";import{M as j}from"./avatarData-BuQSOXo3.js";import{S as O}from"./save-DidAD_jg.js";import{S as V}from"./sparkles-DiaNugT9.js";import{S as fe}from"./shirt-DhJu64M2.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 i,j as e}from"./vendor-react-B4AQeu28.js";import{e as se,L as ae,g as re,f as oe}from"./vendor-radix-BPuEd8FG.js";import{e as S,u as le,L as w,a4 as R,m as y,h as ie,j as c,aM as ne,aN as ce}from"./index-CR5aYAL9.js";import{u as de}from"./useFeatureAccess-DCme1VYw.js";import{T as me,a as ue,b as xe}from"./tooltip-COrnGY4E.js";import{C as pe}from"./CompositeAvatar-Col05lJc.js";import{M as j}from"./avatarData-BuQSOXo3.js";import{S as O}from"./save-BpEMiY1d.js";import{S as V}from"./sparkles-Df420Y_c.js";import{S as fe}from"./shirt-DT9OZcT1.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-Dn0t_isr.js b/assets/ChatMarkdown-kQBhTXf0.js similarity index 97% rename from assets/ChatMarkdown-Dn0t_isr.js rename to assets/ChatMarkdown-kQBhTXf0.js index de97f9dea40e0b44e0ebc06d62fe8a4719f21387..37ac89e694c3c58bcb24473ebf854f945656cd20 100644 --- a/assets/ChatMarkdown-Dn0t_isr.js +++ b/assets/ChatMarkdown-kQBhTXf0.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{b4 as d,_ as c}from"./index-BYG24j30.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-BPuEd8FG.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{b4 as d,_ as c}from"./index-CR5aYAL9.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-BPuEd8FG.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-wJLEa8V5.js b/assets/CompetencyRadarChart-DMNMZ6Ga.js similarity index 97% rename from assets/CompetencyRadarChart-wJLEa8V5.js rename to assets/CompetencyRadarChart-DMNMZ6Ga.js index cb067b948ab1b3bb8adccaa64f9895014567c83c..85fb6a5ffef85aa99e4c29ab8e844c18d40b1891 100644 --- a/assets/CompetencyRadarChart-wJLEa8V5.js +++ b/assets/CompetencyRadarChart-DMNMZ6Ga.js @@ -1 +1 @@ -import{r as g,j as t}from"./vendor-react-B4AQeu28.js";import{g as A,ab as I,u as B,m as L,B as O,R as W,b as H}from"./index-BYG24j30.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-CnMsFeDX.js";import{S as Z}from"./sparkles-DiaNugT9.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-BPuEd8FG.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-BOgIfbES.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,ab as I,u as B,m as L,B as O,R as W,b as H}from"./index-CR5aYAL9.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-CruSaBwq.js";import{S as Z}from"./sparkles-Df420Y_c.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-BPuEd8FG.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-nZ0JrvMi.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-BDSADafu.js b/assets/ConfirmModal-BVHZuXaM.js similarity index 91% rename from assets/ConfirmModal-BDSADafu.js rename to assets/ConfirmModal-BVHZuXaM.js index f07ed0eaf79b80fe8cbfc625b68726d20011d39b..bbaa9d803f4e1e1b93d4f27d358d6eaf5b0c58b7 100644 --- a/assets/ConfirmModal-BDSADafu.js +++ b/assets/ConfirmModal-BVHZuXaM.js @@ -1 +1 @@ -import{j as e}from"./vendor-react-B4AQeu28.js";import{B as i}from"./button-LR_FKM7p.js";import{h as u,m as r,x as f}from"./index-BYG24j30.js";import{X as y}from"./x-DU8WEZ6X.js";import{T as j}from"./trash-2-Bz07bxtW.js";import{L as w}from"./log-out-7LnFvNg-.js";import"./vendor-radix-BPuEd8FG.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:x="warning",icon:m="warning",zIndexClass:g="z-50"})=>{const b=()=>{switch(m){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(x){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-CbtAHv27.js";import{h as u,m as r,x as f}from"./index-CR5aYAL9.js";import{X as y}from"./x-DiyyYv8Q.js";import{T as j}from"./trash-2-BtGasoad.js";import{L as w}from"./log-out-BT_ShBSM.js";import"./vendor-radix-BPuEd8FG.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:x="warning",icon:m="warning",zIndexClass:g="z-50"})=>{const b=()=>{switch(m){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(x){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-DMdwTTKX.js b/assets/DiagnosticBreakdown-lTfPVQ3_.js similarity index 97% rename from assets/DiagnosticBreakdown-DMdwTTKX.js rename to assets/DiagnosticBreakdown-lTfPVQ3_.js index 271fe54fdb6680a20cd8dee74c69a7d75c93b9e9..f5a09b90790dd69f59f5abdd8a1b0fb5583696ab 100644 --- a/assets/DiagnosticBreakdown-DMdwTTKX.js +++ b/assets/DiagnosticBreakdown-lTfPVQ3_.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,v as Z,B as H,Z as J,x as C,T as W,q as S,m,h as Y}from"./index-BYG24j30.js";import{X as G}from"./x-DU8WEZ6X.js";import{C as q}from"./clock-CGFFx3Yv.js";import{L as A,C as K}from"./lightbulb-C6VPAE81.js";import{C as T}from"./circle-check-_6J4FrSd.js";import{C as D}from"./chart-column-BOgIfbES.js";import{a as O,C as V}from"./chevron-up-vEHTl-in.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-BPuEd8FG.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 N=t.testId;let v={};if(N){const l=await y(_(k,"diagnosticSessions",N));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)}},b=o.filter(s=>s.is_correct).length,n=o.length,u=o.reduce((s,t)=>s+t.time_spent_seconds,0),F=n>0?Math.round(u/n):0,I=n>0?Math.round(b/n*100):0;if(!c)return null;const f=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:"sticky top-0 z-10 bg-white/80 backdrop-blur-xl 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:[b,"/",n," correct"]})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(q,{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 shadow-sm",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(u/60),"m ",u%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 shadow-sm",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 shadow-sm 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(A,{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(q,{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(T,{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(A,{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 shadow-sm 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 shadow-sm 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(T,{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 backdrop-blur-sm flex items-center justify-center p-4",onClick:p,children:e.jsx(m.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[90vh] overflow-y-auto",onClick:s=>s.stopPropagation(),children:f})})}):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:f})};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,v as Z,B as H,Z as J,x as C,T as W,q as S,m,h as Y}from"./index-CR5aYAL9.js";import{X as G}from"./x-DiyyYv8Q.js";import{C as q}from"./clock-BF2L28Gg.js";import{L as A,C as K}from"./lightbulb-CRrzx6iX.js";import{C as T}from"./circle-check--_-gyncR.js";import{C as D}from"./chart-column-nZ0JrvMi.js";import{a as O,C as V}from"./chevron-up-BrrK8Cng.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-BPuEd8FG.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 N=t.testId;let v={};if(N){const l=await y(_(k,"diagnosticSessions",N));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)}},b=o.filter(s=>s.is_correct).length,n=o.length,u=o.reduce((s,t)=>s+t.time_spent_seconds,0),F=n>0?Math.round(u/n):0,I=n>0?Math.round(b/n*100):0;if(!c)return null;const f=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:"sticky top-0 z-10 bg-white/80 backdrop-blur-xl 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:[b,"/",n," correct"]})]}),e.jsxs("div",{className:"bg-white rounded-2xl p-5 border border-slate-100 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(q,{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 shadow-sm",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(u/60),"m ",u%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 shadow-sm",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 shadow-sm 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(A,{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(q,{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(T,{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(A,{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 shadow-sm 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 shadow-sm 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(T,{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 backdrop-blur-sm flex items-center justify-center p-4",onClick:p,children:e.jsx(m.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[90vh] overflow-y-auto",onClick:s=>s.stopPropagation(),children:f})})}):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:f})};export{ge as default}; diff --git a/assets/FloatingAITutor-C6E9qFVh.js b/assets/FloatingAITutor-DpWLWA30.js similarity index 94% rename from assets/FloatingAITutor-C6E9qFVh.js rename to assets/FloatingAITutor-DpWLWA30.js index 1542d15d934df6d071bc128cedc545145393ad57..b4a835810ec7de3d9ec1cda5443d80976662c186 100644 --- a/assets/FloatingAITutor-C6E9qFVh.js +++ b/assets/FloatingAITutor-DpWLWA30.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatMarkdown-Dn0t_isr.js","assets/index-BYG24j30.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); -import{aE as C,_ as y,m as b,I as A}from"./index-BYG24j30.js";import{r as i,j as e}from"./vendor-react-B4AQeu28.js";import{M}from"./maximize-2-7OlWKBmu.js";import{M as w}from"./minus-sZ1MmK-H.js";import{X as g}from"./x-DU8WEZ6X.js";import{S as L}from"./send-Cs_bBaZx.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const E=i.lazy(()=>y(()=>import("./ChatMarkdown-Dn0t_isr.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])));function O(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 Q=({constraintsRef:a,onFullScreen:j})=>{const{activeSessionId:r,setActiveSessionId:v,createNewSession:N,getActiveSession:k,sendMessage:I,isLoading:o}=C(),[s,l]=i.useState(!1),[c,u]=i.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("floating_ai_tutor_minimized")==="1"),[n,m]=i.useState(""),h=i.useRef(null);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem("floating_ai_tutor_minimized",c?"1":"0")},[c]),i.useEffect(()=>{s&&y(async()=>{const{warmupBackend:t}=await import("./index-BYG24j30.js").then(d=>d.b6);return{warmupBackend:t}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({warmupBackend:t})=>{t()}).catch(t=>{console.warn("Floating tutor warmup skipped:",t)})},[s]),i.useEffect(()=>{if(s&&!r){const t={id:"1",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"})},d=N(t);v(d)}},[s]);const x=k()?.messages||[],S=()=>{h.current?.scrollIntoView({behavior:"smooth"})};i.useEffect(()=>{S()},[x]);const p=async()=>{if(!n.trim()||!r||o)return;const t=n.trim();m(""),await I(r,t)},_=()=>{j()},f=()=>{l(!1),u(!0)},z=()=>{u(!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 ${s?"opacity-100 scale-100 translate-y-0":"opacity-0 scale-95 translate-y-10 pointer-events-none h-0"}`,style:{"--max-h":s?"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:_,type:"button","aria-label":"Open fullscreen",className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Open fullscreen",children:e.jsx(M,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",onClick:f,className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Minimize",children:e.jsx(w,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Close chat",onClick:()=>l(!1),className:"p-2 hover:bg-white/20 rounded-lg transition-colors",children:e.jsx(g,{size:16,className:"text-white"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 bg-[#edf1f7]",children:[x.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(i.Suspense,{fallback:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.text}),children:e.jsx(E,{children:t.text})}),e.jsx("p",{className:`text-[10px] mt-1 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:O(t.timestamp)})]})},t.id)),o&&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:h})]}),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:n,onChange:t=>m(t.target.value),onKeyPress:t=>t.key==="Enter"&&p(),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:p,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:!n.trim()||o,children:e.jsx(L,{size:18})})]})})]}),e.jsx("div",{className:"pointer-events-auto relative self-end",children:c?e.jsx(b.button,{type:"button",onClick:z,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(A,{size:14})}):e.jsxs("div",{className:"relative group",children:[!s&&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"})]}),!s&&e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",title:"Minimize",onClick:f,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(w,{size:12})}),e.jsx(b.button,{type:"button",onClick:()=>l(!s),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":s?"Close AI tutor chat":"Open AI tutor chat",style:{willChange:"transform"},children:s?e.jsx(g,{size:28}):e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-14 h-14 object-contain drop-shadow-lg"})})]})})]})};export{Q as default}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatMarkdown-kQBhTXf0.js","assets/index-CR5aYAL9.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); +import{aE as C,_ as y,m as b,I as A}from"./index-CR5aYAL9.js";import{r as i,j as e}from"./vendor-react-B4AQeu28.js";import{M}from"./maximize-2-DtyTSFtD.js";import{M as w}from"./minus-D8MfEHLl.js";import{X as g}from"./x-DiyyYv8Q.js";import{S as L}from"./send-B1wbvsc_.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const E=i.lazy(()=>y(()=>import("./ChatMarkdown-kQBhTXf0.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])));function O(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 Q=({constraintsRef:a,onFullScreen:j})=>{const{activeSessionId:r,setActiveSessionId:v,createNewSession:N,getActiveSession:k,sendMessage:I,isLoading:o}=C(),[s,l]=i.useState(!1),[c,u]=i.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("floating_ai_tutor_minimized")==="1"),[n,m]=i.useState(""),h=i.useRef(null);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem("floating_ai_tutor_minimized",c?"1":"0")},[c]),i.useEffect(()=>{s&&y(async()=>{const{warmupBackend:t}=await import("./index-CR5aYAL9.js").then(d=>d.b6);return{warmupBackend:t}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({warmupBackend:t})=>{t()}).catch(t=>{console.warn("Floating tutor warmup skipped:",t)})},[s]),i.useEffect(()=>{if(s&&!r){const t={id:"1",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"})},d=N(t);v(d)}},[s]);const x=k()?.messages||[],S=()=>{h.current?.scrollIntoView({behavior:"smooth"})};i.useEffect(()=>{S()},[x]);const p=async()=>{if(!n.trim()||!r||o)return;const t=n.trim();m(""),await I(r,t)},_=()=>{j()},f=()=>{l(!1),u(!0)},z=()=>{u(!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 ${s?"opacity-100 scale-100 translate-y-0":"opacity-0 scale-95 translate-y-10 pointer-events-none h-0"}`,style:{"--max-h":s?"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:_,type:"button","aria-label":"Open fullscreen",className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Open fullscreen",children:e.jsx(M,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",onClick:f,className:"p-2 hover:bg-white/20 rounded-lg transition-colors",title:"Minimize",children:e.jsx(w,{size:16,className:"text-white"})}),e.jsx("button",{type:"button","aria-label":"Close chat",onClick:()=>l(!1),className:"p-2 hover:bg-white/20 rounded-lg transition-colors",children:e.jsx(g,{size:16,className:"text-white"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 bg-[#edf1f7]",children:[x.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(i.Suspense,{fallback:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.text}),children:e.jsx(E,{children:t.text})}),e.jsx("p",{className:`text-[10px] mt-1 ${t.sender==="user"?"text-sky-200":"text-slate-500"}`,children:O(t.timestamp)})]})},t.id)),o&&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:h})]}),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:n,onChange:t=>m(t.target.value),onKeyPress:t=>t.key==="Enter"&&p(),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:p,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:!n.trim()||o,children:e.jsx(L,{size:18})})]})})]}),e.jsx("div",{className:"pointer-events-auto relative self-end",children:c?e.jsx(b.button,{type:"button",onClick:z,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(A,{size:14})}):e.jsxs("div",{className:"relative group",children:[!s&&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"})]}),!s&&e.jsx("button",{type:"button","aria-label":"Minimize AI tutor launcher",title:"Minimize",onClick:f,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(w,{size:12})}),e.jsx(b.button,{type:"button",onClick:()=>l(!s),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":s?"Close AI tutor chat":"Open AI tutor chat",style:{willChange:"transform"},children:s?e.jsx(g,{size:28}):e.jsx("img",{src:"/avatar/avatar_icon.png",alt:"AI Tutor",className:"w-14 h-14 object-contain drop-shadow-lg"})})]})})]})};export{Q as default}; diff --git a/assets/GradesPage-DFzgWMGj.js b/assets/GradesPage-D7AMuxL8.js similarity index 95% rename from assets/GradesPage-DFzgWMGj.js rename to assets/GradesPage-D7AMuxL8.js index cf0e96b23080da4105e87387572ffad0bc32401c..2f1080d99d8b165af97b9a60f513512217e0b5d5 100644 --- a/assets/GradesPage-DFzgWMGj.js +++ b/assets/GradesPage-D7AMuxL8.js @@ -1,3 +1,3 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiagnosticBreakdown-DMdwTTKX.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/index-BYG24j30.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css","assets/x-DU8WEZ6X.js","assets/clock-CGFFx3Yv.js","assets/lightbulb-C6VPAE81.js","assets/circle-check-_6J4FrSd.js","assets/chart-column-BOgIfbES.js","assets/chevron-up-vEHTl-in.js"])))=>i.map(i=>d[i]); -import{u as se,aF as te,aG as ae,g as P,F as re,A as le,q as M,T as $,B as ne,_ as oe}from"./index-BYG24j30.js";import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as N}from"./button-LR_FKM7p.js";import{g as ie,S as B}from"./subjects-CnMsFeDX.js";import{u as de}from"./useCurriculum-BCsJVZ1p.js";import{getDoc as F,doc as G}from"./vendor-firebase-firestore-CNv3xXal.js";import{D as ce}from"./download-DRtqT_j8.js";import{C as me}from"./circle-check-_6J4FrSd.js";import{C as xe}from"./circle-alert-D1BZWAsh.js";import{F as Q}from"./funnel-CkgPZM71.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-BOgIfbES.js";const pe=r.lazy(()=>oe(()=>import("./DiagnosticBreakdown-DMdwTTKX.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]))),Ee=()=>{const{currentUser:l,userProfile:y}=se(),[d,S]=r.useState("all"),[x,O]=r.useState("all"),[I,h]=r.useState(!0),[b,U]=r.useState(null),[H,V]=r.useState([]),[n,k]=r.useState(null),[_,g]=r.useState(!1),A=y?.grade,C=ie(A),T=new Set(C),{isLoading:Y}=de(A);r.useEffect(()=>{},[Y]);const K=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]};r.useEffect(()=>{if(!l)return;h(!0);const s=te(l.uid,a=>{U(a),h(!1)}),t=ae(l.uid,a=>{V(a),h(!1)});return()=>{s(),t()}},[l]),r.useEffect(()=>{l?.uid&&(async()=>{try{const s=await F(G(P,"users",l.uid,"dashboardSummary","heroBannerModal"));if(s.exists()){const a=s.data();if(a.status==="ready"){k({score:a.latestScorePercent||0,riskLevel:a.latestRiskLevel||"Unknown",weaknesses:a.weaknesses||[],recommendation:a.recommendation||""});return}}const t=await F(G(P,"users",l.uid));if(t.exists()){const a=t.data();(a.initialAssessmentCompleted||a.hasCompletedInitialAssessment)&&k({score:0,riskLevel:a.atRiskSubjects?.length>0?"Moderate":"Low",weaknesses:a.atRiskSubjects||[],recommendation:"Continue with your personalized learning path."})}}catch{}})()},[l?.uid]);const f=b?.averageScore?Math.round(b.averageScore):0,J=b?.quizzesCompleted??0,W=f>0?(f/100*4).toFixed(2):"0.00",X={"gen-math":"indigo","stats-prob":"violet"},L={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"}},R=B.reduce((s,t)=>(s[t.id]={label:t.name,color:X[t.id]||"slate"},s),{}),c=B.filter(s=>T.has(s.id)).map(s=>s.name),E=Object.entries({}).filter(([s])=>T.has(s)).map(([s,t])=>{const a=R[s]||{label:s,color:"slate"},i=[],j=i.length>0?Math.round(i.reduce((w,u)=>w+u.score,0)/i.length):Math.round(t?.progress??0);return{subject:a.label,average:j,quizzes:i.length||t?.completedModules,color:a.color}}),Z=C.map(s=>{const t=R[s]||{label:s,color:"slate"};return{subject:t.label,average:0,quizzes:0,color:t.color}}),z=E.length>0?E:Z,D=H.slice().sort((s,t)=>{const a=s.completedAt?.toDate?.()?.getTime()??0;return(t.completedAt?.toDate?.()?.getTime()??0)-a}).slice(0,10).map((s,t)=>({id:t+1,title:s.title||`Assessment ${t+1}`,subject:s.subject||"General",score:s.score,date:s.completedAt?K(s.completedAt.toDate()):"N/A",type:s.type==="practice"?"practice":(s.type==="diagnostic","module"),status:s.score>=80?"Excellent":s.score>=60?"Passing":"Needs Review"})).filter(s=>c.includes(s.subject)),p=D.filter(s=>{if(!c.includes(s.subject))return!1;const t=d==="all"||s.subject===d,a=x==="all"||s.type===x;return t&&a});r.useEffect(()=>{d!=="all"&&(c.includes(d)||S("all"))},[c,d]);const q=()=>{const s=o=>{const v=String(o??"");return/[",\n]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},t=[],a=y?.name||l?.displayName||l?.email||"Student",i=new Date().toISOString().split("T")[0];t.push("Grade Report"),t.push(`Student,${s(a)}`),t.push(`Export Date,${s(i)}`),t.push(`Subject Filter,${s(d)}`),t.push(`Type Filter,${s(x)}`),t.push(""),t.push("Subject Performance"),t.push("Subject,Average Score"),z.forEach(o=>{t.push([s(o.subject),s(o.average)].join(","))}),t.push(""),t.push("Recent Quizzes"),t.push("Title,Subject,Score,Date,Type,Status"),p.length===0?t.push("No quiz data available for the selected filters"):p.forEach(o=>{t.push([s(o.title),s(o.subject),s(o.score),s(o.date),s(o.type),s(o.status)].join(","))});const j=t.join(` +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiagnosticBreakdown-lTfPVQ3_.js","assets/vendor-react-B4AQeu28.js","assets/vendor-firebase-firestore-CNv3xXal.js","assets/vendor-firebase-core-D7GXCeNu.js","assets/index-CR5aYAL9.js","assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-storage-Bi7H_66d.js","assets/vendor-firebase-analytics-rHarj5hR.js","assets/vendor-radix-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css","assets/x-DiyyYv8Q.js","assets/clock-BF2L28Gg.js","assets/lightbulb-CRrzx6iX.js","assets/circle-check--_-gyncR.js","assets/chart-column-nZ0JrvMi.js","assets/chevron-up-BrrK8Cng.js"])))=>i.map(i=>d[i]); +import{u as se,aF as te,aG as ae,g as P,F as re,A as le,q as M,T as $,B as ne,_ as oe}from"./index-CR5aYAL9.js";import{r,j as e}from"./vendor-react-B4AQeu28.js";import{B as N}from"./button-CbtAHv27.js";import{g as ie,S as B}from"./subjects-CruSaBwq.js";import{u as de}from"./useCurriculum-BQeS3LyA.js";import{getDoc as F,doc as G}from"./vendor-firebase-firestore-CNv3xXal.js";import{D as ce}from"./download-teQqHQmt.js";import{C as me}from"./circle-check--_-gyncR.js";import{C as xe}from"./circle-alert-CSWToxPb.js";import{F as Q}from"./funnel-nXEzWYRv.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chart-column-nZ0JrvMi.js";const pe=r.lazy(()=>oe(()=>import("./DiagnosticBreakdown-lTfPVQ3_.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]))),Ee=()=>{const{currentUser:l,userProfile:y}=se(),[d,S]=r.useState("all"),[x,O]=r.useState("all"),[I,h]=r.useState(!0),[b,U]=r.useState(null),[H,V]=r.useState([]),[n,k]=r.useState(null),[_,g]=r.useState(!1),A=y?.grade,C=ie(A),T=new Set(C),{isLoading:Y}=de(A);r.useEffect(()=>{},[Y]);const K=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]};r.useEffect(()=>{if(!l)return;h(!0);const s=te(l.uid,a=>{U(a),h(!1)}),t=ae(l.uid,a=>{V(a),h(!1)});return()=>{s(),t()}},[l]),r.useEffect(()=>{l?.uid&&(async()=>{try{const s=await F(G(P,"users",l.uid,"dashboardSummary","heroBannerModal"));if(s.exists()){const a=s.data();if(a.status==="ready"){k({score:a.latestScorePercent||0,riskLevel:a.latestRiskLevel||"Unknown",weaknesses:a.weaknesses||[],recommendation:a.recommendation||""});return}}const t=await F(G(P,"users",l.uid));if(t.exists()){const a=t.data();(a.initialAssessmentCompleted||a.hasCompletedInitialAssessment)&&k({score:0,riskLevel:a.atRiskSubjects?.length>0?"Moderate":"Low",weaknesses:a.atRiskSubjects||[],recommendation:"Continue with your personalized learning path."})}}catch{}})()},[l?.uid]);const f=b?.averageScore?Math.round(b.averageScore):0,J=b?.quizzesCompleted??0,W=f>0?(f/100*4).toFixed(2):"0.00",X={"gen-math":"indigo","stats-prob":"violet"},L={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"}},R=B.reduce((s,t)=>(s[t.id]={label:t.name,color:X[t.id]||"slate"},s),{}),c=B.filter(s=>T.has(s.id)).map(s=>s.name),E=Object.entries({}).filter(([s])=>T.has(s)).map(([s,t])=>{const a=R[s]||{label:s,color:"slate"},i=[],j=i.length>0?Math.round(i.reduce((w,u)=>w+u.score,0)/i.length):Math.round(t?.progress??0);return{subject:a.label,average:j,quizzes:i.length||t?.completedModules,color:a.color}}),Z=C.map(s=>{const t=R[s]||{label:s,color:"slate"};return{subject:t.label,average:0,quizzes:0,color:t.color}}),z=E.length>0?E:Z,D=H.slice().sort((s,t)=>{const a=s.completedAt?.toDate?.()?.getTime()??0;return(t.completedAt?.toDate?.()?.getTime()??0)-a}).slice(0,10).map((s,t)=>({id:t+1,title:s.title||`Assessment ${t+1}`,subject:s.subject||"General",score:s.score,date:s.completedAt?K(s.completedAt.toDate()):"N/A",type:s.type==="practice"?"practice":(s.type==="diagnostic","module"),status:s.score>=80?"Excellent":s.score>=60?"Passing":"Needs Review"})).filter(s=>c.includes(s.subject)),p=D.filter(s=>{if(!c.includes(s.subject))return!1;const t=d==="all"||s.subject===d,a=x==="all"||s.type===x;return t&&a});r.useEffect(()=>{d!=="all"&&(c.includes(d)||S("all"))},[c,d]);const q=()=>{const s=o=>{const v=String(o??"");return/[",\n]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},t=[],a=y?.name||l?.displayName||l?.email||"Student",i=new Date().toISOString().split("T")[0];t.push("Grade Report"),t.push(`Student,${s(a)}`),t.push(`Export Date,${s(i)}`),t.push(`Subject Filter,${s(d)}`),t.push(`Type Filter,${s(x)}`),t.push(""),t.push("Subject Performance"),t.push("Subject,Average Score"),z.forEach(o=>{t.push([s(o.subject),s(o.average)].join(","))}),t.push(""),t.push("Recent Quizzes"),t.push("Title,Subject,Score,Date,Type,Status"),p.length===0?t.push("No quiz data available for the selected filters"):p.forEach(o=>{t.push([s(o.title),s(o.subject),s(o.score),s(o.date),s(o.type),s(o.status)].join(","))});const j=t.join(` `),w=new Blob([j],{type:"text/csv;charset=utf-8;"}),u=window.URL.createObjectURL(w),m=document.createElement("a"),ee=a.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()||"student";m.href=u,m.setAttribute("download",`grade-report-${ee}-${i}.csv`),document.body.appendChild(m),m.click(),document.body.removeChild(m),window.URL.revokeObjectURL(u)};return I?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(N,{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(re,{className:"w-4 h-4 mr-2 text-slate-400"}),"This Quarter"]}),e.jsxs(N,{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:q,children:[e.jsx(ce,{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(le,{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:"GPA"}),e.jsx("span",{className:"hidden sm:inline",children:"Overall GPA"})]}),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:W})})]})]}),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(M,{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:"Avg Score"}),e.jsx("span",{className:"hidden sm:inline",children:"Average Score"})]}),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:[f,"%"]})})]})]}),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($,{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:J})})]})]})]}),n&&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:()=>g(!0),role:"button",tabIndex:0,onKeyDown:s=>{s.key==="Enter"&&g(!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(ne,{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 ${n.riskLevel==="Low"?"bg-emerald-100 text-emerald-700":n.riskLevel==="High"||n.riskLevel==="At Risk"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[n.riskLevel==="Low"?e.jsx(me,{size:12}):e.jsx(xe,{size:12}),n.riskLevel]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[n.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:[n.score,"%"]})]}),n.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:n.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))})]}),n.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:n.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:d,onChange:s=>S(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"}),c.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:x,onChange:s=>O(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:"module",children:"Module 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:p.length>0?p.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(M,{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:z.map((s,t)=>{const a=L[s.color]||L.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 ${a.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 ${a.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($,{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:D.length})," activities recently. Try a practice session to boost your lowest scores."]}),e.jsx(N,{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"})]})]})]})]}),_&&l?.uid&&e.jsx(r.Suspense,{fallback:null,children:e.jsx(pe,{userId:l.uid,mode:"modal",isOpen:_,onClose:()=>g(!1)})})]})};export{Ee as default}; diff --git a/assets/HeroBanner--aQVgKP1.js b/assets/HeroBanner-DGWA0f42.js similarity index 98% rename from assets/HeroBanner--aQVgKP1.js rename to assets/HeroBanner-DGWA0f42.js index dba2e0b7abc68b1b84befac16c911b185c93eccc..9cdc6ac169414f2d5840c57658a7ce5efbbff26f 100644 --- a/assets/HeroBanner--aQVgKP1.js +++ b/assets/HeroBanner-DGWA0f42.js @@ -1,3 +1,3 @@ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DashboardAvatar-CbAKGmA6.js","assets/vendor-react-B4AQeu28.js","assets/avatarData-BuQSOXo3.js"])))=>i.map(i=>d[i]); -import{T as R,g as b,a1 as M,h as _,m as f,a2 as E,A as G,B as S,q as z,Z as Y,a as F,_ as Q}from"./index-BYG24j30.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-H4V35jbm.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-DU8WEZ6X.js";import{C as H}from"./circle-alert-D1BZWAsh.js";import{C as se}from"./circle-check-_6J4FrSd.js";import{S as te}from"./sparkles-DiaNugT9.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-BPuEd8FG.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,a1 as M,h as _,m as f,a2 as E,A as G,B as S,q as z,Z as Y,a as F,_ as Q}from"./index-CR5aYAL9.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-BhXeykx9.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-DiyyYv8Q.js";import{C as H}from"./circle-alert-CSWToxPb.js";import{C as se}from"./circle-check--_-gyncR.js";import{S as te}from"./sparkles-Df420Y_c.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-BPuEd8FG.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-CbAKGmA6.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-BXrHaNxu.js b/assets/InitialAssessmentModal-BXyrazRg.js similarity index 94% rename from assets/InitialAssessmentModal-BXrHaNxu.js rename to assets/InitialAssessmentModal-BXyrazRg.js index a659bbb6caed6994faea60438d8db874a49fc45d..32caf1de25adf8f780b6a7a3bf77b0123005fbf5 100644 --- a/assets/InitialAssessmentModal-BXrHaNxu.js +++ b/assets/InitialAssessmentModal-BXyrazRg.js @@ -1 +1 @@ -import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{B as j}from"./button-LR_FKM7p.js";import{g as y}from"./diagnosticService-DGOeuGMt.js";import{updateDoc as N,doc as v,serverTimestamp as w}from"./vendor-firebase-firestore-CNv3xXal.js";import{m as o,B as k,x as C,p as L,g as z}from"./index-BYG24j30.js";import{X as S}from"./x-DU8WEZ6X.js";import{C as A}from"./circle-check-big-uJgj_456.js";import"./vendor-radix-BPuEd8FG.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-CbtAHv27.js";import{g as y}from"./diagnosticService-C3w1VDru.js";import{updateDoc as N,doc as v,serverTimestamp as w}from"./vendor-firebase-firestore-CNv3xXal.js";import{m as o,B as k,x as C,p as L,g as z}from"./index-CR5aYAL9.js";import{X as S}from"./x-DiyyYv8Q.js";import{C as A}from"./circle-check-big-CWD8eO1a.js";import"./vendor-radix-BPuEd8FG.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-BhhK2vnv.js b/assets/LeaderboardPage-DIBnra9H.js similarity index 99% rename from assets/LeaderboardPage-BhhK2vnv.js rename to assets/LeaderboardPage-DIBnra9H.js index 7c7f5dd317f009d607269609cf3116dbad26d1ac..be5938765af1cae6f9b042cff66fdce439027504 100644 --- a/assets/LeaderboardPage-BhhK2vnv.js +++ b/assets/LeaderboardPage-DIBnra9H.js @@ -1,4 +1,4 @@ -import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{e as O,aI as W,h as q,m as n,b as y,q as P,A as k,E as m,T as E,p as _,a4 as I,a5 as H,X as U,u as $,aJ as G,R as J,L as K,z as X}from"./index-BYG24j30.js";import{X as Q}from"./x-DU8WEZ6X.js";import{C as V}from"./clock-CGFFx3Yv.js";import{u as Z}from"./useFeatureAccess-BqmsqlKE.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-BPuEd8FG.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 O,aI as W,h as q,m as n,b as y,q as P,A as k,E as m,T as E,p as _,a4 as I,a5 as H,X as U,u as $,aJ as G,R as J,L as K,z as X}from"./index-CR5aYAL9.js";import{X as Q}from"./x-DiyyYv8Q.js";import{C as V}from"./clock-BF2L28Gg.js";import{u as Z}from"./useFeatureAccess-DCme1VYw.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-BPuEd8FG.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/LearningPath-6C1pnB-M.js b/assets/LearningPath-BkBmgh8H.js similarity index 91% rename from assets/LearningPath-6C1pnB-M.js rename to assets/LearningPath-BkBmgh8H.js index fb3cb5ba0e84f271a7c6a9bc97304937f05f6d79..b545b7f5cfd98538dfa58f1c8512b1c6c0af73f0 100644 --- a/assets/LearningPath-6C1pnB-M.js +++ b/assets/LearningPath-BkBmgh8H.js @@ -1 +1 @@ -import{r as p,d as g,j as r}from"./vendor-react-B4AQeu28.js";import{u as b,a9 as j,aa as N,y as k,b as P,a as I}from"./index-BYG24j30.js";import{M as v}from"./ModuleFolderCard-7StF4eM7.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./useSubjectAvailability-CNwO6mr3.js";import"./clock-CGFFx3Yv.js";const z=({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{z as default}; +import{r as p,d as g,j as r}from"./vendor-react-B4AQeu28.js";import{u as b,a9 as j,aa as N,y as k,b as P,a as I}from"./index-CR5aYAL9.js";import{M as v}from"./ModuleFolderCard-DaH-e6Ze.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./useSubjectAvailability-SVKjmUD3.js";import"./clock-BF2L28Gg.js";const z=({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{z as default}; diff --git a/assets/LoginPage-DKWs9ixZ.js b/assets/LoginPage-BLe3Cr5c.js similarity index 97% rename from assets/LoginPage-DKWs9ixZ.js rename to assets/LoginPage-BLe3Cr5c.js index e5490d1b132950974c8e444acb6afa1a873167ce..0096a0cf340c8c7cd240ac759d4c5aa7a143ae8f 100644 --- a/assets/LoginPage-DKWs9ixZ.js +++ b/assets/LoginPage-BLe3Cr5c.js @@ -1 +1 @@ -import{r as s,j as e}from"./vendor-react-B4AQeu28.js";import{B as je}from"./button-LR_FKM7p.js";import{I as L}from"./input-CtjqQUbX.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-BYG24j30.js";import{S as Me}from"./sparkles-DiaNugT9.js";import{M as Re}from"./mail-B8qfL-UK.js";import{E as Ce,a as Ee}from"./eye-Cjs8eHiG.js";import{S as Te}from"./shield-check-CoyMgFec.js";import"./vendor-radix-BPuEd8FG.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-CbtAHv27.js";import{I as L}from"./input-DgZjxAsx.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-CR5aYAL9.js";import{S as Me}from"./sparkles-Df420Y_c.js";import{M as Re}from"./mail-sfPSTvMi.js";import{E as Ce,a as Ee}from"./eye-BuiZU-wn.js";import{S as Te}from"./shield-check-CuuwgPnV.js";import"./vendor-radix-BPuEd8FG.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-U0Q7JjxX.js b/assets/LogoutActionButton-tEi5DIaj.js similarity index 94% rename from assets/LogoutActionButton-U0Q7JjxX.js rename to assets/LogoutActionButton-tEi5DIaj.js index fd821bf62199593b8b5b009b75e4cc8f84e93f54..5cf9e9c33609cb63f3f2c0e6b934f28d21bf9d11 100644 --- a/assets/LogoutActionButton-U0Q7JjxX.js +++ b/assets/LogoutActionButton-tEi5DIaj.js @@ -1,4 +1,4 @@ -import{e,m as r,n as l}from"./index-BYG24j30.js";import{j as t}from"./vendor-react-B4AQeu28.js";import{L as n}from"./log-out-7LnFvNg-.js";/** +import{e,m as r,n as l}from"./index-CR5aYAL9.js";import{j as t}from"./vendor-react-B4AQeu28.js";import{L as n}from"./log-out-BT_ShBSM.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ModuleFolderCard-7StF4eM7.js b/assets/ModuleFolderCard-DaH-e6Ze.js similarity index 97% rename from assets/ModuleFolderCard-7StF4eM7.js rename to assets/ModuleFolderCard-DaH-e6Ze.js index 70928412c698451f2f603ffa563c4e0f52bea8f3..017caf35dce508aadebcbef6aabd537b578b2328 100644 --- a/assets/ModuleFolderCard-7StF4eM7.js +++ b/assets/ModuleFolderCard-DaH-e6Ze.js @@ -1,4 +1,4 @@ -import{j as e}from"./vendor-react-B4AQeu28.js";import{u}from"./useSubjectAvailability-CNwO6mr3.js";import{e as w,m as f,b as j,x as v,L as y}from"./index-BYG24j30.js";import{C as k}from"./clock-CGFFx3Yv.js";/** +import{j as e}from"./vendor-react-B4AQeu28.js";import{u}from"./useSubjectAvailability-SVKjmUD3.js";import{e as w,m as f,b as j,x as v,L as y}from"./index-CR5aYAL9.js";import{C as k}from"./clock-BF2L28Gg.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ModulesPage-Dw5f2_tQ.js b/assets/ModulesPage-BVHCL2m4.js similarity index 99% rename from assets/ModulesPage-Dw5f2_tQ.js rename to assets/ModulesPage-BVHCL2m4.js index b8ca96dd26935064ff5621fe15820ef46e43105d..942da76ad21fe1327ed87dbdeee689368c4f432f 100644 --- a/assets/ModulesPage-Dw5f2_tQ.js +++ b/assets/ModulesPage-BVHCL2m4.js @@ -1,5 +1,5 @@ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-firebase-auth-T_wvTOvf.js","assets/vendor-firebase-core-D7GXCeNu.js"])))=>i.map(i=>d[i]); -import{r as s,j as e,b as Ct,d as Te,c as aa}from"./vendor-react-B4AQeu28.js";import{u as ra}from"./useQuery-C5wg1Gx-.js";import{getDoc as Kt,doc as zt,onSnapshot as ts,runTransaction as la,serverTimestamp as na,query as ia,where as oa,collection as ca}from"./vendor-firebase-firestore-CNv3xXal.js";import{e as pe,m as S,Z as rt,C as Nt,h as tt,X as qs,M as da,a as bt,T as At,q as it,a5 as ss,R as Hs,E as Bt,_ as as,v as qt,I as ma,N as xa,u as Ht,A as Pt,b as Je,n as It,x as Os,ab as hs,ac as ua,ad as fs,ae as pa,p as Qs,af as ha,L as Ws,g as ct,B as fa,ag as ba,ah as ga,ai as Us,aj as wa,ak as ya,al as ja,a9 as va,w as Na,am as bs,an as ka,ao as gs,G as Ca,j as Mt,a7 as Sa,aa as za}from"./index-BYG24j30.js";import{M as Zt}from"./ModuleFolderCard-7StF4eM7.js";import{B as Fe}from"./button-LR_FKM7p.js";import rs from"./ScientificCalculator-Ba2j64OY.js";import{C as Dt}from"./check-C-Jb6xS0.js";import{X as et}from"./x-DU8WEZ6X.js";import{V as Ft,a as Rt,M as ls,b as ns}from"./volume-x-WJgblgWN.js";import{C as $t}from"./chevron-left-CIE_NDv7.js";import{C as qe}from"./chevron-right-CF79oTk8.js";import{C as Gs}from"./circle-help-BYya03qM.js";import{P as Xs,A as Jt,b as es,c as Ma,L as _a}from"./quizService-Dg-FcCkj.js";import{C as ot}from"./circle-check-big-uJgj_456.js";import{C as Et,L as kt}from"./lightbulb-C6VPAE81.js";import{logLessonView as Aa}from"./trackingService-MJBRfiN7.js";import{C as St}from"./clock-CGFFx3Yv.js";import{C as Ea}from"./clipboard-check-CC5IRbh7.js";import{s as Gt,S as ws}from"./subjects-CnMsFeDX.js";import{C as Vs}from"./circle-check-_6J4FrSd.js";import{C as Ta}from"./chart-column-BOgIfbES.js";import{D as Pa}from"./dollar-sign-CFYvEMYD.js";import{triggerQuizSubmitted as La}from"./automationService-Cn_PZsKR.js";import ys from"./confetti.module-C94ZD2ww.js";import{u as Ia}from"./useCurriculum-BCsJVZ1p.js";import{S as Da}from"./search-qXpo6Bz-.js";import{F as Fa}from"./funnel-CkgPZM71.js";import{S as Ra}from"./sparkles-DiaNugT9.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./useSubjectAvailability-CNwO6mr3.js";import"./chevron-up-vEHTl-in.js";/** +import{r as s,j as e,b as Ct,d as Te,c as aa}from"./vendor-react-B4AQeu28.js";import{u as ra}from"./useQuery-CFyiy_x4.js";import{getDoc as Kt,doc as zt,onSnapshot as ts,runTransaction as la,serverTimestamp as na,query as ia,where as oa,collection as ca}from"./vendor-firebase-firestore-CNv3xXal.js";import{e as pe,m as S,Z as rt,C as Nt,h as tt,X as qs,M as da,a as bt,T as At,q as it,a5 as ss,R as Hs,E as Bt,_ as as,v as qt,I as ma,N as xa,u as Ht,A as Pt,b as Je,n as It,x as Os,ab as hs,ac as ua,ad as fs,ae as pa,p as Qs,af as ha,L as Ws,g as ct,B as fa,ag as ba,ah as ga,ai as Us,aj as wa,ak as ya,al as ja,a9 as va,w as Na,am as bs,an as ka,ao as gs,G as Ca,j as Mt,a7 as Sa,aa as za}from"./index-CR5aYAL9.js";import{M as Zt}from"./ModuleFolderCard-DaH-e6Ze.js";import{B as Fe}from"./button-CbtAHv27.js";import rs from"./ScientificCalculator-CLa3avU-.js";import{C as Dt}from"./check-MAu_C8ty.js";import{X as et}from"./x-DiyyYv8Q.js";import{V as Ft,a as Rt,M as ls,b as ns}from"./volume-x-FcYe0Ron.js";import{C as $t}from"./chevron-left-Buq4JTY_.js";import{C as qe}from"./chevron-right-d9v3XH9Z.js";import{C as Gs}from"./circle-help-CS95sLmI.js";import{P as Xs,A as Jt,b as es,c as Ma,L as _a}from"./quizService-83ZGYTl6.js";import{C as ot}from"./circle-check-big-CWD8eO1a.js";import{C as Et,L as kt}from"./lightbulb-CRrzx6iX.js";import{logLessonView as Aa}from"./trackingService-BGfVSr6K.js";import{C as St}from"./clock-BF2L28Gg.js";import{C as Ea}from"./clipboard-check-B4PuSMw1.js";import{s as Gt,S as ws}from"./subjects-CruSaBwq.js";import{C as Vs}from"./circle-check--_-gyncR.js";import{C as Ta}from"./chart-column-nZ0JrvMi.js";import{D as Pa}from"./dollar-sign-a1mi5_q1.js";import{triggerQuizSubmitted as La}from"./automationService-BUinEhr-.js";import ys from"./confetti.module-C94ZD2ww.js";import{u as Ia}from"./useCurriculum-BQeS3LyA.js";import{S as Da}from"./search-1a4wCp_r.js";import{F as Fa}from"./funnel-nXEzWYRv.js";import{S as Ra}from"./sparkles-Df420Y_c.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./useSubjectAvailability-SVKjmUD3.js";import"./chevron-up-BrrK8Cng.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/NotificationDropdown-vpdHjkTB.js b/assets/NotificationDropdown-DBksmA1S.js similarity index 94% rename from assets/NotificationDropdown-vpdHjkTB.js rename to assets/NotificationDropdown-DBksmA1S.js index a969469fd6c6edd3dfd47c458d6d985d7c9de0c2..655acba7ec4c2afe2520ca3d99f9f29707001feb 100644 --- a/assets/NotificationDropdown-vpdHjkTB.js +++ b/assets/NotificationDropdown-DBksmA1S.js @@ -1,4 +1,4 @@ -import{e as a,D as b,u as N,h as w,m as y,a as j,U as k}from"./index-BYG24j30.js";import{r as _,j as e}from"./vendor-react-B4AQeu28.js";import"./vendor-firebase-firestore-CNv3xXal.js";import{C as g,f as v}from"./formatDistanceToNow-C9WeR9GV.js";import{B as n}from"./bell-CJfHcVLS.js";import{C}from"./circle-check-_6J4FrSd.js";import{C as A}from"./circle-alert-D1BZWAsh.js";import{S as M}from"./sparkles-DiaNugT9.js";/** +import{e as a,D as b,u as N,h as w,m as y,a as j,U as k}from"./index-CR5aYAL9.js";import{r as _,j as e}from"./vendor-react-B4AQeu28.js";import"./vendor-firebase-firestore-CNv3xXal.js";import{C as g,f as v}from"./formatDistanceToNow-B4dD00jc.js";import{B as n}from"./bell-DVzATilo.js";import{C}from"./circle-check--_-gyncR.js";import{C as A}from"./circle-alert-CSWToxPb.js";import{S as M}from"./sparkles-Df420Y_c.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ProfileModal-BujeMrz5.js b/assets/ProfileModal-BpvupEPF.js similarity index 96% rename from assets/ProfileModal-BujeMrz5.js rename to assets/ProfileModal-BpvupEPF.js index bd3462fc544d327d693a4868ec8a03218643dfc1..e6d3575986b034d87439e295a6ef09851755f1c4 100644 --- a/assets/ProfileModal-BujeMrz5.js +++ b/assets/ProfileModal-BpvupEPF.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,F as _,$ as D,aJ as T,aS as B,j as $}from"./index-BYG24j30.js";import{B as b}from"./button-LR_FKM7p.js";import{I as d}from"./input-CtjqQUbX.js";import{S as q,a as G,c as V,d as p}from"./select-DM5m46Pk.js";import{P as X,M as z,V as C}from"./ProfilePictureUploader-C40Uwtje.js";import{X as Y}from"./x-DU8WEZ6X.js";import{M as H}from"./mail-B8qfL-UK.js";import{C as L}from"./circle-help-BYya03qM.js";import{S as J}from"./save-DidAD_jg.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-vEHTl-in.js";import"./check-C-Jb6xS0.js";import"./minus-sZ1MmK-H.js";import"./plus-C5IM0tm0.js";import"./upload-z5a73neo.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,F as _,$ as D,aJ as T,aS as B,j as $}from"./index-CR5aYAL9.js";import{B as b}from"./button-CbtAHv27.js";import{I as d}from"./input-DgZjxAsx.js";import{S as q,a as G,c as V,d as p}from"./select-DMAe8pN9.js";import{P as X,M as z,V as C}from"./ProfilePictureUploader-CZ4lHPeL.js";import{X as Y}from"./x-DiyyYv8Q.js";import{M as H}from"./mail-sfPSTvMi.js";import{C as L}from"./circle-help-CS95sLmI.js";import{S as J}from"./save-BpEMiY1d.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-BrrK8Cng.js";import"./check-MAu_C8ty.js";import"./minus-D8MfEHLl.js";import"./plus-Cp5Q-YTc.js";import"./upload-Dv-dcZHV.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/ProfilePictureUploader-C40Uwtje.js b/assets/ProfilePictureUploader-CZ4lHPeL.js similarity index 98% rename from assets/ProfilePictureUploader-C40Uwtje.js rename to assets/ProfilePictureUploader-CZ4lHPeL.js index ecd9263005aaf0ab2ba99a92b9e0540b67d02cb9..e2e61d07e164369cc9b8c1c0ef5fcfc85eab2f7e 100644 --- a/assets/ProfilePictureUploader-C40Uwtje.js +++ b/assets/ProfilePictureUploader-CZ4lHPeL.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-BYG24j30.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); -import{e as V,n as B,N as K,_ as $,b1 as ge,b2 as we,u as xe,Q as ye,V as be,W as Ce,h as Pe,m as J,j as Q}from"./index-BYG24j30.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-BPuEd8FG.js";import{B as ee}from"./button-LR_FKM7p.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-DU8WEZ6X.js";import{M as Ue}from"./minus-sZ1MmK-H.js";import{P as Fe}from"./plus-C5IM0tm0.js";import{U as Ie}from"./upload-z5a73neo.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-CR5aYAL9.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); +import{e as V,n as B,N as K,_ as $,b1 as ge,b2 as we,u as xe,Q as ye,V as be,W as Ce,h as Pe,m as J,j as Q}from"./index-CR5aYAL9.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-BPuEd8FG.js";import{B as ee}from"./button-CbtAHv27.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-DiyyYv8Q.js";import{M as Ue}from"./minus-D8MfEHLl.js";import{P as Fe}from"./plus-Cp5Q-YTc.js";import{U as Ie}from"./upload-Dv-dcZHV.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,n as B,N as K,_ as $,b1 as ge,b2 as we,u as xe,Q as ye,V as be,W a 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-BYG24j30.js").then(f=>f.b5);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 W=u||o||"",k=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:W,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:k})]}),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-CR5aYAL9.js").then(f=>f.b5);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 W=u||o||"",k=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:W,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:k})]}),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-B59IiVNM.js b/assets/QuizBattlePage-Cm-cnqCP.js similarity index 99% rename from assets/QuizBattlePage-B59IiVNM.js rename to assets/QuizBattlePage-Cm-cnqCP.js index c13e721b67b9afbe9a5e91857fd96e5e37ce57c9..9b26e879c2bbf5df2feafcbf4804d3b9e0992482 100644 --- a/assets/QuizBattlePage-B59IiVNM.js +++ b/assets/QuizBattlePage-Cm-cnqCP.js @@ -1,4 +1,4 @@ -import{e as ma,n as u,m as y,g as et,aK as De,N as st,aL as Q,X as $a,q as St,M as Oa,I as Te,U as ge,h as Ze,p as Ke,u as Ha,_ as Va,a0 as gt,a5 as wt,E as Kt,a4 as Jt}from"./index-BYG24j30.js";import{r as i,j as e,d as Mt}from"./vendor-react-B4AQeu28.js";import{q as vt}from"./quiz_battle_avatar-BXHPSput.js";import{g as Ua,s as ea}from"./subjects-CnMsFeDX.js";import{doc as Wa,getDoc as Ya,where as ta,orderBy as xa,limit as At,getDocs as zt,query as Ct,collection as It}from"./vendor-firebase-firestore-CNv3xXal.js";import{a4 as q,a5 as pa,a6 as ha,a7 as _e,a8 as Xa}from"./vendor-firebase-core-D7GXCeNu.js";import{B as A}from"./button-LR_FKM7p.js";import{e as Ga,f as Za}from"./vendor-radix-BPuEd8FG.js";import{S as Me,a as Fe,b as Ee,c as Re,d as de}from"./select-DM5m46Pk.js";import{I as Ka}from"./input-CtjqQUbX.js";import{S as Ja}from"./switch-CqM6p44O.js";import{H as es,S as xe,C as aa}from"./skeleton-9NZnc9sp.js";import{V as ba,a as fa,M as ts,b as as}from"./volume-x-WJgblgWN.js";import{C as ss}from"./CompositeAvatar-Col05lJc.js";import{S as Je}from"./sparkles-DiaNugT9.js";import{C as jt}from"./check-C-Jb6xS0.js";import{C as Ue}from"./chevron-right-CF79oTk8.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-BOgIfbES.js";import"./chevron-up-vEHTl-in.js";import"./avatarData-BuQSOXo3.js";/** +import{e as ma,n as u,m as y,g as et,aK as De,N as st,aL as Q,X as $a,q as St,M as Oa,I as Te,U as ge,h as Ze,p as Ke,u as Ha,_ as Va,a0 as gt,a5 as wt,E as Kt,a4 as Jt}from"./index-CR5aYAL9.js";import{r as i,j as e,d as Mt}from"./vendor-react-B4AQeu28.js";import{q as vt}from"./quiz_battle_avatar-BXHPSput.js";import{g as Ua,s as ea}from"./subjects-CruSaBwq.js";import{doc as Wa,getDoc as Ya,where as ta,orderBy as xa,limit as At,getDocs as zt,query as Ct,collection as It}from"./vendor-firebase-firestore-CNv3xXal.js";import{a4 as q,a5 as pa,a6 as ha,a7 as _e,a8 as Xa}from"./vendor-firebase-core-D7GXCeNu.js";import{B as A}from"./button-CbtAHv27.js";import{e as Ga,f as Za}from"./vendor-radix-BPuEd8FG.js";import{S as Me,a as Fe,b as Ee,c as Re,d as de}from"./select-DMAe8pN9.js";import{I as Ka}from"./input-DgZjxAsx.js";import{S as Ja}from"./switch-DI6PCkYC.js";import{H as es,S as xe,C as aa}from"./skeleton-nK8OdpwJ.js";import{V as ba,a as fa,M as ts,b as as}from"./volume-x-FcYe0Ron.js";import{C as ss}from"./CompositeAvatar-Col05lJc.js";import{S as Je}from"./sparkles-Df420Y_c.js";import{C as jt}from"./check-MAu_C8ty.js";import{C as Ue}from"./chevron-right-d9v3XH9Z.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-nZ0JrvMi.js";import"./chevron-up-BrrK8Cng.js";import"./avatarData-BuQSOXo3.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/RewardsModal-vFV0nluD.js b/assets/RewardsModal-e7BnIl6w.js similarity index 99% rename from assets/RewardsModal-vFV0nluD.js rename to assets/RewardsModal-e7BnIl6w.js index a81af41b5c7466bfb3b220c052d3a955ee6ca7d0..332497808c554f73b0b0df72378507019f258b36 100644 --- a/assets/RewardsModal-vFV0nluD.js +++ b/assets/RewardsModal-e7BnIl6w.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{aO as g,A as u,aP as U,aQ as P,U as $,F as B,i as I,z as R,$ as q,T as j,aR as T,a4 as N,R as L,S as M,a0 as X,X as v,a5 as w,B as G,Z as H,q as Q,E as Z,G as O,b as V,aI as W,g as J}from"./index-BYG24j30.js";import{X as K}from"./x-DU8WEZ6X.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const Y={BookOpen:V,GraduationCap:O,Trophy:Z,Target:Q,Zap:H,Brain:G,Star:w,Flame:v,Swords:X,Shield:M,RefreshCw:L,Crown:N,Sun:T,TrendingUp:j,Globe:q,User:R,UserPlus:I,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(A=>A.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"}}),z=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:[z," / ",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(K,{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{aO as g,A as u,aP as U,aQ as P,U as $,F as B,i as I,z as R,$ as q,T as j,aR as T,a4 as N,R as L,S as M,a0 as X,X as v,a5 as w,B as G,Z as H,q as Q,E as Z,G as O,b as V,aI as W,g as J}from"./index-CR5aYAL9.js";import{X as K}from"./x-DiyyYv8Q.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const Y={BookOpen:V,GraduationCap:O,Trophy:Z,Target:Q,Zap:H,Brain:G,Star:w,Flame:v,Swords:X,Shield:M,RefreshCw:L,Crown:N,Sun:T,TrendingUp:j,Globe:q,User:R,UserPlus:I,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(A=>A.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"}}),z=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:[z," / ",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(K,{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-BF7n5nEK.js b/assets/RightSidebar-DY3YTL-R.js similarity index 98% rename from assets/RightSidebar-BF7n5nEK.js rename to assets/RightSidebar-DY3YTL-R.js index fce140a93e2760752a1a39b7c0be5453187bc4e6..6016358197219ebdaa1fe45e4380f7247fa2445c 100644 --- a/assets/RightSidebar-BF7n5nEK.js +++ b/assets/RightSidebar-DY3YTL-R.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 B,m as c,Z as _,a0 as q,a3 as P,E as W,a4 as v,a5 as X,p as Y,z as k}from"./index-BYG24j30.js";import{C as M}from"./circle-check-big-uJgj_456.js";import{T as O,a as Z,b as H}from"./tooltip-B8dZx5CM.js";import{C as T}from"./chevron-right-CF79oTk8.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-BPuEd8FG.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(q,{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(B,{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 B,m as c,Z as _,a0 as q,a3 as P,E as W,a4 as v,a5 as X,p as Y,z as k}from"./index-CR5aYAL9.js";import{C as M}from"./circle-check-big-CWD8eO1a.js";import{T as O,a as Z,b as H}from"./tooltip-COrnGY4E.js";import{C as T}from"./chevron-right-d9v3XH9Z.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-BPuEd8FG.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(q,{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(B,{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-Ba2j64OY.js b/assets/ScientificCalculator-CLa3avU-.js similarity index 99% rename from assets/ScientificCalculator-Ba2j64OY.js rename to assets/ScientificCalculator-CLa3avU-.js index e69b2430939aad2aea8ad8ef8a20b38bfd6ae4aa..e59b217d8a0203fbb9524ebfc9aeafcd53bbdaf5 100644 --- a/assets/ScientificCalculator-Ba2j64OY.js +++ b/assets/ScientificCalculator-CLa3avU-.js @@ -1,4 +1,4 @@ -import{r as c,j as e}from"./vendor-react-B4AQeu28.js";import{e as Z,l as de,h as U,m as ue}from"./index-BYG24j30.js";import{a as fe,C as pe}from"./chevron-up-vEHTl-in.js";import{X as be}from"./x-DU8WEZ6X.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-BPuEd8FG.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,l as de,h as U,m as ue}from"./index-CR5aYAL9.js";import{a as fe,C as pe}from"./chevron-up-BrrK8Cng.js";import{X as be}from"./x-DiyyYv8Q.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-BPuEd8FG.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-BlqFNEeQ.js b/assets/SettingsModal-Bj9L7UBt.js similarity index 96% rename from assets/SettingsModal-BlqFNEeQ.js rename to assets/SettingsModal-Bj9L7UBt.js index 82407ed9367677b1249779644c5b96cbb056397b..14ef18d32bcdbb43db86ad77d46a0c20aacb7723 100644 --- a/assets/SettingsModal-BlqFNEeQ.js +++ b/assets/SettingsModal-Bj9L7UBt.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BYG24j30.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); -import{e as D,u as Me,aT as Le,aU as De,aV as qe,aW as Ie,aX as Fe,aY as Ve,z as Oe,S as He,$ as Ge,b as Ue,h as $e,m as G,L as Xe,E as Be,a0 as Ye,X as Qe,_ as U,j as d,aZ as We,aS as Je,a_ as Ke,a$ as Ze,b0 as es}from"./index-BYG24j30.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-DM5m46Pk.js";import{B as p}from"./button-LR_FKM7p.js";import{I as n}from"./input-CtjqQUbX.js";import{S as x}from"./switch-CqM6p44O.js";import je from"./ConfirmModal-BDSADafu.js";import{P as is,M as rs,V as ls}from"./ProfilePictureUploader-C40Uwtje.js";import{B as ge}from"./bell-CJfHcVLS.js";import{D as ve}from"./download-DRtqT_j8.js";import{X as Ne}from"./x-DU8WEZ6X.js";import{C as cs}from"./circle-help-BYya03qM.js";import{C as os}from"./chart-column-BOgIfbES.js";import{M as ds}from"./megaphone-DX0jSVq2.js";import{C as xs}from"./clock-CGFFx3Yv.js";import{T as ms}from"./trash-2-Bz07bxtW.js";import{E as hs,a as us}from"./eye-Cjs8eHiG.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-vEHTl-in.js";import"./check-C-Jb6xS0.js";import"./log-out-7LnFvNg-.js";import"./minus-sZ1MmK-H.js";import"./plus-C5IM0tm0.js";import"./upload-z5a73neo.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CR5aYAL9.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); +import{e as D,u as Me,aT as Le,aU as De,aV as qe,aW as Ie,aX as Fe,aY as Ve,z as Oe,S as He,$ as Ge,b as Ue,h as $e,m as G,L as Xe,E as Be,a0 as Ye,X as Qe,_ as U,j as d,aZ as We,aS as Je,a_ as Ke,a$ as Ze,b0 as es}from"./index-CR5aYAL9.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-DMAe8pN9.js";import{B as p}from"./button-CbtAHv27.js";import{I as n}from"./input-DgZjxAsx.js";import{S as x}from"./switch-DI6PCkYC.js";import je from"./ConfirmModal-BVHZuXaM.js";import{P as is,M as rs,V as ls}from"./ProfilePictureUploader-CZ4lHPeL.js";import{B as ge}from"./bell-DVzATilo.js";import{D as ve}from"./download-teQqHQmt.js";import{X as Ne}from"./x-DiyyYv8Q.js";import{C as cs}from"./circle-help-CS95sLmI.js";import{C as os}from"./chart-column-nZ0JrvMi.js";import{M as ds}from"./megaphone-D_BUBJZ4.js";import{C as xs}from"./clock-BF2L28Gg.js";import{T as ms}from"./trash-2-BtGasoad.js";import{E as hs,a as us}from"./eye-BuiZU-wn.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";import"./chevron-up-BrrK8Cng.js";import"./check-MAu_C8ty.js";import"./log-out-BT_ShBSM.js";import"./minus-D8MfEHLl.js";import"./plus-Cp5Q-YTc.js";import"./upload-Dv-dcZHV.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -24,4 +24,4 @@ import{e as D,u as Me,aT as Le,aU as De,aV as qe,aW as Ie,aX as Fe,aY as Ve,z as * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const ks=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],ws=D("smartphone",ks),Cs=()=>{const{userProfile:m,userRole:y}=Me(),[r,z]=a.useState(Le),[_,R]=a.useState(De),[k,T]=a.useState(!1),[q,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();R(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);R(u)},[]);return{teacherPrefs:r,adminConfig:_,loading:k,error:q,saveTeacherPrefs:o,saveAdminConfig:M}},ae=()=>JSON.parse(JSON.stringify(We)),rt=({isOpen:m,onClose:y,profileData:r,onSave:z,settingsData:_,onSaveSettings:R,onApplySettingsPreview:k,onExportData:T,onClearCache:q,onResetData:E})=>{const o=r?.role||"student",{teacherPrefs:M,adminConfig:g,saveTeacherPrefs:u,saveAdminConfig:ke}=Cs(),[b,ne]=a.useState("account"),[l,h]=a.useState({}),[i,ie]=a.useState(ae()),[w,C]=a.useState(M),[j,$]=a.useState(g),[X,re]=a.useState(!1),[I,le]=a.useState(!1),[B,ce]=a.useState(!1),[Y,oe]=a.useState(!1),[de,Ss]=a.useState(!1),[we,F]=a.useState(!1),[Ce,V]=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(""),[O,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=_?JSON.parse(JSON.stringify(_)):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,_,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:gs}];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:Ns}),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(!O.includes("@")){d.error("Enter a valid email");return}await Ze(L,O),h(s=>({...s,email:O})),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),R&&await R(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),F(!1),V(!1),k?.(K.current),y()},Pe=async()=>{if(!(!T||B)){ce(!0);try{await T()}catch(s){d.error(s instanceof Error?s.message:"Failed to export data")}finally{ce(!1)}}},ze=async()=>{if(!(!q||Y)){oe(!0);try{await q()}catch(s){d.error(s instanceof Error?s.message:"Failed to clear cache")}finally{oe(!1)}}},_e=async()=>{if(!(!E||I)){F(!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)}}},Re=()=>{V(!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(G.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:se,className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(G.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(Xe,{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:Be},{key:"quiz_battle",label:"Quiz battle invites & results",icon:Ye},{key:"daily_reward",label:"Daily reward reminders",icon:ys},{key:"assignment",label:"New assignments / deadlines",icon:fs},{key:"streak_reminder",label:"Streak reminders",icon:Qe},{key:"leaderboard",label:"Leaderboard updates",icon:os},{key:"system",label:"System announcements",icon:ds}].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(H=>({...H,pushPreferences:{...H.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 U(async()=>{const{requestPushPermissionAndRegister:S}=await import("./index-BYG24j30.js").then(A=>A.b7);return{requestPushPermissionAndRegister:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),{auth:t}=await U(async()=>{const{auth:S}=await import("./index-BYG24j30.js").then(A=>A.b5);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:H}=await U(async()=>{const{httpsCallable:S}=await import("./vendor-firebase-core-D7GXCeNu.js").then(A=>A.a9);return{httpsCallable:S}},[]),{cloudFunctions:Te}=await U(async()=>{const{cloudFunctions:S}=await import("./index-BYG24j30.js").then(A=>A.b5);return{cloudFunctions:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),ye=(await H(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(xs,{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(ws,{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:B,children:[e.jsx(ve,{size:16,className:"mr-2"}),B?"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||I,onClick:()=>F(!0),children:I?"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:()=>V(!0),disabled:de,children:[e.jsx(ms,{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:X,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:X,children:X?"Saving...":"Save Changes"})]})]})]})]})]}),Se&&e.jsx(G.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(G.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(hs,{size:16}):e.jsx(us,{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:O,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:()=>F(!1),onConfirm:_e,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:I?"Resetting...":"Reset Data",cancelText:"Cancel",type:"warning",icon:"warning",zIndexClass:"z-[130]"}),e.jsx(je,{isOpen:Ce,onClose:()=>V(!1),onConfirm:Re,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 ks=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],ws=D("smartphone",ks),Cs=()=>{const{userProfile:m,userRole:y}=Me(),[r,z]=a.useState(Le),[_,R]=a.useState(De),[k,T]=a.useState(!1),[q,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();R(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);R(u)},[]);return{teacherPrefs:r,adminConfig:_,loading:k,error:q,saveTeacherPrefs:o,saveAdminConfig:M}},ae=()=>JSON.parse(JSON.stringify(We)),rt=({isOpen:m,onClose:y,profileData:r,onSave:z,settingsData:_,onSaveSettings:R,onApplySettingsPreview:k,onExportData:T,onClearCache:q,onResetData:E})=>{const o=r?.role||"student",{teacherPrefs:M,adminConfig:g,saveTeacherPrefs:u,saveAdminConfig:ke}=Cs(),[b,ne]=a.useState("account"),[l,h]=a.useState({}),[i,ie]=a.useState(ae()),[w,C]=a.useState(M),[j,$]=a.useState(g),[X,re]=a.useState(!1),[I,le]=a.useState(!1),[B,ce]=a.useState(!1),[Y,oe]=a.useState(!1),[de,Ss]=a.useState(!1),[we,F]=a.useState(!1),[Ce,V]=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(""),[O,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=_?JSON.parse(JSON.stringify(_)):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,_,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:gs}];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:Ns}),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(!O.includes("@")){d.error("Enter a valid email");return}await Ze(L,O),h(s=>({...s,email:O})),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),R&&await R(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),F(!1),V(!1),k?.(K.current),y()},Pe=async()=>{if(!(!T||B)){ce(!0);try{await T()}catch(s){d.error(s instanceof Error?s.message:"Failed to export data")}finally{ce(!1)}}},ze=async()=>{if(!(!q||Y)){oe(!0);try{await q()}catch(s){d.error(s instanceof Error?s.message:"Failed to clear cache")}finally{oe(!1)}}},_e=async()=>{if(!(!E||I)){F(!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)}}},Re=()=>{V(!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(G.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:se,className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs(G.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(Xe,{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:Be},{key:"quiz_battle",label:"Quiz battle invites & results",icon:Ye},{key:"daily_reward",label:"Daily reward reminders",icon:ys},{key:"assignment",label:"New assignments / deadlines",icon:fs},{key:"streak_reminder",label:"Streak reminders",icon:Qe},{key:"leaderboard",label:"Leaderboard updates",icon:os},{key:"system",label:"System announcements",icon:ds}].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(H=>({...H,pushPreferences:{...H.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 U(async()=>{const{requestPushPermissionAndRegister:S}=await import("./index-CR5aYAL9.js").then(A=>A.b7);return{requestPushPermissionAndRegister:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),{auth:t}=await U(async()=>{const{auth:S}=await import("./index-CR5aYAL9.js").then(A=>A.b5);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:H}=await U(async()=>{const{httpsCallable:S}=await import("./vendor-firebase-core-D7GXCeNu.js").then(A=>A.a9);return{httpsCallable:S}},[]),{cloudFunctions:Te}=await U(async()=>{const{cloudFunctions:S}=await import("./index-CR5aYAL9.js").then(A=>A.b5);return{cloudFunctions:S}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),ye=(await H(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(xs,{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(ws,{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:B,children:[e.jsx(ve,{size:16,className:"mr-2"}),B?"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||I,onClick:()=>F(!0),children:I?"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:()=>V(!0),disabled:de,children:[e.jsx(ms,{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:X,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:X,children:X?"Saving...":"Save Changes"})]})]})]})]})]}),Se&&e.jsx(G.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(G.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(hs,{size:16}):e.jsx(us,{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:O,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:()=>F(!1),onConfirm:_e,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:I?"Resetting...":"Reset Data",cancelText:"Cancel",type:"warning",icon:"warning",zIndexClass:"z-[130]"}),e.jsx(je,{isOpen:Ce,onClose:()=>V(!1),onConfirm:Re,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-DAee_vGE.js b/assets/Sidebar-DPdujCJv.js similarity index 93% rename from assets/Sidebar-DAee_vGE.js rename to assets/Sidebar-DPdujCJv.js index b4513b1f5ad1a166bdc96278f051d03050a01302..9838f5a6117db021ada4b63906adad25b59b508f 100644 --- a/assets/Sidebar-DAee_vGE.js +++ b/assets/Sidebar-DPdujCJv.js @@ -1,4 +1,4 @@ -import{r as x,j as e}from"./vendor-react-B4AQeu28.js";import{S as H,a as $,L as u,D as B,M as D}from"./LogoutActionButton-U0Q7JjxX.js";import{e as G,m as c,n as P,U as S,G as N,b as m,S as U,a0 as q,E as F}from"./index-BYG24j30.js";import{T as M,a as L,b as C}from"./tooltip-B8dZx5CM.js";import{X as Q}from"./x-DU8WEZ6X.js";import{C as W}from"./chevron-right-CF79oTk8.js";import{C as R}from"./chevron-left-CIE_NDv7.js";import{C as A}from"./chart-column-BOgIfbES.js";import{S as X}from"./shirt-DhJu64M2.js";/** +import{r as x,j as e}from"./vendor-react-B4AQeu28.js";import{S as H,a as $,L as u,D as B,M as D}from"./LogoutActionButton-tEi5DIaj.js";import{e as G,m as c,n as P,U as S,G as N,b as m,S as U,a0 as q,E as F}from"./index-CR5aYAL9.js";import{T as M,a as L,b as C}from"./tooltip-COrnGY4E.js";import{X as Q}from"./x-DiyyYv8Q.js";import{C as W}from"./chevron-right-d9v3XH9Z.js";import{C as R}from"./chevron-left-Buq4JTY_.js";import{C as A}from"./chart-column-nZ0JrvMi.js";import{S as X}from"./shirt-DT9OZcT1.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/SupplementalBanner-DptF9mye.js b/assets/SupplementalBanner-BLQPu9lu.js similarity index 97% rename from assets/SupplementalBanner-DptF9mye.js rename to assets/SupplementalBanner-BLQPu9lu.js index 098dfa1bfa6b46164113bb6755e675913f7dc98c..bb64c75c7256829c65513501d1abf680cc95a604 100644 --- a/assets/SupplementalBanner-DptF9mye.js +++ b/assets/SupplementalBanner-BLQPu9lu.js @@ -1 +1 @@ -import{j as e,r as y}from"./vendor-react-B4AQeu28.js";import{h as j,m as p,x as h,b as f,T as m,B as u}from"./index-BYG24j30.js";import{X as v}from"./x-DU8WEZ6X.js";import{S as w}from"./sparkles-DiaNugT9.js";import{C as g}from"./chevron-right-CF79oTk8.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-BPuEd8FG.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(u,{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(u,{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(u,{size:14})}]};function x(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?x(i):null;if(!s.some(r=>{const t=x(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?x(i):null,r=n.some(c=>{const d=x(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,x as h,b as f,T as m,B as u}from"./index-CR5aYAL9.js";import{X as v}from"./x-DiyyYv8Q.js";import{S as w}from"./sparkles-Df420Y_c.js";import{C as g}from"./chevron-right-d9v3XH9Z.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-BPuEd8FG.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(u,{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(u,{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(u,{size:14})}]};function x(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?x(i):null;if(!s.some(r=>{const t=x(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?x(i):null,r=n.some(c=>{const d=x(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-BucFK7HK.js b/assets/SupplementalPillCarousel-BmES_4dd.js similarity index 94% rename from assets/SupplementalPillCarousel-BucFK7HK.js rename to assets/SupplementalPillCarousel-BmES_4dd.js index 46e0cdb5325037b69179fee635a182f69d4bf620..88098fd5ce57b844be3a94cb0cbf2c5dfae2e241 100644 --- a/assets/SupplementalPillCarousel-BucFK7HK.js +++ b/assets/SupplementalPillCarousel-BmES_4dd.js @@ -1,4 +1,4 @@ -import{r as a,j as e}from"./vendor-react-B4AQeu28.js";import{m as f,x}from"./index-BYG24j30.js";import{C as n}from"./chevron-right-CF79oTk8.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const o={pillBg:"#E9D5FF",pillText:"#6B21A8",headerText:"#1F2937",arrowBg:"#F3F4F6"},b={functions:"Functions & Graphs",businessmath:"Business Math",logic:"Logic & Reasoning",statistics:"Statistics",probability:"Probability",precalc:"Pre-Calculus",calculus:"Basic Calculus",geometry:"Geometry",trigonometry:"Trigonometry",algebra:"Algebra"};function g(t){const s=t.toLowerCase().trim();return b[s]||t.split(/[-_]/).map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")}const L=({atRiskSubjects:t=[],onTopicClick:s})=>{const l=a.useRef(null),[c,m]=a.useState(!1);if(t.length===0)return null;const h=()=>{if(l.current){const{scrollLeft:r,scrollWidth:i,clientWidth:d}=l.current;m(r+d{s?.(r)},u=()=>{l.current&&l.current.scrollBy({left:200,behavior:"smooth"})};return e.jsxs(f.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},className:"mb-4",children:[e.jsx("h3",{className:"text-base font-bold mb-3",style:{color:o.headerText},children:"Recommended for Review"}),e.jsxs("div",{className:"relative flex items-center",children:[e.jsx("div",{ref:l,onScroll:h,className:"flex gap-2 overflow-x-auto scrollbar-hide pb-1",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:t.slice(0,8).map((r,i)=>e.jsxs("button",{onClick:()=>p(r),className:"flex items-center gap-1.5 px-4 py-2 rounded-full text-sm font-semibold transition-all hover:scale-[1.02] whitespace-nowrap",style:{backgroundColor:o.pillBg,color:o.pillText},children:[e.jsx(x,{size:14}),g(r),e.jsx(n,{size:14})]},`${r}-${i}`))}),c&&e.jsx("button",{onClick:u,className:"flex-shrink-0 ml-2 w-8 h-8 rounded-full flex items-center justify-center transition-colors",style:{backgroundColor:o.arrowBg},"aria-label":"Scroll right",children:e.jsx(n,{size:16,className:"text-gray-600"})})]}),e.jsx("style",{children:` +import{r as a,j as e}from"./vendor-react-B4AQeu28.js";import{m as f,x}from"./index-CR5aYAL9.js";import{C as n}from"./chevron-right-d9v3XH9Z.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const o={pillBg:"#E9D5FF",pillText:"#6B21A8",headerText:"#1F2937",arrowBg:"#F3F4F6"},b={functions:"Functions & Graphs",businessmath:"Business Math",logic:"Logic & Reasoning",statistics:"Statistics",probability:"Probability",precalc:"Pre-Calculus",calculus:"Basic Calculus",geometry:"Geometry",trigonometry:"Trigonometry",algebra:"Algebra"};function g(t){const s=t.toLowerCase().trim();return b[s]||t.split(/[-_]/).map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")}const L=({atRiskSubjects:t=[],onTopicClick:s})=>{const l=a.useRef(null),[c,m]=a.useState(!1);if(t.length===0)return null;const h=()=>{if(l.current){const{scrollLeft:r,scrollWidth:i,clientWidth:d}=l.current;m(r+d{s?.(r)},u=()=>{l.current&&l.current.scrollBy({left:200,behavior:"smooth"})};return e.jsxs(f.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},className:"mb-4",children:[e.jsx("h3",{className:"text-base font-bold mb-3",style:{color:o.headerText},children:"Recommended for Review"}),e.jsxs("div",{className:"relative flex items-center",children:[e.jsx("div",{ref:l,onScroll:h,className:"flex gap-2 overflow-x-auto scrollbar-hide pb-1",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:t.slice(0,8).map((r,i)=>e.jsxs("button",{onClick:()=>p(r),className:"flex items-center gap-1.5 px-4 py-2 rounded-full text-sm font-semibold transition-all hover:scale-[1.02] whitespace-nowrap",style:{backgroundColor:o.pillBg,color:o.pillText},children:[e.jsx(x,{size:14}),g(r),e.jsx(n,{size:14})]},`${r}-${i}`))}),c&&e.jsx("button",{onClick:u,className:"flex-shrink-0 ml-2 w-8 h-8 rounded-full flex items-center justify-center transition-colors",style:{backgroundColor:o.arrowBg},"aria-label":"Scroll right",children:e.jsx(n,{size:16,className:"text-gray-600"})})]}),e.jsx("style",{children:` .scrollbar-hide::-webkit-scrollbar { display: none; } diff --git a/assets/TeacherDashboard-Uxc_axO7.js b/assets/TeacherDashboard-D7do0AjP.js similarity index 72% rename from assets/TeacherDashboard-Uxc_axO7.js rename to assets/TeacherDashboard-D7do0AjP.js index 68f86a35e3430b44526f24676f374eafc968b4a4..dc2158510b731e3e198c3be9feb10c98ddbd45af 100644 --- a/assets/TeacherDashboard-Uxc_axO7.js +++ b/assets/TeacherDashboard-D7do0AjP.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BYG24j30.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); -import{e as ft,t as gl,f as yn,g as Ue,_ as Ar,u as ms,h as Mt,m as Re,i as Ko,j as me,k as bl,l as it,n as Xo,b as Vt,G as Jo,B as zr,Z as vl,o as Ya,p as mt,A as Zo,U as is,q as Ns,T as Ea,r as Ga,C as wl,v as Sn,R as Ls,w as Nl,x as Js,y as kn,z as Cn,D as ei,E as jl,F as Ka,H as yl,M as Sl,I as In,J as kl,K as Cl}from"./index-BYG24j30.js";import{d as ue,j as e,r as u,c as Lr}from"./vendor-react-B4AQeu28.js";import{B as ht,c as Il}from"./button-LR_FKM7p.js";import{I as js}from"./input-CtjqQUbX.js";import Tl from"./ConfirmModal-BDSADafu.js";import{collection as At,query as Ct,limit as Xa,where as St,getDocs as zt,doc as xt,getDoc as bs,updateDoc as ls,serverTimestamp as lt,setDoc as ts,Timestamp as El,orderBy as Rl,onSnapshot as ti,deleteDoc as _l}from"./vendor-firebase-firestore-CNv3xXal.js";import{X as ds}from"./x-DU8WEZ6X.js";import{S as Bs}from"./search-qXpo6Bz-.js";import{C as Ot}from"./check-C-Jb6xS0.js";import{P as Zs}from"./plus-C5IM0tm0.js";import{I as ba,F as vs,N as Ml,A as si}from"./NotificationDropdown-vpdHjkTB.js";import{M as Al,L as zl,D as Ll,S as Dl,a as $l}from"./LogoutActionButton-U0Q7JjxX.js";import{s as Tn,f as ai,L as Ja,d as Fl,p as Ol,a as Bl,A as Za,P as Pl,b as Hl}from"./quizService-Dg-FcCkj.js";import{S as Ql}from"./vendor-radix-BPuEd8FG.js";import{T as Gl,a as Ul,b as Vl}from"./tooltip-B8dZx5CM.js";import{C as Wl}from"./circle-help-BYya03qM.js";import{E as ql,a as Yl}from"./eye-Cjs8eHiG.js";import{S as Da}from"./send-Cs_bBaZx.js";import{T as ri}from"./trash-2-Bz07bxtW.js";import{C as lr}from"./circle-alert-D1BZWAsh.js";import{C as _t,a as Na}from"./chevron-up-vEHTl-in.js";import{M as En}from"./minus-sZ1MmK-H.js";import{C as $s}from"./chart-column-BOgIfbES.js";import{C as Dr,H as Rn,S as _n}from"./skeleton-9NZnc9sp.js";import{D as Kl}from"./download-DRtqT_j8.js";import{C as ks}from"./chevron-left-CIE_NDv7.js";import{C as Ss}from"./chevron-right-CF79oTk8.js";import{S as ni}from"./save-DidAD_jg.js";import{C as qr}from"./circle-check-_6J4FrSd.js";import{S as Fs}from"./sparkles-DiaNugT9.js";import{U as Mn}from"./upload-z5a73neo.js";import{u as Xl}from"./useQuery-C5wg1Gx-.js";import{S as An,g as Jl,G as Zl,s as zn}from"./subjects-CnMsFeDX.js";import{u as ec}from"./useCurriculum-BCsJVZ1p.js";import{C as Yr}from"./circle-check-big-uJgj_456.js";import tc from"./ChatMarkdown-Dn0t_isr.js";import{c as sc,a as oi,C as ac,f as rc}from"./formatDistanceToNow-C9WeR9GV.js";import{C as ea}from"./clock-CGFFx3Yv.js";import{B as er}from"./bell-CJfHcVLS.js";import{D as Ln,a as Dn,b as nc,c as oc,d as ic,S as lc}from"./dialog-H4V35jbm.js";import{u as Yt,r as cc}from"./vendor-xlsx-uZelXSz_.js";import{C as ii}from"./clipboard-check-CC5IRbh7.js";import{R as $n,B as Fn,C as On,X as Bn,Y as Pn,T as Hn,a as Qn,b as Gn}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-markdown-yqZQ_iQm.js";import"./log-out-7LnFvNg-.js";/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CR5aYAL9.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); +import{e as ft,t as gl,f as yn,g as Ue,_ as Ar,u as ms,h as Mt,m as Re,i as Ko,j as me,k as bl,l as it,n as Xo,b as Vt,G as Jo,B as zr,Z as vl,o as Ya,p as mt,A as Zo,U as is,q as Ns,T as Ea,r as Ga,C as wl,v as Sn,R as Ls,w as Nl,x as Js,y as kn,z as Cn,D as ei,E as jl,F as Ka,H as yl,M as Sl,I as In,J as kl,K as Cl}from"./index-CR5aYAL9.js";import{d as ue,j as e,r as u,c as Lr}from"./vendor-react-B4AQeu28.js";import{B as ht,c as Il}from"./button-CbtAHv27.js";import{I as js}from"./input-DgZjxAsx.js";import Tl from"./ConfirmModal-BVHZuXaM.js";import{collection as At,query as Ct,limit as Xa,where as St,getDocs as zt,doc as xt,getDoc as bs,updateDoc as ls,serverTimestamp as lt,setDoc as ts,Timestamp as El,orderBy as Rl,onSnapshot as ti,deleteDoc as _l}from"./vendor-firebase-firestore-CNv3xXal.js";import{X as ds}from"./x-DiyyYv8Q.js";import{S as Bs}from"./search-1a4wCp_r.js";import{C as Ot}from"./check-MAu_C8ty.js";import{P as Zs}from"./plus-Cp5Q-YTc.js";import{I as ba,F as vs,N as Ml,A as si}from"./NotificationDropdown-DBksmA1S.js";import{M as Al,L as zl,D as Ll,S as Dl,a as $l}from"./LogoutActionButton-tEi5DIaj.js";import{s as Tn,f as ai,L as Ja,d as Fl,p as Ol,a as Bl,A as Za,P as Pl,b as Hl}from"./quizService-83ZGYTl6.js";import{S as Ql}from"./vendor-radix-BPuEd8FG.js";import{T as Gl,a as Ul,b as Vl}from"./tooltip-COrnGY4E.js";import{C as Wl}from"./circle-help-CS95sLmI.js";import{E as ql,a as Yl}from"./eye-BuiZU-wn.js";import{S as Da}from"./send-B1wbvsc_.js";import{T as ri}from"./trash-2-BtGasoad.js";import{C as lr}from"./circle-alert-CSWToxPb.js";import{C as _t,a as Na}from"./chevron-up-BrrK8Cng.js";import{M as En}from"./minus-D8MfEHLl.js";import{C as $s}from"./chart-column-nZ0JrvMi.js";import{C as Dr,H as Rn,S as _n}from"./skeleton-nK8OdpwJ.js";import{D as Kl}from"./download-teQqHQmt.js";import{C as ks}from"./chevron-left-Buq4JTY_.js";import{C as Ss}from"./chevron-right-d9v3XH9Z.js";import{S as ni}from"./save-BpEMiY1d.js";import{C as qr}from"./circle-check--_-gyncR.js";import{S as Fs}from"./sparkles-Df420Y_c.js";import{U as Mn}from"./upload-Dv-dcZHV.js";import{u as Xl}from"./useQuery-CFyiy_x4.js";import{S as An,g as Jl,G as Zl,s as zn}from"./subjects-CruSaBwq.js";import{u as ec}from"./useCurriculum-BQeS3LyA.js";import{C as Yr}from"./circle-check-big-CWD8eO1a.js";import tc from"./ChatMarkdown-kQBhTXf0.js";import{c as sc,a as oi,C as ac,f as rc}from"./formatDistanceToNow-B4dD00jc.js";import{C as ea}from"./clock-BF2L28Gg.js";import{B as er}from"./bell-DVzATilo.js";import{D as Ln,a as Dn,b as nc,c as oc,d as ic,S as lc}from"./dialog-BhXeykx9.js";import{u as Yt,r as cc}from"./vendor-xlsx-uZelXSz_.js";import{C as ii}from"./clipboard-check-B4PuSMw1.js";import{R as $n,B as Fn,C as On,X as Bn,Y as Pn,T as Hn,a as Qn,b as Gn}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-markdown-yqZQ_iQm.js";import"./log-out-BT_ShBSM.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. @@ -89,21 +89,21 @@ import{e as ft,t as gl,f as yn,g as Ue,_ as Ar,u as ms,h as Mt,m as Re,i as Ko,j * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const $c=[["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"}]],Fr=ft("wand-sparkles",$c);function Fc(t,s){const a=gl(t);return isNaN(s)?sc(t,NaN):(a.setDate(a.getDate()+s),a)}function mi(t,s){const a=yn(t),r=yn(s);return+a==+r}function Vn(t){return mi(t,oi(t))}function Oc(t,s){return Fc(t,-1)}function Wn(t){return mi(t,Oc(oi(t)))}const cr=0,Is=1,ta=2,ui=4;function qn(t){return()=>t}function Bc(t){t()}function xi(t,s){return a=>t(s(a))}function Yn(t,s){return()=>t(s)}function Pc(t,s){return a=>t(s,a)}function Kr(t){return t!==void 0}function Hc(...t){return()=>{t.map(Bc)}}function sa(){}function dr(t,s){return s(t),t}function Qc(t,s){return s(t)}function et(...t){return t}function Ve(t,s){return t(Is,s)}function Ie(t,s){t(cr,s)}function Xr(t){t(ta)}function st(t){return t(ui)}function pe(t,s){return Ve(t,Pc(s,cr))}function ss(t,s){const a=t(Is,r=>{a(),s(r)});return a}function Kn(t){let s,a;return r=>o=>{s=o,a&&clearTimeout(a),a=setTimeout(()=>{r(s)},t)}}function pi(t,s){return t===s}function Ze(t=pi){let s;return a=>r=>{t(s,r)||(s=r,a(r))}}function ve(t){return s=>a=>{t(a)&&s(a)}}function le(t){return s=>xi(s,t)}function ns(t){return s=>()=>{s(t)}}function U(t,...s){const a=Gc(...s);return((r,o)=>{switch(r){case ta:Xr(t);return;case Is:return Ve(t,a(o))}})}function os(t,s){return a=>r=>{a(s=t(s,r))}}function Os(t){return s=>a=>{t>0?t--:s(a)}}function ws(t){let s=null,a;return r=>o=>{s=o,!a&&(a=setTimeout(()=>{a=void 0,r(s)},t))}}function Te(...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;Ve(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 Gc(...t){return s=>t.reduceRight(Qc,s)}function Uc(t){let s,a;const r=()=>s?.();return function(o,n){switch(o){case Is:return n?a===n?void 0:(r(),a=n,s=Ve(t,n),s):(r(),sa);case ta:r(),a=null;return}}}function X(t){let s=t;const a=Le();return((r,o)=>{switch(r){case cr:s=o;break;case Is:{o(s);break}case ui:return s}return a(r,o)})}function kt(t,s){return dr(X(s),a=>pe(t,a))}function Le(){const t=[];return((s,a)=>{switch(s){case cr:t.slice().forEach(r=>{r(a)});return;case ta:t.splice(0,t.length);return;case Is:return t.push(a),()=>{const r=t.indexOf(a);r>-1&&t.splice(r,1)}}})}function Pt(t){return dr(Le(),s=>pe(t,s))}function Qe(t,s=[],{singleton:a}={singleton:!0}){return{constructor:t,dependencies:s,id:Vc(),singleton:a}}const Vc=()=>Symbol();function Wc(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 ct(...t){const s=Le(),a=new Array(t.length);let r=0;const o=2**t.length-1;return t.forEach((n,i)=>{const l=2**i;Ve(n,c=>{a[i]=c,r|=l,r===o&&Ie(s,a)})}),function(n,i){switch(n){case ta:{Xr(s);return}case Is:return r===o&&i(a),Ve(s,i)}}}function be(t,s=pi){return U(t,Ze(s))}function Or(...t){return function(s,a){switch(s){case ta:return;case Is:return Hc(...t.map(r=>Ve(r,a)))}}}const pt={DEBUG:0,INFO:1,WARN:2,ERROR:3},qc={[pt.DEBUG]:"debug",[pt.ERROR]:"error",[pt.INFO]:"log",[pt.WARN]:"warn"},Yc=()=>typeof globalThis>"u"?window:globalThis,Ts=Qe(()=>{const t=X(pt.ERROR);return{log:X((s,a,r=pt.INFO)=>{const o=Yc().VIRTUOSO_LOG_LEVEL??st(t);r>=o&&console[qc[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",s,a)}),logLevel:t}},[],{singleton:!0});function Ps(t,s,a){return Jr(t,s,a).callbackRef}function Jr(t,s,a){const r=ue.useRef(null);let o=i=>{};const n=ue.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 Kc(t,s,a,r,o,n,i,l,c){const d=ue.useCallback(m=>{const f=Xc(m.children,s,l?"offsetWidth":"offsetHeight",o);let p=m.parentElement;for(;p.dataset.virtuosoScroller===void 0;)p=p.parentElement;const g=p.lastElementChild.dataset.viewportType==="window";let S;g&&(S=p.ownerDocument.defaultView);const N=i?l?i.scrollLeft:i.scrollTop:g?l?S.scrollX||S.document.documentElement.scrollLeft:S.scrollY||S.document.documentElement.scrollTop:l?p.scrollLeft:p.scrollTop,j=i?l?i.scrollWidth:i.scrollHeight:g?l?S.document.documentElement.scrollWidth:S.document.documentElement.scrollHeight:l?p.scrollWidth:p.scrollHeight,h=i?l?i.offsetWidth:i.offsetHeight:g?l?S.innerWidth:S.innerHeight:l?p.offsetWidth:p.offsetHeight;r({scrollHeight:j,scrollTop:Math.max(N,0),viewportHeight:h}),n?.(l?Xn("column-gap",getComputedStyle(m).columnGap,o):Xn("row-gap",getComputedStyle(m).rowGap,o)),f!==null&&t(f)},[t,s,o,n,i,r,l]);return Jr(d,a,c)}function Xc(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 f,p;if(s){const g=s.getBoundingClientRect(),S=d.top-g.top;p=g.height-Math.max(0,S),f=S+s.scrollTop}else{const g=i.current.ownerDocument.defaultView;p=g.innerHeight-Math.max(0,d.top),f=d.top+g.scrollY}r.current={listHeight:d.height,offsetTop:f,visibleHeight:p,visibleWidth:m},t(r.current)},[t,s]),{callbackRef:n,ref:i}=Jr(o,!0,a),l=ue.useCallback(()=>{o(i.current)},[o,i]);return ue.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 It=Qe(()=>{const t=Le(),s=Le(),a=X(0),r=Le(),o=X(0),n=Le(),i=Le(),l=X(0),c=X(0),d=X(0),m=X(0),f=Le(),p=Le(),g=X(!1),S=X(!1),N=X(!1);return pe(U(t,le(({scrollTop:j})=>j)),s),pe(U(t,le(({scrollHeight:j})=>j)),i),pe(s,o),{deviation:a,fixedFooterHeight:d,fixedHeaderHeight:c,footerHeight:m,headerHeight:l,horizontalDirection:S,scrollBy:p,scrollContainerState:t,scrollHeight:i,scrollingInProgress:g,scrollTo:f,scrollTop:s,skipAnimationFrameInResizeObserver:N,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:n}},[],{singleton:!0}),ja={lvl:0};function fi(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(Pr(o,s,a))),r>=s&&r<=a&&l.push({k:r,v:i}),r<=a&&(l=l.concat(Pr(n,s,a))),l}function Ua(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(Nr(s))return wi(ut(t,{lvl:a-1}));if(!Ke(s)&&!Ke(s.r))return ut(s.r,{l:ut(s,{r:s.r.l}),lvl:a,r:ut(t,{l:s.r.r,lvl:a-1})});throw new Error("Unexpected empty nodes")}if(Nr(t))return Hr(ut(t,{lvl:a-1}));if(!Ke(r)&&!Ke(r.l)){const o=r.l,n=Nr(o)?r.lvl-1:r.lvl;return ut(o,{l:ut(t,{lvl:a-1,r:o.l}),lvl:o.lvl+1,r:Hr(ut(r,{l:o.r,lvl:n}))})}throw new Error("Unexpected empty nodes")}function ut(t,s){return vi(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 gi(t){return Ke(t.r)?t.l:Ua(ut(t,{r:gi(t.r)}))}function Nr(t){return Ke(t)||t.lvl>t.r.lvl}function bi(t){return Ke(t.r)?[t.k,t.v]:bi(t.r)}function vi(t,s,a,r=ja,o=ja){return{k:t,l:r,lvl:a,r:o,v:s}}function Jn(t){return Hr(wi(t))}function wi(t){const{l:s}=t;return!Ke(s)&&s.lvl===t.lvl?ut(s,{r:ut(t,{l:s.r})}):t}function Hr(t){const{lvl:s,r:a}=t;return!Ke(a)&&!Ke(a.r)&&a.lvl===s&&a.r.lvl===s?ut(a,{l:ut(t,{r:a.l}),lvl:s+1}):t}function Jc(t){return fi(t,({k:s,v:a})=>({index:s,value:a}))}function Ni(t,s){return!!(t&&t.startIndex===s.startIndex&&t.endIndex===s.endIndex)}function Sa(t,s){return!!(t&&t[0]===s[0]&&t[1]===s[1])}const Zr=Qe(()=>({recalcInProgress:X(!1)}),[],{singleton:!0});function ji(t,s,a){return t[sr(t,s,a)]}function sr(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 Zc(t,s,a,r){const o=sr(t,s,r),n=sr(t,a,r,o);return t.slice(o,n+1)}function Cs(t,s){return Math.round(t.getBoundingClientRect()[s])}function mr(t){return!Ke(t.groupOffsetTree)}function en({index:t},s){return s===t?0:s=f||n===p)&&(t=Br(t,f)):(d=p!==n,c=!0),m>o&&o>=f&&p!==n&&(t=Bt(t,o+1,p));d&&(t=Bt(t,i,n))}return[t,a]}function sd(t){return typeof t.groupIndex<"u"}function ad({offset:t},s){return s===t?0:s0?l+a:l}function yi(t,s){if(!mr(s))return t;let a=0;for(;s.groupIndices[a]<=t+a;)a++;return t+a}function Si(t,s,a){if(sd(t))return s.groupIndices[t.groupIndex]+1;const r=t.index==="LAST"?a:t.index;let o=yi(r,s);return o=Math.max(0,o,Math.min(a,o)),o}function rd(t,s,a,r=0){return r>0&&(s=Math.max(s,ji(t,r,en).offset)),fi(Zc(t,s,a,ad),id)}function nd(t,[s,a,r,o]){s.length>0&&r("received item sizes",s,pt.DEBUG);const n=t.sizeTree;let i=n,l=0;if(a.length>0&&Ke(n)&&s.length===2){const p=s[0].size,g=s[1].size;i=a.reduce((S,N)=>Bt(Bt(S,N,p),N+1,g),i)}else[i,l]=td(i,s);if(i===n)return t;const{lastIndex:c,lastOffset:d,lastSize:m,offsetTree:f}=Qr(t.offsetTree,l,i,o);return{groupIndices:a,groupOffsetTree:a.reduce((p,g)=>Bt(p,g,ka(g,f,o)),Ks()),lastIndex:c,lastOffset:d,lastSize:m,offsetTree:f,sizeTree:i}}function od(t){return Ds(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 Zn(t,s){let a=0,r=0;for(;ao.start===r&&(o.end===s||o.end===1/0)&&o.value===a}const cd={offsetHeight:"height",offsetWidth:"width"},us=Qe(([{log:t},{recalcInProgress:s}])=>{const a=Le(),r=Le(),o=kt(r,0),n=Le(),i=Le(),l=X(0),c=X([]),d=X(void 0),m=X(void 0),f=X(void 0),p=X(void 0),g=X((b,y)=>Cs(b,cd[y])),S=X(void 0),N=X(0),j=ed(),h=kt(U(a,Te(c,t,N),os(nd,j),Ze()),j),w=kt(U(c,Ze(),os((b,y)=>({current:y,prev:b.current}),{current:[],prev:[]}),le(({prev:b})=>b)),[]);pe(U(c,ve(b=>b.length>0),Te(h,N),le(([b,y,v])=>{const z=b.reduce((F,I,V)=>Bt(F,I,ka(I,y.offsetTree,v)||V),Ks());return{...y,groupIndices:b,groupOffsetTree:z}})),h),pe(U(r,Te(h),ve(([b,{lastIndex:y}])=>b[{endIndex:y,size:v,startIndex:b}])),a),pe(d,m);const C=kt(U(d,le(b=>b===void 0)),!0);pe(U(m,ve(b=>b!==void 0&&Ke(st(h).sizeTree)),le(b=>{const y=st(f),v=st(c).length>0;return y!==void 0&&y!==0?v?[{endIndex:0,size:y,startIndex:0},{endIndex:1,size:b,startIndex:1}]:[]:[{endIndex:0,size:b,startIndex:0}]})),a),pe(U(p,ve(b=>b!==void 0&&b.length>0&&Ke(st(h).sizeTree)),le(b=>{const y=[];let v=b[0],z=0;for(let F=1;Fb!==void 0&&y!==void 0),le(([b,y,v])=>{const z=[];for(let F=0;F({changed:v!==b,sizes:v}),{changed:!1,sizes:j}),le(b=>b.changed)));Ve(U(l,os((b,y)=>({diff:b.prev-y,prev:y}),{diff:0,prev:0}),le(b=>b.diff)),b=>{const{groupIndices:y}=st(h);if(b>0)Ie(s,!0),Ie(n,b+Zn(b,y));else if(b<0){const v=st(w);v.length>0&&(b-=Zn(-b,v)),Ie(i,b)}}),Ve(U(l,Te(t)),([b,y])=>{b<0&&y("`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},pt.ERROR)});const k=Pt(n);pe(U(n,Te(h),le(([b,y])=>{const v=y.groupIndices.length>0,z=[],F=y.lastSize;if(v){const I=ya(y.sizeTree,0);let V=0,Y=0;for(;V{let we=ie.ranges;return ie.prevSize!==0&&(we=[...ie.ranges,{endIndex:ae+b-1,size:ie.prevSize,startIndex:ie.prevIndex}]),{prevIndex:ae+b,prevSize:he,ranges:we}},{prevIndex:b,prevSize:0,ranges:z}).ranges}return Ds(y.sizeTree).reduce((I,{k:V,v:Y})=>({prevIndex:V+b,prevSize:Y,ranges:[...I.ranges,{endIndex:V+b-1,size:I.prevSize,startIndex:I.prevIndex}]}),{prevIndex:0,prevSize:F,ranges:[]}).ranges})),a);const W=Pt(U(i,Te(h,N),le(([b,{offsetTree:y},v])=>{const z=-b;return ka(z,y,v)})));return pe(U(i,Te(h,N),le(([b,y,v])=>{if(y.groupIndices.length>0){if(Ke(y.sizeTree))return y;let F=Ks();const I=st(w);let V=0,Y=0,se=0;for(;V<-b;){se=I[Y];const ie=I[Y+1]-se-1;Y++,V+=ie+1}if(F=Ds(y.sizeTree).reduce((ie,{k:ae,v:he})=>Bt(ie,Math.max(0,ae+b),he),F),V!==-b){const ie=ya(y.sizeTree,se);F=Bt(F,0,ie);const ae=as(y.sizeTree,-b+1)[1];F=Bt(F,1,ae)}return{...y,sizeTree:F,...Qr(y.offsetTree,0,F,v)}}const z=Ds(y.sizeTree).reduce((F,{k:I,v:V})=>Bt(F,Math.max(0,I+b),V),Ks());return{...y,sizeTree:z,...Qr(y.offsetTree,0,z,v)}})),h),{beforeUnshiftWith:k,data:S,defaultItemSize:m,firstItemIndex:l,fixedItemSize:d,fixedGroupSize:f,gap:N,groupIndices:c,heightEstimates:p,itemSize:g,listRefresh:M,shiftWith:i,shiftWithOffset:W,sizeRanges:a,sizes:h,statefulTotalCount:o,totalCount:r,trackItemSizes:C,unshiftWith:n}},et(Ts,Zr),{singleton:!0});function dd(t){return t.reduce((s,a)=>(s.groupIndices.push(s.totalCount),s.totalCount+=a+1,s),{groupIndices:[],totalCount:0})}const ki=Qe(([{groupIndices:t,sizes:s,totalCount:a},{headerHeight:r,scrollTop:o}])=>{const n=Le(),i=Le(),l=Pt(U(n,le(dd)));return pe(U(l,le(c=>c.totalCount)),a),pe(U(l,le(c=>c.groupIndices)),t),pe(U(ct(o,s,r),ve(([c,d])=>mr(d)),le(([c,d,m])=>as(d.groupOffsetTree,Math.max(c-m,0),"v")[0]),Ze(),le(c=>[c])),i),{groupCounts:n,topItemsIndexes:i}},et(us,It)),Es=Qe(([{log:t}])=>{const s=X(!1),a=Pt(U(s,ve(r=>r),Ze()));return Ve(s,r=>{r&&st(t)("props updated",{},pt.DEBUG)}),{didMount:a,propsReady:s}},et(Ts),{singleton:!0}),md=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Ci(t){const s=typeof t=="number"?{index:t}:t;return s.align||(s.align="start"),(!s.behavior||!md)&&(s.behavior="auto"),s.offset===void 0&&(s.offset=0),s}const Ra=Qe(([{gap:t,listRefresh:s,sizes:a,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:n,footerHeight:i,headerHeight:l,scrollingInProgress:c,scrollTo:d,smoothScrollTargetReached:m,viewportHeight:f},{log:p}])=>{const g=Le(),S=Le(),N=X(0);let j=null,h=null,w=null;function C(){j!==null&&(j(),j=null),w!==null&&(w(),w=null),h&&(clearTimeout(h),h=null),Ie(c,!1)}return pe(U(g,Te(a,f,r,N,l,i,p),Te(t,n,o),le(([[M,k,W,b,y,v,z,F],I,V,Y])=>{const se=Ci(M),{align:ie,behavior:ae,offset:he}=se,we=b-1,O=Si(se,k,we);let J=ka(O,k.offsetTree,I)+v;ie==="end"?(J+=V+as(k.sizeTree,O)[1]-W+Y,O===we&&(J+=z)):ie==="center"?J+=(V+as(k.sizeTree,O)[1]-W+Y)/2:J-=y,he!==void 0&&he!==0&&(J+=he);const A=Z=>{C(),Z?(F("retrying to scroll to",{location:M},pt.DEBUG),Ie(g,M)):(Ie(S,!0),F("list did not change, scroll successful",{},pt.DEBUG))};if(C(),ae==="smooth"){let Z=!1;w=Ve(s,ne=>{Z=Z||ne}),j=ss(m,()=>{A(Z)})}else j=ss(U(s,ud(150)),A);return h=setTimeout(()=>{C()},1200),Ie(c,!0),F("scrolling from index to",{behavior:ae,index:O,top:J},pt.DEBUG),{behavior:ae,top:J}})),d),{scrollTargetReached:S,scrollToIndex:g,topListHeight:N}},et(us,It,Ts),{singleton:!0});function ud(t){return s=>{const a=setTimeout(()=>{s(!1)},t);return r=>{r&&(s(!0),clearTimeout(a))}}}function tn(t,s){t===0?s():requestAnimationFrame(()=>{tn(t-1,s)})}function sn(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=X(!0),c=X(0),d=X(!0);return pe(U(i,Te(c),ve(([m,f])=>f!==0),ns(!1)),l),pe(U(i,Te(c),ve(([m,f])=>f!==0),ns(!1)),d),Ve(U(ct(s,i),Te(l,a,t,d),ve(([[,m],f,{sizeTree:p},g,S])=>m&&(!Ke(p)||Kr(g))&&!f&&!S),Te(c)),([,m])=>{ss(o,()=>{Ie(d,!0)}),tn(4,()=>{ss(r,()=>{Ie(l,!0)}),Ie(n,m)})}),{initialItemFinalLocationReached:d,initialTopMostItemIndex:c,scrolledToInitialItem:l}},et(us,It,Ra,Es),{singleton:!0});function Ii(t,s){return Math.abs(t-s)<1.01}const Ca="up",va="down",xd="none",pd={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},hd=0,Ma=Qe(([{footerHeight:t,headerHeight:s,scrollBy:a,scrollContainerState:r,scrollTop:o,viewportHeight:n}])=>{const i=X(!1),l=X(!0),c=Le(),d=Le(),m=X(4),f=X(hd),p=kt(U(Or(U(be(o),Os(1),ns(!0)),U(be(o),Os(1),ns(!1),Kn(100))),Ze()),!1),g=kt(U(Or(U(a,ns(!0)),U(a,ns(!1),Kn(200))),Ze()),!1);pe(U(ct(be(o),be(f)),le(([w,C])=>w<=C),Ze()),l),pe(U(l,ws(50)),d);const S=Pt(U(ct(r,be(n),be(s),be(t),be(m)),os((w,[{scrollHeight:C,scrollTop:M},k,W,b,y])=>{const v=M+k-C>-y,z={scrollHeight:C,scrollTop:M,viewportHeight:k};if(v){let I,V;return M>w.state.scrollTop?(I="SCROLLED_DOWN",V=w.state.scrollTop-M):(I="SIZE_DECREASED",V=w.state.scrollTop-M||w.scrollTopDelta),{atBottom:!0,atBottomBecause:I,scrollTopDelta:V,state:z}}let F;return z.scrollHeight>w.state.scrollHeight?F="SIZE_INCREASED":kw!==void 0&&w.atBottom===C.atBottom))),N=kt(U(r,os((w,{scrollHeight:C,scrollTop:M,viewportHeight:k})=>{if(!Ii(w.scrollHeight,C)){const W=C-(M+k)<1;return w.scrollTop!==M&&W?{changed:!0,jump:w.scrollTop-M,scrollHeight:C,scrollTop:M}:{changed:!0,jump:0,scrollHeight:C,scrollTop:M}}return{changed:!1,jump:0,scrollHeight:C,scrollTop:M}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),ve(w=>w.changed),le(w=>w.jump)),0);pe(U(S,le(w=>w.atBottom)),i),pe(U(i,ws(50)),c);const j=X(va);pe(U(r,le(({scrollTop:w})=>w),Ze(),os((w,C)=>st(g)?{direction:w.direction,prevScrollTop:C}:{direction:Cw.direction)),j),pe(U(r,ws(50),ns(xd)),j);const h=X(0);return pe(U(p,ve(w=>!w),ns(0)),h),pe(U(o,ws(100),Te(p),ve(([w,C])=>C),os(([w,C],[M])=>[C,M],[0,0]),le(([w,C])=>C-w)),h),{atBottomState:S,atBottomStateChange:c,atBottomThreshold:m,atTopStateChange:d,atTopThreshold:f,isAtBottom:i,isAtTop:l,isScrolling:p,lastJumpDueToItemResize:N,scrollDirection:j,scrollVelocity:h}},et(It)),Ia="top",Ta="bottom",eo="none";function to(t,s,a){return typeof t=="number"?a===Ca&&s===Ia||a===va&&s===Ta?t:0:a===Ca?s===Ia?t.main:t.reverse:s===Ta?t.main:t.reverse}function so(t,s){return typeof t=="number"?t:t[s]??0}const an=Qe(([{deviation:t,fixedHeaderHeight:s,headerHeight:a,scrollTop:r,viewportHeight:o}])=>{const n=Le(),i=X(0),l=X(0),c=X(0),d=kt(U(ct(be(r),be(o),be(a),be(n,Sa),be(c),be(i),be(s),be(t),be(l)),le(([m,f,p,[g,S],N,j,h,w,C])=>{const M=m-w,k=j+h,W=Math.max(p-M,0);let b=eo;const y=so(C,Ia),v=so(C,Ta);return g-=w,g+=p+h,S+=p+h,S-=w,g>m+k-y&&(b=Ca),Sm!==null),Ze(Sa)),[0,0]);return{increaseViewportBy:l,listBoundary:n,overscan:c,topListHeight:i,visibleRange:d}},et(It),{singleton:!0});function fd(t,s,a){if(mr(s)){const r=yi(t,s);return[{index:as(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 jr={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Va(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 N=t[t.length-1];m=N.offset+N.size}const f=a-i,p=l+f*c+(f-1)*r,g=d,S=p-m;return{bottom:m,firstItemIndex:n,items:ao(t,o,n),offsetBottom:S,offsetTop:d,top:g,topItems:ao(s,o,n),topListHeight:s.reduce((N,j)=>j.size+N,0),totalCount:a}}function Ti(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=sn(s,l),d=Array.from({length:l}).map((m,f)=>({data:n[f+c],index:f+c,offset:0,size:0}));return Va(d,[],l,o,a,r)}function ao(t,s,a){if(t.length===0)return[];if(!mr(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=Xs(s.groupOffsetTree,r,o);let l,c=0;for(const d of t){(!l||l.end{const N=X([]),j=X(0),h=Le(),w=X(0);pe(n.topItemsIndexes,N);const C=kt(U(ct(g,S,be(c,Sa),be(o),be(r),be(d),m,be(N),be(s),be(a),be(w),t),ve(([b,y,,v,,,,,,,,z])=>{const F=z!==void 0&&z.length!==v;return b&&!y&&!F}),le(([,,[b,y],v,z,F,I,V,Y,se,ie,ae])=>{const he=z,{offsetTree:we,sizeTree:O}=he,J=st(j);if(v===0)return{...jr,totalCount:v};if(b===0&&y===0)return J===0?{...jr,totalCount:v}:Ti(J,F,z,Y,se,ae||[]);if(Ke(O))return J>0?null:Va(fd(sn(F,v),he,ae),[],v,se,he,Y);const A=[];if(V.length>0){const re=V[0],T=V[V.length-1];let G=0;for(const H of Xs(O,re,T)){const ce=H.value,_=Math.max(H.start,re),Q=Math.min(H.end,T);for(let q=_;q<=Q;q++)A.push({data:ae?.[q],index:q,offset:G,size:ce}),G+=ce}}if(!I)return Va([],A,v,se,he,Y);const Z=V.length>0?V[V.length-1]+1:0,ne=rd(we,b,y,Z);if(ne.length===0)return null;const $e=v-1,Me=dr([],re=>{for(const T of ne){const G=T.value;let H=G.offset,ce=T.start;const _=G.size;if(G.offset=y);q++)re.push({data:ae?.[q],index:q,offset:H,size:_}),H+=_+se}}),We=ro(ie,Ia),P=ro(ie,Ta);if(Me.length>0&&(We>0||P>0)){const re=Me[0],T=Me[Me.length-1];if(We>0&&re.index>Z){const G=Math.min(We,re.index-Z),H=[];let ce=re.offset;for(let _=re.index-1;_>=re.index-G;_--){const Q=Xs(O,_,_)[0]?.value??re.size;ce-=Q+se,H.unshift({data:ae?.[_],index:_,offset:ce,size:Q})}Me.unshift(...H)}if(P>0&&T.index<$e){const G=Math.min(P,$e-T.index);let H=T.offset+T.size+se;for(let ce=T.index+1;ce<=T.index+G;ce++){const _=Xs(O,ce,ce)[0]?.value??T.size;Me.push({data:ae?.[ce],index:ce,offset:H,size:_}),H+=_+se}}}return Va(Me,A,v,se,he,Y)}),ve(b=>b!==null),Ze()),jr);pe(U(t,ve(Kr),le(b=>b?.length)),o),pe(U(C,le(b=>b.topListHeight)),f),pe(f,l),pe(U(C,le(b=>[b.top,b.bottom])),i),pe(U(C,le(b=>b.items)),h);const M=Pt(U(C,ve(({items:b})=>b.length>0),Te(o,t),ve(([{items:b},y])=>b[b.length-1].originalIndex===y-1),le(([,b,y])=>[b-1,y]),Ze(Sa),le(([b])=>b))),k=Pt(U(C,ws(200),ve(({items:b,topItems:y})=>b.length>0&&b[0].originalIndex===y.length),le(({items:b})=>b[0].index),Ze())),W=Pt(U(C,ve(({items:b})=>b.length>0),le(({items:b})=>{let y=0,v=b.length-1;for(;b[y].type==="group"&&yy;)v--;return{endIndex:b[v].index,startIndex:b[y].index}}),Ze(Ni)));return{endReached:M,initialItemCount:j,itemsRendered:h,listState:C,minOverscanItemCount:w,rangeChanged:W,startReached:k,topItemsIndexes:N,...p}},et(us,ki,an,_a,Ra,Ma,Es,Zr),{singleton:!0}),Ei=Qe(([{fixedFooterHeight:t,fixedHeaderHeight:s,footerHeight:a,headerHeight:r},{listState:o}])=>{const n=Le(),i=kt(U(ct(a,t,r,s,o),le(([l,c,d,m,f])=>l+c+d+m+f.offsetBottom+f.bottom)),0);return pe(be(i),n),{totalListHeight:i,totalListHeightChanged:n}},et(It,Hs),{singleton:!0}),gd=Qe(([{viewportHeight:t},{totalListHeight:s}])=>{const a=X(!1),r=kt(U(ct(a,t,s),ve(([o])=>o),le(([,o,n])=>Math.max(0,o-n)),ws(0),Ze()),0);return{alignToBottom:a,paddingTopAddition:r}},et(It,Ei),{singleton:!0}),Ri=Qe(()=>({context:X(null)})),bd=({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,_i=Qe(([{gap:t,sizes:s,totalCount:a},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:n,scrollingInProgress:i,scrollTop:l,viewportHeight:c},{scrollToIndex:d}])=>{const m=Le();return pe(U(m,Te(s,c,a,n,o,r,l),Te(t),le(([[f,p,g,S,N,j,h,w],C])=>{const{calculateViewLocation:M=bd,done:k,...W}=f,b=Si(f,p,S-1),y=ka(b,p.offsetTree,C)+N+j,v=y+as(p.sizeTree,b)[1],z=w+j,F=w+g-h,I=M({itemBottom:v,itemTop:y,locationParams:W,viewportBottom:F,viewportTop:z});return I!==null?k&&ss(U(i,ve(V=>!V),Os(st(i)?1:2)),k):k?.(),I}),ve(f=>f!==null)),d),{scrollIntoView:m}},et(us,It,Ra,Hs,Ts),{singleton:!0});function no(t){return t===!1?!1:t==="smooth"?"smooth":"auto"}const vd=(t,s)=>typeof t=="function"?no(t(s)):s&&no(t),wd=Qe(([{listRefresh:t,totalCount:s,fixedItemSize:a,data:r},{atBottomState:o,isAtBottom:n},{scrollToIndex:i},{scrolledToInitialItem:l},{didMount:c,propsReady:d},{log:m},{scrollingInProgress:f},{context:p},{scrollIntoView:g}])=>{const S=X(!1),N=Le();let j=null;function h(k){Ie(i,{align:"end",behavior:k,index:"LAST"})}Ve(U(ct(U(be(s),Os(1)),c),Te(be(S),n,l,f),le(([[k,W],b,y,v,z])=>{let F=W&&v,I="auto";return F&&(I=vd(b,y||z),F=F&&I!==!1),{followOutputBehavior:I,shouldFollow:F,totalCount:k}}),ve(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:W})=>{j!==null&&(j(),j=null),st(a)!==void 0?requestAnimationFrame(()=>{st(m)("following output to ",{totalCount:W},pt.DEBUG),h(k)}):j=ss(t,()=>{st(m)("following output to ",{totalCount:W},pt.DEBUG),h(k),j=null})});function w(k){const W=ss(o,b=>{k&&!b.atBottom&&b.notAtBottomBecause==="SIZE_INCREASED"&&j===null&&(st(m)("scrolling to bottom due to increased size",{},pt.DEBUG),h("auto"))});setTimeout(W,100)}Ve(U(ct(be(S),s,d),ve(([k,,W])=>k!==!1&&W),os(({value:k},[,W])=>({refreshed:k===W,value:W}),{refreshed:!1,value:0}),ve(({refreshed:k})=>k),Te(S,s)),([,k])=>{st(l)&&w(k!==!1)}),Ve(N,()=>{w(st(S)!==!1)}),Ve(ct(be(S),o),([k,W])=>{k!==!1&&!W.atBottom&&W.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&h("auto")});const C=X(null),M=Le();return pe(Or(U(be(r),le(k=>k?.length??0)),U(be(s))),M),Ve(U(ct(U(M,Os(1)),c),Te(be(C),l,f,p),le(([[k,W],b,y,v,z])=>W&&y&&b?.({context:z,totalCount:k,scrollingInProgress:v})),ve(k=>!!k),ws(0)),k=>{j!==null&&(j(),j=null),st(a)!==void 0?requestAnimationFrame(()=>{st(m)("scrolling into view",{}),Ie(g,k)}):j=ss(t,()=>{st(m)("scrolling into view",{}),Ie(g,k),j=null})}),{autoscrollToBottom:N,followOutput:S,scrollIntoViewOnChange:C}},et(us,Ma,Ra,_a,Es,Ts,It,Ri,_i)),Nd=Qe(([{data:t,firstItemIndex:s,gap:a,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:n,listState:i},{didMount:l}])=>(pe(U(l,Te(n),ve(([,c])=>c!==0),Te(o,r,s,a,t),le(([[,c],d,m,f,p,g=[]])=>Ti(c,d,m,f,p,g))),i),{}),et(us,_a,Hs,Es),{singleton:!0}),jd=Qe(([{didMount:t},{scrollTo:s},{listState:a}])=>{const r=X(0);return Ve(U(t,Te(r),ve(([,o])=>o!==0),le(([,o])=>({top:o}))),o=>{ss(U(a,Os(1),ve(n=>n.items.length>1)),()=>{requestAnimationFrame(()=>{Ie(s,o)})})}),{initialScrollTop:r}},et(Es,It,Hs),{singleton:!0}),Mi=Qe(([{scrollVelocity:t}])=>{const s=X(!1),a=Le(),r=X(!1);return pe(U(t,Te(r,s,a),ve(([o,n])=>n!==!1&&n!==void 0),le(([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}),Ze()),s),Ve(U(ct(s,t,a),Te(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}},et(Ma),{singleton:!0}),rn=Qe(([{scrollContainerState:t,scrollTo:s}])=>{const a=Le(),r=Le(),o=Le(),n=X(!1),i=X(void 0);return pe(U(ct(a,r),le(([{scrollTop:l,viewportHeight:c},{offsetTop:d,listHeight:m}])=>({scrollHeight:m,scrollTop:Math.max(0,l-d),viewportHeight:c}))),t),pe(U(s,Te(r),le(([l,{offsetTop:c}])=>({...l,top:l.top+c}))),o),{customScrollParent:i,useWindowScroll:n,windowScrollContainerState:a,windowScrollTo:o,windowViewportRect:r}},et(It)),yd=Qe(([{sizeRanges:t,sizes:s},{headerHeight:a,scrollTop:r},{initialTopMostItemIndex:o},{didMount:n},{useWindowScroll:i,windowScrollContainerState:l,windowViewportRect:c}])=>{const d=Le(),m=X(void 0),f=X(null),p=X(null);return pe(l,f),pe(c,p),Ve(U(d,Te(s,r,i,f,p,a)),([g,S,N,j,h,w,C])=>{const M=od(S.sizeTree);j&&h!==null&&w!==null&&(N=h.scrollTop-w.offsetTop),N-=C,g({ranges:M,scrollTop:N})}),pe(U(m,ve(Kr),le(Sd)),o),pe(U(n,Te(m),ve(([,g])=>g!==void 0),Ze(),le(([,g])=>g.ranges)),t),{getState:d,restoreStateFrom:m}},et(us,It,_a,Es,rn));function Sd(t){return{align:"start",index:0,offset:t.scrollTop}}const kd=Qe(([{topItemsIndexes:t}])=>{const s=X(0);return pe(U(s,ve(a=>a>=0),le(a=>Array.from({length:a}).map((r,o)=>o))),t),{topItemCount:s}},et(Hs));function Ai(t){let s=!1,a;return(()=>(s||(s=!0,a=t()),a))}const Cd=Ai(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Id=Qe(([{deviation:t,scrollBy:s,scrollingInProgress:a,scrollTop:r},{isAtBottom:o,isScrolling:n,lastJumpDueToItemResize:i,scrollDirection:l},{listState:c},{beforeUnshiftWith:d,gap:m,shiftWithOffset:f,sizes:p},{log:g},{recalcInProgress:S}])=>{const N=Pt(U(c,Te(i),os(([,h,w,C],[{bottom:M,items:k,offsetBottom:W,totalCount:b},y])=>{const v=M+W;let z=0;return w===b&&h.length>0&&k.length>0&&(k[0].originalIndex===0&&h[0].originalIndex===0||(z=v-C,z!==0&&(z+=y))),[z,k,b,v]},[0,[],0,0]),ve(([h])=>h!==0),Te(r,l,a,o,g,S),ve(([,h,w,C,,,M])=>!M&&!C&&h!==0&&w===Ca),le(([[h],,,,,w])=>(w("Upward scrolling compensation",{amount:h},pt.DEBUG),h))));function j(h){h>0?(Ie(s,{behavior:"auto",top:-h}),Ie(t,0)):(Ie(t,0),Ie(s,{behavior:"auto",top:-h}))}return Ve(U(N,Te(t,n)),([h,w,C])=>{C&&Cd()?Ie(t,w-h):j(-h)}),Ve(U(ct(kt(n,!1),t,S),ve(([h,w,C])=>!h&&!C&&w!==0),le(([h,w])=>w),ws(1)),j),pe(U(f,le(h=>({top:-h}))),s),Ve(U(d,Te(p,m),le(([h,{groupIndices:w,lastSize:C,sizeTree:M},k])=>{function W(F){return F*(C+k)}if(w.length===0)return W(h);let b=0;const y=ya(M,0);let v=0,z=0;for(;vh&&(b-=y,F=h-v+1),v+=F,b+=W(F),z++}return b})),h=>{Ie(t,h),requestAnimationFrame(()=>{Ie(s,{top:h}),requestAnimationFrame(()=>{Ie(t,0),Ie(S,!1)})})}),{deviation:t}},et(It,Ma,Hs,us,Ts,Zr)),Td=Qe(([t,s,a,r,o,n,i,l,c,d,m])=>({...t,...s,...a,...r,...o,...n,...i,...l,...c,...d,...m}),et(an,Nd,Es,Mi,Ei,jd,gd,rn,_i,Ts,Ri)),zi=Qe(([{data:t,defaultItemSize:s,firstItemIndex:a,fixedItemSize:r,fixedGroupSize:o,gap:n,groupIndices:i,heightEstimates:l,itemSize:c,sizeRanges:d,sizes:m,statefulTotalCount:f,totalCount:p,trackItemSizes:g},{initialItemFinalLocationReached:S,initialTopMostItemIndex:N,scrolledToInitialItem:j},h,w,C,M,{scrollToIndex:k},W,{topItemCount:b},{groupCounts:y},v])=>{const{listState:z,minOverscanItemCount:F,topItemsIndexes:I,rangeChanged:V,...Y}=M;return pe(V,v.scrollSeekRangeChanged),pe(U(v.windowViewportRect,le(se=>se.visibleHeight)),h.viewportHeight),{data:t,defaultItemHeight:s,firstItemIndex:a,fixedItemHeight:r,fixedGroupHeight:o,gap:n,groupCounts:y,heightEstimates:l,initialItemFinalLocationReached:S,initialTopMostItemIndex:N,scrolledToInitialItem:j,sizeRanges:d,topItemCount:b,topItemsIndexes:I,totalCount:p,...C,groupIndices:i,itemSize:c,listState:z,minOverscanItemCount:F,scrollToIndex:k,statefulTotalCount:f,trackItemSizes:g,rangeChanged:V,...Y,...v,...h,sizes:m,...w}},et(us,_a,It,yd,wd,Hs,Ra,Id,kd,ki,Td));function Ed(t,s){const a={},r={};let o=0;const n=t.length;for(;o(h[w]=C=>{const M=j[s.methods[w]];Ie(M,C)},h),{})}function m(j){return i.reduce((h,w)=>(h[w]=Uc(j[s.events[w]]),h),{})}const f=ue.forwardRef(function(j,h){const{children:w,...C}=j,[M]=ue.useState(()=>dr(Wc(t),b=>{c(b,C)})),[k]=ue.useState(Yn(m,M));$a(()=>{for(const b of i)b in C&&Ve(k[b],C[b]);return()=>{Object.values(k).map(Xr)}},[C,k,M]),$a(()=>{c(M,C)}),ue.useImperativeHandle(h,qn(d(M)));const W=a;return e.jsx(l.Provider,{value:M,children:a!==void 0?e.jsx(W,{...Ed([...r,...o,...i],C),children:w}):w})}),p=j=>{const h=ue.useContext(l);return ue.useCallback(w=>{Ie(h[j],w)},[h,j])},g=j=>{const h=ue.useContext(l)[j],w=ue.useCallback(C=>Ve(h,C),[h]);return ue.useSyncExternalStore(w,()=>st(h),()=>st(h))},S=j=>{const h=ue.useContext(l)[j],[w,C]=ue.useState(Yn(st,h));return $a(()=>Ve(h,M=>{M!==w&&C(qn(M))}),[h,w]),w},N=parseInt(ue.version)>=18?g:S;return{Component:f,useEmitter:(j,h)=>{const w=ue.useContext(l)[j];$a(()=>Ve(w,h),[h,w])},useEmitterValue:N,usePublisher:p}}const Di=ue.createContext(void 0),$i=ue.createContext(void 0),yr="-webkit-sticky",oo="sticky",nn=Ai(()=>{if(typeof document>"u")return oo;const t=document.createElement("div");return t.style.position=yr,t.style.position===yr?yr:oo}),Fi=typeof document<"u"?ue.useLayoutEffect:ue.useEffect;function Sr(t){return"self"in t}function Rd(t){return"body"in t}function Oi(t,s,a,r=sa,o,n){const i=ue.useRef(null),l=ue.useRef(null),c=ue.useRef(null),d=ue.useCallback(p=>{let g,S,N;const j=p.target;if(Rd(j)||Sr(j)){const w=Sr(j)?j:j.defaultView;N=n===!0?w.scrollX:w.scrollY,g=n===!0?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,S=n===!0?w.innerWidth:w.innerHeight}else N=n===!0?j.scrollLeft:j.scrollTop,g=n===!0?j.scrollWidth:j.scrollHeight,S=n===!0?j.offsetWidth:j.offsetHeight;const h=()=>{t({scrollHeight:g,scrollTop:Math.max(N,0),viewportHeight:S})};p.suppressFlushSync===!0?h():Lr.flushSync(h),l.current!==null&&(N===l.current||N<=0||N===g-S)&&(l.current=null,s(!0),c.current&&(clearTimeout(c.current),c.current=null))},[t,s,n]);ue.useEffect(()=>{const p=o||i.current;return r(o||i.current),d({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",d,{passive:!0}),()=>{r(null),p.removeEventListener("scroll",d)}},[i,d,a,r,o]);function m(p){const g=i.current;if(!g||(n===!0?"offsetWidth"in g&&g.offsetWidth===0:"offsetHeight"in g&&g.offsetHeight===0))return;const S=p.behavior==="smooth";let N,j,h;Sr(g)?(j=Math.max(Cs(g.document.documentElement,n===!0?"width":"height"),n===!0?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight),N=n===!0?g.innerWidth:g.innerHeight,h=n===!0?window.scrollX:window.scrollY):(j=g[n===!0?"scrollWidth":"scrollHeight"],N=Cs(g,n===!0?"width":"height"),h=g[n===!0?"scrollLeft":"scrollTop"]);const w=j-N;if(p.top=Math.ceil(Math.max(Math.min(w,p.top),0)),Ii(N,j)||p.top===h){t({scrollHeight:j,scrollTop:h,viewportHeight:N}),S&&s(!0);return}S?(l.current=p.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,l.current=null,s(!0)},1e3)):l.current=null,n===!0&&(p={...p.behavior!==void 0?{behavior:p.behavior}:{},left:p.top}),g.scrollTo(p)}function f(p){n===!0&&(p={...p.behavior!==void 0?{behavior:p.behavior}:{},...p.top!==void 0?{left:p.top}:{}}),i.current.scrollBy(p)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:m}}function on(t){return t}const _d=Qe(()=>{const t=X(l=>`Item ${l}`),s=X(l=>`Group ${l}`),a=X({}),r=X(on),o=X("div"),n=X(sa),i=(l,c=null)=>kt(U(a,le(d=>d[l]),Ze()),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")}}),Md=Qe(([t,s])=>({...t,...s}),et(zi,_d)),Ad=({height:t})=>e.jsx("div",{style:{height:t}}),zd={overflowAnchor:"none",position:nn(),zIndex:1},Bi={overflowAnchor:"none"},Ld={...Bi,display:"inline-block",height:"100%"},io=ue.memo(function({showTopList:t=!1}){const s=ye("listState"),a=Wt("sizeRanges"),r=ye("useWindowScroll"),o=ye("customScrollParent"),n=Wt("windowScrollContainerState"),i=Wt("scrollContainerState"),l=o||r?n:i,c=ye("itemContent"),d=ye("context"),m=ye("groupContent"),f=ye("trackItemSizes"),p=ye("itemSize"),g=ye("log"),S=Wt("gap"),N=ye("horizontalDirection"),{callbackRef:j}=Kc(a,p,f,t?sa:l,g,S,o,N,ye("skipAnimationFrameInResizeObserver")),[h,w]=ue.useState(0);cn("deviation",Y=>{h!==Y&&w(Y)});const C=ye("EmptyPlaceholder"),M=ye("ScrollSeekPlaceholder")??Ad,k=ye("ListComponent"),W=ye("ItemComponent"),b=ye("GroupComponent"),y=ye("computeItemKey"),v=ye("isSeeking"),z=ye("groupIndices").length>0,F=ye("alignToBottom"),I=ye("initialItemFinalLocationReached"),V=t?{}:{boxSizing:"border-box",...N?{display:"inline-block",height:"100%",marginLeft:h!==0?h:F?"auto":0,paddingLeft:s.offsetTop,paddingRight:s.offsetBottom,whiteSpace:"nowrap"}:{marginTop:h!==0?h:F?"auto":0,paddingBottom:s.offsetBottom,paddingTop:s.offsetTop},...I?{}:{visibility:"hidden"}};return!t&&s.totalCount===0&&C!==null&&C!==void 0?e.jsx(C,{...yt(C,d)}):e.jsx(k,{...yt(k,d),"data-testid":t?"virtuoso-top-item-list":"virtuoso-item-list",ref:j,style:V,children:(t?s.topItems:s.items).map(Y=>{const se=Y.originalIndex,ie=y(se+s.firstItemIndex,Y.data,d);return v?u.createElement(M,{...yt(M,d),height:Y.size,index:Y.index,key:ie,type:Y.type||"item",...Y.type==="group"?{}:{groupIndex:Y.groupIndex}}):Y.type==="group"?u.createElement(b,{...yt(b,d),"data-index":se,"data-item-index":Y.index,"data-known-size":Y.size,key:ie,style:zd},m(Y.index,d)):u.createElement(W,{...yt(W,d),...Od(W,Y.data),"data-index":se,"data-item-group-index":Y.groupIndex,"data-item-index":Y.index,"data-known-size":Y.size,key:ie,style:N?Ld:Bi},z?c(Y.index,Y.groupIndex,Y.data,d):c(Y.index,Y.data,d))})})}),Dd={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},$d={outline:"none",overflowX:"auto",position:"relative"},ln=t=>({height:"100%",position:"absolute",top:0,width:"100%",...t?{display:"flex",flexDirection:"column"}:void 0}),Pi=(t,s,a=0)=>({...ln(t),position:s?"relative":"absolute",top:s?-a:0}),Fd={position:nn(),top:0,width:"100%",zIndex:1};function yt(t,s){if(typeof t!="string")return{context:s}}function Od(t,s){return{item:typeof t=="string"?void 0:s}}const Bd=ue.memo(function(){const t=ye("HeaderComponent"),s=Wt("headerHeight"),a=ye("HeaderFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,ye("skipAnimationFrameInResizeObserver")),o=ye("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null}),Pd=ue.memo(function(){const t=ye("FooterComponent"),s=Wt("footerHeight"),a=ye("HeaderFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,ye("skipAnimationFrameInResizeObserver")),o=ye("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null});function Hi({useEmitter:t,useEmitterValue:s,usePublisher:a}){return ue.memo(function({children:r,style:o,context:n,...i}){const l=a("scrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("scrollerRef"),f=s("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:g,scrollToCallback:S}=Oi(l,d,c,m,void 0,f);return t("scrollTo",S),t("scrollBy",p),e.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:g,style:{...f?$d:Dd,...o},tabIndex:0,...i,...yt(c,n),children:r})})}function Qi({useEmitter:t,useEmitterValue:s,usePublisher:a}){return ue.memo(function({children:r,style:o,context:n,...i}){const l=a("windowScrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("totalListHeight"),f=s("deviation"),p=s("customScrollParent"),g=ue.useRef(null),S=s("scrollerRef"),{scrollByCallback:N,scrollerRef:j,scrollToCallback:h}=Oi(l,d,c,S,p);return Fi(()=>(j.current=p||g.current?.ownerDocument.defaultView,()=>{j.current=null}),[j,p]),t("windowScrollTo",h),t("scrollBy",N),e.jsx(c,{ref:g,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...m!==0?{height:m+f}:void 0},...i,...yt(c,n),children:r})})}const Hd=({children:t})=>{const s=ue.useContext(Di),a=Wt("viewportHeight"),r=Wt("fixedItemHeight"),o=ye("alignToBottom"),n=ye("horizontalDirection"),i=ue.useMemo(()=>xi(a,c=>Cs(c,n?"width":"height")),[a,n]),l=Ps(i,!0,ye("skipAnimationFrameInResizeObserver"));return ue.useEffect(()=>{s&&(a(s.viewportHeight),r(s.itemHeight))},[s,a,r]),e.jsx("div",{"data-viewport-type":"element",ref:l,style:ln(o),children:t})},Qd=({children:t})=>{const s=ue.useContext(Di),a=Wt("windowViewportRect"),r=Wt("fixedItemHeight"),o=ye("customScrollParent"),n=ye("useWindowScroll"),i=ye("topListHeight"),l=hi(a,o,ye("skipAnimationFrameInResizeObserver")),c=ye("alignToBottom");return ue.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:Pi(c,n,i),children:t})},Gd=({children:t})=>{const s=ye("TopItemListComponent")??"div",a=ye("headerHeight"),r={...Fd,marginTop:`${a}px`},o=ye("context");return e.jsx(s,{style:r,...yt(s,o),children:t})},Ud=ue.memo(function(t){const s=ye("useWindowScroll"),a=ye("topItemsIndexes").length>0,r=ye("customScrollParent"),o=ye("context");return e.jsxs(r||s?qd:Wd,{...t,context:o,children:[a&&e.jsx(Gd,{children:e.jsx(io,{showTopList:!0})}),e.jsxs(r||s?Qd:Hd,{children:[e.jsx(Bd,{}),e.jsx(io,{}),e.jsx(Pd,{})]})]})}),{Component:Vd,useEmitter:cn,useEmitterValue:ye,usePublisher:Wt}=Li(Md,{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"}},Ud),Wd=Hi({useEmitter:cn,useEmitterValue:ye,usePublisher:Wt}),qd=Qi({useEmitter:cn,useEmitterValue:ye,usePublisher:Wt}),Yd=Vd,Kd=Qe(()=>{const t=X(d=>e.jsxs("td",{children:["Item $",d]})),s=X(null),a=X(d=>e.jsxs("td",{colSpan:1e3,children:["Group ",d]})),r=X(null),o=X(null),n=X({}),i=X(on),l=X(sa),c=(d,m=null)=>kt(U(n,le(f=>f[d]),Ze()),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")}});et(zi,Kd);nn();const lo={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Xd={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:co,floor:ar,max:wa,min:kr,round:mo}=Math;function uo(t,s,a){return Array.from({length:s-t+1}).map((r,o)=>({data:a===null?null:a[o+t],index:o+t}))}function Jd(t){return{...Xd,items:t}}function Fa(t,s){return t!==void 0&&t.width===s.width&&t.height===s.height}function Zd(t,s){return t!==void 0&&t.column===s.column&&t.row===s.row}const em=Qe(([{increaseViewportBy:t,listBoundary:s,overscan:a,visibleRange:r},{footerHeight:o,headerHeight:n,scrollBy:i,scrollContainerState:l,scrollTo:c,scrollTop:d,smoothScrollTargetReached:m,viewportHeight:f},p,g,{didMount:S,propsReady:N},{customScrollParent:j,useWindowScroll:h,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:M},k])=>{const W=X(0),b=X(0),y=X(lo),v=X({height:0,width:0}),z=X({height:0,width:0}),F=Le(),I=Le(),V=X(0),Y=X(null),se=X({column:0,row:0}),ie=Le(),ae=Le(),he=X(!1),we=X(0),O=X(!0),J=X(!1),A=X(!1);Ve(U(S,Te(we),ve(([P,re])=>re!==0)),()=>{Ie(O,!1)}),Ve(U(ct(S,O,z,v,we,J),ve(([P,re,T,G,,H])=>P&&!re&&T.height!==0&&G.height!==0&&!H)),([,,,,P])=>{Ie(J,!0),tn(1,()=>{Ie(F,P)}),ss(U(d),()=>{Ie(s,[0,0]),Ie(O,!0)})}),pe(U(ae,ve(P=>P!=null&&P.scrollTop>0),ns(0)),b),Ve(U(S,Te(ae),ve(([,P])=>P!=null)),([,P])=>{P&&(Ie(v,P.viewport),Ie(z,P.item),Ie(se,P.gap),P.scrollTop>0&&(Ie(he,!0),ss(U(d,Os(1)),re=>{Ie(he,!1)}),Ie(c,{top:P.scrollTop})))}),pe(U(v,le(({height:P})=>P)),f),pe(U(ct(be(v,Fa),be(z,Fa),be(se,(P,re)=>P!==void 0&&P.column===re.column&&P.row===re.row),be(d)),le(([P,re,T,G])=>({gap:T,item:re,scrollTop:G,viewport:P}))),ie),pe(U(ct(be(W),r,be(se,Zd),be(z,Fa),be(v,Fa),be(Y),be(b),be(he),be(O),be(we)),ve(([,,,,,,,P])=>!P),le(([P,[re,T],G,H,ce,_,Q,,q,E])=>{const{column:te,row:de}=G,{height:xe,width:oe}=H,{width:fe}=ce;if(Q===0&&(P===0||fe===0))return lo;if(oe===0){const B=sn(E,P),Ae=B+Math.max(Q-1,0);return Jd(uo(B,Ae,_))}const qe=Gi(fe,oe,te);let Fe,Pe;q?re===0&&T===0&&Q>0?(Fe=0,Pe=Q-1):(Fe=qe*ar((re+de)/(xe+de)),Pe=qe*co((T+de)/(xe+de))-1,Pe=kr(P-1,wa(Pe,qe-1)),Fe=kr(Pe,wa(0,Fe))):(Fe=0,Pe=-1);const tt=uo(Fe,Pe,_),{bottom:Tt,top:dt}=xo(ce,G,H,tt),wt=co(P/qe),Lt=wt*xe+(wt-1)*de-Tt;return{bottom:Tt,itemHeight:xe,items:tt,itemWidth:oe,offsetBottom:Lt,offsetTop:dt,top:dt}})),y),pe(U(Y,ve(P=>P!==null),le(P=>P.length)),W),pe(U(ct(v,z,y,se),ve(([P,re,{items:T}])=>T.length>0&&re.height!==0&&P.height!==0),le(([P,re,{items:T},G])=>{const{bottom:H,top:ce}=xo(P,G,re,T);return[ce,H]}),Ze(Sa)),s);const Z=X(!1);pe(U(d,Te(Z),le(([P,re])=>re||P!==0)),Z);const ne=Pt(U(ct(y,W),ve(([{items:P}])=>P.length>0),Te(Z),ve(([[P,re],T])=>{const G=P.items[P.items.length-1].index===re-1;return(T||P.bottom>0&&P.itemHeight>0&&P.offsetBottom===0&&P.items.length===re)&&G}),le(([[,P]])=>P-1),Ze())),$e=Pt(U(be(y),ve(({items:P})=>P.length>0&&P[0].index===0),ns(0),Ze())),Me=Pt(U(be(y),Te(he),ve(([{items:P},re])=>P.length>0&&!re),le(([{items:P}])=>({endIndex:P[P.length-1].index,startIndex:P[0].index})),Ze(Ni),ws(0)));pe(Me,g.scrollSeekRangeChanged),pe(U(F,Te(v,z,W,se),le(([P,re,T,G,H])=>{const ce=Ci(P),{align:_,behavior:Q,offset:q}=ce;let E=ce.index;E==="LAST"&&(E=G-1),E=wa(0,E,kr(G-1,E));let te=Gr(re,H,T,E);return _==="end"?te=mo(te-re.height+T.height):_==="center"&&(te=mo(te-re.height/2+T.height/2)),q!==void 0&&q!==0&&(te+=q),{behavior:Q,top:te}})),c);const We=kt(U(y,le(P=>P.offsetBottom+P.bottom)),0);return pe(U(M,le(P=>({height:P.visibleHeight,width:P.visibleWidth}))),v),{customScrollParent:j,data:Y,deviation:V,footerHeight:o,gap:se,headerHeight:n,increaseViewportBy:t,initialItemCount:b,itemDimensions:z,overscan:a,restoreStateFrom:ae,scrollBy:i,scrollContainerState:l,scrollHeight:I,scrollTo:c,scrollToIndex:F,scrollTop:d,smoothScrollTargetReached:m,totalCount:W,useWindowScroll:h,viewportDimensions:v,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:M,...g,gridState:y,horizontalDirection:A,initialTopMostItemIndex:we,totalListHeight:We,...p,endReached:ne,propsReady:N,rangeChanged:Me,startReached:$e,stateChanged:ie,stateRestoreInProgress:he,...k}},et(an,It,Ma,Mi,Es,rn,Ts));function Gi(t,s,a){return wa(1,ar((t+a)/(ar(s)+a)))}function xo(t,s,a,r){const{height:o}=a;if(o===void 0||r.length===0)return{bottom:0,top:0};const n=Gr(t,s,a,r[0].index);return{bottom:Gr(t,s,a,r[r.length-1].index)+o,top:n}}function Gr(t,s,a,r){const o=Gi(t.width,a.width,s.column),n=ar(r/o),i=n*a.height+wa(0,n-1)*s.row;return i>0?i+s.row:i}const tm=Qe(()=>{const t=X(f=>`Item ${f}`),s=X({}),a=X(null),r=X("virtuoso-grid-item"),o=X("virtuoso-grid-list"),n=X(on),i=X("div"),l=X(sa),c=(f,p=null)=>kt(U(s,le(g=>g[f]),Ze()),p),d=X(!1),m=X(!1);return pe(be(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")}}),sm=Qe(([t,s])=>({...t,...s}),et(em,tm)),am=ue.memo(function(){const t=Je("gridState"),s=Je("listClassName"),a=Je("itemClassName"),r=Je("itemContent"),o=Je("computeItemKey"),n=Je("isSeeking"),i=qt("scrollHeight"),l=Je("ItemComponent"),c=Je("ListComponent"),d=Je("ScrollSeekPlaceholder"),m=Je("context"),f=qt("itemDimensions"),p=qt("gap"),g=Je("log"),S=Je("stateRestoreInProgress"),N=qt("reportReadyState"),j=Ps(ue.useMemo(()=>h=>{const w=h.parentElement.parentElement.scrollHeight;i(w);const C=h.firstChild;if(C!==null){const{height:M,width:k}=C.getBoundingClientRect();f({height:M,width:k})}p({column:po("column-gap",getComputedStyle(h).columnGap,g),row:po("row-gap",getComputedStyle(h).rowGap,g)})},[i,f,p,g]),!0,!1);return Fi(()=>{t.itemHeight>0&&t.itemWidth>0&&N(!0)},[t]),S?null:e.jsx(c,{className:s,ref:j,...yt(c,m),"data-testid":"virtuoso-item-list",style:{paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},children:t.items.map(h=>{const w=o(h.index,h.data,m);return n?e.jsx(d,{...yt(d,m),height:t.itemHeight,index:h.index,width:t.itemWidth},w):u.createElement(l,{...yt(l,m),className:a,"data-index":h.index,key:w},r(h.index,h.data,m))})})}),rm=ue.memo(function(){const t=Je("HeaderComponent"),s=qt("headerHeight"),a=Je("headerFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,!1),o=Je("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null}),nm=ue.memo(function(){const t=Je("FooterComponent"),s=qt("footerHeight"),a=Je("headerFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,!1),o=Je("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null}),om=({children:t})=>{const s=ue.useContext($i),a=qt("itemDimensions"),r=qt("viewportDimensions"),o=Ps(ue.useMemo(()=>n=>{r(n.getBoundingClientRect())},[r]),!0,!1);return ue.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:ln(!1),children:t})},im=({children:t})=>{const s=ue.useContext($i),a=qt("windowViewportRect"),r=qt("itemDimensions"),o=Je("customScrollParent"),n=Je("useWindowScroll"),i=hi(a,o,!1);return ue.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:Pi(!1,n),children:t})},lm=ue.memo(function({...t}){const s=Je("useWindowScroll"),a=Je("customScrollParent"),r=a||s?dm:cm,o=a||s?im:om,n=Je("context");return e.jsx(r,{...t,...yt(r,n),children:e.jsxs(o,{children:[e.jsx(rm,{}),e.jsx(am,{}),e.jsx(nm,{})]})})}),{useEmitter:Ui,useEmitterValue:Je,usePublisher:qt}=Li(sm,{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"}},lm),cm=Hi({useEmitter:Ui,useEmitterValue:Je,usePublisher:qt}),dm=Qi({useEmitter:Ui,useEmitterValue:Je,usePublisher:qt});function po(t,s,a){return s!=="normal"&&s?.endsWith("px")!==!0&&a(`${t} was not resolved to pixel value correctly`,s,pt.WARN),s==="normal"?0:parseInt(s??"0",10)}function ho(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 fo=new Set(["p","h1","h2","h3","h4","h5","h6","li","td","th"]);function mm(t,s="component",a){const r=t.getBoundingClientRect(),o=[],n=a?.leafTags?new Set([...fo,...a.leafTags]):fo,i=a?.captureRoundedBorders??!0,l=a?.excludeTags?new Set(a.excludeTags):null,c=a?.excludeSelectors??null;function d(m){const f=getComputedStyle(m);if(f.display==="none"||f.visibility==="hidden"||f.opacity==="0")return;const p=m.tagName.toLowerCase();if(l?.has(p)||c?.some(v=>m.matches(v)))return;const g=[...m.children].filter(v=>{const z=getComputedStyle(v);return z.display!=="none"&&z.visibility!=="hidden"&&z.opacity!=="0"}),S=p==="img"||p==="svg"||p==="video"||p==="canvas",N=p==="input"||p==="button"||p==="textarea"||p==="select",j=g.length===0||S||N||n.has(p),h=f.backgroundColor,w=h!=="rgba(0, 0, 0, 0)"&&h!=="transparent",C=f.backgroundImage!=="none",M=parseFloat(f.borderTopWidth)||0,k=i&&M>0&&f.borderTopColor!=="rgba(0, 0, 0, 0)"&&f.borderTopColor!=="transparent",W=(parseFloat(f.borderTopLeftRadius)||0)>0,b=w||C||k&&W,y=p==="tr"||p==="td"||p==="th"||p==="thead"||p==="tbody"||p==="table";if(j){const v=m.getBoundingClientRect();if(v.width<1||v.height<1)return;const z=S&&v.width>0&&v.height>0&&Math.abs(v.width-v.height)<4,F=y?0:z?"50%":go(f,m)??8,I=r.width;o.push({x:I>0?+((v.left-r.left)/I*100).toFixed(4):0,y:Math.round(v.top-r.top),w:I>0?+(v.width/I*100).toFixed(4):0,h:Math.round(v.height),r:F});return}if(b){const v=m.getBoundingClientRect();if(v.width>=1&&v.height>=1){const z=y?0:go(f,m)??8,F=r.width;o.push({x:F>0?+((v.left-r.left)/F*100).toFixed(4):0,y:Math.round(v.top-r.top),w:F>0?+(v.width/F*100).toFixed(4):0,h:Math.round(v.height),r:z,c:!0})}}for(const v of g)d(v)}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 go(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 um=new Map;function xm(t){return um.get(t)}function pm(){typeof window<"u"&&window.__BONEYARD_BUILD&&(window.__BONEYARD_SNAPSHOT=mm)}function hm(){return typeof window<"u"&&window.__BONEYARD_BUILD===!0}function fm(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 Vs={angle:110,start:30,end:70,speed:"2s",lightHighlight:"#f7f7f7",darkHighlight:"#2c2c2c"},xa={speed:"1.8s",lightAdjust:.3,darkAdjust:.02},bo={web:{light:"#f0f0f0",dark:"#222222"}},gm=/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+))?\s*\)/;function vo(t,s){const a=t.match(gm);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}pm();let rs={};function wo({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:f,fixture:p,snapshotConfig:g}){const S=u.useRef(null),N=u.useRef(Math.random().toString(36).slice(2,8)).current,[j,h]=u.useState(0),[w,C]=u.useState(0),[M,k]=u.useState(!1);u.useEffect(()=>{if(typeof window>"u")return;const T=()=>{const ce=document.documentElement.classList.contains("dark")||!!S.current?.closest(".dark");k(ce)};T();const G=new MutationObserver(T);G.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const H=window.matchMedia("(prefers-color-scheme: dark)");return H.addEventListener("change",T),()=>{G.disconnect(),H.removeEventListener("change",T)}},[]);const W=o??rs.color??bo.web.light,b=n??rs.darkColor??bo.web.dark,y=M?b:W,v=i??rs.animate??"pulse",z=v===!0?"pulse":v===!1?"solid":v;u.useEffect(()=>{const T=S.current;if(!T)return;const G=new ResizeObserver(ce=>{const _=ce[0]?.contentRect;h(Math.round(_?.width??0)),_&&_.height>0&&C(Math.round(_.height))});G.observe(T);const H=T.getBoundingClientRect();return h(Math.round(H.width)),H.height>0&&C(Math.round(H.height)),()=>G.disconnect()},[]);const F={};if(a&&(F["data-boneyard"]=a,g&&(F["data-boneyard-config"]=JSON.stringify(g))),hm())return e.jsx("div",{ref:S,className:m,style:{position:"relative"},...F,children:e.jsx("div",{children:p??s})});const[I,V]=u.useState(!1);u.useLayoutEffect(()=>{V(!0)},[]);const Y=r??(a?xm(a):void 0),se=I&&typeof window<"u"?window.innerWidth:0,ie=j>0?j:se,ae=Y&&ie>0?fm(Y,ie):null,he=d??rs.boneClass,we=(()=>{const T=l??rs.stagger;return T===!0?80:T===!1||!T?0:T})(),O=(()=>{const T=c??rs.transition;return T===!0?300:T===!1||!T?0:T})(),[J,A]=u.useState(!1),Z=u.useRef(t),ne=u.useRef(null);u.useEffect(()=>(Z.current&&!t&&O>0&&ae&&(ne.current&&clearTimeout(ne.current),A(!0),ne.current=setTimeout(()=>{A(!1),ne.current=null},O)),Z.current=t,()=>{ne.current&&clearTimeout(ne.current)}),[t,O,ae]);const $e=(t||J)&&ae,Me=t&&!ae&&!J,We=w>0?w:ae?.height??0,P=ae?.height??0,re=We>0&&P>0?We/P:1;return e.jsxs("div",{ref:S,className:m,style:{position:"relative"},...F,children:[e.jsx("div",{"data-boneyard-content":"true",style:$e&&!J?{visibility:"hidden"}:void 0,children:Me?f:s}),$e&&e.jsx("div",{"data-boneyard-overlay":"true",style:{position:"absolute",inset:0,overflow:"hidden",opacity:J?0:1,transition:O>0?`opacity ${O}ms ease-out`:void 0},children:e.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[ae.bones.filter(T=>!ho(T).c).map((T,G)=>{const H=ho(T),ce=y;vo(y,M?xa.darkAdjust:xa.lightAdjust);const _=H.w/100*(ae.width??0),Q=H.r==="50%"&&Math.abs(_-H.h)<4,q={position:"absolute",left:`${H.x}%`,top:H.y*re,width:Q?H.h*re:`${H.w}%`,height:H.h*re,borderRadius:typeof H.r=="string"?H.r:`${H.r}px`,backgroundColor:ce},E=rs.speed;if(z==="pulse")q.animation=`bp-${N} ${E??xa.speed} ease-in-out infinite`;else if(z==="shimmer"){const te=M?rs.darkShimmerColor??Vs.darkHighlight:rs.shimmerColor??Vs.lightHighlight,de=rs.shimmerAngle??Vs.angle;delete q.backgroundColor,q.backgroundImage=`linear-gradient(${de}deg, ${ce} ${Vs.start}%, ${te} 50%, ${ce} ${Vs.end}%)`,q.backgroundSize="200% 100%",q.animation=`bs-${N} ${E??Vs.speed} linear infinite`}return we>0&&(q.opacity=0,q.animation=`${q.animation?q.animation+",":""} by-${N} 0.3s ease-out ${G*we}ms forwards`),e.jsx("div",{"data-boneyard-bone":"true",className:he,style:q},G)}),z==="pulse"&&e.jsx("style",{children:`@keyframes bp-${N}{0%,100%{background-color:${y}}50%{background-color:${vo(y,M?xa.darkAdjust:xa.lightAdjust)}}}`}),z==="shimmer"&&e.jsx("style",{children:`@keyframes bs-${N}{0%{background-position:200% 0}100%{background-position:-200% 0}}`}),we>0&&e.jsx("style",{children:`@keyframes by-${N}{from{opacity:0}to{opacity:1}}`})]})})]})}async function dn(t){const s=At(Ue,"managedStudents");try{const n=Ct(s,St("teacherId","==",t)),i=await zt(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 Wi(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 bm(t,s=[]){if(!t)return[];const a=At(Ue,"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=Ct(a,St("role","==","student"),St("adviserTeacherId","==",t));(await zt(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 f=o(m.id,m.data());f&&r.set(m.id,f)})}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 vm(t){const s=`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||"Student")}&background=random`,a=El.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:xs(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 No(t){return(t||"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9\s]+/g," ").trim().replace(/\s+/g," ")}async function wm(t){const s=(t.studentId||"").trim();if(!s)throw new Error("Cannot reassign section: studentId is required.");const a=(t.newClassSectionId||"").trim()||Ht(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=xt(Ue,"managedStudents",s),c=await bs(l);c.exists()&&await ls(l,{grade:t.newGrade,section:t.newSection,classSectionId:a,gradeLevel:xs(t.newGrade)||t.newGrade,teacherId:r||c.data()?.teacherId,updatedAt:lt()})}catch(l){console.warn("[studentService] reassignStudentSection: managedStudents update failed:",l)}if(t.isRegisteredAccount)try{await ts(xt(Ue,"users",s),{grade:t.newGrade,section:t.newSection,classSectionId:a,adviserTeacherId:r||void 0,adviserTeacherName:o||void 0,updatedAt:lt()},{merge:!0})}catch(l){console.warn("[studentService] reassignStudentSection: users profile update failed:",l)}try{await ur({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=xt(Ue,"classSectionOwnership",i),c=await bs(l);if(c.exists()){const m=(c.data().studentUids||[]).filter(f=>f!==s);await ls(l,{studentUids:m,updatedAt:lt()})}}catch(l){console.warn("[studentService] reassignStudentSection: previous-section cleanup failed:",l)}}async function Nm(t){const{apiService:s}=await Ar(async()=>{const{apiService:d}=await import("./index-BYG24j30.js").then(m=>m.b6);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?Ht(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 ts(xt(Ue,"managedStudents",c),rr({accountUid:c,name:(t.name||"").trim()||"Student",email:r,lrn:t.lrn?.trim()||null,teacherId:a,grade:o||null,gradeLevel:xs(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:lt(),updatedAt:lt()}))}catch(d){console.warn("[studentService] createStudentAccountFromRoster: managed-student merge failed:",d)}if(i&&o&&n)try{await ur({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 Vi(t,s,a){const r=Ht(s,a),o=xt(Ue,"managedStudents",t);await ls(o,{grade:s,section:a,classSectionId:r,updatedAt:lt()})}function Ht(t,s){return[t,s].filter(Boolean).join("_").replace(/\s+/g,"_").toLowerCase()}function rr(t){const s=Object.entries(t).filter(([,a])=>a!==void 0);return Object.fromEntries(s)}function xs(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 aa(t){const a=xs(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 ra(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 cs(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 bt(t){const s=t.metadata||{},a=t.className||s.className,r=cs(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?Ht(o,n):"")||null,l=(a||"").trim()||(o&&n?`${o} - ${n}`:"")||null,c=xs(t.gradeLevel||s.gradeLevel||o),d=(t.classification||s.classification||"").trim()||aa(c)||null,m=(t.strand||s.strand||"").trim()||ra(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 jm(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?Ht(o,n):"")||null,l=s||(o&&n?`${o} - ${n}`:null),c=xs(t.gradeLevel||o),d=(t.classification||"").trim()||aa(c),m=(t.strand||"").trim()||ra(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 Wi(t){const s=At(Ue,"classrooms"),a=new Map,r=Ct(s,St("teacherId","==",t));(await zt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=Ct(s,St("managerId","==",t));return(await zt(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 ur(t){const s=t.classSectionId||Ht(t.grade,t.section),a=xt(Ue,"classSectionOwnership",s),r=await bs(a),o=r.exists()?r.data().studentUids||[]:[],n=Array.from(new Set([...t.studentUids||[],...o])),i=rr(t);return r.exists()?await ls(a,{...i,classSectionId:s,studentUids:n,updatedAt:lt()}):await ts(a,{...i,classSectionId:s,studentUids:n,createdAt:lt(),updatedAt:lt()}),s}async function qi(t){const s=(t.classSectionId||"").trim()||Ht(t.grade,t.section),a=(t.className||"").trim()||`${t.grade} - ${t.section}`,r=jm({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 ur({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=At(Ue,"classrooms"),n=Ct(o,St("classSectionId","==",s)),i=await zt(n);if(i.empty){const l=rr({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:lt(),updatedAt:lt()});await ts(xt(Ue,"classrooms",s),l,{merge:!0})}else for(const l of i.docs){const c=rr({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:lt()});await ls(l.ref,c)}return s}async function xr(t,s,a,r,o,n){const i=Ht(s,a);await ur({classSectionId:i,grade:s,section:a,schoolYear:o,ownerTeacherId:r,ownerTeacherName:n,studentUids:[t]});const l=await bs(xt(Ue,"users",t)),c=l.exists()?l.data():{};await ts(xt(Ue,"users",t),{grade:s,section:a,classSectionId:i,adviserTeacherId:r,adviserTeacherName:n||"",updatedAt:lt()},{merge:!0}),await ts(xt(Ue,"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:lt()},{merge:!0})}async function ym(t){const s=At(Ue,"classSectionOwnership"),a=new Map,r=Ct(s,St("ownerTeacherId","==",t));(await zt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=Ct(s,St("managerId","==",t));return(await zt(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 Sm(t="",s=25){const a=At(Ue,"users"),r=Math.max(1,Math.min(100,s)),o=Ct(a,St("role","==","teacher"),Xa(r*4)),n=await zt(o),i=t.trim().toLowerCase();return n.docs.map(c=>{const d=c.data(),m=String(d.name||"").trim(),f=String(d.email||"").trim();return{uid:c.id,name:m||"Teacher",email:f,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 km(t,s,a=20){if(t.length===0)return s([]),()=>{};const r=At(Ue,"activities"),o=Ct(r,St("classroomId","in",t),Rl("timestamp","desc"));return ti(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 Cm=({open:t,onClose:s,onCreated:a,teacherName:r})=>{const{currentUser:o}=ms(),[n,i]=u.useState("details"),[l,c]=u.useState(""),d="Grade 11",[m,f]=u.useState(""),[p,g]=u.useState(!1),[S,N]=u.useState(""),[j,h]=u.useState([]),[w,C]=u.useState(new Set),[M,k]=u.useState(""),[W,b]=u.useState(!1);u.useEffect(()=>{t||(i("details"),c(""),f(""),N(""),C(new Set),k(""))},[t]),u.useEffect(()=>{t&&n==="students"&&y()},[t,n]);const y=async()=>{b(!0);try{const I=At(Ue,"users"),V=Ct(I,St("role","==","student")),Y=await zt(V),se=[];Y.docs.forEach(ie=>{const ae=ie.data();se.push({uid:ie.id,name:ae.name||ae.displayName||"Student",email:ae.email||"",grade:ae.grade,section:ae.section})}),h(se.sort((ie,ae)=>ie.name.localeCompare(ae.name)))}catch(I){console.error("[CreateClassModal] Failed to load students:",I)}finally{b(!1)}},v=async()=>{if(o){if(!m.trim()){N("Section name is required");return}N(""),g(!0);try{const I=String(new Date().getFullYear());if(await qi({classSectionId:"",grade:d,section:m.trim(),schoolYear:I,ownerTeacherId:o.uid,ownerTeacherName:r||o.displayName||"",managerId:o.uid,managerName:r||o.displayName||"",className:l.trim()||`${d} - ${m.trim()}`}),w.size>0){const V=Array.from(w).map(Y=>xr(Y,d,m.trim(),o.uid,I,r||o.displayName||""));await Promise.allSettled(V)}a(),s()}catch(I){N(I instanceof Error?I.message:"Failed to create class")}finally{g(!1)}}},z=I=>{C(V=>{const Y=new Set(V);return Y.has(I)?Y.delete(I):Y.add(I),Y})},F=j.filter(I=>I.name.toLowerCase().includes(M.toLowerCase())||I.email.toLowerCase().includes(M.toLowerCase()));return t?e.jsx(Mt,{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(ds,{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(js,{placeholder:"e.g. Grade 11 - Section A",value:l,onChange:I=>c(I.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(js,{placeholder:"e.g. Section A, STEM-1, Rizal",value:m,onChange:I=>f(I.target.value)})]}),S&&e.jsx("p",{className:"text-sm text-rose-500",children:S})]}),n==="students"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Bs,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(js,{placeholder:"Search students...",value:M,onChange:I=>k(I.target.value),className:"pl-9"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[w.size," student(s) selected"]}),W?e.jsx("p",{className:"text-sm text-[#64748b] text-center py-4",children:"Loading students..."}):F.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:F.map(I=>e.jsxs("button",{onClick:()=>z(I.uid),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${w.has(I.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 ${w.has(I.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:w.has(I.uid)&&e.jsx(Ot,{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:I.name}),e.jsx("p",{className:"text-xs text-[#64748b] truncate",children:I.email})]}),I.grade&&e.jsx("span",{className:"text-xs text-[#94a3b8]",children:I.grade})]},I.uid))}),S&&e.jsx("p",{className:"text-sm text-rose-500",children:S})]})]}),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(ht,{variant:"outline",onClick:s,children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{variant:"outline",onClick:()=>{if(!m.trim()){N("Section is required");return}N(""),i("students")},children:"Add Students"}),e.jsx(ht,{onClick:v,disabled:p||!m.trim(),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:p?"Creating...":"Create Class"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ht,{variant:"outline",onClick:()=>i("details"),children:"Back"}),e.jsxs(ht,{onClick:v,disabled:p,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(Zs,{size:16,className:"mr-1"}),p?"Creating...":`Create with ${w.size} Student${w.size!==1?"s":""}`]})]})})]})]})}):null},Im=({open:t,onClose:s,onAdded:a,grade:r,section:o,teacherName:n,existingStudentUids:i=[]})=>{const{currentUser:l}=ms(),[c,d]=u.useState([]),[m,f]=u.useState(new Set),[p,g]=u.useState(""),[S,N]=u.useState(!1),[j,h]=u.useState(!1);u.useEffect(()=>{t&&(f(new Set),g(""),w())},[t]);const w=async()=>{N(!0);try{const k=Ct(At(Ue,"users"),St("role","==","student")),b=(await zt(k)).docs.filter(y=>!i.includes(y.id)).map(y=>{const v=y.data();return{uid:y.id,name:v.name||v.displayName||"Student",email:v.email||""}}).sort((y,v)=>y.name.localeCompare(v.name));d(b)}catch{}N(!1)},C=async()=>{if(!(!l||m.size===0)){h(!0);try{const k=String(new Date().getFullYear()),W=Array.from(m).map(b=>xr(b,r,o,l.uid,k,n||l.displayName||""));await Promise.allSettled(W),me.success(`Added ${m.size} student(s) to class`),a(),s()}catch{me.error("Failed to add students")}h(!1)}},M=c.filter(k=>k.name.toLowerCase().includes(p.toLowerCase())||k.email.toLowerCase().includes(p.toLowerCase()));return t?e.jsx(Mt,{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(ds,{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(Bs,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(js,{placeholder:"Search students...",value:p,onChange:k=>g(k.target.value),className:"pl-8 h-9 text-sm"})]}),e.jsx("button",{onClick:()=>{m.size===M.length?f(new Set):f(new Set(M.map(k=>k.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===M.length&&M.length>0?"Deselect All":"Select All"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[m.size," of ",M.length," selected"]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-1 min-h-[300px]",children:S?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"Loading..."}):M.length===0?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"No students available"}):M.map(k=>e.jsxs("button",{onClick:()=>f(W=>{const b=new Set(W);return b.has(k.uid)?b.delete(k.uid):b.add(k.uid),b}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${m.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 shrink-0 ${m.has(k.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:m.has(k.uid)&&e.jsx(Ot,{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:k.name}),e.jsx("p",{className:"text-[11px] text-[#64748b] truncate",children:k.email})]})]},k.uid))})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-[#f1f5f9]",children:[e.jsx(ht,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),e.jsxs(ht,{size:"sm",onClick:C,disabled:j||m.size===0,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(Ko,{size:14,className:"mr-1.5"}),j?"Adding...":`Add ${m.size} Student${m.size!==1?"s":""}`]})]})]})]})}):null};async function Tm(t,s,a){const r=xt(At(Ue,"generatedLessonPlans"));return await ts(r,{...t,teacherId:s,teacherName:a?.teacherName||null,studentId:a?.studentId||null,studentName:a?.studentName||null,status:"draft",createdAt:lt(),updatedAt:lt()}),r.id}async function Em(t){const s=xt(Ue,"generatedLessonPlans",t),a=await bs(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 ls(s,{status:"published",publishedAt:lt(),updatedAt:lt()})}async function Rm(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 g=await bl(a,r,o,{lessonTitle:t.lessonTitle,learningCompetency:t.learningCompetency,moduleUnit:t.moduleUnit,learnerLevel:t.learnerLevel});i=g.sources||[],n=g.explanation||"",l=g.retrievalConfidence,c=g.retrievalBand,d=g.retrievalQuery,m=g.needsReview??!1}catch{n="",i=[]}const f={...t,subject:r,quarter:o,curriculumContext:n?`[CURRICULUM CONTEXT] -${n}`:void 0,curriculumRetrievalConfidence:l,curriculumRetrievalBand:c,curriculumRetrievalQuery:d,needsReview:m};return{...await it.generateLessonPlan(f),curriculumSources:i,curriculumContext:n}}const _m=Il("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 Mm({className:t,variant:s,asChild:a=!1,...r}){const o=a?Ql:"span";return e.jsx(o,{"data-slot":"badge",className:Xo(_m({variant:s}),t),...r})}function Am(t){return t.length<=42?t:`${t.slice(0,18)}...${t.slice(-20)}`}const jo=({sources:t=[],className:s})=>t.length?e.jsxs(Gl,{children:[e.jsx(Ul,{asChild:!0,children:e.jsxs(Mm,{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(Vl,{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:[Am(a.sourceFile)," | p.",a.page]}),e.jsxs("p",{className:"text-[#5a6578]",children:["Similarity: ",(a.score*100).toFixed(1),"%"]})]},`${a.sourceFile}-${a.page}-${r}`))})]})]}):null,zm=[{level:"Remember",icon:zr,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:vl,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:pc,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"}],Lm=({isOpen:t,onClose:s})=>t?e.jsx(Mt,{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(Jo,{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(ds,{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:zm.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(vc,{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,Dm={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"},Oa={identification:{label:"Identification",icon:e.jsx(vs,{size:16}),description:"Define or identify concepts"},enumeration:{label:"Enumeration",icon:e.jsx(Ja,{size:16}),description:"List steps or properties"},multiple_choice:{label:"Multiple Choice",icon:e.jsx(Ot,{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(wl,{size:16}),description:"Solve equations"}},yo={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"}},$m=["Grade 11","Grade 12"],Cr=t=>{const s=(t||"").trim().toLowerCase();return s==="grade 12"||s==="12"||s.includes("12")?"Grade 12":"Grade 11"},Fm={"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"]}},Om={"Grade 11":["General Mathematics - "],"Grade 12":["Pre-Calculus - ","Basic Calculus - "]},So=(t,s)=>{const a=Om[s];return Object.fromEntries(Object.entries(t).filter(([r])=>a.some(o=>r.startsWith(o))))},pa=30,ha=12,Ir="mathpulse:quiz-maker:active-task",Bm={easy:"text-green-600",medium:"text-rose-600",hard:"text-red-600"},Yi=({onBack:t,gradeLevel:s,selectedClassId:a,selectedClassName:r,onOpenNotifications:o,onOpenProfile:n,onOpenInsightModal:i,userPhoto:l,teacherName:c,drawerMode:d=!1,onQuizSaved:m,onQuizGenerating:f})=>{const{currentUser:p,loading:g}=ms(),S=u.useMemo(()=>it.getImportGroundedRolloutFlags(),[]),[N,j]=u.useState("create"),[h,w]=u.useState("setup"),[C,M]=u.useState(Cr(s)),[k,W]=u.useState(10),[b,y]=u.useState([]),[v,z]=u.useState([]),[F,I]=u.useState(["multiple_choice","word_problem","identification"]),[V,Y]=u.useState(["remember","understand","apply","analyze"]),[se,ie]=u.useState(!1),[ae,he]=u.useState({easy:30,medium:50,hard:20}),[we,O]=u.useState({}),[J,A]=u.useState(!1),[Z,ne]=u.useState([]),[$e,Me]=u.useState(!1),[We,P]=u.useState(""),[re,T]=u.useState(!1),[G,H]=u.useState(!1),[ce,_]=u.useState(null),[Q,q]=u.useState(0),[E,te]=u.useState("queued"),[de,xe]=u.useState("Waiting to start generation..."),[oe,fe]=u.useState(null),[qe,Fe]=u.useState(null),[Pe,tt]=u.useState(""),[Tt,dt]=u.useState(!1),wt=u.useRef(!1),[Lt,B]=u.useState("topics"),[Ae,Xe]=u.useState(null),[Nt,Kt]=u.useState(!1),[Et,Dt]=u.useState("all"),[$t,_s]=u.useState("all"),[at,za]=u.useState(!1),[Ft,R]=u.useState(null),[ee,ze]=u.useState(!1),[Ne,Ge]=u.useState(!1),[je,gt]=u.useState(!1),[nt,Ce]=u.useState([]),[ps,Xt]=u.useState(!1),[Ms,La]=u.useState(""),[Jt,na]=u.useState(null),[oa,hs]=u.useState([]),[ia,la]=u.useState(!1),[Qs,pr]=u.useState("all"),[hr,ca]=u.useState(null),[da,L]=u.useState(null),K=u.useCallback(async()=>{A(!0);const x=Cr(C);try{const D=await it.getQuizTopics(x);D.topics&&O(So(D.topics,x))}catch{O(So(Fm[x],x))}finally{A(!1)}},[C]),ke=u.useCallback(async()=>{if(!S.quizEnabled){ne([]),P("Import-grounded quiz generation is disabled by rollout flag; using curriculum defaults."),Me(!1);return}Me(!0),P("");try{const x=await it.getCourseMaterialTopics({classSectionId:a,limit:20}),D=(x.topics||[]).filter($=>$.title?.trim());ne(D),x.warnings&&x.warnings.length>0&&P(x.warnings.join(" "))}catch{ne([]),P("Imported topics are currently unavailable; quiz generation will use curriculum defaults.")}finally{Me(!1)}},[a,S.quizEnabled]);u.useEffect(()=>{K(),y([]),z([])},[K]),u.useEffect(()=>{ke()},[ke]);const _e=u.useMemo(()=>{const x=Array.from(new Set(Z.map(D=>D.title.trim()).filter(Boolean)));return x.length===0?we:{"Imported Course Materials":x,...we}},[we,Z]);u.useEffect(()=>{Dt("all"),_s("all")},[oe]);const Qt=u.useMemo(()=>{if(!oe)return[];const x=oe.questions.map($=>$.provenance?.sourceFile?.trim()).filter($=>!!$),D=(oe.metadata.topicProvenance||[]).map($=>$.sourceFile?.trim()).filter($=>!!$);return Array.from(new Set([...x,...D])).sort(($,ge)=>$.localeCompare(ge))},[oe]),Ee=u.useMemo(()=>{if(!oe)return[];const x=oe.questions.map($=>$.provenance?.materialId?.trim()).filter($=>!!$),D=(oe.metadata.topicProvenance||[]).map($=>$.materialId?.trim()).filter($=>!!$);return Array.from(new Set([...x,...D])).sort(($,ge)=>$.localeCompare(ge))},[oe]),Gs=u.useMemo(()=>oe?oe.questions.filter(x=>{const D=Et==="all"||(x.provenance?.sourceFile||"").trim()===Et,$=$t==="all"||(x.provenance?.materialId||"").trim()===$t;return D&&$}):[],[oe,Et,$t]),Rt=(x,D)=>{const $={...ae},ge=Math.max(0,Math.min(100,$[x]+D)),Oe=ge-$[x];$[x]=ge;const Ye=Object.keys($).filter(ot=>ot!==x),Gt=Ye.reduce((ot,Zt)=>ot+$[Zt],0);if(Gt>0)for(const ot of Ye)$[ot]=Math.max(0,Math.round($[ot]-Oe*$[ot]/Gt));const Us=Object.values($).reduce((ot,Zt)=>ot+Zt,0);if(Us!==100){const ot=Ye.reduce((Zt,jn)=>$[Zt]>=$[jn]?Zt:jn);$[ot]+=100-Us}he($)},He=x=>{y(D=>D.includes(x)?D.filter($=>$!==x):[...D,x]),z(D=>D.filter($=>$!==x))},ma=x=>{I(D=>D.includes(x)?D.length>1?D.filter($=>$!==x):D:[...D,x])},ua=x=>{Y(D=>D.includes(x)?D.length>1?D.filter($=>$!==x):D:[...D,x])},ol=()=>{let x=b.length>0?b.filter($=>!v.includes($)):Object.values(_e).flat().filter($=>!v.includes($)).slice(0,3);x.length>ha&&(x=x.slice(0,ha));const D=Math.min(k,pa);return{topics:x,gradeLevel:C,numQuestions:D,questionTypes:F,includeGraphs:se,difficultyDistribution:ae,bloomLevels:V,excludeTopics:v,classSectionId:a,className:r,preferImportedTopics:S.quizEnabled}},il=u.useCallback((x,D)=>{const $={taskId:x,request:D,createdAt:new Date().toISOString(),ownerUid:p?.uid};try{sessionStorage.setItem(Ir,JSON.stringify($))}catch{}},[p]),fs=u.useCallback(()=>{try{sessionStorage.removeItem(Ir)}catch{}},[]),fr=u.useCallback(x=>{const D=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)));q($=>{let ge=Math.max($,D);if(x.status==="running"&&D<=$){const Oe=String(x.progressStage||"").toLowerCase(),Ye=Oe.includes("assembling")||Oe.includes("final")?97:Oe.includes("generating")?89:95;ge=Math.min(Ye,$+1)}return ge}),te(x.progressStage||x.status),xe(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(g||wt.current)return;if(wt.current=!0,!p){fs();return}let x=!1;const D=sessionStorage.getItem(Ir);if(!D)return;let $=null;try{$=JSON.parse(D)}catch{fs();return}if(!$?.taskId){fs();return}if($.ownerUid&&$.ownerUid!==p.uid){fs();return}return T(!0),_($.taskId),tt(""),it.waitForTaskResult($.taskId,{timeoutMs:24e4,pollIntervalMs:1500,onProgress:fr}).then(async ge=>{if(x)return;const Oe=ge.result;if(!Oe||typeof Oe!="object")throw new Error("Quiz generation completed without a valid result payload.");const Ye=Oe;fe(Ye),w("results"),q(100),te("completed"),xe("Generation complete."),_(null),fs();try{await gn(Ye,$.request),me.success("Quiz auto-saved to your library as draft.")}catch(Gt){me.error(Gt instanceof Error?Gt.message:"Quiz generated but failed to save to library")}}).catch(ge=>{if(!x){if(ge instanceof Ya&&(ge.status===401||ge.status===403)){wt.current=!1,T(!1);return}tt(ge instanceof Error?ge.message:"Failed to resume quiz generation"),_(null),fs()}}).finally(()=>{x||T(!1)}),()=>{x=!0}},[fr,g,fs,p]);const pn=()=>{if(re){window.confirm("Quiz generation is in progress. Are you sure you want to leave?")&&(w("setup"),fe(null),tt(""),t());return}w("setup"),fe(null),tt(""),t()},ll=async()=>{f?.(),tt(""),T(!0),L(null),q(8),te("queued"),xe("Submitting quiz generation task..."),fe(null);const x=ol();try{const D=await it.generateQuiz(x,{onTaskCreated:$=>{_($),il($,x),q(ge=>Math.max(ge,12)),te("queued"),xe("Task queued. Generation is running in the background.")},onProgress:$=>{fr($),$.taskId&&$.taskId!==ce&&_($.taskId)}});fe(D),w("results"),q(100),te("completed"),xe("Generation complete."),_(null),fs();try{await gn(D,x),me.success("Quiz auto-saved to your library as draft.")}catch($){me.error($ instanceof Error?$.message:"Quiz generated but failed to save to library")}it.reportImportGroundedFeedback({flow:"quiz",status:"success",classSectionId:x.classSectionId,className:x.className,metadata:{totalQuestions:D.metadata.totalQuestions,usedImportedTopics:!!D.metadata.usedImportedTopics,importedTopicCount:D.metadata.importedTopicCount??0,importGroundingEnabled:S.quizEnabled}})}catch(D){tt(D instanceof Error?D.message:"Quiz generation failed"),q(100),te("failed"),xe("Generation failed."),_(null),fs(),it.reportImportGroundedFeedback({flow:"quiz",status:"failed",classSectionId:x.classSectionId,className:x.className,metadata:{error:D instanceof Error?D.message:"Quiz generation failed",importGroundingEnabled:S.quizEnabled}})}finally{T(!1)}},cl=()=>{if(!oe)return;const x=oe.questions.map((D,$)=>{let ge=`${$+1}. [${D.difficulty.toUpperCase()}] [${D.bloomLevel}] (${D.points} pts) + */const $c=[["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"}]],Fr=ft("wand-sparkles",$c);function Fc(t,s){const a=gl(t);return isNaN(s)?sc(t,NaN):(a.setDate(a.getDate()+s),a)}function mi(t,s){const a=yn(t),r=yn(s);return+a==+r}function Vn(t){return mi(t,oi(t))}function Oc(t,s){return Fc(t,-1)}function Wn(t){return mi(t,Oc(oi(t)))}const cr=0,Is=1,ta=2,ui=4;function qn(t){return()=>t}function Bc(t){t()}function xi(t,s){return a=>t(s(a))}function Yn(t,s){return()=>t(s)}function Pc(t,s){return a=>t(s,a)}function Kr(t){return t!==void 0}function Hc(...t){return()=>{t.map(Bc)}}function sa(){}function dr(t,s){return s(t),t}function Qc(t,s){return s(t)}function et(...t){return t}function Ve(t,s){return t(Is,s)}function Ie(t,s){t(cr,s)}function Xr(t){t(ta)}function st(t){return t(ui)}function pe(t,s){return Ve(t,Pc(s,cr))}function ss(t,s){const a=t(Is,r=>{a(),s(r)});return a}function Kn(t){let s,a;return r=>o=>{s=o,a&&clearTimeout(a),a=setTimeout(()=>{r(s)},t)}}function pi(t,s){return t===s}function Ze(t=pi){let s;return a=>r=>{t(s,r)||(s=r,a(r))}}function ve(t){return s=>a=>{t(a)&&s(a)}}function le(t){return s=>xi(s,t)}function ns(t){return s=>()=>{s(t)}}function V(t,...s){const a=Gc(...s);return((r,o)=>{switch(r){case ta:Xr(t);return;case Is:return Ve(t,a(o))}})}function os(t,s){return a=>r=>{a(s=t(s,r))}}function Os(t){return s=>a=>{t>0?t--:s(a)}}function ws(t){let s=null,a;return r=>o=>{s=o,!a&&(a=setTimeout(()=>{a=void 0,r(s)},t))}}function Te(...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;Ve(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 Gc(...t){return s=>t.reduceRight(Qc,s)}function Uc(t){let s,a;const r=()=>s?.();return function(o,n){switch(o){case Is:return n?a===n?void 0:(r(),a=n,s=Ve(t,n),s):(r(),sa);case ta:r(),a=null;return}}}function X(t){let s=t;const a=Le();return((r,o)=>{switch(r){case cr:s=o;break;case Is:{o(s);break}case ui:return s}return a(r,o)})}function kt(t,s){return dr(X(s),a=>pe(t,a))}function Le(){const t=[];return((s,a)=>{switch(s){case cr:t.slice().forEach(r=>{r(a)});return;case ta:t.splice(0,t.length);return;case Is:return t.push(a),()=>{const r=t.indexOf(a);r>-1&&t.splice(r,1)}}})}function Pt(t){return dr(Le(),s=>pe(t,s))}function Qe(t,s=[],{singleton:a}={singleton:!0}){return{constructor:t,dependencies:s,id:Vc(),singleton:a}}const Vc=()=>Symbol();function Wc(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 ct(...t){const s=Le(),a=new Array(t.length);let r=0;const o=2**t.length-1;return t.forEach((n,i)=>{const l=2**i;Ve(n,c=>{a[i]=c,r|=l,r===o&&Ie(s,a)})}),function(n,i){switch(n){case ta:{Xr(s);return}case Is:return r===o&&i(a),Ve(s,i)}}}function be(t,s=pi){return V(t,Ze(s))}function Or(...t){return function(s,a){switch(s){case ta:return;case Is:return Hc(...t.map(r=>Ve(r,a)))}}}const pt={DEBUG:0,INFO:1,WARN:2,ERROR:3},qc={[pt.DEBUG]:"debug",[pt.ERROR]:"error",[pt.INFO]:"log",[pt.WARN]:"warn"},Yc=()=>typeof globalThis>"u"?window:globalThis,Ts=Qe(()=>{const t=X(pt.ERROR);return{log:X((s,a,r=pt.INFO)=>{const o=Yc().VIRTUOSO_LOG_LEVEL??st(t);r>=o&&console[qc[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",s,a)}),logLevel:t}},[],{singleton:!0});function Ps(t,s,a){return Jr(t,s,a).callbackRef}function Jr(t,s,a){const r=ue.useRef(null);let o=i=>{};const n=ue.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 Kc(t,s,a,r,o,n,i,l,c){const d=ue.useCallback(m=>{const f=Xc(m.children,s,l?"offsetWidth":"offsetHeight",o);let p=m.parentElement;for(;p.dataset.virtuosoScroller===void 0;)p=p.parentElement;const g=p.lastElementChild.dataset.viewportType==="window";let S;g&&(S=p.ownerDocument.defaultView);const N=i?l?i.scrollLeft:i.scrollTop:g?l?S.scrollX||S.document.documentElement.scrollLeft:S.scrollY||S.document.documentElement.scrollTop:l?p.scrollLeft:p.scrollTop,j=i?l?i.scrollWidth:i.scrollHeight:g?l?S.document.documentElement.scrollWidth:S.document.documentElement.scrollHeight:l?p.scrollWidth:p.scrollHeight,h=i?l?i.offsetWidth:i.offsetHeight:g?l?S.innerWidth:S.innerHeight:l?p.offsetWidth:p.offsetHeight;r({scrollHeight:j,scrollTop:Math.max(N,0),viewportHeight:h}),n?.(l?Xn("column-gap",getComputedStyle(m).columnGap,o):Xn("row-gap",getComputedStyle(m).rowGap,o)),f!==null&&t(f)},[t,s,o,n,i,r,l]);return Jr(d,a,c)}function Xc(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 f,p;if(s){const g=s.getBoundingClientRect(),S=d.top-g.top;p=g.height-Math.max(0,S),f=S+s.scrollTop}else{const g=i.current.ownerDocument.defaultView;p=g.innerHeight-Math.max(0,d.top),f=d.top+g.scrollY}r.current={listHeight:d.height,offsetTop:f,visibleHeight:p,visibleWidth:m},t(r.current)},[t,s]),{callbackRef:n,ref:i}=Jr(o,!0,a),l=ue.useCallback(()=>{o(i.current)},[o,i]);return ue.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 It=Qe(()=>{const t=Le(),s=Le(),a=X(0),r=Le(),o=X(0),n=Le(),i=Le(),l=X(0),c=X(0),d=X(0),m=X(0),f=Le(),p=Le(),g=X(!1),S=X(!1),N=X(!1);return pe(V(t,le(({scrollTop:j})=>j)),s),pe(V(t,le(({scrollHeight:j})=>j)),i),pe(s,o),{deviation:a,fixedFooterHeight:d,fixedHeaderHeight:c,footerHeight:m,headerHeight:l,horizontalDirection:S,scrollBy:p,scrollContainerState:t,scrollHeight:i,scrollingInProgress:g,scrollTo:f,scrollTop:s,skipAnimationFrameInResizeObserver:N,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:n}},[],{singleton:!0}),ja={lvl:0};function fi(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(Pr(o,s,a))),r>=s&&r<=a&&l.push({k:r,v:i}),r<=a&&(l=l.concat(Pr(n,s,a))),l}function Ua(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(Nr(s))return wi(ut(t,{lvl:a-1}));if(!Ke(s)&&!Ke(s.r))return ut(s.r,{l:ut(s,{r:s.r.l}),lvl:a,r:ut(t,{l:s.r.r,lvl:a-1})});throw new Error("Unexpected empty nodes")}if(Nr(t))return Hr(ut(t,{lvl:a-1}));if(!Ke(r)&&!Ke(r.l)){const o=r.l,n=Nr(o)?r.lvl-1:r.lvl;return ut(o,{l:ut(t,{lvl:a-1,r:o.l}),lvl:o.lvl+1,r:Hr(ut(r,{l:o.r,lvl:n}))})}throw new Error("Unexpected empty nodes")}function ut(t,s){return vi(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 gi(t){return Ke(t.r)?t.l:Ua(ut(t,{r:gi(t.r)}))}function Nr(t){return Ke(t)||t.lvl>t.r.lvl}function bi(t){return Ke(t.r)?[t.k,t.v]:bi(t.r)}function vi(t,s,a,r=ja,o=ja){return{k:t,l:r,lvl:a,r:o,v:s}}function Jn(t){return Hr(wi(t))}function wi(t){const{l:s}=t;return!Ke(s)&&s.lvl===t.lvl?ut(s,{r:ut(t,{l:s.r})}):t}function Hr(t){const{lvl:s,r:a}=t;return!Ke(a)&&!Ke(a.r)&&a.lvl===s&&a.r.lvl===s?ut(a,{l:ut(t,{r:a.l}),lvl:s+1}):t}function Jc(t){return fi(t,({k:s,v:a})=>({index:s,value:a}))}function Ni(t,s){return!!(t&&t.startIndex===s.startIndex&&t.endIndex===s.endIndex)}function Sa(t,s){return!!(t&&t[0]===s[0]&&t[1]===s[1])}const Zr=Qe(()=>({recalcInProgress:X(!1)}),[],{singleton:!0});function ji(t,s,a){return t[sr(t,s,a)]}function sr(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 Zc(t,s,a,r){const o=sr(t,s,r),n=sr(t,a,r,o);return t.slice(o,n+1)}function Cs(t,s){return Math.round(t.getBoundingClientRect()[s])}function mr(t){return!Ke(t.groupOffsetTree)}function en({index:t},s){return s===t?0:s=f||n===p)&&(t=Br(t,f)):(d=p!==n,c=!0),m>o&&o>=f&&p!==n&&(t=Bt(t,o+1,p));d&&(t=Bt(t,i,n))}return[t,a]}function sd(t){return typeof t.groupIndex<"u"}function ad({offset:t},s){return s===t?0:s0?l+a:l}function yi(t,s){if(!mr(s))return t;let a=0;for(;s.groupIndices[a]<=t+a;)a++;return t+a}function Si(t,s,a){if(sd(t))return s.groupIndices[t.groupIndex]+1;const r=t.index==="LAST"?a:t.index;let o=yi(r,s);return o=Math.max(0,o,Math.min(a,o)),o}function rd(t,s,a,r=0){return r>0&&(s=Math.max(s,ji(t,r,en).offset)),fi(Zc(t,s,a,ad),id)}function nd(t,[s,a,r,o]){s.length>0&&r("received item sizes",s,pt.DEBUG);const n=t.sizeTree;let i=n,l=0;if(a.length>0&&Ke(n)&&s.length===2){const p=s[0].size,g=s[1].size;i=a.reduce((S,N)=>Bt(Bt(S,N,p),N+1,g),i)}else[i,l]=td(i,s);if(i===n)return t;const{lastIndex:c,lastOffset:d,lastSize:m,offsetTree:f}=Qr(t.offsetTree,l,i,o);return{groupIndices:a,groupOffsetTree:a.reduce((p,g)=>Bt(p,g,ka(g,f,o)),Ks()),lastIndex:c,lastOffset:d,lastSize:m,offsetTree:f,sizeTree:i}}function od(t){return Ds(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 Zn(t,s){let a=0,r=0;for(;ao.start===r&&(o.end===s||o.end===1/0)&&o.value===a}const cd={offsetHeight:"height",offsetWidth:"width"},us=Qe(([{log:t},{recalcInProgress:s}])=>{const a=Le(),r=Le(),o=kt(r,0),n=Le(),i=Le(),l=X(0),c=X([]),d=X(void 0),m=X(void 0),f=X(void 0),p=X(void 0),g=X((b,y)=>Cs(b,cd[y])),S=X(void 0),N=X(0),j=ed(),h=kt(V(a,Te(c,t,N),os(nd,j),Ze()),j),w=kt(V(c,Ze(),os((b,y)=>({current:y,prev:b.current}),{current:[],prev:[]}),le(({prev:b})=>b)),[]);pe(V(c,ve(b=>b.length>0),Te(h,N),le(([b,y,v])=>{const z=b.reduce((F,I,W)=>Bt(F,I,ka(I,y.offsetTree,v)||W),Ks());return{...y,groupIndices:b,groupOffsetTree:z}})),h),pe(V(r,Te(h),ve(([b,{lastIndex:y}])=>b[{endIndex:y,size:v,startIndex:b}])),a),pe(d,m);const C=kt(V(d,le(b=>b===void 0)),!0);pe(V(m,ve(b=>b!==void 0&&Ke(st(h).sizeTree)),le(b=>{const y=st(f),v=st(c).length>0;return y!==void 0&&y!==0?v?[{endIndex:0,size:y,startIndex:0},{endIndex:1,size:b,startIndex:1}]:[]:[{endIndex:0,size:b,startIndex:0}]})),a),pe(V(p,ve(b=>b!==void 0&&b.length>0&&Ke(st(h).sizeTree)),le(b=>{const y=[];let v=b[0],z=0;for(let F=1;Fb!==void 0&&y!==void 0),le(([b,y,v])=>{const z=[];for(let F=0;F({changed:v!==b,sizes:v}),{changed:!1,sizes:j}),le(b=>b.changed)));Ve(V(l,os((b,y)=>({diff:b.prev-y,prev:y}),{diff:0,prev:0}),le(b=>b.diff)),b=>{const{groupIndices:y}=st(h);if(b>0)Ie(s,!0),Ie(n,b+Zn(b,y));else if(b<0){const v=st(w);v.length>0&&(b-=Zn(-b,v)),Ie(i,b)}}),Ve(V(l,Te(t)),([b,y])=>{b<0&&y("`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},pt.ERROR)});const k=Pt(n);pe(V(n,Te(h),le(([b,y])=>{const v=y.groupIndices.length>0,z=[],F=y.lastSize;if(v){const I=ya(y.sizeTree,0);let W=0,Y=0;for(;W{let we=ie.ranges;return ie.prevSize!==0&&(we=[...ie.ranges,{endIndex:ae+b-1,size:ie.prevSize,startIndex:ie.prevIndex}]),{prevIndex:ae+b,prevSize:he,ranges:we}},{prevIndex:b,prevSize:0,ranges:z}).ranges}return Ds(y.sizeTree).reduce((I,{k:W,v:Y})=>({prevIndex:W+b,prevSize:Y,ranges:[...I.ranges,{endIndex:W+b-1,size:I.prevSize,startIndex:I.prevIndex}]}),{prevIndex:0,prevSize:F,ranges:[]}).ranges})),a);const q=Pt(V(i,Te(h,N),le(([b,{offsetTree:y},v])=>{const z=-b;return ka(z,y,v)})));return pe(V(i,Te(h,N),le(([b,y,v])=>{if(y.groupIndices.length>0){if(Ke(y.sizeTree))return y;let F=Ks();const I=st(w);let W=0,Y=0,se=0;for(;W<-b;){se=I[Y];const ie=I[Y+1]-se-1;Y++,W+=ie+1}if(F=Ds(y.sizeTree).reduce((ie,{k:ae,v:he})=>Bt(ie,Math.max(0,ae+b),he),F),W!==-b){const ie=ya(y.sizeTree,se);F=Bt(F,0,ie);const ae=as(y.sizeTree,-b+1)[1];F=Bt(F,1,ae)}return{...y,sizeTree:F,...Qr(y.offsetTree,0,F,v)}}const z=Ds(y.sizeTree).reduce((F,{k:I,v:W})=>Bt(F,Math.max(0,I+b),W),Ks());return{...y,sizeTree:z,...Qr(y.offsetTree,0,z,v)}})),h),{beforeUnshiftWith:k,data:S,defaultItemSize:m,firstItemIndex:l,fixedItemSize:d,fixedGroupSize:f,gap:N,groupIndices:c,heightEstimates:p,itemSize:g,listRefresh:M,shiftWith:i,shiftWithOffset:q,sizeRanges:a,sizes:h,statefulTotalCount:o,totalCount:r,trackItemSizes:C,unshiftWith:n}},et(Ts,Zr),{singleton:!0});function dd(t){return t.reduce((s,a)=>(s.groupIndices.push(s.totalCount),s.totalCount+=a+1,s),{groupIndices:[],totalCount:0})}const ki=Qe(([{groupIndices:t,sizes:s,totalCount:a},{headerHeight:r,scrollTop:o}])=>{const n=Le(),i=Le(),l=Pt(V(n,le(dd)));return pe(V(l,le(c=>c.totalCount)),a),pe(V(l,le(c=>c.groupIndices)),t),pe(V(ct(o,s,r),ve(([c,d])=>mr(d)),le(([c,d,m])=>as(d.groupOffsetTree,Math.max(c-m,0),"v")[0]),Ze(),le(c=>[c])),i),{groupCounts:n,topItemsIndexes:i}},et(us,It)),Es=Qe(([{log:t}])=>{const s=X(!1),a=Pt(V(s,ve(r=>r),Ze()));return Ve(s,r=>{r&&st(t)("props updated",{},pt.DEBUG)}),{didMount:a,propsReady:s}},et(Ts),{singleton:!0}),md=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Ci(t){const s=typeof t=="number"?{index:t}:t;return s.align||(s.align="start"),(!s.behavior||!md)&&(s.behavior="auto"),s.offset===void 0&&(s.offset=0),s}const Ra=Qe(([{gap:t,listRefresh:s,sizes:a,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:n,footerHeight:i,headerHeight:l,scrollingInProgress:c,scrollTo:d,smoothScrollTargetReached:m,viewportHeight:f},{log:p}])=>{const g=Le(),S=Le(),N=X(0);let j=null,h=null,w=null;function C(){j!==null&&(j(),j=null),w!==null&&(w(),w=null),h&&(clearTimeout(h),h=null),Ie(c,!1)}return pe(V(g,Te(a,f,r,N,l,i,p),Te(t,n,o),le(([[M,k,q,b,y,v,z,F],I,W,Y])=>{const se=Ci(M),{align:ie,behavior:ae,offset:he}=se,we=b-1,O=Si(se,k,we);let J=ka(O,k.offsetTree,I)+v;ie==="end"?(J+=W+as(k.sizeTree,O)[1]-q+Y,O===we&&(J+=z)):ie==="center"?J+=(W+as(k.sizeTree,O)[1]-q+Y)/2:J-=y,he!==void 0&&he!==0&&(J+=he);const A=Z=>{C(),Z?(F("retrying to scroll to",{location:M},pt.DEBUG),Ie(g,M)):(Ie(S,!0),F("list did not change, scroll successful",{},pt.DEBUG))};if(C(),ae==="smooth"){let Z=!1;w=Ve(s,ne=>{Z=Z||ne}),j=ss(m,()=>{A(Z)})}else j=ss(V(s,ud(150)),A);return h=setTimeout(()=>{C()},1200),Ie(c,!0),F("scrolling from index to",{behavior:ae,index:O,top:J},pt.DEBUG),{behavior:ae,top:J}})),d),{scrollTargetReached:S,scrollToIndex:g,topListHeight:N}},et(us,It,Ts),{singleton:!0});function ud(t){return s=>{const a=setTimeout(()=>{s(!1)},t);return r=>{r&&(s(!0),clearTimeout(a))}}}function tn(t,s){t===0?s():requestAnimationFrame(()=>{tn(t-1,s)})}function sn(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=X(!0),c=X(0),d=X(!0);return pe(V(i,Te(c),ve(([m,f])=>f!==0),ns(!1)),l),pe(V(i,Te(c),ve(([m,f])=>f!==0),ns(!1)),d),Ve(V(ct(s,i),Te(l,a,t,d),ve(([[,m],f,{sizeTree:p},g,S])=>m&&(!Ke(p)||Kr(g))&&!f&&!S),Te(c)),([,m])=>{ss(o,()=>{Ie(d,!0)}),tn(4,()=>{ss(r,()=>{Ie(l,!0)}),Ie(n,m)})}),{initialItemFinalLocationReached:d,initialTopMostItemIndex:c,scrolledToInitialItem:l}},et(us,It,Ra,Es),{singleton:!0});function Ii(t,s){return Math.abs(t-s)<1.01}const Ca="up",va="down",xd="none",pd={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},hd=0,Ma=Qe(([{footerHeight:t,headerHeight:s,scrollBy:a,scrollContainerState:r,scrollTop:o,viewportHeight:n}])=>{const i=X(!1),l=X(!0),c=Le(),d=Le(),m=X(4),f=X(hd),p=kt(V(Or(V(be(o),Os(1),ns(!0)),V(be(o),Os(1),ns(!1),Kn(100))),Ze()),!1),g=kt(V(Or(V(a,ns(!0)),V(a,ns(!1),Kn(200))),Ze()),!1);pe(V(ct(be(o),be(f)),le(([w,C])=>w<=C),Ze()),l),pe(V(l,ws(50)),d);const S=Pt(V(ct(r,be(n),be(s),be(t),be(m)),os((w,[{scrollHeight:C,scrollTop:M},k,q,b,y])=>{const v=M+k-C>-y,z={scrollHeight:C,scrollTop:M,viewportHeight:k};if(v){let I,W;return M>w.state.scrollTop?(I="SCROLLED_DOWN",W=w.state.scrollTop-M):(I="SIZE_DECREASED",W=w.state.scrollTop-M||w.scrollTopDelta),{atBottom:!0,atBottomBecause:I,scrollTopDelta:W,state:z}}let F;return z.scrollHeight>w.state.scrollHeight?F="SIZE_INCREASED":kw!==void 0&&w.atBottom===C.atBottom))),N=kt(V(r,os((w,{scrollHeight:C,scrollTop:M,viewportHeight:k})=>{if(!Ii(w.scrollHeight,C)){const q=C-(M+k)<1;return w.scrollTop!==M&&q?{changed:!0,jump:w.scrollTop-M,scrollHeight:C,scrollTop:M}:{changed:!0,jump:0,scrollHeight:C,scrollTop:M}}return{changed:!1,jump:0,scrollHeight:C,scrollTop:M}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),ve(w=>w.changed),le(w=>w.jump)),0);pe(V(S,le(w=>w.atBottom)),i),pe(V(i,ws(50)),c);const j=X(va);pe(V(r,le(({scrollTop:w})=>w),Ze(),os((w,C)=>st(g)?{direction:w.direction,prevScrollTop:C}:{direction:Cw.direction)),j),pe(V(r,ws(50),ns(xd)),j);const h=X(0);return pe(V(p,ve(w=>!w),ns(0)),h),pe(V(o,ws(100),Te(p),ve(([w,C])=>C),os(([w,C],[M])=>[C,M],[0,0]),le(([w,C])=>C-w)),h),{atBottomState:S,atBottomStateChange:c,atBottomThreshold:m,atTopStateChange:d,atTopThreshold:f,isAtBottom:i,isAtTop:l,isScrolling:p,lastJumpDueToItemResize:N,scrollDirection:j,scrollVelocity:h}},et(It)),Ia="top",Ta="bottom",eo="none";function to(t,s,a){return typeof t=="number"?a===Ca&&s===Ia||a===va&&s===Ta?t:0:a===Ca?s===Ia?t.main:t.reverse:s===Ta?t.main:t.reverse}function so(t,s){return typeof t=="number"?t:t[s]??0}const an=Qe(([{deviation:t,fixedHeaderHeight:s,headerHeight:a,scrollTop:r,viewportHeight:o}])=>{const n=Le(),i=X(0),l=X(0),c=X(0),d=kt(V(ct(be(r),be(o),be(a),be(n,Sa),be(c),be(i),be(s),be(t),be(l)),le(([m,f,p,[g,S],N,j,h,w,C])=>{const M=m-w,k=j+h,q=Math.max(p-M,0);let b=eo;const y=so(C,Ia),v=so(C,Ta);return g-=w,g+=p+h,S+=p+h,S-=w,g>m+k-y&&(b=Ca),Sm!==null),Ze(Sa)),[0,0]);return{increaseViewportBy:l,listBoundary:n,overscan:c,topListHeight:i,visibleRange:d}},et(It),{singleton:!0});function fd(t,s,a){if(mr(s)){const r=yi(t,s);return[{index:as(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 jr={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Va(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 N=t[t.length-1];m=N.offset+N.size}const f=a-i,p=l+f*c+(f-1)*r,g=d,S=p-m;return{bottom:m,firstItemIndex:n,items:ao(t,o,n),offsetBottom:S,offsetTop:d,top:g,topItems:ao(s,o,n),topListHeight:s.reduce((N,j)=>j.size+N,0),totalCount:a}}function Ti(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=sn(s,l),d=Array.from({length:l}).map((m,f)=>({data:n[f+c],index:f+c,offset:0,size:0}));return Va(d,[],l,o,a,r)}function ao(t,s,a){if(t.length===0)return[];if(!mr(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=Xs(s.groupOffsetTree,r,o);let l,c=0;for(const d of t){(!l||l.end{const N=X([]),j=X(0),h=Le(),w=X(0);pe(n.topItemsIndexes,N);const C=kt(V(ct(g,S,be(c,Sa),be(o),be(r),be(d),m,be(N),be(s),be(a),be(w),t),ve(([b,y,,v,,,,,,,,z])=>{const F=z!==void 0&&z.length!==v;return b&&!y&&!F}),le(([,,[b,y],v,z,F,I,W,Y,se,ie,ae])=>{const he=z,{offsetTree:we,sizeTree:O}=he,J=st(j);if(v===0)return{...jr,totalCount:v};if(b===0&&y===0)return J===0?{...jr,totalCount:v}:Ti(J,F,z,Y,se,ae||[]);if(Ke(O))return J>0?null:Va(fd(sn(F,v),he,ae),[],v,se,he,Y);const A=[];if(W.length>0){const re=W[0],T=W[W.length-1];let G=0;for(const H of Xs(O,re,T)){const ce=H.value,_=Math.max(H.start,re),Q=Math.min(H.end,T);for(let U=_;U<=Q;U++)A.push({data:ae?.[U],index:U,offset:G,size:ce}),G+=ce}}if(!I)return Va([],A,v,se,he,Y);const Z=W.length>0?W[W.length-1]+1:0,ne=rd(we,b,y,Z);if(ne.length===0)return null;const $e=v-1,Me=dr([],re=>{for(const T of ne){const G=T.value;let H=G.offset,ce=T.start;const _=G.size;if(G.offset=y);U++)re.push({data:ae?.[U],index:U,offset:H,size:_}),H+=_+se}}),We=ro(ie,Ia),P=ro(ie,Ta);if(Me.length>0&&(We>0||P>0)){const re=Me[0],T=Me[Me.length-1];if(We>0&&re.index>Z){const G=Math.min(We,re.index-Z),H=[];let ce=re.offset;for(let _=re.index-1;_>=re.index-G;_--){const Q=Xs(O,_,_)[0]?.value??re.size;ce-=Q+se,H.unshift({data:ae?.[_],index:_,offset:ce,size:Q})}Me.unshift(...H)}if(P>0&&T.index<$e){const G=Math.min(P,$e-T.index);let H=T.offset+T.size+se;for(let ce=T.index+1;ce<=T.index+G;ce++){const _=Xs(O,ce,ce)[0]?.value??T.size;Me.push({data:ae?.[ce],index:ce,offset:H,size:_}),H+=_+se}}}return Va(Me,A,v,se,he,Y)}),ve(b=>b!==null),Ze()),jr);pe(V(t,ve(Kr),le(b=>b?.length)),o),pe(V(C,le(b=>b.topListHeight)),f),pe(f,l),pe(V(C,le(b=>[b.top,b.bottom])),i),pe(V(C,le(b=>b.items)),h);const M=Pt(V(C,ve(({items:b})=>b.length>0),Te(o,t),ve(([{items:b},y])=>b[b.length-1].originalIndex===y-1),le(([,b,y])=>[b-1,y]),Ze(Sa),le(([b])=>b))),k=Pt(V(C,ws(200),ve(({items:b,topItems:y})=>b.length>0&&b[0].originalIndex===y.length),le(({items:b})=>b[0].index),Ze())),q=Pt(V(C,ve(({items:b})=>b.length>0),le(({items:b})=>{let y=0,v=b.length-1;for(;b[y].type==="group"&&yy;)v--;return{endIndex:b[v].index,startIndex:b[y].index}}),Ze(Ni)));return{endReached:M,initialItemCount:j,itemsRendered:h,listState:C,minOverscanItemCount:w,rangeChanged:q,startReached:k,topItemsIndexes:N,...p}},et(us,ki,an,_a,Ra,Ma,Es,Zr),{singleton:!0}),Ei=Qe(([{fixedFooterHeight:t,fixedHeaderHeight:s,footerHeight:a,headerHeight:r},{listState:o}])=>{const n=Le(),i=kt(V(ct(a,t,r,s,o),le(([l,c,d,m,f])=>l+c+d+m+f.offsetBottom+f.bottom)),0);return pe(be(i),n),{totalListHeight:i,totalListHeightChanged:n}},et(It,Hs),{singleton:!0}),gd=Qe(([{viewportHeight:t},{totalListHeight:s}])=>{const a=X(!1),r=kt(V(ct(a,t,s),ve(([o])=>o),le(([,o,n])=>Math.max(0,o-n)),ws(0),Ze()),0);return{alignToBottom:a,paddingTopAddition:r}},et(It,Ei),{singleton:!0}),Ri=Qe(()=>({context:X(null)})),bd=({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,_i=Qe(([{gap:t,sizes:s,totalCount:a},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:n,scrollingInProgress:i,scrollTop:l,viewportHeight:c},{scrollToIndex:d}])=>{const m=Le();return pe(V(m,Te(s,c,a,n,o,r,l),Te(t),le(([[f,p,g,S,N,j,h,w],C])=>{const{calculateViewLocation:M=bd,done:k,...q}=f,b=Si(f,p,S-1),y=ka(b,p.offsetTree,C)+N+j,v=y+as(p.sizeTree,b)[1],z=w+j,F=w+g-h,I=M({itemBottom:v,itemTop:y,locationParams:q,viewportBottom:F,viewportTop:z});return I!==null?k&&ss(V(i,ve(W=>!W),Os(st(i)?1:2)),k):k?.(),I}),ve(f=>f!==null)),d),{scrollIntoView:m}},et(us,It,Ra,Hs,Ts),{singleton:!0});function no(t){return t===!1?!1:t==="smooth"?"smooth":"auto"}const vd=(t,s)=>typeof t=="function"?no(t(s)):s&&no(t),wd=Qe(([{listRefresh:t,totalCount:s,fixedItemSize:a,data:r},{atBottomState:o,isAtBottom:n},{scrollToIndex:i},{scrolledToInitialItem:l},{didMount:c,propsReady:d},{log:m},{scrollingInProgress:f},{context:p},{scrollIntoView:g}])=>{const S=X(!1),N=Le();let j=null;function h(k){Ie(i,{align:"end",behavior:k,index:"LAST"})}Ve(V(ct(V(be(s),Os(1)),c),Te(be(S),n,l,f),le(([[k,q],b,y,v,z])=>{let F=q&&v,I="auto";return F&&(I=vd(b,y||z),F=F&&I!==!1),{followOutputBehavior:I,shouldFollow:F,totalCount:k}}),ve(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:q})=>{j!==null&&(j(),j=null),st(a)!==void 0?requestAnimationFrame(()=>{st(m)("following output to ",{totalCount:q},pt.DEBUG),h(k)}):j=ss(t,()=>{st(m)("following output to ",{totalCount:q},pt.DEBUG),h(k),j=null})});function w(k){const q=ss(o,b=>{k&&!b.atBottom&&b.notAtBottomBecause==="SIZE_INCREASED"&&j===null&&(st(m)("scrolling to bottom due to increased size",{},pt.DEBUG),h("auto"))});setTimeout(q,100)}Ve(V(ct(be(S),s,d),ve(([k,,q])=>k!==!1&&q),os(({value:k},[,q])=>({refreshed:k===q,value:q}),{refreshed:!1,value:0}),ve(({refreshed:k})=>k),Te(S,s)),([,k])=>{st(l)&&w(k!==!1)}),Ve(N,()=>{w(st(S)!==!1)}),Ve(ct(be(S),o),([k,q])=>{k!==!1&&!q.atBottom&&q.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&h("auto")});const C=X(null),M=Le();return pe(Or(V(be(r),le(k=>k?.length??0)),V(be(s))),M),Ve(V(ct(V(M,Os(1)),c),Te(be(C),l,f,p),le(([[k,q],b,y,v,z])=>q&&y&&b?.({context:z,totalCount:k,scrollingInProgress:v})),ve(k=>!!k),ws(0)),k=>{j!==null&&(j(),j=null),st(a)!==void 0?requestAnimationFrame(()=>{st(m)("scrolling into view",{}),Ie(g,k)}):j=ss(t,()=>{st(m)("scrolling into view",{}),Ie(g,k),j=null})}),{autoscrollToBottom:N,followOutput:S,scrollIntoViewOnChange:C}},et(us,Ma,Ra,_a,Es,Ts,It,Ri,_i)),Nd=Qe(([{data:t,firstItemIndex:s,gap:a,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:n,listState:i},{didMount:l}])=>(pe(V(l,Te(n),ve(([,c])=>c!==0),Te(o,r,s,a,t),le(([[,c],d,m,f,p,g=[]])=>Ti(c,d,m,f,p,g))),i),{}),et(us,_a,Hs,Es),{singleton:!0}),jd=Qe(([{didMount:t},{scrollTo:s},{listState:a}])=>{const r=X(0);return Ve(V(t,Te(r),ve(([,o])=>o!==0),le(([,o])=>({top:o}))),o=>{ss(V(a,Os(1),ve(n=>n.items.length>1)),()=>{requestAnimationFrame(()=>{Ie(s,o)})})}),{initialScrollTop:r}},et(Es,It,Hs),{singleton:!0}),Mi=Qe(([{scrollVelocity:t}])=>{const s=X(!1),a=Le(),r=X(!1);return pe(V(t,Te(r,s,a),ve(([o,n])=>n!==!1&&n!==void 0),le(([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}),Ze()),s),Ve(V(ct(s,t,a),Te(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}},et(Ma),{singleton:!0}),rn=Qe(([{scrollContainerState:t,scrollTo:s}])=>{const a=Le(),r=Le(),o=Le(),n=X(!1),i=X(void 0);return pe(V(ct(a,r),le(([{scrollTop:l,viewportHeight:c},{offsetTop:d,listHeight:m}])=>({scrollHeight:m,scrollTop:Math.max(0,l-d),viewportHeight:c}))),t),pe(V(s,Te(r),le(([l,{offsetTop:c}])=>({...l,top:l.top+c}))),o),{customScrollParent:i,useWindowScroll:n,windowScrollContainerState:a,windowScrollTo:o,windowViewportRect:r}},et(It)),yd=Qe(([{sizeRanges:t,sizes:s},{headerHeight:a,scrollTop:r},{initialTopMostItemIndex:o},{didMount:n},{useWindowScroll:i,windowScrollContainerState:l,windowViewportRect:c}])=>{const d=Le(),m=X(void 0),f=X(null),p=X(null);return pe(l,f),pe(c,p),Ve(V(d,Te(s,r,i,f,p,a)),([g,S,N,j,h,w,C])=>{const M=od(S.sizeTree);j&&h!==null&&w!==null&&(N=h.scrollTop-w.offsetTop),N-=C,g({ranges:M,scrollTop:N})}),pe(V(m,ve(Kr),le(Sd)),o),pe(V(n,Te(m),ve(([,g])=>g!==void 0),Ze(),le(([,g])=>g.ranges)),t),{getState:d,restoreStateFrom:m}},et(us,It,_a,Es,rn));function Sd(t){return{align:"start",index:0,offset:t.scrollTop}}const kd=Qe(([{topItemsIndexes:t}])=>{const s=X(0);return pe(V(s,ve(a=>a>=0),le(a=>Array.from({length:a}).map((r,o)=>o))),t),{topItemCount:s}},et(Hs));function Ai(t){let s=!1,a;return(()=>(s||(s=!0,a=t()),a))}const Cd=Ai(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Id=Qe(([{deviation:t,scrollBy:s,scrollingInProgress:a,scrollTop:r},{isAtBottom:o,isScrolling:n,lastJumpDueToItemResize:i,scrollDirection:l},{listState:c},{beforeUnshiftWith:d,gap:m,shiftWithOffset:f,sizes:p},{log:g},{recalcInProgress:S}])=>{const N=Pt(V(c,Te(i),os(([,h,w,C],[{bottom:M,items:k,offsetBottom:q,totalCount:b},y])=>{const v=M+q;let z=0;return w===b&&h.length>0&&k.length>0&&(k[0].originalIndex===0&&h[0].originalIndex===0||(z=v-C,z!==0&&(z+=y))),[z,k,b,v]},[0,[],0,0]),ve(([h])=>h!==0),Te(r,l,a,o,g,S),ve(([,h,w,C,,,M])=>!M&&!C&&h!==0&&w===Ca),le(([[h],,,,,w])=>(w("Upward scrolling compensation",{amount:h},pt.DEBUG),h))));function j(h){h>0?(Ie(s,{behavior:"auto",top:-h}),Ie(t,0)):(Ie(t,0),Ie(s,{behavior:"auto",top:-h}))}return Ve(V(N,Te(t,n)),([h,w,C])=>{C&&Cd()?Ie(t,w-h):j(-h)}),Ve(V(ct(kt(n,!1),t,S),ve(([h,w,C])=>!h&&!C&&w!==0),le(([h,w])=>w),ws(1)),j),pe(V(f,le(h=>({top:-h}))),s),Ve(V(d,Te(p,m),le(([h,{groupIndices:w,lastSize:C,sizeTree:M},k])=>{function q(F){return F*(C+k)}if(w.length===0)return q(h);let b=0;const y=ya(M,0);let v=0,z=0;for(;vh&&(b-=y,F=h-v+1),v+=F,b+=q(F),z++}return b})),h=>{Ie(t,h),requestAnimationFrame(()=>{Ie(s,{top:h}),requestAnimationFrame(()=>{Ie(t,0),Ie(S,!1)})})}),{deviation:t}},et(It,Ma,Hs,us,Ts,Zr)),Td=Qe(([t,s,a,r,o,n,i,l,c,d,m])=>({...t,...s,...a,...r,...o,...n,...i,...l,...c,...d,...m}),et(an,Nd,Es,Mi,Ei,jd,gd,rn,_i,Ts,Ri)),zi=Qe(([{data:t,defaultItemSize:s,firstItemIndex:a,fixedItemSize:r,fixedGroupSize:o,gap:n,groupIndices:i,heightEstimates:l,itemSize:c,sizeRanges:d,sizes:m,statefulTotalCount:f,totalCount:p,trackItemSizes:g},{initialItemFinalLocationReached:S,initialTopMostItemIndex:N,scrolledToInitialItem:j},h,w,C,M,{scrollToIndex:k},q,{topItemCount:b},{groupCounts:y},v])=>{const{listState:z,minOverscanItemCount:F,topItemsIndexes:I,rangeChanged:W,...Y}=M;return pe(W,v.scrollSeekRangeChanged),pe(V(v.windowViewportRect,le(se=>se.visibleHeight)),h.viewportHeight),{data:t,defaultItemHeight:s,firstItemIndex:a,fixedItemHeight:r,fixedGroupHeight:o,gap:n,groupCounts:y,heightEstimates:l,initialItemFinalLocationReached:S,initialTopMostItemIndex:N,scrolledToInitialItem:j,sizeRanges:d,topItemCount:b,topItemsIndexes:I,totalCount:p,...C,groupIndices:i,itemSize:c,listState:z,minOverscanItemCount:F,scrollToIndex:k,statefulTotalCount:f,trackItemSizes:g,rangeChanged:W,...Y,...v,...h,sizes:m,...w}},et(us,_a,It,yd,wd,Hs,Ra,Id,kd,ki,Td));function Ed(t,s){const a={},r={};let o=0;const n=t.length;for(;o(h[w]=C=>{const M=j[s.methods[w]];Ie(M,C)},h),{})}function m(j){return i.reduce((h,w)=>(h[w]=Uc(j[s.events[w]]),h),{})}const f=ue.forwardRef(function(j,h){const{children:w,...C}=j,[M]=ue.useState(()=>dr(Wc(t),b=>{c(b,C)})),[k]=ue.useState(Yn(m,M));$a(()=>{for(const b of i)b in C&&Ve(k[b],C[b]);return()=>{Object.values(k).map(Xr)}},[C,k,M]),$a(()=>{c(M,C)}),ue.useImperativeHandle(h,qn(d(M)));const q=a;return e.jsx(l.Provider,{value:M,children:a!==void 0?e.jsx(q,{...Ed([...r,...o,...i],C),children:w}):w})}),p=j=>{const h=ue.useContext(l);return ue.useCallback(w=>{Ie(h[j],w)},[h,j])},g=j=>{const h=ue.useContext(l)[j],w=ue.useCallback(C=>Ve(h,C),[h]);return ue.useSyncExternalStore(w,()=>st(h),()=>st(h))},S=j=>{const h=ue.useContext(l)[j],[w,C]=ue.useState(Yn(st,h));return $a(()=>Ve(h,M=>{M!==w&&C(qn(M))}),[h,w]),w},N=parseInt(ue.version)>=18?g:S;return{Component:f,useEmitter:(j,h)=>{const w=ue.useContext(l)[j];$a(()=>Ve(w,h),[h,w])},useEmitterValue:N,usePublisher:p}}const Di=ue.createContext(void 0),$i=ue.createContext(void 0),yr="-webkit-sticky",oo="sticky",nn=Ai(()=>{if(typeof document>"u")return oo;const t=document.createElement("div");return t.style.position=yr,t.style.position===yr?yr:oo}),Fi=typeof document<"u"?ue.useLayoutEffect:ue.useEffect;function Sr(t){return"self"in t}function Rd(t){return"body"in t}function Oi(t,s,a,r=sa,o,n){const i=ue.useRef(null),l=ue.useRef(null),c=ue.useRef(null),d=ue.useCallback(p=>{let g,S,N;const j=p.target;if(Rd(j)||Sr(j)){const w=Sr(j)?j:j.defaultView;N=n===!0?w.scrollX:w.scrollY,g=n===!0?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,S=n===!0?w.innerWidth:w.innerHeight}else N=n===!0?j.scrollLeft:j.scrollTop,g=n===!0?j.scrollWidth:j.scrollHeight,S=n===!0?j.offsetWidth:j.offsetHeight;const h=()=>{t({scrollHeight:g,scrollTop:Math.max(N,0),viewportHeight:S})};p.suppressFlushSync===!0?h():Lr.flushSync(h),l.current!==null&&(N===l.current||N<=0||N===g-S)&&(l.current=null,s(!0),c.current&&(clearTimeout(c.current),c.current=null))},[t,s,n]);ue.useEffect(()=>{const p=o||i.current;return r(o||i.current),d({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",d,{passive:!0}),()=>{r(null),p.removeEventListener("scroll",d)}},[i,d,a,r,o]);function m(p){const g=i.current;if(!g||(n===!0?"offsetWidth"in g&&g.offsetWidth===0:"offsetHeight"in g&&g.offsetHeight===0))return;const S=p.behavior==="smooth";let N,j,h;Sr(g)?(j=Math.max(Cs(g.document.documentElement,n===!0?"width":"height"),n===!0?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight),N=n===!0?g.innerWidth:g.innerHeight,h=n===!0?window.scrollX:window.scrollY):(j=g[n===!0?"scrollWidth":"scrollHeight"],N=Cs(g,n===!0?"width":"height"),h=g[n===!0?"scrollLeft":"scrollTop"]);const w=j-N;if(p.top=Math.ceil(Math.max(Math.min(w,p.top),0)),Ii(N,j)||p.top===h){t({scrollHeight:j,scrollTop:h,viewportHeight:N}),S&&s(!0);return}S?(l.current=p.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,l.current=null,s(!0)},1e3)):l.current=null,n===!0&&(p={...p.behavior!==void 0?{behavior:p.behavior}:{},left:p.top}),g.scrollTo(p)}function f(p){n===!0&&(p={...p.behavior!==void 0?{behavior:p.behavior}:{},...p.top!==void 0?{left:p.top}:{}}),i.current.scrollBy(p)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:m}}function on(t){return t}const _d=Qe(()=>{const t=X(l=>`Item ${l}`),s=X(l=>`Group ${l}`),a=X({}),r=X(on),o=X("div"),n=X(sa),i=(l,c=null)=>kt(V(a,le(d=>d[l]),Ze()),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")}}),Md=Qe(([t,s])=>({...t,...s}),et(zi,_d)),Ad=({height:t})=>e.jsx("div",{style:{height:t}}),zd={overflowAnchor:"none",position:nn(),zIndex:1},Bi={overflowAnchor:"none"},Ld={...Bi,display:"inline-block",height:"100%"},io=ue.memo(function({showTopList:t=!1}){const s=ye("listState"),a=Wt("sizeRanges"),r=ye("useWindowScroll"),o=ye("customScrollParent"),n=Wt("windowScrollContainerState"),i=Wt("scrollContainerState"),l=o||r?n:i,c=ye("itemContent"),d=ye("context"),m=ye("groupContent"),f=ye("trackItemSizes"),p=ye("itemSize"),g=ye("log"),S=Wt("gap"),N=ye("horizontalDirection"),{callbackRef:j}=Kc(a,p,f,t?sa:l,g,S,o,N,ye("skipAnimationFrameInResizeObserver")),[h,w]=ue.useState(0);cn("deviation",Y=>{h!==Y&&w(Y)});const C=ye("EmptyPlaceholder"),M=ye("ScrollSeekPlaceholder")??Ad,k=ye("ListComponent"),q=ye("ItemComponent"),b=ye("GroupComponent"),y=ye("computeItemKey"),v=ye("isSeeking"),z=ye("groupIndices").length>0,F=ye("alignToBottom"),I=ye("initialItemFinalLocationReached"),W=t?{}:{boxSizing:"border-box",...N?{display:"inline-block",height:"100%",marginLeft:h!==0?h:F?"auto":0,paddingLeft:s.offsetTop,paddingRight:s.offsetBottom,whiteSpace:"nowrap"}:{marginTop:h!==0?h:F?"auto":0,paddingBottom:s.offsetBottom,paddingTop:s.offsetTop},...I?{}:{visibility:"hidden"}};return!t&&s.totalCount===0&&C!==null&&C!==void 0?e.jsx(C,{...yt(C,d)}):e.jsx(k,{...yt(k,d),"data-testid":t?"virtuoso-top-item-list":"virtuoso-item-list",ref:j,style:W,children:(t?s.topItems:s.items).map(Y=>{const se=Y.originalIndex,ie=y(se+s.firstItemIndex,Y.data,d);return v?u.createElement(M,{...yt(M,d),height:Y.size,index:Y.index,key:ie,type:Y.type||"item",...Y.type==="group"?{}:{groupIndex:Y.groupIndex}}):Y.type==="group"?u.createElement(b,{...yt(b,d),"data-index":se,"data-item-index":Y.index,"data-known-size":Y.size,key:ie,style:zd},m(Y.index,d)):u.createElement(q,{...yt(q,d),...Od(q,Y.data),"data-index":se,"data-item-group-index":Y.groupIndex,"data-item-index":Y.index,"data-known-size":Y.size,key:ie,style:N?Ld:Bi},z?c(Y.index,Y.groupIndex,Y.data,d):c(Y.index,Y.data,d))})})}),Dd={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},$d={outline:"none",overflowX:"auto",position:"relative"},ln=t=>({height:"100%",position:"absolute",top:0,width:"100%",...t?{display:"flex",flexDirection:"column"}:void 0}),Pi=(t,s,a=0)=>({...ln(t),position:s?"relative":"absolute",top:s?-a:0}),Fd={position:nn(),top:0,width:"100%",zIndex:1};function yt(t,s){if(typeof t!="string")return{context:s}}function Od(t,s){return{item:typeof t=="string"?void 0:s}}const Bd=ue.memo(function(){const t=ye("HeaderComponent"),s=Wt("headerHeight"),a=ye("HeaderFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,ye("skipAnimationFrameInResizeObserver")),o=ye("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null}),Pd=ue.memo(function(){const t=ye("FooterComponent"),s=Wt("footerHeight"),a=ye("HeaderFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,ye("skipAnimationFrameInResizeObserver")),o=ye("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null});function Hi({useEmitter:t,useEmitterValue:s,usePublisher:a}){return ue.memo(function({children:r,style:o,context:n,...i}){const l=a("scrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("scrollerRef"),f=s("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:g,scrollToCallback:S}=Oi(l,d,c,m,void 0,f);return t("scrollTo",S),t("scrollBy",p),e.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:g,style:{...f?$d:Dd,...o},tabIndex:0,...i,...yt(c,n),children:r})})}function Qi({useEmitter:t,useEmitterValue:s,usePublisher:a}){return ue.memo(function({children:r,style:o,context:n,...i}){const l=a("windowScrollContainerState"),c=s("ScrollerComponent"),d=a("smoothScrollTargetReached"),m=s("totalListHeight"),f=s("deviation"),p=s("customScrollParent"),g=ue.useRef(null),S=s("scrollerRef"),{scrollByCallback:N,scrollerRef:j,scrollToCallback:h}=Oi(l,d,c,S,p);return Fi(()=>(j.current=p||g.current?.ownerDocument.defaultView,()=>{j.current=null}),[j,p]),t("windowScrollTo",h),t("scrollBy",N),e.jsx(c,{ref:g,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...m!==0?{height:m+f}:void 0},...i,...yt(c,n),children:r})})}const Hd=({children:t})=>{const s=ue.useContext(Di),a=Wt("viewportHeight"),r=Wt("fixedItemHeight"),o=ye("alignToBottom"),n=ye("horizontalDirection"),i=ue.useMemo(()=>xi(a,c=>Cs(c,n?"width":"height")),[a,n]),l=Ps(i,!0,ye("skipAnimationFrameInResizeObserver"));return ue.useEffect(()=>{s&&(a(s.viewportHeight),r(s.itemHeight))},[s,a,r]),e.jsx("div",{"data-viewport-type":"element",ref:l,style:ln(o),children:t})},Qd=({children:t})=>{const s=ue.useContext(Di),a=Wt("windowViewportRect"),r=Wt("fixedItemHeight"),o=ye("customScrollParent"),n=ye("useWindowScroll"),i=ye("topListHeight"),l=hi(a,o,ye("skipAnimationFrameInResizeObserver")),c=ye("alignToBottom");return ue.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:Pi(c,n,i),children:t})},Gd=({children:t})=>{const s=ye("TopItemListComponent")??"div",a=ye("headerHeight"),r={...Fd,marginTop:`${a}px`},o=ye("context");return e.jsx(s,{style:r,...yt(s,o),children:t})},Ud=ue.memo(function(t){const s=ye("useWindowScroll"),a=ye("topItemsIndexes").length>0,r=ye("customScrollParent"),o=ye("context");return e.jsxs(r||s?qd:Wd,{...t,context:o,children:[a&&e.jsx(Gd,{children:e.jsx(io,{showTopList:!0})}),e.jsxs(r||s?Qd:Hd,{children:[e.jsx(Bd,{}),e.jsx(io,{}),e.jsx(Pd,{})]})]})}),{Component:Vd,useEmitter:cn,useEmitterValue:ye,usePublisher:Wt}=Li(Md,{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"}},Ud),Wd=Hi({useEmitter:cn,useEmitterValue:ye,usePublisher:Wt}),qd=Qi({useEmitter:cn,useEmitterValue:ye,usePublisher:Wt}),Yd=Vd,Kd=Qe(()=>{const t=X(d=>e.jsxs("td",{children:["Item $",d]})),s=X(null),a=X(d=>e.jsxs("td",{colSpan:1e3,children:["Group ",d]})),r=X(null),o=X(null),n=X({}),i=X(on),l=X(sa),c=(d,m=null)=>kt(V(n,le(f=>f[d]),Ze()),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")}});et(zi,Kd);nn();const lo={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Xd={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:co,floor:ar,max:wa,min:kr,round:mo}=Math;function uo(t,s,a){return Array.from({length:s-t+1}).map((r,o)=>({data:a===null?null:a[o+t],index:o+t}))}function Jd(t){return{...Xd,items:t}}function Fa(t,s){return t!==void 0&&t.width===s.width&&t.height===s.height}function Zd(t,s){return t!==void 0&&t.column===s.column&&t.row===s.row}const em=Qe(([{increaseViewportBy:t,listBoundary:s,overscan:a,visibleRange:r},{footerHeight:o,headerHeight:n,scrollBy:i,scrollContainerState:l,scrollTo:c,scrollTop:d,smoothScrollTargetReached:m,viewportHeight:f},p,g,{didMount:S,propsReady:N},{customScrollParent:j,useWindowScroll:h,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:M},k])=>{const q=X(0),b=X(0),y=X(lo),v=X({height:0,width:0}),z=X({height:0,width:0}),F=Le(),I=Le(),W=X(0),Y=X(null),se=X({column:0,row:0}),ie=Le(),ae=Le(),he=X(!1),we=X(0),O=X(!0),J=X(!1),A=X(!1);Ve(V(S,Te(we),ve(([P,re])=>re!==0)),()=>{Ie(O,!1)}),Ve(V(ct(S,O,z,v,we,J),ve(([P,re,T,G,,H])=>P&&!re&&T.height!==0&&G.height!==0&&!H)),([,,,,P])=>{Ie(J,!0),tn(1,()=>{Ie(F,P)}),ss(V(d),()=>{Ie(s,[0,0]),Ie(O,!0)})}),pe(V(ae,ve(P=>P!=null&&P.scrollTop>0),ns(0)),b),Ve(V(S,Te(ae),ve(([,P])=>P!=null)),([,P])=>{P&&(Ie(v,P.viewport),Ie(z,P.item),Ie(se,P.gap),P.scrollTop>0&&(Ie(he,!0),ss(V(d,Os(1)),re=>{Ie(he,!1)}),Ie(c,{top:P.scrollTop})))}),pe(V(v,le(({height:P})=>P)),f),pe(V(ct(be(v,Fa),be(z,Fa),be(se,(P,re)=>P!==void 0&&P.column===re.column&&P.row===re.row),be(d)),le(([P,re,T,G])=>({gap:T,item:re,scrollTop:G,viewport:P}))),ie),pe(V(ct(be(q),r,be(se,Zd),be(z,Fa),be(v,Fa),be(Y),be(b),be(he),be(O),be(we)),ve(([,,,,,,,P])=>!P),le(([P,[re,T],G,H,ce,_,Q,,U,E])=>{const{column:te,row:de}=G,{height:xe,width:oe}=H,{width:fe}=ce;if(Q===0&&(P===0||fe===0))return lo;if(oe===0){const B=sn(E,P),Ae=B+Math.max(Q-1,0);return Jd(uo(B,Ae,_))}const qe=Gi(fe,oe,te);let Fe,Pe;U?re===0&&T===0&&Q>0?(Fe=0,Pe=Q-1):(Fe=qe*ar((re+de)/(xe+de)),Pe=qe*co((T+de)/(xe+de))-1,Pe=kr(P-1,wa(Pe,qe-1)),Fe=kr(Pe,wa(0,Fe))):(Fe=0,Pe=-1);const tt=uo(Fe,Pe,_),{bottom:Tt,top:dt}=xo(ce,G,H,tt),wt=co(P/qe),Lt=wt*xe+(wt-1)*de-Tt;return{bottom:Tt,itemHeight:xe,items:tt,itemWidth:oe,offsetBottom:Lt,offsetTop:dt,top:dt}})),y),pe(V(Y,ve(P=>P!==null),le(P=>P.length)),q),pe(V(ct(v,z,y,se),ve(([P,re,{items:T}])=>T.length>0&&re.height!==0&&P.height!==0),le(([P,re,{items:T},G])=>{const{bottom:H,top:ce}=xo(P,G,re,T);return[ce,H]}),Ze(Sa)),s);const Z=X(!1);pe(V(d,Te(Z),le(([P,re])=>re||P!==0)),Z);const ne=Pt(V(ct(y,q),ve(([{items:P}])=>P.length>0),Te(Z),ve(([[P,re],T])=>{const G=P.items[P.items.length-1].index===re-1;return(T||P.bottom>0&&P.itemHeight>0&&P.offsetBottom===0&&P.items.length===re)&&G}),le(([[,P]])=>P-1),Ze())),$e=Pt(V(be(y),ve(({items:P})=>P.length>0&&P[0].index===0),ns(0),Ze())),Me=Pt(V(be(y),Te(he),ve(([{items:P},re])=>P.length>0&&!re),le(([{items:P}])=>({endIndex:P[P.length-1].index,startIndex:P[0].index})),Ze(Ni),ws(0)));pe(Me,g.scrollSeekRangeChanged),pe(V(F,Te(v,z,q,se),le(([P,re,T,G,H])=>{const ce=Ci(P),{align:_,behavior:Q,offset:U}=ce;let E=ce.index;E==="LAST"&&(E=G-1),E=wa(0,E,kr(G-1,E));let te=Gr(re,H,T,E);return _==="end"?te=mo(te-re.height+T.height):_==="center"&&(te=mo(te-re.height/2+T.height/2)),U!==void 0&&U!==0&&(te+=U),{behavior:Q,top:te}})),c);const We=kt(V(y,le(P=>P.offsetBottom+P.bottom)),0);return pe(V(M,le(P=>({height:P.visibleHeight,width:P.visibleWidth}))),v),{customScrollParent:j,data:Y,deviation:W,footerHeight:o,gap:se,headerHeight:n,increaseViewportBy:t,initialItemCount:b,itemDimensions:z,overscan:a,restoreStateFrom:ae,scrollBy:i,scrollContainerState:l,scrollHeight:I,scrollTo:c,scrollToIndex:F,scrollTop:d,smoothScrollTargetReached:m,totalCount:q,useWindowScroll:h,viewportDimensions:v,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:M,...g,gridState:y,horizontalDirection:A,initialTopMostItemIndex:we,totalListHeight:We,...p,endReached:ne,propsReady:N,rangeChanged:Me,startReached:$e,stateChanged:ie,stateRestoreInProgress:he,...k}},et(an,It,Ma,Mi,Es,rn,Ts));function Gi(t,s,a){return wa(1,ar((t+a)/(ar(s)+a)))}function xo(t,s,a,r){const{height:o}=a;if(o===void 0||r.length===0)return{bottom:0,top:0};const n=Gr(t,s,a,r[0].index);return{bottom:Gr(t,s,a,r[r.length-1].index)+o,top:n}}function Gr(t,s,a,r){const o=Gi(t.width,a.width,s.column),n=ar(r/o),i=n*a.height+wa(0,n-1)*s.row;return i>0?i+s.row:i}const tm=Qe(()=>{const t=X(f=>`Item ${f}`),s=X({}),a=X(null),r=X("virtuoso-grid-item"),o=X("virtuoso-grid-list"),n=X(on),i=X("div"),l=X(sa),c=(f,p=null)=>kt(V(s,le(g=>g[f]),Ze()),p),d=X(!1),m=X(!1);return pe(be(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")}}),sm=Qe(([t,s])=>({...t,...s}),et(em,tm)),am=ue.memo(function(){const t=Je("gridState"),s=Je("listClassName"),a=Je("itemClassName"),r=Je("itemContent"),o=Je("computeItemKey"),n=Je("isSeeking"),i=qt("scrollHeight"),l=Je("ItemComponent"),c=Je("ListComponent"),d=Je("ScrollSeekPlaceholder"),m=Je("context"),f=qt("itemDimensions"),p=qt("gap"),g=Je("log"),S=Je("stateRestoreInProgress"),N=qt("reportReadyState"),j=Ps(ue.useMemo(()=>h=>{const w=h.parentElement.parentElement.scrollHeight;i(w);const C=h.firstChild;if(C!==null){const{height:M,width:k}=C.getBoundingClientRect();f({height:M,width:k})}p({column:po("column-gap",getComputedStyle(h).columnGap,g),row:po("row-gap",getComputedStyle(h).rowGap,g)})},[i,f,p,g]),!0,!1);return Fi(()=>{t.itemHeight>0&&t.itemWidth>0&&N(!0)},[t]),S?null:e.jsx(c,{className:s,ref:j,...yt(c,m),"data-testid":"virtuoso-item-list",style:{paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},children:t.items.map(h=>{const w=o(h.index,h.data,m);return n?e.jsx(d,{...yt(d,m),height:t.itemHeight,index:h.index,width:t.itemWidth},w):u.createElement(l,{...yt(l,m),className:a,"data-index":h.index,key:w},r(h.index,h.data,m))})})}),rm=ue.memo(function(){const t=Je("HeaderComponent"),s=qt("headerHeight"),a=Je("headerFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,!1),o=Je("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null}),nm=ue.memo(function(){const t=Je("FooterComponent"),s=qt("footerHeight"),a=Je("headerFooterTag"),r=Ps(ue.useMemo(()=>n=>{s(Cs(n,"height"))},[s]),!0,!1),o=Je("context");return t!=null?e.jsx(a,{ref:r,children:e.jsx(t,{...yt(t,o)})}):null}),om=({children:t})=>{const s=ue.useContext($i),a=qt("itemDimensions"),r=qt("viewportDimensions"),o=Ps(ue.useMemo(()=>n=>{r(n.getBoundingClientRect())},[r]),!0,!1);return ue.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:ln(!1),children:t})},im=({children:t})=>{const s=ue.useContext($i),a=qt("windowViewportRect"),r=qt("itemDimensions"),o=Je("customScrollParent"),n=Je("useWindowScroll"),i=hi(a,o,!1);return ue.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:Pi(!1,n),children:t})},lm=ue.memo(function({...t}){const s=Je("useWindowScroll"),a=Je("customScrollParent"),r=a||s?dm:cm,o=a||s?im:om,n=Je("context");return e.jsx(r,{...t,...yt(r,n),children:e.jsxs(o,{children:[e.jsx(rm,{}),e.jsx(am,{}),e.jsx(nm,{})]})})}),{useEmitter:Ui,useEmitterValue:Je,usePublisher:qt}=Li(sm,{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"}},lm),cm=Hi({useEmitter:Ui,useEmitterValue:Je,usePublisher:qt}),dm=Qi({useEmitter:Ui,useEmitterValue:Je,usePublisher:qt});function po(t,s,a){return s!=="normal"&&s?.endsWith("px")!==!0&&a(`${t} was not resolved to pixel value correctly`,s,pt.WARN),s==="normal"?0:parseInt(s??"0",10)}function ho(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 fo=new Set(["p","h1","h2","h3","h4","h5","h6","li","td","th"]);function mm(t,s="component",a){const r=t.getBoundingClientRect(),o=[],n=a?.leafTags?new Set([...fo,...a.leafTags]):fo,i=a?.captureRoundedBorders??!0,l=a?.excludeTags?new Set(a.excludeTags):null,c=a?.excludeSelectors??null;function d(m){const f=getComputedStyle(m);if(f.display==="none"||f.visibility==="hidden"||f.opacity==="0")return;const p=m.tagName.toLowerCase();if(l?.has(p)||c?.some(v=>m.matches(v)))return;const g=[...m.children].filter(v=>{const z=getComputedStyle(v);return z.display!=="none"&&z.visibility!=="hidden"&&z.opacity!=="0"}),S=p==="img"||p==="svg"||p==="video"||p==="canvas",N=p==="input"||p==="button"||p==="textarea"||p==="select",j=g.length===0||S||N||n.has(p),h=f.backgroundColor,w=h!=="rgba(0, 0, 0, 0)"&&h!=="transparent",C=f.backgroundImage!=="none",M=parseFloat(f.borderTopWidth)||0,k=i&&M>0&&f.borderTopColor!=="rgba(0, 0, 0, 0)"&&f.borderTopColor!=="transparent",q=(parseFloat(f.borderTopLeftRadius)||0)>0,b=w||C||k&&q,y=p==="tr"||p==="td"||p==="th"||p==="thead"||p==="tbody"||p==="table";if(j){const v=m.getBoundingClientRect();if(v.width<1||v.height<1)return;const z=S&&v.width>0&&v.height>0&&Math.abs(v.width-v.height)<4,F=y?0:z?"50%":go(f,m)??8,I=r.width;o.push({x:I>0?+((v.left-r.left)/I*100).toFixed(4):0,y:Math.round(v.top-r.top),w:I>0?+(v.width/I*100).toFixed(4):0,h:Math.round(v.height),r:F});return}if(b){const v=m.getBoundingClientRect();if(v.width>=1&&v.height>=1){const z=y?0:go(f,m)??8,F=r.width;o.push({x:F>0?+((v.left-r.left)/F*100).toFixed(4):0,y:Math.round(v.top-r.top),w:F>0?+(v.width/F*100).toFixed(4):0,h:Math.round(v.height),r:z,c:!0})}}for(const v of g)d(v)}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 go(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 um=new Map;function xm(t){return um.get(t)}function pm(){typeof window<"u"&&window.__BONEYARD_BUILD&&(window.__BONEYARD_SNAPSHOT=mm)}function hm(){return typeof window<"u"&&window.__BONEYARD_BUILD===!0}function fm(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 Vs={angle:110,start:30,end:70,speed:"2s",lightHighlight:"#f7f7f7",darkHighlight:"#2c2c2c"},xa={speed:"1.8s",lightAdjust:.3,darkAdjust:.02},bo={web:{light:"#f0f0f0",dark:"#222222"}},gm=/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+))?\s*\)/;function vo(t,s){const a=t.match(gm);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}pm();let rs={};function wo({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:f,fixture:p,snapshotConfig:g}){const S=u.useRef(null),N=u.useRef(Math.random().toString(36).slice(2,8)).current,[j,h]=u.useState(0),[w,C]=u.useState(0),[M,k]=u.useState(!1);u.useEffect(()=>{if(typeof window>"u")return;const T=()=>{const ce=document.documentElement.classList.contains("dark")||!!S.current?.closest(".dark");k(ce)};T();const G=new MutationObserver(T);G.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const H=window.matchMedia("(prefers-color-scheme: dark)");return H.addEventListener("change",T),()=>{G.disconnect(),H.removeEventListener("change",T)}},[]);const q=o??rs.color??bo.web.light,b=n??rs.darkColor??bo.web.dark,y=M?b:q,v=i??rs.animate??"pulse",z=v===!0?"pulse":v===!1?"solid":v;u.useEffect(()=>{const T=S.current;if(!T)return;const G=new ResizeObserver(ce=>{const _=ce[0]?.contentRect;h(Math.round(_?.width??0)),_&&_.height>0&&C(Math.round(_.height))});G.observe(T);const H=T.getBoundingClientRect();return h(Math.round(H.width)),H.height>0&&C(Math.round(H.height)),()=>G.disconnect()},[]);const F={};if(a&&(F["data-boneyard"]=a,g&&(F["data-boneyard-config"]=JSON.stringify(g))),hm())return e.jsx("div",{ref:S,className:m,style:{position:"relative"},...F,children:e.jsx("div",{children:p??s})});const[I,W]=u.useState(!1);u.useLayoutEffect(()=>{W(!0)},[]);const Y=r??(a?xm(a):void 0),se=I&&typeof window<"u"?window.innerWidth:0,ie=j>0?j:se,ae=Y&&ie>0?fm(Y,ie):null,he=d??rs.boneClass,we=(()=>{const T=l??rs.stagger;return T===!0?80:T===!1||!T?0:T})(),O=(()=>{const T=c??rs.transition;return T===!0?300:T===!1||!T?0:T})(),[J,A]=u.useState(!1),Z=u.useRef(t),ne=u.useRef(null);u.useEffect(()=>(Z.current&&!t&&O>0&&ae&&(ne.current&&clearTimeout(ne.current),A(!0),ne.current=setTimeout(()=>{A(!1),ne.current=null},O)),Z.current=t,()=>{ne.current&&clearTimeout(ne.current)}),[t,O,ae]);const $e=(t||J)&&ae,Me=t&&!ae&&!J,We=w>0?w:ae?.height??0,P=ae?.height??0,re=We>0&&P>0?We/P:1;return e.jsxs("div",{ref:S,className:m,style:{position:"relative"},...F,children:[e.jsx("div",{"data-boneyard-content":"true",style:$e&&!J?{visibility:"hidden"}:void 0,children:Me?f:s}),$e&&e.jsx("div",{"data-boneyard-overlay":"true",style:{position:"absolute",inset:0,overflow:"hidden",opacity:J?0:1,transition:O>0?`opacity ${O}ms ease-out`:void 0},children:e.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[ae.bones.filter(T=>!ho(T).c).map((T,G)=>{const H=ho(T),ce=y;vo(y,M?xa.darkAdjust:xa.lightAdjust);const _=H.w/100*(ae.width??0),Q=H.r==="50%"&&Math.abs(_-H.h)<4,U={position:"absolute",left:`${H.x}%`,top:H.y*re,width:Q?H.h*re:`${H.w}%`,height:H.h*re,borderRadius:typeof H.r=="string"?H.r:`${H.r}px`,backgroundColor:ce},E=rs.speed;if(z==="pulse")U.animation=`bp-${N} ${E??xa.speed} ease-in-out infinite`;else if(z==="shimmer"){const te=M?rs.darkShimmerColor??Vs.darkHighlight:rs.shimmerColor??Vs.lightHighlight,de=rs.shimmerAngle??Vs.angle;delete U.backgroundColor,U.backgroundImage=`linear-gradient(${de}deg, ${ce} ${Vs.start}%, ${te} 50%, ${ce} ${Vs.end}%)`,U.backgroundSize="200% 100%",U.animation=`bs-${N} ${E??Vs.speed} linear infinite`}return we>0&&(U.opacity=0,U.animation=`${U.animation?U.animation+",":""} by-${N} 0.3s ease-out ${G*we}ms forwards`),e.jsx("div",{"data-boneyard-bone":"true",className:he,style:U},G)}),z==="pulse"&&e.jsx("style",{children:`@keyframes bp-${N}{0%,100%{background-color:${y}}50%{background-color:${vo(y,M?xa.darkAdjust:xa.lightAdjust)}}}`}),z==="shimmer"&&e.jsx("style",{children:`@keyframes bs-${N}{0%{background-position:200% 0}100%{background-position:-200% 0}}`}),we>0&&e.jsx("style",{children:`@keyframes by-${N}{from{opacity:0}to{opacity:1}}`})]})})]})}async function dn(t){const s=At(Ue,"managedStudents");try{const n=Ct(s,St("teacherId","==",t)),i=await zt(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 Wi(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 bm(t,s=[]){if(!t)return[];const a=At(Ue,"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=Ct(a,St("role","==","student"),St("adviserTeacherId","==",t));(await zt(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 f=o(m.id,m.data());f&&r.set(m.id,f)})}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 vm(t){const s=`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||"Student")}&background=random`,a=El.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:xs(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 No(t){return(t||"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9\s]+/g," ").trim().replace(/\s+/g," ")}async function wm(t){const s=(t.studentId||"").trim();if(!s)throw new Error("Cannot reassign section: studentId is required.");const a=(t.newClassSectionId||"").trim()||Ht(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=xt(Ue,"managedStudents",s),c=await bs(l);c.exists()&&await ls(l,{grade:t.newGrade,section:t.newSection,classSectionId:a,gradeLevel:xs(t.newGrade)||t.newGrade,teacherId:r||c.data()?.teacherId,updatedAt:lt()})}catch(l){console.warn("[studentService] reassignStudentSection: managedStudents update failed:",l)}if(t.isRegisteredAccount)try{await ts(xt(Ue,"users",s),{grade:t.newGrade,section:t.newSection,classSectionId:a,adviserTeacherId:r||void 0,adviserTeacherName:o||void 0,updatedAt:lt()},{merge:!0})}catch(l){console.warn("[studentService] reassignStudentSection: users profile update failed:",l)}try{await ur({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=xt(Ue,"classSectionOwnership",i),c=await bs(l);if(c.exists()){const m=(c.data().studentUids||[]).filter(f=>f!==s);await ls(l,{studentUids:m,updatedAt:lt()})}}catch(l){console.warn("[studentService] reassignStudentSection: previous-section cleanup failed:",l)}}async function Nm(t){const{apiService:s}=await Ar(async()=>{const{apiService:d}=await import("./index-CR5aYAL9.js").then(m=>m.b6);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?Ht(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 ts(xt(Ue,"managedStudents",c),rr({accountUid:c,name:(t.name||"").trim()||"Student",email:r,lrn:t.lrn?.trim()||null,teacherId:a,grade:o||null,gradeLevel:xs(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:lt(),updatedAt:lt()}))}catch(d){console.warn("[studentService] createStudentAccountFromRoster: managed-student merge failed:",d)}if(i&&o&&n)try{await ur({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 Vi(t,s,a){const r=Ht(s,a),o=xt(Ue,"managedStudents",t);await ls(o,{grade:s,section:a,classSectionId:r,updatedAt:lt()})}function Ht(t,s){return[t,s].filter(Boolean).join("_").replace(/\s+/g,"_").toLowerCase()}function rr(t){const s=Object.entries(t).filter(([,a])=>a!==void 0);return Object.fromEntries(s)}function xs(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 aa(t){const a=xs(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 ra(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 cs(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 bt(t){const s=t.metadata||{},a=t.className||s.className,r=cs(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?Ht(o,n):"")||null,l=(a||"").trim()||(o&&n?`${o} - ${n}`:"")||null,c=xs(t.gradeLevel||s.gradeLevel||o),d=(t.classification||s.classification||"").trim()||aa(c)||null,m=(t.strand||s.strand||"").trim()||ra(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 jm(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?Ht(o,n):"")||null,l=s||(o&&n?`${o} - ${n}`:null),c=xs(t.gradeLevel||o),d=(t.classification||"").trim()||aa(c),m=(t.strand||"").trim()||ra(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 Wi(t){const s=At(Ue,"classrooms"),a=new Map,r=Ct(s,St("teacherId","==",t));(await zt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=Ct(s,St("managerId","==",t));return(await zt(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 ur(t){const s=t.classSectionId||Ht(t.grade,t.section),a=xt(Ue,"classSectionOwnership",s),r=await bs(a),o=r.exists()?r.data().studentUids||[]:[],n=Array.from(new Set([...t.studentUids||[],...o])),i=rr(t);return r.exists()?await ls(a,{...i,classSectionId:s,studentUids:n,updatedAt:lt()}):await ts(a,{...i,classSectionId:s,studentUids:n,createdAt:lt(),updatedAt:lt()}),s}async function qi(t){const s=(t.classSectionId||"").trim()||Ht(t.grade,t.section),a=(t.className||"").trim()||`${t.grade} - ${t.section}`,r=jm({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 ur({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=At(Ue,"classrooms"),n=Ct(o,St("classSectionId","==",s)),i=await zt(n);if(i.empty){const l=rr({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:lt(),updatedAt:lt()});await ts(xt(Ue,"classrooms",s),l,{merge:!0})}else for(const l of i.docs){const c=rr({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:lt()});await ls(l.ref,c)}return s}async function xr(t,s,a,r,o,n){const i=Ht(s,a);await ur({classSectionId:i,grade:s,section:a,schoolYear:o,ownerTeacherId:r,ownerTeacherName:n,studentUids:[t]});const l=await bs(xt(Ue,"users",t)),c=l.exists()?l.data():{};await ts(xt(Ue,"users",t),{grade:s,section:a,classSectionId:i,adviserTeacherId:r,adviserTeacherName:n||"",updatedAt:lt()},{merge:!0}),await ts(xt(Ue,"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:lt()},{merge:!0})}async function ym(t){const s=At(Ue,"classSectionOwnership"),a=new Map,r=Ct(s,St("ownerTeacherId","==",t));(await zt(r)).docs.forEach(l=>{a.set(l.id,{id:l.id,...l.data()})});const n=Ct(s,St("managerId","==",t));return(await zt(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 Sm(t="",s=25){const a=At(Ue,"users"),r=Math.max(1,Math.min(100,s)),o=Ct(a,St("role","==","teacher"),Xa(r*4)),n=await zt(o),i=t.trim().toLowerCase();return n.docs.map(c=>{const d=c.data(),m=String(d.name||"").trim(),f=String(d.email||"").trim();return{uid:c.id,name:m||"Teacher",email:f,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 km(t,s,a=20){if(t.length===0)return s([]),()=>{};const r=At(Ue,"activities"),o=Ct(r,St("classroomId","in",t),Rl("timestamp","desc"));return ti(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 Cm=({open:t,onClose:s,onCreated:a,teacherName:r})=>{const{currentUser:o}=ms(),[n,i]=u.useState("details"),[l,c]=u.useState(""),d="Grade 11",[m,f]=u.useState(""),[p,g]=u.useState(!1),[S,N]=u.useState(""),[j,h]=u.useState([]),[w,C]=u.useState(new Set),[M,k]=u.useState(""),[q,b]=u.useState(!1);u.useEffect(()=>{t||(i("details"),c(""),f(""),N(""),C(new Set),k(""))},[t]),u.useEffect(()=>{t&&n==="students"&&y()},[t,n]);const y=async()=>{b(!0);try{const I=At(Ue,"users"),W=Ct(I,St("role","==","student")),Y=await zt(W),se=[];Y.docs.forEach(ie=>{const ae=ie.data();se.push({uid:ie.id,name:ae.name||ae.displayName||"Student",email:ae.email||"",grade:ae.grade,section:ae.section})}),h(se.sort((ie,ae)=>ie.name.localeCompare(ae.name)))}catch(I){console.error("[CreateClassModal] Failed to load students:",I)}finally{b(!1)}},v=async()=>{if(o){if(!m.trim()){N("Section name is required");return}N(""),g(!0);try{const I=String(new Date().getFullYear());if(await qi({classSectionId:"",grade:d,section:m.trim(),schoolYear:I,ownerTeacherId:o.uid,ownerTeacherName:r||o.displayName||"",managerId:o.uid,managerName:r||o.displayName||"",className:l.trim()||`${d} - ${m.trim()}`}),w.size>0){const W=Array.from(w).map(Y=>xr(Y,d,m.trim(),o.uid,I,r||o.displayName||""));await Promise.allSettled(W)}a(),s()}catch(I){N(I instanceof Error?I.message:"Failed to create class")}finally{g(!1)}}},z=I=>{C(W=>{const Y=new Set(W);return Y.has(I)?Y.delete(I):Y.add(I),Y})},F=j.filter(I=>I.name.toLowerCase().includes(M.toLowerCase())||I.email.toLowerCase().includes(M.toLowerCase()));return t?e.jsx(Mt,{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(ds,{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(js,{placeholder:"e.g. Grade 11 - Section A",value:l,onChange:I=>c(I.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(js,{placeholder:"e.g. Section A, STEM-1, Rizal",value:m,onChange:I=>f(I.target.value)})]}),S&&e.jsx("p",{className:"text-sm text-rose-500",children:S})]}),n==="students"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Bs,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(js,{placeholder:"Search students...",value:M,onChange:I=>k(I.target.value),className:"pl-9"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[w.size," student(s) selected"]}),q?e.jsx("p",{className:"text-sm text-[#64748b] text-center py-4",children:"Loading students..."}):F.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:F.map(I=>e.jsxs("button",{onClick:()=>z(I.uid),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${w.has(I.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 ${w.has(I.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:w.has(I.uid)&&e.jsx(Ot,{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:I.name}),e.jsx("p",{className:"text-xs text-[#64748b] truncate",children:I.email})]}),I.grade&&e.jsx("span",{className:"text-xs text-[#94a3b8]",children:I.grade})]},I.uid))}),S&&e.jsx("p",{className:"text-sm text-rose-500",children:S})]})]}),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(ht,{variant:"outline",onClick:s,children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{variant:"outline",onClick:()=>{if(!m.trim()){N("Section is required");return}N(""),i("students")},children:"Add Students"}),e.jsx(ht,{onClick:v,disabled:p||!m.trim(),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:p?"Creating...":"Create Class"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ht,{variant:"outline",onClick:()=>i("details"),children:"Back"}),e.jsxs(ht,{onClick:v,disabled:p,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(Zs,{size:16,className:"mr-1"}),p?"Creating...":`Create with ${w.size} Student${w.size!==1?"s":""}`]})]})})]})]})}):null},Im=({open:t,onClose:s,onAdded:a,grade:r,section:o,teacherName:n,existingStudentUids:i=[]})=>{const{currentUser:l}=ms(),[c,d]=u.useState([]),[m,f]=u.useState(new Set),[p,g]=u.useState(""),[S,N]=u.useState(!1),[j,h]=u.useState(!1);u.useEffect(()=>{t&&(f(new Set),g(""),w())},[t]);const w=async()=>{N(!0);try{const k=Ct(At(Ue,"users"),St("role","==","student")),b=(await zt(k)).docs.filter(y=>!i.includes(y.id)).map(y=>{const v=y.data();return{uid:y.id,name:v.name||v.displayName||"Student",email:v.email||""}}).sort((y,v)=>y.name.localeCompare(v.name));d(b)}catch{}N(!1)},C=async()=>{if(!(!l||m.size===0)){h(!0);try{const k=String(new Date().getFullYear()),q=Array.from(m).map(b=>xr(b,r,o,l.uid,k,n||l.displayName||""));await Promise.allSettled(q),me.success(`Added ${m.size} student(s) to class`),a(),s()}catch{me.error("Failed to add students")}h(!1)}},M=c.filter(k=>k.name.toLowerCase().includes(p.toLowerCase())||k.email.toLowerCase().includes(p.toLowerCase()));return t?e.jsx(Mt,{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(ds,{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(Bs,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]"}),e.jsx(js,{placeholder:"Search students...",value:p,onChange:k=>g(k.target.value),className:"pl-8 h-9 text-sm"})]}),e.jsx("button",{onClick:()=>{m.size===M.length?f(new Set):f(new Set(M.map(k=>k.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===M.length&&M.length>0?"Deselect All":"Select All"})]}),e.jsxs("p",{className:"text-xs text-[#64748b]",children:[m.size," of ",M.length," selected"]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-1 min-h-[300px]",children:S?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"Loading..."}):M.length===0?e.jsx("p",{className:"text-sm text-center text-[#64748b] py-6",children:"No students available"}):M.map(k=>e.jsxs("button",{onClick:()=>f(q=>{const b=new Set(q);return b.has(k.uid)?b.delete(k.uid):b.add(k.uid),b}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${m.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 shrink-0 ${m.has(k.uid)?"bg-[#9956DE] border-[#9956DE]":"border-[#cbd5e1]"}`,children:m.has(k.uid)&&e.jsx(Ot,{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:k.name}),e.jsx("p",{className:"text-[11px] text-[#64748b] truncate",children:k.email})]})]},k.uid))})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-[#f1f5f9]",children:[e.jsx(ht,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),e.jsxs(ht,{size:"sm",onClick:C,disabled:j||m.size===0,className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(Ko,{size:14,className:"mr-1.5"}),j?"Adding...":`Add ${m.size} Student${m.size!==1?"s":""}`]})]})]})]})}):null};async function Tm(t,s,a){const r=xt(At(Ue,"generatedLessonPlans"));return await ts(r,{...t,teacherId:s,teacherName:a?.teacherName||null,studentId:a?.studentId||null,studentName:a?.studentName||null,status:"draft",createdAt:lt(),updatedAt:lt()}),r.id}async function Em(t){const s=xt(Ue,"generatedLessonPlans",t),a=await bs(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 ls(s,{status:"published",publishedAt:lt(),updatedAt:lt()})}async function Rm(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 g=await bl(a,r,o,{lessonTitle:t.lessonTitle,learningCompetency:t.learningCompetency,moduleUnit:t.moduleUnit,learnerLevel:t.learnerLevel});i=g.sources||[],n=g.explanation||"",l=g.retrievalConfidence,c=g.retrievalBand,d=g.retrievalQuery,m=g.needsReview??!1}catch{n="",i=[]}const f={...t,subject:r,quarter:o,curriculumContext:n?`[CURRICULUM CONTEXT] +${n}`:void 0,curriculumRetrievalConfidence:l,curriculumRetrievalBand:c,curriculumRetrievalQuery:d,needsReview:m};return{...await it.generateLessonPlan(f),curriculumSources:i,curriculumContext:n}}const _m=Il("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 Mm({className:t,variant:s,asChild:a=!1,...r}){const o=a?Ql:"span";return e.jsx(o,{"data-slot":"badge",className:Xo(_m({variant:s}),t),...r})}function Am(t){return t.length<=42?t:`${t.slice(0,18)}...${t.slice(-20)}`}const jo=({sources:t=[],className:s})=>t.length?e.jsxs(Gl,{children:[e.jsx(Ul,{asChild:!0,children:e.jsxs(Mm,{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(Vl,{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:[Am(a.sourceFile)," | p.",a.page]}),e.jsxs("p",{className:"text-[#5a6578]",children:["Similarity: ",(a.score*100).toFixed(1),"%"]})]},`${a.sourceFile}-${a.page}-${r}`))})]})]}):null,zm=[{level:"Remember",icon:zr,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:vl,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:pc,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"}],Lm=({isOpen:t,onClose:s})=>t?e.jsx(Mt,{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(Jo,{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(ds,{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:zm.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(vc,{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,Dm={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"},Oa={identification:{label:"Identification",icon:e.jsx(vs,{size:16}),description:"Define or identify concepts"},enumeration:{label:"Enumeration",icon:e.jsx(Ja,{size:16}),description:"List steps or properties"},multiple_choice:{label:"Multiple Choice",icon:e.jsx(Ot,{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(wl,{size:16}),description:"Solve equations"}},yo={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"}},$m=["Grade 11","Grade 12"],Cr=t=>{const s=(t||"").trim().toLowerCase();return s==="grade 12"||s==="12"||s.includes("12")?"Grade 12":"Grade 11"},Fm={"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"]}},Om={"Grade 11":["General Mathematics - "],"Grade 12":["Pre-Calculus - ","Basic Calculus - "]},So=(t,s)=>{const a=Om[s];return Object.fromEntries(Object.entries(t).filter(([r])=>a.some(o=>r.startsWith(o))))},pa=30,ha=12,Ir="mathpulse:quiz-maker:active-task",Bm={easy:"text-green-600",medium:"text-rose-600",hard:"text-red-600"},Yi=({onBack:t,gradeLevel:s,selectedClassId:a,selectedClassName:r,onOpenNotifications:o,onOpenProfile:n,onOpenInsightModal:i,userPhoto:l,teacherName:c,drawerMode:d=!1,onQuizSaved:m,onQuizGenerating:f})=>{const{currentUser:p,loading:g}=ms(),S=u.useMemo(()=>it.getImportGroundedRolloutFlags(),[]),[N,j]=u.useState("create"),[h,w]=u.useState("setup"),[C,M]=u.useState(Cr(s)),[k,q]=u.useState(10),[b,y]=u.useState([]),[v,z]=u.useState([]),[F,I]=u.useState(["multiple_choice","word_problem","identification"]),[W,Y]=u.useState(["remember","understand","apply","analyze"]),[se,ie]=u.useState(!1),[ae,he]=u.useState({easy:30,medium:50,hard:20}),[we,O]=u.useState({}),[J,A]=u.useState(!1),[Z,ne]=u.useState([]),[$e,Me]=u.useState(!1),[We,P]=u.useState(""),[re,T]=u.useState(!1),[G,H]=u.useState(!1),[ce,_]=u.useState(null),[Q,U]=u.useState(0),[E,te]=u.useState("queued"),[de,xe]=u.useState("Waiting to start generation..."),[oe,fe]=u.useState(null),[qe,Fe]=u.useState(null),[Pe,tt]=u.useState(""),[Tt,dt]=u.useState(!1),wt=u.useRef(!1),[Lt,B]=u.useState("topics"),[Ae,Xe]=u.useState(null),[Nt,Kt]=u.useState(!1),[Et,Dt]=u.useState("all"),[$t,_s]=u.useState("all"),[at,za]=u.useState(!1),[Ft,R]=u.useState(null),[ee,ze]=u.useState(!1),[Ne,Ge]=u.useState(!1),[je,gt]=u.useState(!1),[nt,Ce]=u.useState([]),[ps,Xt]=u.useState(!1),[Ms,La]=u.useState(""),[Jt,na]=u.useState(null),[oa,hs]=u.useState([]),[ia,la]=u.useState(!1),[Qs,pr]=u.useState("all"),[hr,ca]=u.useState(null),[da,L]=u.useState(null),K=u.useCallback(async()=>{A(!0);const x=Cr(C);try{const D=await it.getQuizTopics(x);D.topics&&O(So(D.topics,x))}catch{O(So(Fm[x],x))}finally{A(!1)}},[C]),ke=u.useCallback(async()=>{if(!S.quizEnabled){ne([]),P("Import-grounded quiz generation is disabled by rollout flag; using curriculum defaults."),Me(!1);return}Me(!0),P("");try{const x=await it.getCourseMaterialTopics({classSectionId:a,limit:20}),D=(x.topics||[]).filter($=>$.title?.trim());ne(D),x.warnings&&x.warnings.length>0&&P(x.warnings.join(" "))}catch{ne([]),P("Imported topics are currently unavailable; quiz generation will use curriculum defaults.")}finally{Me(!1)}},[a,S.quizEnabled]);u.useEffect(()=>{K(),y([]),z([])},[K]),u.useEffect(()=>{ke()},[ke]);const _e=u.useMemo(()=>{const x=Array.from(new Set(Z.map(D=>D.title.trim()).filter(Boolean)));return x.length===0?we:{"Imported Course Materials":x,...we}},[we,Z]);u.useEffect(()=>{Dt("all"),_s("all")},[oe]);const Qt=u.useMemo(()=>{if(!oe)return[];const x=oe.questions.map($=>$.provenance?.sourceFile?.trim()).filter($=>!!$),D=(oe.metadata.topicProvenance||[]).map($=>$.sourceFile?.trim()).filter($=>!!$);return Array.from(new Set([...x,...D])).sort(($,ge)=>$.localeCompare(ge))},[oe]),Ee=u.useMemo(()=>{if(!oe)return[];const x=oe.questions.map($=>$.provenance?.materialId?.trim()).filter($=>!!$),D=(oe.metadata.topicProvenance||[]).map($=>$.materialId?.trim()).filter($=>!!$);return Array.from(new Set([...x,...D])).sort(($,ge)=>$.localeCompare(ge))},[oe]),Gs=u.useMemo(()=>oe?oe.questions.filter(x=>{const D=Et==="all"||(x.provenance?.sourceFile||"").trim()===Et,$=$t==="all"||(x.provenance?.materialId||"").trim()===$t;return D&&$}):[],[oe,Et,$t]),Rt=(x,D)=>{const $={...ae},ge=Math.max(0,Math.min(100,$[x]+D)),Oe=ge-$[x];$[x]=ge;const Ye=Object.keys($).filter(ot=>ot!==x),Gt=Ye.reduce((ot,Zt)=>ot+$[Zt],0);if(Gt>0)for(const ot of Ye)$[ot]=Math.max(0,Math.round($[ot]-Oe*$[ot]/Gt));const Us=Object.values($).reduce((ot,Zt)=>ot+Zt,0);if(Us!==100){const ot=Ye.reduce((Zt,jn)=>$[Zt]>=$[jn]?Zt:jn);$[ot]+=100-Us}he($)},He=x=>{y(D=>D.includes(x)?D.filter($=>$!==x):[...D,x]),z(D=>D.filter($=>$!==x))},ma=x=>{I(D=>D.includes(x)?D.length>1?D.filter($=>$!==x):D:[...D,x])},ua=x=>{Y(D=>D.includes(x)?D.length>1?D.filter($=>$!==x):D:[...D,x])},ol=()=>{let x=b.length>0?b.filter($=>!v.includes($)):Object.values(_e).flat().filter($=>!v.includes($)).slice(0,3);x.length>ha&&(x=x.slice(0,ha));const D=Math.min(k,pa);return{topics:x,gradeLevel:C,numQuestions:D,questionTypes:F,includeGraphs:se,difficultyDistribution:ae,bloomLevels:W,excludeTopics:v,classSectionId:a,className:r,preferImportedTopics:S.quizEnabled}},il=u.useCallback((x,D)=>{const $={taskId:x,request:D,createdAt:new Date().toISOString(),ownerUid:p?.uid};try{sessionStorage.setItem(Ir,JSON.stringify($))}catch{}},[p]),fs=u.useCallback(()=>{try{sessionStorage.removeItem(Ir)}catch{}},[]),fr=u.useCallback(x=>{const D=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)));U($=>{let ge=Math.max($,D);if(x.status==="running"&&D<=$){const Oe=String(x.progressStage||"").toLowerCase(),Ye=Oe.includes("assembling")||Oe.includes("final")?97:Oe.includes("generating")?89:95;ge=Math.min(Ye,$+1)}return ge}),te(x.progressStage||x.status),xe(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(g||wt.current)return;if(wt.current=!0,!p){fs();return}let x=!1;const D=sessionStorage.getItem(Ir);if(!D)return;let $=null;try{$=JSON.parse(D)}catch{fs();return}if(!$?.taskId){fs();return}if($.ownerUid&&$.ownerUid!==p.uid){fs();return}return T(!0),_($.taskId),tt(""),it.waitForTaskResult($.taskId,{timeoutMs:24e4,pollIntervalMs:1500,onProgress:fr}).then(async ge=>{if(x)return;const Oe=ge.result;if(!Oe||typeof Oe!="object")throw new Error("Quiz generation completed without a valid result payload.");const Ye=Oe;fe(Ye),w("results"),U(100),te("completed"),xe("Generation complete."),_(null),fs();try{await gn(Ye,$.request),me.success("Quiz auto-saved to your library as draft.")}catch(Gt){me.error(Gt instanceof Error?Gt.message:"Quiz generated but failed to save to library")}}).catch(ge=>{if(!x){if(ge instanceof Ya&&(ge.status===401||ge.status===403)){wt.current=!1,T(!1);return}tt(ge instanceof Error?ge.message:"Failed to resume quiz generation"),_(null),fs()}}).finally(()=>{x||T(!1)}),()=>{x=!0}},[fr,g,fs,p]);const pn=()=>{if(re){window.confirm("Quiz generation is in progress. Are you sure you want to leave?")&&(w("setup"),fe(null),tt(""),t());return}w("setup"),fe(null),tt(""),t()},ll=async()=>{f?.(),tt(""),T(!0),L(null),U(8),te("queued"),xe("Submitting quiz generation task..."),fe(null);const x=ol();try{const D=await it.generateQuiz(x,{onTaskCreated:$=>{_($),il($,x),U(ge=>Math.max(ge,12)),te("queued"),xe("Task queued. Generation is running in the background.")},onProgress:$=>{fr($),$.taskId&&$.taskId!==ce&&_($.taskId)}});fe(D),w("results"),U(100),te("completed"),xe("Generation complete."),_(null),fs();try{await gn(D,x),me.success("Quiz auto-saved to your library as draft.")}catch($){me.error($ instanceof Error?$.message:"Quiz generated but failed to save to library")}it.reportImportGroundedFeedback({flow:"quiz",status:"success",classSectionId:x.classSectionId,className:x.className,metadata:{totalQuestions:D.metadata.totalQuestions,usedImportedTopics:!!D.metadata.usedImportedTopics,importedTopicCount:D.metadata.importedTopicCount??0,importGroundingEnabled:S.quizEnabled}})}catch(D){tt(D instanceof Error?D.message:"Quiz generation failed"),U(100),te("failed"),xe("Generation failed."),_(null),fs(),it.reportImportGroundedFeedback({flow:"quiz",status:"failed",classSectionId:x.classSectionId,className:x.className,metadata:{error:D instanceof Error?D.message:"Quiz generation failed",importGroundingEnabled:S.quizEnabled}})}finally{T(!1)}},cl=()=>{if(!oe)return;const x=oe.questions.map((D,$)=>{let ge=`${$+1}. [${D.difficulty.toUpperCase()}] [${D.bloomLevel}] (${D.points} pts) `;return ge+=` ${D.question} `,D.options&&(ge+=D.options.map(Oe=>` ${Oe}`).join(` `)+` `),ge+=` Answer: ${D.correctAnswer} `,ge+=` Explanation: ${D.explanation} `,ge}).join(` -`);navigator.clipboard.writeText(x),dt(!0),setTimeout(()=>dt(!1),2e3)},dl=()=>{if(!oe)return;const x=new Blob([JSON.stringify(oe,null,2)],{type:"application/json"}),D=URL.createObjectURL(x),$=document.createElement("a");$.href=D,$.download=`quiz_${C.replace(/\s/g,"_")}_${Date.now()}.json`,$.click(),URL.revokeObjectURL(D)};b.length>0||Object.values(_e).flat().length>0;const hn=(x,D)=>{const $=D?.gradeLevel||C,ge=D?.topics||b,Oe=x.questions.map((Ye,Gt)=>({id:`q_${Date.now()}_${Gt}`,questionType:Ye.questionType||"identification",question:Ye.question,...Ye.options?{options:Ye.options}:{},correctAnswer:Ye.correctAnswer,bloomLevel:Ye.bloomLevel||"understand",difficulty:Ye.difficulty||"medium",topic:Ye.topic,subject:$,points:Ye.points,explanation:Ye.explanation}));return{title:`${$} Quiz – ${ge.length>0?ge.slice(0,2).join(", "):"Mixed Topics"}`,gradeLevel:$,questions:Oe,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"}},fn=u.useCallback(x=>{hs(D=>[x,...D.filter($=>$.id!==x.id)])},[]);async function gn(x,D){if(!p)return null;const $=hn(x,D),ge=await Tn($,p.uid,Ft?{documentId:Ft}:void 0);return R(ge),fn({id:ge,...$,teacherId:p.uid}),ge}const ml=async()=>{if(!oe){me.error("No quiz to save. Generate a quiz first.");return}if(!p){me.error("You must be signed in to save quizzes.");return}za(!0);try{const x=hn(oe),D=await Tn(x,p.uid,Ft?{documentId:Ft}:void 0);R(D),fn({id:D,...x,teacherId:p.uid}),me.success("Quiz saved to your library!"),m?.(D)}catch(x){me.error(x instanceof Error?x.message:"Failed to save quiz")}finally{za(!1)}},ul=async()=>{if(Ft){ze(!0);try{await Ol(Ft),hs(x=>x.map(D=>D.id===Ft?{...D,status:"published"}:D)),me.success("Quiz published to Quiz Bank!")}catch(x){me.error(x instanceof Error?x.message:"Failed to publish quiz")}finally{ze(!1)}}},gr=async x=>{const D=x??Ft;if(!D){me.error("Save the quiz first before assigning.");return}if(ca(D),Ge(!0),na(null),La(""),nt.length===0&&p){Xt(!0);try{const $=await dn(p.uid);Ce($)}catch{me.error("Failed to load students")}finally{Xt(!1)}}},xl=async()=>{const x=hr??Ft;if(!(!Jt||!x||!p)){gt(!0);try{await Bl(x,Jt,p.uid),hs(D=>D.map($=>$.id===x?{...$,status:"assigned",metadata:{...$.metadata,assignedTo:Jt}}:$)),me.success("Quiz assigned to student!"),Ge(!1),ca(null),N==="bank"&&br()}catch(D){me.error(D instanceof Error?D.message:"Failed to assign quiz")}finally{gt(!1)}}},br=u.useCallback(async()=>{if(p){la(!0);try{const x=await ai(p.uid);hs(x)}catch{me.error("Failed to load quiz bank")}finally{la(!1)}}},[p]);u.useEffect(()=>{N==="bank"&&br()},[N,br]);const pl=async x=>{try{await Fl(x),hs(D=>D.filter($=>$.id!==x)),me.success("Quiz deleted")}catch{me.error("Failed to delete quiz")}},bn=nt.filter(x=>x.name.toLowerCase().includes(Ms.toLowerCase())||x.email.toLowerCase().includes(Ms.toLowerCase())),vn=Qs==="all"?oa:oa.filter(x=>x.status===Qs),hl=x=>{const D=(x.metadata.topicsCovered||[]).reduce(($,ge)=>($[ge]=($[ge]||0)+1,$),{});return{questions:x.questions.map($=>({questionType:$.questionType,question:$.question,correctAnswer:$.correctAnswer,options:$.options??null,bloomLevel:$.bloomLevel,difficulty:$.difficulty,topic:$.topic,points:$.points,explanation:$.explanation})),totalPoints:x.totalPoints,metadata:{topicsCovered:D,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||[]}}},vr=x=>{R(x.id),fe(hl(x)),Fe(null),L(x.id),Dt("all"),_s("all"),Xe(null),w("results"),j("create")},wn={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"}},fl=(x,D,$)=>{const ge=Ae===D,Oe=wn[x.bloomLevel?.toLowerCase()]||wn.remember,Ye=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:D*.05},className:`border border-[#e2e8f0] rounded-[20px] overflow-hidden bg-white shadow-sm hover:shadow-md ${Ye} 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:()=>Xe(ge?null:D),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 ${Oe.card} text-white flex items-center justify-center font-bold text-[13px] shadow-sm`,children:["Q",D+1]}),e.jsx("span",{className:`px-2.5 py-1 rounded-md border text-[10px] font-bold uppercase tracking-wider shadow-sm ${Oe.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 ${Oe.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:ge?e.jsx(Na,{size:16,className:"text-[#64748b] transition-transform duration-300"}):e.jsx(_t,{size:16,className:"text-[#64748b]"})})]})]}),e.jsx(Mt,{children:ge&&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((Gt,Us)=>{const ot=Gt.includes(x.correctAnswer);return e.jsxs("div",{className:`rounded-[12px] p-4 text-[14px] font-medium transition-all cursor-pointer relative overflow-hidden ${ot?"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:[ot&&e.jsx("div",{className:"absolute left-0 top-0 w-1 h-full bg-emerald-500"}),e.jsx("span",{className:ot?"pl-2":"",children:Gt}),ot&&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(Ot,{size:13})})]},Us)})})]}),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(qr,{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(Fs,{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(vs,{size:14})," ",e.jsx("strong",{className:"text-[#1e293b]",children:"Type:"})," ",Oa[x.questionType]?.label||x.questionType]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(zr,{size:14})," ",e.jsx("strong",{className:"text-[#1e293b]",children:"Bloom:"})," ",x.bloomLevel]})]})]})})})]},D)},Nn=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:()=>j("create"),className:`px-6 py-2 rounded-full text-[13px] font-bold flex items-center gap-2 transition-all duration-300 ease-out ${N==="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(Fr,{size:16})," Create Quiz"]}),e.jsxs("button",{onClick:()=>j("bank"),className:`px-6 py-2 rounded-full text-[13px] font-bold flex items-center gap-2 transition-all duration-300 ease-out ${N==="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(tr,{size:16})," Quiz Bank"]})]})}),e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] pb-[32px] flex-1",children:[N==="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:()=>pr(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))}),ia?e.jsxs("div",{className:"flex items-center justify-center py-16",children:[e.jsx(mt,{size:24,className:"animate-spin text-sky-500"}),e.jsx("span",{className:"ml-2 text-sm text-[#5a6578]",children:"Loading quiz bank…"})]}):vn.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(tr,{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:vn.map(x=>e.jsxs(Re.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},onClick:()=>vr(x),role:"button",tabIndex:0,onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),vr(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 ${Dm[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(D=>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:D},D))}),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(Wl,{size:14})," ",x.questions.length," questions"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Zo,{size:14})," ",x.totalPoints," pts"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(is,{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:D=>{D.stopPropagation(),vr(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(ql,{size:14})," View"]}),e.jsxs("button",{onClick:D=>{D.stopPropagation(),gr(x.id)},className:"flex items-center gap-1.5 text-[13px] font-bold text-[#a855f7] hover:text-[#9333ea] transition-colors",children:[e.jsx(Da,{size:14})," Assign"]}),e.jsxs("button",{onClick:D=>{D.stopPropagation(),pl(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(ri,{size:14})," Delete"]})]})]},x.id))})]}),N==="create"&&e.jsxs(e.Fragment,{children:[Pe&&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(lr,{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:Pe})]}),e.jsx("button",{onClick:()=>tt(""),className:"ml-auto",children:e.jsx(ds,{size:14,className:"text-red-400"})})]})}),re&&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(mt,{size:20,className:"animate-spin text-[#a855f7]"}),"Generating Quiz in Background"]}),e.jsxs("span",{className:"text-[14px] font-extrabold text-[#9333ea]",children:[Q,"%"]})]}),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:`${Q}%`},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:E.replace(/_/g," ")})]}),e.jsx("p",{children:de}),ce&&e.jsxs("p",{className:"text-[11px] mt-3 opacity-60 font-mono",children:["Task ID: ",ce]})]})]}),e.jsxs("p",{className:"mt-8 text-[14px] font-medium text-[#64748b] flex items-center gap-2 animate-pulse",children:[e.jsx(mt,{size:16,className:"animate-spin"})," Generating quiz... Please wait."]})]}),!re&&h!=="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,D)=>{const ge=["setup","topics","style","preview"].indexOf(h),Oe=ge>D,Ye=ge===D;return e.jsxs("div",{className:`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl transition-all duration-500 ${Ye?"bg-purple-50/80 shadow-[0_1px_3px_rgba(168,85,247,0.1)]":Oe?"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 ${Ye?"bg-gradient-to-br from-[#a855f7] to-[#9333ea] text-white shadow-md":Oe?"bg-emerald-500 text-white shadow-sm":"bg-slate-100 text-[#64748b]"}`,children:Oe?e.jsx(Ot,{size:13,strokeWidth:3}):D+1}),e.jsx("span",{className:`text-[13px] font-bold whitespace-nowrap ${Ye?"text-[#9333ea]":Oe?"text-[#1e293b]":"text-[#64748b]"}`,children:x.label})]},x.id)})})}),h==="setup"&&!re&&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(ba,{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 ",pa," questions and ",ha," 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:C,onChange:x=>M(Cr(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:$m.map(x=>e.jsx("option",{value:x,children:x},x))}),e.jsx(_t,{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,k-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(En,{size:16})}),e.jsx("input",{id:"quiz-num-questions",type:"number",min:1,max:pa,value:k,onChange:x=>W(Math.min(pa,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(pa,k+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(Zs,{size:16})})]})]})]})]})]}),h==="topics"&&!re&&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 ",ha," 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:[b.filter(x=>!v.includes(x)).length," of ",ha," selected"]})]})]}),J?e.jsxs("div",{className:"flex items-center justify-center py-10 text-sm text-[#5a6578]",children:[e.jsx(mt,{size:24,className:"animate-spin text-[#9b51e0] mr-2"})," Loading topics..."]}):e.jsx("div",{className:"space-y-3",children:Object.entries(_e).map(([x,D])=>{const $=D.filter(Oe=>b.includes(Oe)&&!v.includes(Oe)).length,ge=Lt===x;return e.jsxs("div",{className:"border border-[#dde3eb] rounded-xl bg-white overflow-hidden shadow-sm",children:[e.jsxs("button",{onClick:()=>B(ge?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:[D.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:[$," selected"]}),ge?e.jsx(Na,{size:18,className:"text-slate-400"}):e.jsx(_t,{size:18,className:"text-slate-400"})]})]}),e.jsx(Mt,{children:ge&&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:D.map((Oe,Ye)=>{const Gt=b.includes(Oe),Us=v.includes(Oe),ot=Gt&&!Us;let Zt="Core";return Ye%3===0&&(Zt="Foundation"),Ye%3===2&&(Zt="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 ${ot?"bg-[#9b51e0] border-[#9b51e0]":"border-2 border-[#dde3eb] bg-white"}`,children:ot&&e.jsx(Ot,{size:14,className:"text-white"})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:ot,onChange:()=>He(Oe)}),e.jsx("span",{className:`text-sm font-semibold ${ot?"text-[#0a1628]":"text-[#5a6578]"}`,children:Oe})]}),e.jsx("span",{className:`border px-3 py-1 rounded-full text-[10px] uppercase font-bold tracking-wider ${Zt==="Advanced"?"bg-white text-slate-400 border-[#dde3eb]":"bg-purple-50 text-[#9b51e0] border-purple-100"}`,children:Zt})]},Oe)})})})})]},x)})})]}),h==="style"&&!re&&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(Oa).map(([x,D])=>{const $=F.includes(x);return e.jsxs("button",{onClick:()=>ma(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 ${$?"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:[$&&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(Ot,{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 ${$?"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:$?"text-[#a855f7]":"text-slate-500",children:D.icon})}),e.jsx("span",{className:`font-bold text-[12px] leading-tight ${$?"text-[#9333ea]":"text-slate-700"}`,children:D.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(yo).map(([x,D])=>{const $=V.includes(x);return e.jsx("button",{onClick:()=>ua(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 ${$?"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(ae).map(([x,D])=>{const $={easy:"bg-emerald-400",medium:"bg-amber-400",hard:"bg-rose-400"},ge={easy:"text-emerald-600",medium:"text-amber-500",hard:"text-rose-500"},Oe={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:${ge[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:`${D}%`},className:`h-full rounded-full transition-all duration-500 ease-out ${$[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 ${Oe[x]}`,children:[e.jsx("button",{onClick:()=>Rt(x,-5),className:`w-8 h-full flex items-center justify-center text-[#64748b] hover:bg-slate-50 hover:${ge[x]} rounded-lg transition-colors`,children:e.jsx(En,{className:"w-3.5 h-3.5"})}),e.jsx("input",{type:"text",value:`${D}%`,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:()=>Rt(x,5),className:`w-8 h-full flex items-center justify-center text-[#64748b] hover:bg-slate-50 hover:${ge[x]} rounded-lg transition-colors`,children:e.jsx(Zs,{className:"w-3.5 h-3.5"})})]})]},x)})})]})]}),h==="preview"&&!re&&!oe&&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($s,{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:k},{label:"Topics",value:b.filter(x=>!v.includes(x)).length},{label:"Level",value:C.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(ba,{size:18,className:"text-[#94a3b8] shrink-0 mt-0.5"}),e.jsxs("p",{children:[F.map(x=>Oa[x]?.label).join(" and ")," questions across"," ",e.jsxs("span",{className:"font-bold text-[#1e293b]",children:[b.filter(x=>!v.includes(x)).length," topics"]})," ","— aligned to ",e.jsx("span",{className:"font-semibold",children:V.map(x=>yo[x]?.label).join(", ")})," levels of Bloom's Taxonomy."," ",e.jsxs("span",{className:"font-semibold text-emerald-600",children:["Easy ",ae.easy,"%"]})," • ",e.jsxs("span",{className:"font-semibold text-amber-500",children:["Medium ",ae.medium,"%"]})," • ",e.jsxs("span",{className:"font-semibold text-rose-500",children:["Hard ",ae.hard,"%"]}),"."]})]})]})}),h==="results"&&oe&&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:cl,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:[Tt?e.jsx(Ot,{size:14,className:"text-green-500"}):e.jsx(Dr,{size:14}),Tt?"Copied!":"Copy All"]}),e.jsxs("button",{onClick:dl,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(Kl,{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(vs,{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:oe.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(Ns,{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:oe.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(oe.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(Ja,{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(oe.metadata.bloomTaxonomyDistribution).length}),e.jsx("span",{className:"text-[12px] font-bold text-white/90 uppercase tracking-widest relative z-10",children:"Bloom Levels"})]})]}),(oe.metadata.usedImportedTopics||(oe.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: ",oe.metadata.usedImportedTopics?"Yes":"No"," • ","Materials: ",oe.metadata.importedMaterialsCount??0," • ","Topics: ",oe.metadata.importedTopicCount??0]}),(oe.metadata.topicProvenance||[]).slice(0,5).map((x,D)=>e.jsxs("div",{className:"text-xs text-[#5a6578]",children:[x.title||"Untitled topic",x.sourceFile?` • ${x.sourceFile}`:""]},`${x.topicId||x.title||"topic"}_${D}`)),(Qt.length>0||Ee.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:Et,onChange:x=>Dt(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"}),Qt.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:$t,onChange:x=>_s(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"}),Ee.map(x=>e.jsx("option",{value:x,children:x},x))]})]})]}),e.jsxs("p",{className:"text-[11px] text-[#5a6578] mt-2",children:["Showing ",Gs.length," of ",oe.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($s,{size:14})," Difficulty"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(oe.metadata.difficultyBreakdown).map(([x,D])=>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 ${Bm[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:D})]},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(zr,{size:14})," Bloom's Taxonomy"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(oe.metadata.bloomTaxonomyDistribution).map(([x,D])=>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:D})]},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(Ja,{size:14})," Question Types"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(oe.metadata.questionTypeBreakdown).map(([x,D])=>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:Oa[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:D})]},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(ba,{size:18,className:"text-[#9333ea]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-bold text-[#9333ea] mb-3",children:oe.metadata.supplementalPurpose||"This quiz is designed to supplement classroom instruction, not replace teacher-led learning."}),oe.metadata.recommendedTeacherActions&&oe.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:oe.metadata.recommendedTeacherActions.map((x,D)=>e.jsx("li",{children:x},D))})]})]})]})]}),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(li,{size:20,className:"text-[#a855f7]"})," Review Questions"]}),e.jsx("div",{className:"space-y-4",children:Gs.length>0?Gs.map((x,D)=>fl(x,D)):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."})})]})]})]})]}),N==="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:[h==="topics"&&!re&&e.jsx("button",{onClick:()=>{y([]),z([])},className:"text-[13px] font-semibold text-[#a855f7] hover:underline",children:"Clear all"}),(h==="style"||h==="preview")&&!re&&e.jsxs("button",{onClick:()=>w(h==="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(ks,{size:16})," Back"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[h==="setup"&&!re&&e.jsxs("button",{onClick:()=>w("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(Ss,{size:16})]}),h==="topics"&&!re&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>w("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(ks,{size:16})," Back"]}),e.jsxs("button",{onClick:()=>w("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(Ss,{size:16})]})]}),h==="style"&&!re&&e.jsxs("button",{onClick:()=>w("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(Ss,{size:16})]}),h==="preview"&&!re&&!oe&&e.jsxs("button",{onClick:ll,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(Ot,{size:16})," Generate Quiz"]}),re&&e.jsxs("div",{className:"flex items-center gap-3 text-slate-500 font-medium text-sm",children:[e.jsx(mt,{size:16,className:"animate-spin"})," Generating quiz... Please wait."]}),h==="results"&&(da?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{j("bank"),L(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:()=>gr(da),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(Da,{size:16})," Assign"]}),e.jsx("button",{onClick:pn,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:()=>{w("setup"),fe(null),Fe(null),R(null),L(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"}),Ft?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:ul,disabled:ee,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:[ee?e.jsx(mt,{size:16,className:"animate-spin"}):e.jsx(Ea,{size:16})," Publish"]}),e.jsxs("button",{onClick:()=>gr(),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(Da,{size:16})," Assign to Class"]})]}):e.jsxs("button",{onClick:ml,disabled:at,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:[at?e.jsx(mt,{size:16,className:"animate-spin"}):e.jsx(ni,{size:16})," Save to Library"]}),e.jsx("button",{onClick:pn,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(Lm,{isOpen:Nt,onClose:()=>Kt(!1)}),e.jsx(Mt,{children:Ne&&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:()=>Ge(!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(is,{size:18,className:"text-sky-600"}),"Assign to Student"]}),e.jsx("button",{onClick:()=>Ge(!1),className:"p-1 hover:bg-[#edf1f7] rounded-lg transition-colors",children:e.jsx(ds,{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(Bs,{size:14,className:"text-slate-500"}),e.jsx("input",{type:"text",placeholder:"Search students…",value:Ms,onChange:x=>La(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:ps?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(mt,{size:20,className:"animate-spin text-sky-500"})}):bn.length===0?e.jsx("p",{className:"text-center text-sm text-slate-500 py-10",children:"No students found"}):bn.map(x=>e.jsxs("button",{onClick:()=>na(x.id),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-left transition-colors ${Jt===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:Ga(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})]}),Jt===x.id&&e.jsx(Ot,{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:()=>Ge(!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:xl,disabled:!Jt||je,className:`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold transition-all ${Jt&&!je?"bg-gradient-to-r from-sky-600 to-sky-500 text-white shadow-sm":"bg-[#dde3eb] text-slate-500 cursor-not-allowed"}`,children:[je?e.jsx(mt,{size:14,className:"animate-spin"}):e.jsx(Da,{size:14}),"Assign"]})]})]})})})]});return d?e.jsx("div",{className:"w-full h-full flex flex-col overflow-hidden bg-white",children:Nn}):Nn},Pm=({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),[f,p]=u.useState(""),[g,S]=u.useState(11),[N,j]=u.useState("general_mathematics"),[h,w]=u.useState([]),[C,M]=u.useState(!1),[k,W]=u.useState(null),b=u.useCallback(async()=>{M(!0);try{const I=Ct(At(Ue,"question_bank",String(g),N,"questions","questions"),Xa(50));let Y=(await zt(I)).docs.map(se=>{const ie=se.data();return{id:se.id,question:ie.question||"",choices:ie.choices||[],correct_answer:ie.correct_answer||"",explanation:ie.explanation||"",topic:ie.topic||"",difficulty:ie.difficulty||"medium",grade_level:ie.grade_level||11}});if(Y.length===0){const se=Ct(At(Ue,"quizBattleQuestionBank"),Xa(50));Y=(await zt(se)).docs.map(ae=>{const he=ae.data();return{id:ae.id,question:he.question||"",choices:he.choices||[],correct_answer:he.correct_answer||"",explanation:he.explanation||"",topic:he.topic||"",difficulty:he.difficulty||"medium",grade_level:he.grade_level||11}})}w(Y)}catch(I){console.warn("[QuestionBankPanel] Failed to load questions:",I)}finally{M(!1)}},[g,N]);u.useEffect(()=>{b()},[b]);const y=u.useCallback(async()=>{c(!0);try{const I=await Sn("/api/quiz-battle/bank-status");i(I.pdfs)}catch(I){const V=I instanceof Ya?I.message:"Failed to load bank status";me.error(V)}finally{c(!1)}},[]);u.useEffect(()=>{y()},[y]);const v=async()=>{if(!f.trim()){me.error("Please enter a storage path");return}m(!0);try{await Sn("/api/quiz-battle/ingest-pdf",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storage_path:f.trim(),grade_level:g,topic:N.trim(),force_reingest:!1})}),me.success("PDF ingestion completed"),await y(),p("")}catch(I){const V=I instanceof Ya?I.message:"Ingestion failed";me.error(V)}finally{m(!1)}},z=n.reduce((I,V)=>I+V.question_count,0),F=n.filter(I=>I.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(vs,{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:z})]}),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(Ls,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:F})]})]}),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(Mn,{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(vs,{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:f,onChange:I=>p(I.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:g,onChange:I=>S(Number(I.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:N,onChange:I=>j(I.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:v,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(mt,{className:"w-4 h-4 animate-spin"}):e.jsx(Mn,{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:y,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(Ls,{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(I=>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 ${I.processed?"bg-indigo-50 text-indigo-500":"bg-amber-50 text-amber-500"}`,children:e.jsx(vs,{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:I.filename})]})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-semibold text-[#475569]",children:I.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:I.topic})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-bold text-[#1e293b] text-center",children:I.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 ${I.processed?"bg-emerald-50 text-emerald-600 border-emerald-200/50":"bg-amber-50 text-amber-600 border-amber-200/50"}`,children:[I.processed?e.jsx(Ls,{className:"w-3 h-3"}):e.jsx(mt,{className:"w-3 h-3 animate-spin"}),I.processed?"Completed":"Processing..."]})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-medium text-[#64748b]",children:I.timestamp?new Date(I.timestamp).toLocaleDateString():"-"})]},I.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(vs,{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 (",h.length,")"]}),e.jsx("button",{onClick:b,disabled:C,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(Ls,{className:`w-4 h-4 ${C?"animate-spin":""}`})})]}),C?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(mt,{className:"w-6 h-6 animate-spin text-[#9956DE]"})}):h.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:h.map(I=>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(k===I.id?null:I.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:I.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 ",I.grade_level]}),e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-md bg-slate-100 text-slate-600 font-medium",children:I.topic}),e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-md font-semibold ${I.difficulty==="easy"?"bg-green-50 text-green-600":I.difficulty==="hard"?"bg-rose-50 text-rose-600":"bg-amber-50 text-amber-600"}`,children:I.difficulty})]})]}),k===I.id?e.jsx(Na,{size:16,className:"text-[#94a3b8] shrink-0"}):e.jsx(_t,{size:16,className:"text-[#94a3b8] shrink-0"})]}),k===I.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:I.choices.map((V,Y)=>e.jsxs("p",{className:`text-[12px] px-3 py-1.5 rounded-lg ${V===I.correct_answer?"bg-green-50 text-green-700 font-semibold border border-green-200":"bg-slate-50 text-[#475569]"}`,children:[String.fromCharCode(65+Y),". ",V]},Y))}),I.explanation&&e.jsxs("p",{className:"text-[12px] text-[#64748b] italic mt-2",children:["💡 ",I.explanation]})]})]},I.id))})]})]})]})},ko={totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:0},Hm={"gen-math":{label:"GEN MATH",color:"bg-sky-100 text-sky-700"},"stats-prob":{label:"STAT&PROB",color:"bg-sky-100 text-sky-700"},"pre-calc":{label:"PRE-CALC",color:"bg-orange-100 text-orange-700"},"basic-calc":{label:"BASIC CALC",color:"bg-red-100 text-red-700"}},Co={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"}},Io={needs_attention:0,on_track:1,no_data:2,mastered:3},Qm=({classSectionId:t,onOpenNotifications:s,onOpenProfile:a})=>{const{currentUser:r,userProfile:o}=ms(),[n,i]=u.useState([]),[l,c]=u.useState(ko),[d,m]=u.useState(!0),[f,p]=u.useState("all"),[g,S]=u.useState("all"),[N,j]=u.useState(""),[h,w]=u.useState("classAverage"),[C,M]=u.useState("asc"),k=An.map(A=>A.id),W=An.reduce((A,Z)=>(A[Z.id]=Z.name,A),{}),{isLoading:b,refetch:y}=ec();u.useEffect(()=>{b||(console.log("[TopicMasteryView] Curriculum ready"),y())},[b,y]);const[v,z]=u.useState(new Set),[F,I]=u.useState([]),V=Xl({queryKey:Nl.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 A=xt(Ue,"teachers",r.uid,"settings","quizSettings"),Z=await bs(A),ne=Z.exists()?Z.data()?.excludedTopics||[]:[],$e="https://deign86-mathpulse-api-v3test.hf.space",Me=new URLSearchParams({teacherId:r.uid});t&&Me.set("classSectionId",t);const We=await r.getIdToken(),P=await fetch(`${$e}/api/analytics/topic-mastery?${Me.toString()}`,{headers:{Authorization:`Bearer ${We}`}});if(!P.ok)return{excluded:ne,topics:[],summary:{totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:ne.length}};const re=await P.json(),T=(re.topics||[]).map(G=>({...G,isExcluded:ne.includes(G.topicName)}));return{excluded:ne,topics:T,summary:re.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(V.isLoading||V.isFetching),!V.data){I([]),i([]),c(ko),z(new Set);return}I(V.data.excluded),i(V.data.topics),c(V.data.summary)},[V.data,V.isFetching,V.isLoading]);const Y=async A=>{if(!r)return;const Z=F.includes(A)?F.filter(ne=>ne!==A):[...F,A];I(Z),i(ne=>ne.map($e=>$e.topicName===A?{...$e,isExcluded:!$e.isExcluded}:$e)),c(ne=>({...ne,excludedCount:Z.length}));try{const ne=xt(Ue,"teachers",r.uid,"settings","quizSettings");(await bs(ne)).exists()?await ls(ne,{excludedTopics:Z}):await ts(ne,{excludedTopics:Z})}catch{me.error("Failed to update excluded topics")}},se=async()=>{if(!r)return;const A=[...new Set([...F,...v])];I(A),i(Z=>Z.map(ne=>v.has(ne.topicName)?{...ne,isExcluded:!0}:ne)),c(Z=>({...Z,excludedCount:A.length})),z(new Set);try{const Z=xt(Ue,"teachers",r.uid,"settings","quizSettings");(await bs(Z)).exists()?await ls(Z,{excludedTopics:A}):await ts(Z,{excludedTopics:A}),me.success(`${v.size} topics excluded from quizzes`)}catch{me.error("Failed to update")}},ie=async()=>{if(!r)return;const A=F.filter(Z=>!v.has(Z));I(A),i(Z=>Z.map(ne=>v.has(ne.topicName)?{...ne,isExcluded:!1}:ne)),c(Z=>({...Z,excludedCount:A.length})),z(new Set);try{const Z=xt(Ue,"teachers",r.uid,"settings","quizSettings");(await bs(Z)).exists()?await ls(Z,{excludedTopics:A}):await ts(Z,{excludedTopics:A}),me.success(`${v.size} topics re-included in quizzes`)}catch{me.error("Failed to update")}},ae=A=>{h===A?M(Z=>Z==="asc"?"desc":"asc"):(w(A),M("asc"))},he=g==="all"?k:Jl(g);u.useEffect(()=>{f!=="all"&&(he.includes(f)||p("all"))},[he,f]);const we=n.filter(A=>!(f!=="all"&&A.subjectId!==f||!he.includes(A.subjectId)||N&&!A.topicName.toLowerCase().includes(N.toLowerCase()))).sort((A,Z)=>{const ne=C==="asc"?1:-1;switch(h){case"topicName":return ne*A.topicName.localeCompare(Z.topicName);case"classAverage":return ne*(A.classAverage-Z.classAverage);case"studentsAttempted":return ne*(A.studentsAttempted-Z.studentsAttempted);case"masteryStatus":return ne*((Io[A.masteryStatus]||0)-(Io[Z.masteryStatus]||0));default:return 0}}),O=()=>{v.size===we.length?z(new Set):z(new Set(we.map(A=>A.topicName)))},J=({field:A})=>h!==A?e.jsx(_t,{size:14,className:"text-white/40"}):C==="asc"?e.jsx(Na,{size:14,className:"text-white font-bold"}):e.jsx(_t,{size:14,className:"text-white font-bold"});return d?e.jsxs("div",{className:"flex items-center justify-center py-20",children:[e.jsx(mt,{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($s,{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(Yr,{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(Js,{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(Yl,{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(Bs,{size:16,className:"text-[#64748b] shrink-0 group-focus-within:text-[#4f46e5] transition-colors"}),e.jsx("input",{type:"text",placeholder:"Search topics...",value:N,onChange:A=>j(A.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:f,onChange:A=>p(A.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"}),he.map(A=>e.jsx("option",{value:A,children:W[A]||A},A))]}),e.jsx(_t,{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:g,onChange:A=>S(A.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"}),Zl.map(A=>e.jsx("option",{value:A,children:A},A))]}),e.jsx(_t,{size:16,className:"text-[#64748b] absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]})]}),e.jsx(Mt,{children:v.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:[v.size," topics selected"]}),e.jsx("button",{onClick:se,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:ie,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:()=>z(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:v.size===we.length&&we.length>0,onChange:O,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:()=>ae("topicName"),children:["TOPIC NAME ",e.jsx(J,{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:()=>ae("classAverage"),children:["CLASS AVG % ",e.jsx(J,{field:"classAverage"})]}),e.jsxs("div",{className:"col-span-2 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ae("studentsAttempted"),children:["STUDENTS ",e.jsx(J,{field:"studentsAttempted"})]}),e.jsxs("div",{className:"col-span-1 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ae("masteryStatus"),children:["STATUS ",e.jsx(J,{field:"masteryStatus"})]}),e.jsx("div",{className:"col-span-1 text-center",children:"EXCLUDE"})]}),e.jsx("div",{className:"flex flex-col",children:we.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($s,{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."})}):we.map(A=>{const Z=v.has(A.topicName),ne=Co[A.masteryStatus]||Co.no_data,$e=Hm[A.subjectId]||{label:A.subjectId.toUpperCase(),color:"bg-[#f8fafc] text-[#64748b]"},Me=A.classAverage<60?"bg-rose-500":A.classAverage<85?"bg-amber-500":"bg-emerald-500",We=A.isExcluded?"bg-slate-50/60 opacity-70":A.masteryStatus==="needs_attention"?"bg-rose-50/30":A.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 ${We} ${A.isExcluded?"line-through decoration-slate-400":""}`,children:[e.jsx("div",{className:"col-span-1 flex justify-center",children:e.jsx("input",{type:"checkbox",checked:Z,onChange:()=>{const P=new Set(v);Z?P.delete(A.topicName):P.add(A.topicName),z(P)},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:A.topicName}),e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded shrink-0 ${$e.color}`,children:$e.label})]}),e.jsx("div",{className:"col-span-2 text-[#475569] text-[13px] truncate pr-2",children:A.unit}),e.jsx("div",{className:"col-span-2",children:e.jsxs("span",{className:"font-bold text-[#1e293b] text-[14px]",children:[A.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:[A.studentsAttempted," / ",A.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 ${Me}`,style:{width:`${A.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:A.isExcluded,onChange:()=>Y(A.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:A.isExcluded?"Include in generation":"Exclude from generation"})]})]},A.topicName)})})]})})})]})]})};function Ki(t){return(t||"").trim().toLowerCase()}function To(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=Ki(t.classSectionId),n=(t.id||"").trim().toLowerCase();return o&&n?`${o}|id:${n}`:n?`id:${n}`:`${o}|anonymous`}function Gm(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 Um(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 Xi(t,s){const a=new Map,r=new Map,o=s?Ki(s):"all";return t.forEach(n=>{const i=Gm(n,o),l=i.map(m=>r.get(m)).find(Boolean)||i[0],c=a.get(l),d=c?Um(c,n):n;a.set(l,d),i.forEach(m=>r.set(m,l))}),Array.from(a.values())}function Eo(t,s){return Xi([...t,...s])}function Ws(t){return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function Vm(t){if(!t)return null;const s="gen-math",a=zn.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=zn.find(j=>j.modules.some(h=>h.id===i.id)),c=l?t?.subjects?.[l.id]?.modulesProgress?.[i.id]:null,d=Ws(c?.progress||0),m=i.lessons.length?i.lessons.reduce((j,h)=>{const w=o?.[h.id]?.score;if(typeof w=="number"&&Number.isFinite(w))return j+Ws(w);const C=!!c?.lessonsCompleted?.includes?.(h.id);return j+(C?100:0)},0)/i.lessons.length:0,f=i.quizzes.length?(c?.quizzesCompleted?.length||0)/i.quizzes.length*100:0,p=Ws(m),g=Ws(f),S=Ws(Math.min(100,(p+g*2)/1.5)),N=Ws(Math.min(100,40+d*.6));r.mastery+=d,r.concept+=p,r.application+=g,r.engagement+=S,r.consistency+=N});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 Ro={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"}},Tr=[{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"}],Wm=({classSectionId:t,className:s,fallbackStudents:a=[],onBack:r,onOpenNotifications:o,onOpenProfile:n,insightDismissed:i,onOpenInsightModal:l})=>{const{currentUser:c,userProfile:d}=ms(),m=u.useRef(0),[f,p]=u.useState([]),[g,S]=u.useState(!0),[N,j]=u.useState(""),[h,w]=u.useState("riskLevel"),[C,M]=u.useState("desc"),[k,W]=u.useState("all"),[b,y]=u.useState([]),[v,z]=u.useState(!1),[F,I]=u.useState(""),[V,Y]=u.useState(""),se=u.useCallback(T=>({id:T.id,lrn:T.lrn||void 0,name:T.name,email:T.email||"",avatar:Ga(T.gender),classSectionId:T.classSectionId??null,riskLevel:T.riskLevel||"Low",engagementScore:T.engagementScore,avgQuizScore:T.avgQuizScore,weakestTopic:T.weakestTopic||"Foundational Skills"}),[]),ie=u.useCallback(T=>({id:T.id,lrn:T.lrn,name:T.name,email:T.email||"",avatar:T.avatar&&!T.avatar.includes("ui-avatars.com")?T.avatar:Ga(T.gender),classSectionId:T.classSectionId??null,riskLevel:String(T.riskLevel).charAt(0).toUpperCase()+String(T.riskLevel).slice(1).toLowerCase(),engagementScore:T.engagementScore,avgQuizScore:Number(T.avgQuizScore??T.avgScore??0),weakestTopic:T.weakestTopic||"Foundational Skills"}),[]),ae=u.useCallback(async(T,G)=>{const H=new Map;T.forEach(_=>H.set(_.id,null));const ce=25;for(let _=0;_{try{const te=await kn(E.id);return{studentId:E.id,summary:Vm(te)}}catch{return{studentId:E.id,summary:null}}}))).forEach((E,te)=>{const de=Q[te]?.id;de&&(E.status==="fulfilled"?H.set(de,E.value.summary):H.set(de,null))})}m.current===G&&p(_=>_.map(Q=>H.has(Q.student.id)?{...Q,competencyMatrix:H.get(Q.student.id)??null,competencyMatrixLoading:!1}:Q))},[]),he=u.useCallback(async()=>{if(c?.uid){S(!0),Y("");try{let G=(await dn(c.uid)).map(Q=>({id:Q.id,name:Q.name,email:Q.email||"",avatar:Q.avatar&&!Q.avatar.includes("ui-avatars.com")?Q.avatar:Ga(Q.gender),classSectionId:Q.classSectionId??null,riskLevel:Q.riskLevel,engagementScore:Q.engagementScore,avgQuizScore:Q.avgQuizScore,weakestTopic:Q.weakestTopic||"Foundational Skills"}));a.length>0&&(G=Eo(G,a.map(ie))),t&&(G=G.filter(Q=>Q.classSectionId===t));const H=await it.getImportedClassOverview({classSectionId:t,limit:3e3});H.warnings.length>0&&Y(H.warnings.join(" ")),G=Eo(G,H.students.map(se));const ce=Xi(G,t),_=m.current+=1;p(ce.map((Q,q)=>({rowKey:`${To(Q)}|row:${q}`,student:Q,competency:null,competencyMatrix:null,competencyMatrixLoading:!0,loading:!1,expanded:!1}))),ae(ce,_)}catch(T){if(console.error("Failed to load students:",T),a.length>0){const G=a.map(ie).filter(H=>!t||H.classSectionId===t).map((H,ce)=>({rowKey:`${To(H)}|row:${ce}`,student:H,competency:null,competencyMatrix:null,competencyMatrixLoading:!1,loading:!1,expanded:!1}));p(G),Y("Showing recently imported students while backend roster sync catches up.")}else p([]),Y("Student competency roster is unavailable right now.")}finally{S(!1)}}},[t,c?.uid,a,ae,ie,se]);u.useEffect(()=>{he()},[he]),u.useEffect(()=>{(async()=>{if(!t){y([]),I("");return}z(!0),I("");try{const G=await it.getCourseMaterialTopics({classSectionId:t,limit:20}),H=(G.topics||[]).filter(ce=>ce.title?.trim());y(H),G.warnings.length>0&&I(G.warnings.join(" "))}catch{y([]),I("Imported topic context is unavailable right now.")}finally{z(!1)}})()},[t]);const we=async T=>{p(G=>G.map(H=>{if(H.rowKey!==T)return H;const ce=!H.expanded,_=H.student.id,Q={weakestTopic:H.student.weakestTopic,avgQuizScore:H.student.avgQuizScore};return ce&&!H.competency&&!H.loading?(O(T,_,Q),{...H,expanded:!0,loading:!0}):{...H,expanded:ce}}))},O=async(T,G,H)=>{try{const _=((await kn(G))?.quizAttempts??[]).map(q=>({topic:q.quizId,score:q.score,total:100,timeTaken:q.timeSpent})),Q=await it.getStudentCompetency(G,_.length>0?_:void 0);p(q=>q.map(E=>E.rowKey===T?{...E,competency:Q,loading:!1}:E))}catch{const _=H.avgQuizScore||50,Q={studentId:G,competencies:[{topic:H.weakestTopic||"Unknown",efficiencyScore:Math.max(15,_-20),competencyLevel:_<50?"beginner":"developing",perspective:`Student needs focused practice in ${H.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:[H.weakestTopic||"Review fundamentals"],excludeTopics:[]};p(q=>q.map(E=>E.rowKey===T?{...E,competency:Q,loading:!1}:E))}},J=T=>{h===T?M(G=>G==="asc"?"desc":"asc"):(w(T),M("asc"))},A={High:0,Medium:1,Low:2},Z=f.filter(T=>{if(k!=="all"&&T.student.riskLevel!==k)return!1;if(N){const G=N.toLowerCase();return T.student.name.toLowerCase().includes(G)||T.student.email.toLowerCase().includes(G)}return!0}).sort((T,G)=>{let H=0;switch(h){case"name":H=T.student.name.localeCompare(G.student.name);break;case"avgQuizScore":H=T.student.avgQuizScore-G.student.avgQuizScore;break;case"riskLevel":H=A[T.student.riskLevel]-A[G.student.riskLevel];break;case"engagementScore":H=T.student.engagementScore-G.student.engagementScore;break}return C==="asc"?H:-H}),ne=f.length,$e=f.filter(T=>T.student.riskLevel==="High").length,Me=ne>0?Math.round(f.reduce((T,G)=>T+G.student.avgQuizScore,0)/ne):0,We=ne>0?Math.round(f.reduce((T,G)=>T+G.student.engagementScore,0)/ne):0,P=Array.from(new Set(b.map(T=>T.title).filter(Boolean))).slice(0,10),re=({field:T})=>h!==T?e.jsx(_t,{size:14,className:"text-white/40"}):C==="asc"?e.jsx(Na,{size:14,className:"text-white font-bold"}):e.jsx(_t,{size:14,className:"text-white font-bold"});return g?e.jsxs("div",{className:"flex items-center justify-center py-20 p-6",children:[e.jsx(mt,{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(ks,{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(Cn,{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(Js,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:$e}),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($s,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:[Me,"%"]}),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(Ea,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:[We,"%"]}),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(Bs,{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:N,onChange:T=>j(T.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(T=>e.jsx("button",{onClick:()=>W(T),className:`px-4 py-1.5 text-[13px] font-semibold rounded-full whitespace-nowrap transition-colors shadow-md ${k===T?"bg-[#9956DE] text-white":"bg-white text-slate-500 hover:text-slate-700 hover:bg-slate-50"}`,children:T==="all"?"All":`${T} Risk`},T))})]}),e.jsxs("button",{onClick:he,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(Ls,{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}`:"",":"]}),v?e.jsx("span",{className:"text-[#8b5cf6] text-[13px]",children:"Loading class-scoped imported topics..."}):P.length>0?e.jsx("div",{className:"flex flex-wrap items-center gap-1.5 mt-1 sm:mt-0",children:P.map((T,G)=>e.jsxs(ue.Fragment,{children:[e.jsx("span",{className:"text-[#8b5cf6] text-[13px]",children:T}),GJ("name"),children:["Student ",e.jsx(re,{field:"name"})]}),e.jsxs("div",{className:"w-[120px] shrink-0 px-4 flex justify-center cursor-pointer hover:text-white/80 transition-colors",onClick:()=>J("riskLevel"),children:["Risk Level ",e.jsx(re,{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:()=>J("avgQuizScore"),children:["Avg. Score ",e.jsx(re,{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:()=>J("engagementScore"),children:["Engagement ",e.jsx(re,{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"}),Tr.map((T,G)=>e.jsx("div",{className:`w-[100px] shrink-0 px-2 flex justify-center ${G===Tr.length-1?"border-r border-transparent":""}`,children:T.header},T.key))]}),Z.length===0?e.jsxs("div",{className:"py-12 text-center text-slate-500",children:[e.jsx(Cn,{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:Z.map(T=>(T.student.riskLevel==="High"||T.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 we(T.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 ${T.expanded?"rotate-90":""}`,children:e.jsx(Ss,{className:"w-4 h-4 text-slate-400"})}),e.jsx("img",{src:T.student.avatar,alt:T.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:T.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 ${T.student.riskLevel==="High"?"bg-rose-50 text-rose-600 border-rose-200":T.student.riskLevel==="Medium"?"bg-amber-50 text-amber-600 border-amber-200":"bg-emerald-50 text-emerald-600 border-emerald-200"}`,children:T.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 ${T.student.avgQuizScore>=80?"bg-emerald-500":T.student.avgQuizScore>=60?"bg-amber-400":"bg-rose-500"}`,style:{width:`${T.student.avgQuizScore}%`}})}),e.jsxs("span",{className:"text-[13px] font-bold text-slate-800 w-8",children:[T.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:`${T.student.engagementScore}%`}})}),e.jsxs("span",{className:"text-[13px] font-bold text-slate-800 w-8",children:[T.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:T.student.weakestTopic})}),Tr.map(G=>{const H=T.competencyMatrix?.[G.key]??0;return e.jsx("div",{className:"w-[100px] shrink-0 px-2 flex justify-center",children:T.competencyMatrixLoading?e.jsx(mt,{size:12,className:"animate-spin text-muted-foreground"}):T.competencyMatrix?e.jsxs("span",{className:`text-[12px] font-medium px-2 rounded-full border ${H>=80?"text-emerald-600 bg-emerald-50 border-emerald-100":H>=60?"text-amber-600 bg-amber-50 border-amber-100":"text-rose-500 bg-rose-50 border-rose-100"}`,children:[H,"%"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})},G.key)})]}),e.jsx(Mt,{children:T.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:T.loading?e.jsxs("div",{className:"flex items-center py-4",children:[e.jsx(mt,{size:16,className:"animate-spin text-indigo-500 mr-2"}),e.jsx("span",{className:"text-sm text-slate-500",children:"Analyzing competency data..."})]}):T.competency?e.jsxs("div",{className:"space-y-4 max-w-4xl",children:[T.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:T.competency.recommendedTopics.map((G,H)=>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:G},H))})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.competency.competencies.map((G,H)=>e.jsx(qm,{competency:G},H))})]}):e.jsx("div",{className:"text-sm text-slate-500 py-4",children:"Failed to load competency details."})})]})})})]},T.rowKey)))})]})})]})},qm=({competency:t})=>{const s=Ro[t.competencyLevel]||Ro.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})]})},Ym=()=>{const{notifications:t,unreadCount:s,isLoading:a,markAsRead:r,markAllAsRead:o}=ei(),[n,i]=u.useState("all"),l=["streak_reminder","daily_checkin","streak_milestone","achievement_unlocked","level_up","xp_earned","quiz_result"],c=t.filter(S=>!S.isRead&&!l.includes(S.type)).length,d=S=>{switch(S){case"achievement_unlocked":case"achievement":return jl;case"message":return Al;case"grade":case"quiz_result":return Jo;case"reminder":case"streak_reminder":case"daily_checkin":return ea;case"risk_alert":return Js;case"sparkles":case"lesson_plan_ready":return Fs;case"users":case"student_import":return is;default:return er}},m=(S,N)=>{switch(S){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"}},f=S=>{switch(S){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)]"}},p=u.useMemo(()=>{let S=t.filter(N=>!l.includes(N.type));return n==="unread"&&(S=S.filter(N=>!N.isRead)),n==="important"&&(S=S.filter(N=>N.type==="risk_alert")),S},[t,n]),g=u.useMemo(()=>{const S=[],N=p.filter(w=>Vn(w.createdAt)),j=p.filter(w=>Wn(w.createdAt)),h=p.filter(w=>!Vn(w.createdAt)&&!Wn(w.createdAt));return N.length>0&&S.push({title:"Today",icon:ea,items:N}),j.length>0&&S.push({title:"Yesterday",icon:Rn,items:j}),h.length>0&&S.push({title:"Earlier",icon:Rn,items:h}),S},[p]);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(S=>S.type==="risk_alert"&&!S.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(ac,{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(mt,{className:"w-8 h-8 text-[#a855f7] animate-spin"}),e.jsx("p",{className:"text-[14px] font-medium text-[#64748b]",children:"Syncing notifications..."})]}):g.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(er,{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."})]}):g.map(S=>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(S.icon,{className:"w-4 h-4"})," ",S.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:S.items.map(N=>{const j=d(N.type),h=N.type==="risk_alert";return e.jsxs(Re.div,{layout:!0,onClick:()=>!N.isRead&&r(N.id),className:`relative p-5 flex gap-5 group cursor-pointer hover:bg-white transition-all duration-300 ${N.isRead?"opacity-80":m(N.type)}`,children:[e.jsx("div",{className:`absolute left-0 top-0 w-1.5 h-full transition-colors ${N.isRead?"bg-transparent":h?"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 ${f(N.type)}`,children:e.jsx(j,{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:[N.title,!N.isRead&&e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${h?"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 ${N.isRead?"text-[#94a3b8]":h?"text-rose-600":"text-[#a855f7]"}`,children:[rc(N.createdAt)," ago"]})]}),e.jsx("p",{className:"text-[14px] text-[#475569] font-medium leading-relaxed",children:N.message}),!N.isRead&&N.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 ${h?"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(fc,{size:18})})]},N.id)})})]},S.title))})]})})},Km=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)}},Xm=async(t,s)=>{const a=xt(At(Ue,"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 ts(a,{...r,createdAt:lt(),updatedAt:lt()}),r},Jm=async(t,s)=>{const a=xt(Ue,"calendarEvents",t);await ls(a,{...s,updatedAt:lt()})},Zm=async t=>{await _l(xt(Ue,"calendarEvents",t))},Ji=(t,s={},a,r)=>{if(!t)return a([]),()=>{};const{limitCount:o=500}=s,n=Ct(At(Ue,"calendarEvents"),St("userId","==",t),Xa(o));return ti(n,i=>{a(i.docs.map(l=>Km(l)))},i=>{console.error("Error subscribing to calendar events:",i),r?.(i)})};function eu({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:Xo("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 Ys=t=>String(t).padStart(2,"0"),As=t=>`${t.getFullYear()}-${Ys(t.getMonth()+1)}-${Ys(t.getDate())}`,Ur=t=>new Date(t.getFullYear(),t.getMonth(),1),_o=t=>new Date(t.getFullYear(),t.getMonth()+1,0),tu=t=>{const s=Ur(t),a=s.getDay(),r=new Date(s);return r.setDate(s.getDate()-a),r.setHours(0,0,0,0),r},su=(t,s)=>{const a=new Date(t);return a.setDate(a.getDate()+s),a},Mo=(t,s)=>t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate(),au=(t,s)=>t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth(),ru=t=>t.toLocaleDateString(void 0,{month:"long",year:"numeric"}),Ba=t=>t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),Ao=(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)},nu=["purple","blue","emerald","amber","rose"],Er=t=>{switch(t){case"blue":return"#3b82f6";case"emerald":return"#10b981";case"amber":return"#f59e0b";case"rose":return"#f43f5e";case"purple":default:return"#a855f7"}},ou=(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"}},iu=(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"}}},Rr=[{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 lu(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=Rr.find(i=>i.names.includes(r[1]))?.day,n=Rr.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 Rr.forEach(({names:o,day:n})=>{o.some(i=>s.includes(i))&&a.add(n)}),Array.from(a).sort((o,n)=>o-n)}const cu=({classes:t,teacherId:s})=>{const{currentUser:a}=ms(),[r,o]=u.useState([]),[n,i]=u.useState(!0),[l,c]=u.useState(""),[d,m]=u.useState(!0),[f,p]=u.useState(()=>{const E=new Date;return E.setHours(0,0,0,0),E}),[g,S]=u.useState(()=>{const E=new Date;return E.setHours(0,0,0,0),E}),[N,j]=u.useState(new Set),[h,w]=u.useState(!1),[C,M]=u.useState(null),[k,W]=u.useState(!1),[b,y]=u.useState(""),[v,z]=u.useState(""),[F,I]=u.useState(()=>As(new Date)),[V,Y]=u.useState("09:00"),[se,ie]=u.useState(""),[ae,he]=u.useState("purple"),[we,O]=u.useState(!1),[J,A]=u.useState(null);u.useEffect(()=>{if(!a?.uid){o([]),i(!1);return}c(""),i(!0);const E=Ji(a.uid,{limitCount:500},te=>{o(te),i(!1)},()=>{c("Unable to load calendar events right now."),i(!1)});return()=>E()},[a?.uid]);const Z=u.useMemo(()=>{const E=Ur(f);return E.setHours(0,0,0,0),E},[f]),ne=u.useMemo(()=>{const E=_o(f);return E.setHours(23,59,59,999),E},[f]),$e=u.useMemo(()=>{if(!t||t.length===0)return[];const E=[],te=Ur(f),de=_o(f),xe=new Date(te);for(;xe<=de;){const oe=xe.getDay();t.forEach(fe=>{if(lu(fe.schedule).includes(oe)){const Fe=`schedule-${fe.id}-${As(xe)}`;N.has(Fe)||E.push({id:Fe,userId:s||"",title:fe.name,startTime:new Date(xe),createdAt:new Date})}}),xe.setDate(xe.getDate()+1)}return E},[t,f,s,N]),Me=u.useMemo(()=>[...r,...$e],[r,$e]),We=u.useMemo(()=>Me.filter(E=>E.startTime>=Z&&E.startTime<=ne).sort((E,te)=>E.startTime.getTime()-te.startTime.getTime()),[Me,Z,ne]),P=u.useMemo(()=>{const E=new Map;for(const te of We){const de=As(te.startTime),xe=E.get(de)||[];xe.push(te),E.set(de,xe)}return E},[We]),re=u.useMemo(()=>As(g),[g]),T=u.useMemo(()=>[...P.get(re)||[]].sort((te,de)=>te.startTime.getTime()-de.startTime.getTime()),[P,re]),G=u.useMemo(()=>{const E=tu(f);return Array.from({length:42}).map((te,de)=>su(E,de))},[f]),H=E=>{const te=As(E);M(null),y(""),z(""),I(te),Y("09:00"),ie(""),he("purple"),w(!0)},ce=E=>{E.id.startsWith("schedule-")?(j(te=>new Set(te).add(E.id)),M(null)):M(E.id),y(E.title),z(E.description||""),I(As(E.startTime)),Y(Ys(E.startTime.getHours())+":"+Ys(E.startTime.getMinutes())),ie(E.endTime?Ys(E.endTime.getHours())+":"+Ys(E.endTime.getMinutes()):""),he(E.color||"purple"),O(!1),w(!0)},_=(E,te)=>{E.stopPropagation(),A(te),O(!0)},Q=async()=>{const E=a?.uid||s||"local-user";if(!b.trim()){c("Event title is required.");return}W(!0),c("");const te=Ao(F,V),de=se?Ao(F,se):void 0,xe={title:b.trim(),description:v.trim()?v.trim():void 0,startTime:te,endTime:de&&de.getTime()>te.getTime()?de:void 0,color:ae};try{if(C)o(oe=>oe.map(fe=>fe.id===C?{...fe,...xe}:fe)),await Jm(C,xe);else{const oe=`temp-${Date.now()}`;o(fe=>[...fe,{id:oe,userId:E,createdAt:new Date,...xe}]),await Xm(E,xe)}w(!1)}catch(oe){console.error(oe),w(!1)}finally{W(!1)}},q=async E=>{if(E.startsWith("schedule-")){j(te=>new Set(te).add(E)),J?.id===E&&O(!1);return}c(""),o(te=>te.filter(de=>de.id!==E)),J?.id===E&&O(!1);try{await Zm(E)}catch(te){console.error(te)}};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:()=>p(new Date(f.getFullYear(),f.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(ks,{className:"w-5 h-5"})}),e.jsx("h2",{className:"text-[22px] font-bold text-white w-44 text-center tracking-tight",children:ru(f)}),e.jsx("button",{onClick:()=>p(new Date(f.getFullYear(),f.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(Ss,{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:[We.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(kc,{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=>e.jsx("div",{className:"text-[12px] font-bold text-[#475569] uppercase tracking-widest",children:E},E))}),e.jsx("div",{className:"grid grid-cols-7 gap-2 pb-6 px-4",children:G.map(E=>{const te=As(E),de=P.get(te)||[],xe=Mo(E,g),oe=Mo(E,new Date),fe=au(E,f);return e.jsxs("div",{onClick:()=>S(new Date(E)),className:`group p-2 rounded-lg transition-all cursor-pointer border-2 flex flex-col relative min-h-[100px] xl:min-h-[120px] ${xe?"bg-purple-50/50 border-[#a855f7] shadow-sm z-10":oe?"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"} ${fe?"":"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 ${oe?"bg-gradient-to-br from-[#a855f7] to-[#9333ea] text-white shadow-md":xe?"text-[#9333ea]":"text-[#1e293b]"}`,children:E.getDate()})}),e.jsxs("div",{className:"mt-1 space-y-1",children:[de.slice(0,3).map(qe=>{const Fe=qe.id.startsWith("schedule-");return e.jsx("div",{onClick:Pe=>_(Pe,qe),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 ${ou(qe.color,Fe)}`,children:qe.title},qe.id)}),de.length>3&&e.jsxs("div",{className:"text-[10px] font-bold text-[#64748b] pl-1 pt-0.5",children:["+",de.length-3," more"]})]})]},te)})})]})]})}),e.jsx(Mt,{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:g.toLocaleDateString(void 0,{weekday:"long"})}),e.jsx("p",{className:"text-[13px] font-medium text-[#64748b]",children:g.toLocaleDateString(void 0,{day:"numeric",month:"long",year:"numeric"})})]}),e.jsx("button",{onClick:()=>H(g),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(Zs,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar pb-12",children:T.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center opacity-40",children:[e.jsx(wr,{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."})]}):T.map(E=>{const te=E.id.startsWith("schedule-"),de=iu(E.color,te);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 ${de.dot}`}),e.jsxs("div",{onClick:xe=>_(xe,E),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 ${de.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:E.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 ${de.time}`,children:[e.jsx(ea,{className:"w-3.5 h-3.5"})," ",e.jsxs("span",{children:[Ba(E.startTime),E.endTime?` - ${Ba(E.endTime)}`:""]})]}),E.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:E.description})]})]},E.id)})})]})})})]}),e.jsx(Ln,{open:h,onOpenChange:w,children:e.jsx(Dn,{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(nc,{className:"mb-6",children:[e.jsx(oc,{className:"text-[24px] font-bold text-[#1e293b] tracking-tight",children:C?"Edit Event":"Add New Event"}),e.jsx(ic,{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(js,{value:b,onChange:E=>y(E.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(js,{type:"date",value:F,onChange:E=>I(E.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(js,{type:"time",value:V,onChange:E=>Y(E.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(eu,{value:v,onChange:E=>z(E.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:nu.map(E=>e.jsx("button",{onClick:()=>he(E),className:`w-8 h-8 rounded-full flex items-center justify-center transition-all ${ae===E?"ring-2 ring-offset-2 ring-slate-800 scale-110 shadow-sm":"hover:scale-110 opacity-80 hover:opacity-100"}`,style:{backgroundColor:Er(E)},title:E,children:ae===E&&e.jsx(Ot,{className:"w-4 h-4 text-white"})},E))})]})]}),e.jsxs("div",{className:"flex gap-3 mt-8",children:[e.jsx(ht,{variant:"outline",onClick:()=>w(!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(ht,{onClick:Q,disabled:k,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:k?e.jsx(mt,{className:"w-5 h-5 animate-spin"}):"Save Event"})]})]})})}),e.jsx(Ln,{open:we,onOpenChange:O,children:e.jsx(Dn,{className:"sm:max-w-[400px] p-0 overflow-hidden rounded-[24px] border-none shadow-2xl [&>button]:hidden",children:J&&e.jsxs("div",{className:"p-8 bg-white relative",children:[e.jsx("button",{onClick:()=>O(!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(ds,{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:Er(J.color||"purple")+"20",color:Er(J.color||"purple")},children:J.id.startsWith("schedule-")?e.jsx(Ka,{size:24}):e.jsx(wr,{size:24})}),e.jsxs("div",{className:"pr-6",children:[e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] leading-tight mb-2",children:J.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(wr,{size:12}),J.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(ea,{size:12}),Ba(J.startTime),J.endTime?` - ${Ba(J.endTime)}`:""]})]})]})]}),J.description&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(mc,{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:J.description})]}),e.jsxs("div",{className:"flex gap-3 pt-2 border-t border-slate-100",children:[e.jsxs(ht,{variant:"outline",onClick:()=>q(J.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(ri,{className:"w-4 h-4 mr-2"})," Delete"]}),e.jsxs(ht,{onClick:()=>ce(J),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"]})]})]})})})]})},nr=[{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]"}],zo=({classes:t,onSelectClass:s,onOpenNotifications:a,onOpenProfile:r,insightDismissed:o,onOpenInsightModal:n,viewType:i="analytics",onCreateClass:l})=>{const{currentUser:c,userProfile:d}=ms(),[m,f]=u.useState(""),p=i==="competency",g=t.reduce((h,w)=>h+(w.studentCount||0),0),S=t.reduce((h,w)=>h+(w.atRiskCount||0),0),N=t.length>0?(t.reduce((h,w)=>h+(w.avgScore||0),0)/t.length).toFixed(1):0,j=t.filter(h=>h.name.toLowerCase().includes(m.toLowerCase())||(h.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(Bs,{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:h=>f(h.target.value),className:"bg-transparent border-none focus:outline-none ml-3 text-[13px] w-full text-[#475569] placeholder:text-[#94a3b8]"})]})})}),p?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(is,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none mb-6",children:g}),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(Ns,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[32px] font-bold relative z-10 leading-none mb-6",children:[N,"%"]}),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:"Vs. expected benchmark"}),e.jsx("span",{className:"text-[11px] font-bold bg-white/20 px-2 py-0.5 rounded-[4px] backdrop-blur-sm",children:"+1.4%"})]})]}),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(Ns,{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:"Attendance rate"}),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(is,{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:"94%"}),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:"Active participants"}),e.jsx("span",{className:"text-[11px] font-bold bg-white/20 px-2 py-0.5 rounded-[4px] backdrop-blur-sm",children:g>0?Math.round(g*.94):0})]})]}),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(Ns,{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:[N,"%"]}),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:"Vs. last month"}),e.jsx("span",{className:"text-[11px] font-bold bg-white/20 px-2 py-0.5 rounded-[4px] backdrop-blur-sm",children:"+2.1%"})]})]}),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(lr,{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:S}),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:[g>0?Math.round(S/g*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.jsx("span",{className:"text-[10px] font-bold text-[#9333ea] bg-white px-2 py-0.5 rounded-[4px]",children:"2 Pending"})]}),e.jsxs("div",{className:"space-y-[8px] flex-1 overflow-y-auto no-scrollbar relative z-10",children:[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(di,{className:"w-4 h-4"})}),e.jsxs("div",{className:"leading-snug text-white/90",children:[e.jsx("span",{className:"font-bold text-white",children:"Grade 11 - Section B"})," average dropped by 4% after the last quiz."]})]}),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(vs,{className:"w-4 h-4"})}),e.jsxs("div",{className:"leading-snug text-white/90",children:[e.jsx("span",{className:"font-bold text-white",children:"3 Lesson Plans"})," generated and awaiting your review."]})]})]})]})]}),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:p?"Select a Class":"My Classes"}),l&&!p&&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(Zs,{size:14}),"Create Class"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-[16px]",children:[j.map((h,w)=>{const C=nr[w%nr.length];let M=null;return h.riskLevel==="high"?M=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"}):h.riskLevel==="medium"?M=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"}):M=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(h),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] ${C.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] ${C.bg} flex items-center justify-center border ${C.border}`,children:e.jsx(Vt,{className:`w-5 h-5 ${C.text}`})}),e.jsxs("div",{children:[e.jsx("h4",{className:`font-bold text-[14px] text-[#1e293b] mb-0.5 transition-colors ${C.groupHover}`,children:h.name}),e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider",children:h.gradeLevel||"Senior High"})]})]}),M]}),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:h.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:p?"Avg Competency":"Average"}),e.jsxs("span",{className:"font-semibold text-[#1e293b]",children:[h.avgScore,"%"]})]}),!p&&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:h.schedule||"Mon-Fri"})]})]})]})]},h.id)}),j.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."})]})]})]})})},Zi="PH_SHS_OFFICIAL_CLASS_RECORD",du=.85,Vr=.85,mu="2026.04.24",el=4,Wa=["INPUT DATA","SENIOR HIGH SCHOOL CLASS RECORD","LEARNERS NAMES","WRITTEN WORK","PERFORMANCE TASKS","QUARTERLY ASSESSMENT","REMARK","FINAL SEMESTRAL GRADES"],uu=[...Wa,"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"],xu=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],Aa=["WITH ATTACHMENTS","OFFICIALLY DROPPED","WITHDRAWN","UNOFFICIALLY DROPPED","TRANSFEREE","SHIFTER"],pu=["TOTAL","SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY","WEIGHT OF COMPONENTS"],hu={SECOND:["SECOND QUARTER","2ND QUARTER","Q2"]},qs={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"]},Ut={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"]},De={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 fu(t){return t==null?null:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:String(t)}function vt(t){return String(t??"").replace(/[\u00a0\t\r\n]+/g," ").replace(/[|]+/g," ").replace(/\s+/g," ").trim().toUpperCase()}function Lo(t){return vt(t).replace(/[^A-Z0-9]+/g,"")}function Se(t,s){const a=vt(t),r=vt(s);if(!a||!r)return!1;if(a.includes(r))return!0;const o=Lo(t),n=Lo(s);return!o||!n?!1:o.includes(n)}function qa(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 _r(t){return vt(t).toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,80)}function tl(t){const s={};return t.forEach(a=>{const r=Yt.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=Yt.encode_cell({r:o,c:n});s[i]=r}}),s}function gu(t,s,a){const o=(a||tl(t.merges))[s]||s;return t.cells[o]||t.cells[s]}const sl="A1:A1",Do=1200,$o=200,Fo=2e5;function bu(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>Do&&(r=s+Do-1),o-a+1>$o&&(o=a+$o-1);const n=r-s+1,i=o-a+1;if(n*i>Fo){const c=Math.max(1,Math.floor(Fo/i));r=s+Math.min(n,c)-1}return{s:{r:s,c:a},e:{r,c:o}}}function vu(t){try{return Yt.decode_range(t)}catch{return Yt.decode_range(sl)}}function wu(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=Yt.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 Nu(t){const s=vu(t.ref||sl),a=wu(t);return bu(a||s)}function ju(t,s){const a=Nu(s),r=`${Yt.encode_cell(a.s)}:${Yt.encode_cell(a.e)}`,o=tl(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 Rs(t,s){return st.endRow?"":(t.cells[s-t.startRow]||[]).map(r=>r?.normalizedText||"").filter(Boolean).join(" ").trim()}function fa(t){return Yt.encode_col(t)}function Pa(t){const s=String(t||"").trim().toUpperCase();if(!s||!/^[A-Z]+$/.test(s))return-1;try{return Yt.decode_col(s)}catch{return-1}}function yu(t){return`${Yt.encode_cell(t.s)}:${Yt.encode_cell(t.e)}`}function Su(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=Be(t,r,n);o.push(i?.displayValue??null)}a.push(o)}return a}function ku(t,s){const a=vt(t),r=vt(s);return!a||!r?0:a===r?1:a.includes(r)?.9:.75}function mn(t,s){const a=[];for(let r=0;r{Se(l.normalizedText,c)&&a.push({sheetName:t.sheetName,anchor:c,row:l.row,col:l.col,address:l.address,value:String(l.displayValue??""),confidence:ku(l.displayValue,c)})})}const o=t.startRow+r,n=Rs(t,o);n&&s.forEach(i=>{if(!Se(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 Cu(t,s){return Object.values(t).flatMap(a=>mn(a,s))}function jt(t,s){return mn(t,[s]).sort((a,r)=>a.row-r.row||a.col-r.col)}function al(t,s,a,r=6){for(let o=1;o<=r;o+=1){const i=Be(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=Be(t,s+o,a)?.displayValue;if(i!=null&&String(i).trim())return String(i).trim()}}function rl(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=Rs(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 Iu(t,s){const a=vt(t).toLowerCase(),r=o=>[...s].some(n=>Se(n,o));return qs.inputData.some(o=>a.includes(o))||r("INPUT DATA")?"inputData":qs.finalSemestral.some(o=>a.includes(o))||r("FINAL SEMESTRAL GRADES")||r("FINAL GRADES")?"finalSemestral":qs.firstQuarter.some(o=>a.includes(o))||r("FIRST QUARTER")?"firstQuarter":qs.secondQuarter.some(o=>a.includes(o))||r("SECOND QUARTER")?"secondQuarter":r("SENIOR HIGH SCHOOL CLASS RECORD")||r("WRITTEN WORK")&&r("PERFORMANCE TASKS")?"firstQuarter":qs.helper.some(o=>a.includes(o))||r("WEIGHT OF COMPONENTS")||r("ATTACHMENTS")||r("HELPER")?"helper":qs.lookup.some(o=>a.includes(o))||r("LOOK UP")?"lookup":"other"}function Tu(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 Eu(t){const s=Cu(t.matrices,uu),a=new Set,r=[];Wa.forEach(g=>{s.some(N=>Se(N.anchor,g))&&(a.add(g),r.push(`Found critical anchor: ${g}`))});const o=Wa.filter(g=>!a.has(g)),n=new Map;s.forEach(g=>{n.has(g.sheetName)||n.set(g.sheetName,new Set),n.get(g.sheetName)?.add(g.anchor)});const i=t.sheetNames.map(g=>{const S=n.get(g)||new Set,N=Iu(g,S),j=Math.min(1,.35+Math.min(.55,S.size*.08)),h=[`sheet:${g}`,`signals:${S.size}`,...[...S].slice(0,5)];return{sheetName:g,role:N,confidence:Number(j.toFixed(3)),evidence:h}}),l={firstQuarter:[],secondQuarter:[],finalSemestral:[],helper:[],lookup:[],other:[]};i.forEach(g=>{switch(g.role){case"inputData":l.inputData?l.other.push(g.sheetName):l.inputData=g.sheetName;break;case"firstQuarter":l.firstQuarter.push(g.sheetName);break;case"secondQuarter":l.secondQuarter.push(g.sheetName);break;case"finalSemestral":l.finalSemestral.push(g.sheetName);break;case"helper":l.helper.push(g.sheetName);break;case"lookup":l.lookup.push(g.sheetName);break;case"other":default:l.other.push(g.sheetName);break}});const c=(l.inputData?1:0)+l.firstQuarter.length+l.secondQuarter.length+l.finalSemestral.length+l.helper.length+l.lookup.length,d=Tu({criticalFound:a.size,criticalTotal:Wa.length,recognizedSheets:c,totalSheets:t.sheetNames.length,hasDepedAnchor:s.some(g=>Se(g.anchor,"Pursuant to DepEd Order 8 series of 2015"))}),m=l.firstQuarter.length>0||l.secondQuarter.length>0,f=!!l.inputData&&m&&l.finalSemestral.length>0,p=d>=.55&&f;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:Zi,isOfficialFormatLikely:p,confidence:d,evidence:r,missingCriticalAnchors:o,detectedSheets:l,anchorMatches:s}}function or(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 un(t){const s=vt(t);if(s.includes("FEMALE"))return"FEMALE";if(s.includes("MALE"))return"MALE"}function xn(t){const s=vt(t.rowText);return s?s==="MALE"||s==="FEMALE"?"sex-header":xu.some(a=>s.includes(a))?"signature":pu.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 Ru(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(o=>{a.push({role:r,name:String(Be(t,o.row,o.col+1)?.displayValue||"").trim()||void 0,sourceSheet:t.sheetName,sourceRow:o.row+1})})}),a}function _u(t){const s=[],a=jt(t,"LEARNERS NAMES")[0],r=a?rl(t,a.row,5):t.startRow,o=(j,h)=>jt(t,j).find(C=>Math.abs(C.row-r)<=2)?.col??h,n=o(De.learnerNo[0],t.startCol),i=o(De.learnerName[0],t.startCol+1),l=o(De.firstQuarter[0],i+1),c=o(De.secondQuarter[0],l+1),d=o(De.firstSemester[0],c+1),m=o(De.finalGrades[0],d+1),f=o(De.remark[0],m+1),p=o(De.additionalRemarks[0],f+1),g=[];let S="UNKNOWN",N=0;for(let j=r+1;j<=t.endRow;j+=1){const h=Rs(t,j),w=xn({rowText:h,hasLearnerNumber:/\b\d{1,2}\b/.test(h),hasLearnerName:/[A-Z]{2,}/.test(h)});if(w==="sex-header"){S=un(h)||S;continue}if(w==="signature"||w==="helper")break;if(w==="blank"){if(N+=1,N>=el)break;continue}if(w!=="learner")continue;N=0;const C=or(Be(t,j,n)?.displayValue),M=String(Be(t,j,i)?.displayValue||"").trim();if(!M&&C===void 0)continue;const k=Be(t,j,l)?.displayValue??null,W=Be(t,j,c)?.displayValue??null,b=Be(t,j,d)?.displayValue??null,y=Be(t,j,m)?.displayValue??null,v=Be(t,j,f)?.displayValue??null;let z=Be(t,j,p)?.displayValue??null;const F=Aa.filter(I=>Se(h,I));F.length>0&&(z=[z,F.join("; ")].filter(Boolean).join("; ")||null),!M&&C!==void 0&&s.push(`Row ${j+1} has learner number ${C} but empty learner name.`),g.push({learnerNo:C,fullName:M||`Unnamed Learner ${C||j+1}`,sex:S,firstQuarter:k,secondQuarter:W,firstSemester:b,finalGrades:y,remark:v,additionalRemarks:z,sourceRow:j+1})}return{sheetName:t.sheetName,learnerGrades:g,signatures:Ru(t),warnings:s}}function es(t,s){for(const a of s){const r=jt(t,a);for(const o of r){const n=al(t,o.row,o.col,8);if(n&&n.trim())return n.trim()}}}function Mu(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(n=>{const i=al(t,n.row,n.col,10);a.push({role:r,name:i,sourceSheet:t.sheetName,sourceRow:n.row+1})})}),a}function Au(t){const s=jt(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 f=Rs(t,m),p=xn({rowText:f,hasLearnerNumber:!!or(Be(t,m,o)?.displayValue),hasLearnerName:!!String(Be(t,m,r)?.displayValue||"").trim()});if(p==="sex-header"){c=un(f)||c,d=0;continue}if(p==="signature"||p==="helper")break;if(p!=="learner"){if(p==="blank"&&(d+=1),d>=5)break;continue}d=0;const g=or(Be(t,m,o)?.displayValue),S=String(Be(t,m,r)?.displayValue||"").trim(),N=String(Be(t,m,n)?.displayValue||"").trim()||void 0,j=String(Be(t,m,i)?.displayValue||"").trim()||void 0,h=Aa.filter(w=>Se(f,w));!S&&g===void 0||l.push({learnerNo:g,sex:c,fullName:S||`Unnamed Learner ${g||m}`,sourceSheet:t.sheetName,sourceRow:m+1,remarks:N,additionalRemarks:j,statuses:h.length>0?h:void 0})}return l}function zu(t){const s=[],a=[];for(let r=t.startRow;r<=t.endRow;r+=1){const o=Rs(t,r);if(o){if(Aa.some(n=>Se(o,n))){s.push(o);continue}(Se(o,"IMPORTANT")||Se(o,"NOTE")||Se(o,"ATTACHMENT")||Se(o,"LOOK UP"))&&a.push(o)}}return{attachmentRules:Array.from(new Set(s)),helperNotes:Array.from(new Set(a))}}function Lu(t){const s=[],a={region:es(t,Ut.region),division:es(t,Ut.division),schoolName:es(t,Ut.schoolName),schoolId:es(t,Ut.schoolId),schoolYear:es(t,Ut.schoolYear),gradeSection:es(t,Ut.gradeSection),semester:es(t,Ut.semester),track:es(t,Ut.track),subjectCode:es(t,Ut.subjectCode),subjectName:es(t,Ut.subjectName),teacherName:es(t,Ut.teacherName)},r=Au(t),o=Mu(t),{attachmentRules:n,helperNotes:i}=zu(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."),mn(t,Object.values(Ut).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 Du(t){const s=vt(t.sheetName);return hu.SECOND.some(a=>Se(s,a))?"SECOND":"FIRST"}function $u(t,s){const a=[],r=[],o=[];let n,i="NONE";for(let l=t.startCol;l<=t.endCol;l+=1){const c=Be(t,s,l),d=vt(c?.displayValue||""),m=Be(t,s+1,l),f=String(m?.displayValue||c?.displayValue||"").trim();if(!d&&!f)continue;if(Se(d,De.writtenWork[0])){i="WW";continue}if(Se(d,De.performanceTasks[0])){i="PT";continue}if(Se(d,De.quarterlyAssessment[0])){n={key:_r(f||"quarterly_assessment"),label:f||"Quarterly Assessment",column:fa(l)},i="DERIVED";continue}if(Se(d,De.initialGrade[0])||Se(d,De.quarterlyGrade[0])||Se(d,De.remark[0])||Se(d,De.additionalRemarks[0])||Se(d,De.firstQuarter[0])||Se(d,De.secondQuarter[0])||Se(d,De.firstSemester[0])||Se(d,De.finalGrades[0])||Se(d,De.ps[0])||Se(d,De.ws[0])||Se(d,De.total[0])){i="DERIVED",o.push({key:_r(f||d),label:f||d,column:fa(l)});continue}const p={key:_r(f||d||fa(l)),label:f||d||fa(l),maxScore:qa(m?.displayValue),column:fa(l)};i==="WW"?a.push(p):i==="PT"?r.push(p):i==="DERIVED"&&o.push(p)}return{writtenWorks:a,performanceTasks:r,quarterlyAssessment:n,derived:o}}function Fu(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(o=>{const n=Be(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 Oo(t,s,a){for(let r=t.startCol;r<=t.endCol;r+=1){const o=vt(Be(t,s,r)?.displayValue||""),n=vt(Be(t,s+1,r)?.displayValue||"");if(a.some(i=>Se(o,i)||Se(n,i)))return r}}function Ou(t,s,a,r){const o={learnerNo:or(Be(t,s,r.numberCol)?.displayValue),fullName:String(Be(t,s,r.nameCol)?.displayValue||"").trim(),sourceRow:s+1},n={};a.writtenWorks.forEach(d=>{const m=d.column?Pa(d.column):-1;if(m<0)return;const f=Be(t,s,m)?.displayValue;n[d.key]=f??null}),Object.keys(n).length>0&&(o.writtenWorks=n);const i={};if(a.performanceTasks.forEach(d=>{const m=d.column?Pa(d.column):-1;if(m<0)return;const f=Be(t,s,m)?.displayValue;i[d.key]=f??null}),Object.keys(i).length>0&&(o.performanceTasks=i),a.quarterlyAssessment?.column){const d=Pa(a.quarterlyAssessment.column);o.quarterlyAssessment=Be(t,s,d)?.displayValue??null}const l=a.derived||[],c={};return l.forEach(d=>{if(!d.column)return;const m=Pa(d.column);if(m<0)return;const f=Be(t,s,m)?.displayValue??null;c[d.key]=f,Se(d.label,De.initialGrade[0])&&(o.initialGrade=f),Se(d.label,De.quarterlyGrade[0])&&(o.quarterlyGrade=f),Se(d.label,De.firstQuarter[0])&&(o.firstQuarter=f),Se(d.label,De.secondQuarter[0])&&(o.secondQuarter=f),Se(d.label,De.firstSemester[0])&&(o.firstSemester=f),Se(d.label,De.finalGrades[0])&&(o.finalGrades=f),Se(d.label,De.remark[0])&&(o.remark=f!==null?String(f):null),Se(d.label,De.additionalRemarks[0])&&(o.additionalRemarks=f!==null?String(f):null)}),Object.keys(c).length>0&&(o.totals=c),o}function Bu(t){const s=Du(t),a=[],r=jt(t,De.learnerName[0])[0]||jt(t,De.learnerName[1])[0],o=r?rl(t,r.row,4):t.startRow,n=$u(t,o),i=Oo(t,o,De.learnerNo)??t.startCol,l=Oo(t,o,De.learnerName)??Math.min(t.endCol,i+1),c=[];let d="UNKNOWN",m=0;for(let S=o+1;S<=t.endRow;S+=1){const N=Rs(t,S),j=xn({rowText:N,hasLearnerNumber:/\b\d{1,2}\b/.test(N),hasLearnerName:/[A-Z]{2,}/.test(N)});if(j==="sex-header"){d=un(N)||d;continue}if(j==="signature"||j==="helper")break;if(j==="blank"){if(m+=1,m>=el)break;continue}if(j!=="learner")continue;m=0;const h=Ou(t,S,n,{numberCol:i,nameCol:l});if(h.sex=d,!h.fullName&&h.learnerNo===void 0)continue;const w=Aa.filter(C=>Se(N,C));w.length>0&&!h.additionalRemarks&&(h.additionalRemarks=w.join("; ")),!h.fullName&&h.learnerNo!==void 0&&(a.push(`Row ${S+1} has learner number ${h.learnerNo} but empty name.`),h.fullName=`Unnamed Learner ${h.learnerNo}`),c.push(h)}n.writtenWorks.length===0&&n.performanceTasks.length===0&&a.push(`No detailed assessment columns detected in ${t.sheetName}.`);const f=qa(jt(t,"WRITTEN WORK %")[0]?.value||jt(t,"WRITTEN WORK")[0]?.value),p=qa(jt(t,"PERFORMANCE TASKS %")[0]?.value||jt(t,"PERFORMANCE TASKS")[0]?.value),g=qa(jt(t,"QUARTERLY ASSESSMENT %")[0]?.value||jt(t,"QUARTERLY ASSESSMENT")[0]?.value);return{sheetName:t.sheetName,quarter:s,gradingWeights:{writtenWork:f,performanceTasks:p,quarterlyAssessment:g},assessmentColumns:n,learnerGrades:c,signatures:Fu(t),warnings:a}}function Pu(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(o=>{a.push({role:r,name:String(Be(t,o.row,o.col+1)?.displayValue||"").trim()||void 0,sourceSheet:t.sheetName,sourceRow:o.row+1})})}),a}function Hu(t){const s=[];let a=!1;for(let r=t.startRow;r<=t.endRow;r+=1){const o=Rs(t,r);if(!o){if(a&&s.length>0)break;continue}if(Se(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=Be(t,r,i)?.displayValue;l==null||String(l).trim()===""||(n[`c${i}`]=l)}Object.keys(n).length>2&&s.push(n)}return s}function Qu(t){const s=[],a=[],r=[],o=[],n=[];return t.forEach(i=>{Pu(i).forEach(l=>a.push(l)),Hu(i).forEach(l=>r.push({...l,sourceSheet:i.sheetName}));for(let l=i.startRow;l<=i.endRow;l+=1){const c=Rs(i,l);if(c){if(Aa.some(d=>Se(c,d))){o.push(`${i.sheetName}: ${c}`);continue}(Se(c,"HELPER")||Se(c,"LOOK UP")||Se(c,"IMPORTANT")||Se(c,"REFERENCE")||Se(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 Gu(t,s,a){const r=new Map,o=n=>{const i=`${vt(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 Uu(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=`${vt(i.role)}|${vt(i.name||"")}|${i.sourceSheet}`;n.set(l,i)}),Array.from(n.values())}function Vu(t){const s=Gu(t.inputData.learners,t.quarterSheets,t.finalSheets);return{format:Zi,version:mu,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:Uu(t.inputData,t.quarterSheets,t.finalSheets,t.references),unclassifiedBlocks:t.unclassifiedBlocks},validation:t.validation,raw:t.workbook.raw}}function Wu(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 qu(t){const s={ref:t["!ref"],merges:Wu(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 Yu(t,s){const a=cc(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=qu(i);o[n]=l,r[n]=ju(n,l)}),{fileName:t,sheetNames:a.SheetNames,raw:{sheets:o},matrices:r}}async function Ku(t){const s=await t.arrayBuffer();return Yu(t.name,s)}class Xu{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=Be(o,l,c);if(!(m&&m.displayValue!==null&&m.displayValue!==void 0&&String(m.displayValue).trim())){n.add(d);continue}const p=this.collectComponent(o,l,c,i,n);p&&r.push({sheetName:o.sheetName,range:yu(p),purposeGuess:a,raw2D:Su(o,p)})}}),r}collectComponent(s,a,r,o,n){const i=[{row:a,col:r}];let l=a,c=a,d=r,m=r,f=!1;for(;i.length>0;){const p=i.shift();if(!p)break;const g=`${p.row}:${p.col}`;if(n.has(g)||o.has(g))continue;n.add(g);const S=Be(s,p.row,p.col);S&&S.displayValue!==null&&S.displayValue!==void 0&&String(S.displayValue).trim()&&(f=!0,l=Math.min(l,p.row),c=Math.max(c,p.row),d=Math.min(d,p.col),m=Math.max(m,p.col),[{row:p.row-1,col:p.col},{row:p.row+1,col:p.col},{row:p.row,col:p.col-1},{row:p.row,col:p.col+1}].forEach(j=>{j.rows.endRow||j.cols.endCol||i.push(j)}))}return f?{s:{r:l,c:d},e:{r:c,c:m}}:null}}function Ju(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 Zu(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 ex(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 tx(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 sx(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(", ")}.`),Zu(t.inputData.learners).forEach(n=>s.push(n)),ex(t.quarterSheets).forEach(n=>s.push(n)),tx(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 Bo=1500;function Po(t){return t?Object.values(t.matrices).reduce((s,a)=>s+a.rowCount*a.colCount,0):0}function Ho(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>=Bo){console.warn(`${s} slow=true threshold=${Bo}ms`);return}}function zs(t,s){t?.onProgress?.(s)}function rx(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 ga(t,s,a,r){rx(a,s).forEach(o=>{t.markRange(s.sheetName,{s:{r:o,c:s.startCol},e:{r:o,c:s.endCol}},r)})}async function nx(t,s){const a=s?.confidenceThreshold??du,r=Date.now();let o=null;try{if(zs(s,{stage:"reading",message:"Reading workbook structure and raw sheets..."}),o=await Ku(t),!o)throw new Error("Workbook read returned null");zs(s,{stage:"detecting-format",message:"Detecting DepEd SHS workbook format..."});const n=Eu(o);zs(s,{stage:"extracting",message:"Extracting metadata, learners, grades, and references..."});const i=n.detectedSheets.inputData||o.sheetNames[0],l=o.matrices[i],c=l?Lu(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(C=>o.matrices[C]).filter(C=>!!C).map(C=>Bu(C)),f=(n.detectedSheets.finalSemestral||[]).map(C=>o.matrices[C]).filter(C=>!!C).map(C=>_u(C)),p=[...n.detectedSheets.helper||[],...n.detectedSheets.lookup||[]].map(C=>o.matrices[C]).filter(C=>!!C),g=Qu(p),S=new Xu;n.anchorMatches.forEach(C=>{const M=o.matrices[C.sheetName];M&&ga(S,M,[C.row],`Anchor match: ${C.anchor}`)}),[c.sheetName].forEach(C=>{const M=o.matrices[C];if(!M)return;const k=Array.from({length:Math.min(14,M.rowCount)},(y,v)=>M.startRow+v),W=c.learners.map(y=>y.sourceRow-1),b=c.signatures.map(y=>y.sourceRow).filter(y=>typeof y=="number").map(y=>y-1);ga(S,M,[...k,...W,...b],"Input Data parsed rows")}),m.forEach(C=>{const M=o.matrices[C.sheetName];if(!M)return;const k=C.learnerGrades.map(y=>y.sourceRow-1),W=C.signatures.map(y=>y.sourceRow).filter(y=>typeof y=="number").map(y=>y-1),b=k.length>0?Math.max(M.startRow,Math.min(...k)-2):M.startRow;ga(S,M,[b,b+1,...k,...W],"Quarter sheet parsed rows")}),f.forEach(C=>{const M=o.matrices[C.sheetName];if(!M)return;const k=C.learnerGrades.map(y=>y.sourceRow-1),W=C.signatures.map(y=>y.sourceRow).filter(y=>typeof y=="number").map(y=>y-1),b=k.length>0?Math.max(M.startRow,Math.min(...k)-2):M.startRow;ga(S,M,[b,b+1,...k,...W],"Final semestral parsed rows")}),p.forEach(C=>{const M=g.componentWeights.filter(b=>b.sourceSheet===C.sheetName).map(b=>b.sourceRow).filter(b=>typeof b=="number").map(b=>b-1),k=g.signatures?.filter(b=>b.sourceSheet===C.sheetName).map(b=>b.sourceRow).filter(b=>typeof b=="number").map(b=>b-1)||[],W=M.length===0&&k.length===0?[C.startRow,C.startRow+1,C.startRow+2]:[];ga(S,C,[...M,...k,...W],"Reference/helper parsed rows")});const N=S.getUnmappedBlocks(o.matrices);zs(s,{stage:"validating",message:"Validating completeness and structural integrity..."});const j=sx({detection:n,inputData:c,quarterSheets:m,finalSheets:f,mappedCellRegions:S.getMappedRegionCount(),unmappedCellRegions:N.length,totalSheets:o.sheetNames.length});zs(s,{stage:"normalizing",message:"Normalizing parsed workbook and creating entity mapping..."});const h=Vu({workbook:o,detection:n,inputData:c,quarterSheets:m,finalSheets:f,references:g,validation:j,unclassifiedBlocks:N});h.validation.confidence_.trim().toLowerCase().replace(/\s+/g," "),he=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;const Q=Number(String(_??"").replace(/[^0-9.-]+/g,""));return Number.isFinite(Q)?Q:null},we=(_,Q)=>{const q=Number.isFinite(_)?_:Q;return Math.max(0,Math.min(100,q))},O=_=>{const Q=String(_??"");return/[",\n]/.test(Q)?`"${Q.replace(/"/g,'""')}"`:Q},J=(_,Q)=>{const q=new Map,E=["quarterlyGrade","finalGrades","firstSemester","firstQuarter","secondQuarter","initialGrade"];_.mapping.gradeEntities.forEach(Pe=>{const tt=ae(Pe.fullName||"");if(!tt)return;const Tt=E.map(wt=>he(Pe[wt])).filter(wt=>wt!==null);if(Tt.length===0)return;const dt=q.get(tt)||[];q.set(tt,dt.concat(Tt))});const te=_.mapping.studentEntities||[];if(te.length===0)return null;const de=(_.imported.schoolContext.semester||_.imported.schoolContext.schoolYear||"First Semester").trim(),xe=(_.imported.schoolContext.subjectName||"Class Record Import").trim(),oe=(t||s||"import").replace(/[^a-zA-Z0-9]+/g,"").toUpperCase().slice(0,12)||"IMPORT",qe=[["name","lrn","email","engagementScore","avgQuizScore","attendance","assignmentCompletion","term","assessmentName"].join(",")];if(te.forEach((Pe,tt)=>{const Tt=ae(Pe.fullName||""),dt=q.get(Tt)||[],wt=dt.length>0?dt.reduce((Dt,$t)=>Dt+$t,0)/dt.length:75,Lt=we(wt,75),B=we(Lt+5,85),Ae=we(Lt*.7+B*.3,80),Xe=we(B*.6+Lt*.4,82),Nt=Pe.learnerNo||tt+1,Kt=`IMP-${oe}-${String(Nt).padStart(4,"0")}`,Et=Pe.fullName||`Learner ${tt+1}`;qe.push([O(Et),O(Kt),O(""),O(Number(Ae.toFixed(1))),O(Number(Lt.toFixed(1))),O(Number(B.toFixed(1))),O(Number(Xe.toFixed(1))),O(de),O(xe)].join(","))}),qe.length<=1)return null;const Fe=Q.replace(/\.(xlsx|xls)$/i,"");return new File([qe.join(` -`)],`${Fe}-normalized.csv`,{type:"text/csv"})},A=async _=>{y(!0),I(""),Y(null);let Q=_;if(/\.(xlsx|xls)$/i.test(_.name))try{const q=await nx(_,{confidenceThreshold:Vr});w(q);const E=J(q,_.name);E&&(Q=E)}catch{w(null)}else w(null);try{const q=await it.uploadClassRecords(Q,{classSectionId:t,className:s,datasetIntent:"synthetic_student_records"}),E=q.students.length,de=((xe,oe,fe,qe)=>({classSectionId:xe.classSectionId||oe||"imported_class",className:xe.className||fe||"Imported Class",classMetadata:xe.classMetadata||qe}))(q,t,s,a);E>0&&l?.({students:q.students,classSectionId:de.classSectionId,className:de.className,classMetadata:de.classMetadata}),q.success?(me.success(`Successfully imported ${E} student records.`),Y({datasetIntent:q.datasetIntent,summary:q.interpretationSummary,columns:q.columnInterpretations?.map(xe=>({columnName:xe.columnName,mappedField:xe.mappedField,usagePolicy:xe.usagePolicy,confidenceBand:xe.confidenceBand,domainSignals:xe.domainSignals}))||[]}),c?.()):me.error("Import completed but no usable student rows were detected. Check required columns and retry.")}catch(q){me.error(q instanceof Error?q.message:"Upload failed")}finally{y(!1)}},Z=async _=>{z(!0);try{const Q=await it.uploadCourseMaterials(_,{classSectionId:t,className:s});if(Q.success){const q=Q.topics?.length??0;me.success(`Course material imported (${q} topics extracted).`),c?.()}}catch(Q){me.error(Q instanceof Error?Q.message:"Course material upload failed")}finally{z(!1)}},[ne,$e]=u.useState(r),[Me,We]=u.useState(!1),[P,re]=u.useState(null),T=u.useMemo(()=>{if(t)return ne.filter(_=>gs(_.classSectionId)===gs(t)||gs(_.classroomId)===gs(t));if(o.length>0){const _=new Set(o.map(Q=>gs(Q.classSectionId||Q.id)));return ne.filter(Q=>_.has(gs(Q.classSectionId))||_.has(gs(Q.classroomId)))}return ne},[ne,t,o]);u.useEffect(()=>{$e(r),H(Object.fromEntries(r.map(_=>[Ha(_),{grade:_.grade||"",section:_.section||""}])))},[r]);const[G,H]=u.useState({}),ce=async()=>{We(!0);let _=0,Q=0;try{for(const E of T){const te=G[Ha(E)],de=te?.grade||E.grade,xe=te?.section||E.section;try{n&&(de!==E.grade||xe!==E.section)&&(await xr(E.id,de,xe,n,new Date().getFullYear().toString(),i),await Vi(E.id,de,xe),_++)}catch(oe){console.warn(`[EditRecords] Failed to save ${E.name}:`,oe),Q++}}const q=ne.map(E=>{const te=G[Ha(E)];if(!te)return E;const de=bt({metadata:E.classMetadata,classSectionId:E.classSectionId,className:[te.grade,te.section].filter(Boolean).join(" - "),grade:te.grade,section:te.section});return{...E,grade:te.grade,section:te.section,className:de.className||[te.grade,te.section].filter(Boolean).join(" - "),classSectionId:de.classSectionId||E.classSectionId,classMetadata:de}});$e(q),m?.(q),Q>0?me.warning(`Saved ${_} records, ${Q} failed`):me.success("Records saved successfully")}catch{me.error("Failed to save changes")}finally{We(!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:[N==="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(Ja,{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(_t,{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(),M(!0)},onDragLeave:()=>M(!1),onDrop:_=>{_.preventDefault(),M(!1);const Q=_.dataTransfer.files[0];Q&&A(Q)},onClick:()=>se.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] ${C?"border-[#1FA7E1] bg-[#1FA7E1]/10":"border-[#1FA7E1]/30 hover:border-[#1FA7E1] bg-white hover:bg-[#1FA7E1]/5"}`,children:[e.jsx("input",{ref:se,type:"file",accept:".csv,.xlsx,.xls",onChange:_=>{const Q=_.target.files?.[0];Q&&A(Q)},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:b?e.jsx("span",{className:"animate-spin text-[#1FA7E1]",children:"..."}):e.jsx(zc,{className:"w-8 h-8 text-[#1FA7E1]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:b?"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 Q=_.dataTransfer.files[0];Q&&Z(Q)},onClick:()=>ie.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] ${k?"border-[#9956DE] bg-[#9956DE]/10":"border-[#9956DE]/30 hover:border-[#9956DE] bg-white hover:bg-[#9956DE]/5"}`,children:[e.jsx("input",{ref:ie,type:"file",accept:".pdf,.docx,.txt",onChange:_=>{const Q=_.target.files?.[0];Q&&Z(Q)},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:v?e.jsx("span",{className:"animate-spin text-[#9956DE]",children:"..."}):e.jsx(vs,{className:"w-8 h-8 text-[#9956DE]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:v?"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(Mc,{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(di,{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(Fs,{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(qr,{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:()=>j("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(Ic,{className:"w-4 h-4"})," Edit Class Records"]}),e.jsx("button",{onClick:()=>j("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:()=>j("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(Nc,{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."})]})]})]})]}),N==="mapping-logs"&&e.jsxs("div",{className:"space-y-[16px]",children:[e.jsx("div",{className:"shrink-0 mb-2",children:e.jsxs("button",{onClick:()=>j("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(Za,{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:V?e.jsx("div",{className:"space-y-3",children:V.columns.map((_,Q)=>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"})]},Q))}):e.jsx("p",{className:"text-slate-500 text-sm",children:"No recent mapping logs to display."})})]})]}),N==="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:()=>j("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(Za,{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:()=>j("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:ce,disabled:Me,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:Me?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(ni,{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(ba,{className:"w-4 h-4"})," Click on any field to edit"]}),e.jsxs("span",{children:["Showing ",T.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:T.map((_,Q)=>{const q=Ha(_),E=_.name.split(" "),te=E.length>1?`${E[0][0]}${E[E.length-1][0]}`.toUpperCase():_.name.substring(0,2).toUpperCase(),de=["bg-[#be185d]","bg-[#3b82f6]","bg-[#f43f5e]","bg-[#2563eb]","bg-[#059669]","bg-[#d946ef]"],xe=de[Q%de.length],oe=(_.avgScore??0)>=75?"text-emerald-500":(_.avgScore??0)>=60?"text-orange-500":"text-rose-500";let fe="bg-slate-50 text-slate-600 border-slate-200";const qe=(_.riskLevel||"").toLowerCase();return qe==="low"?fe="bg-emerald-50 text-emerald-600 border-emerald-200":qe==="high"?fe="bg-rose-50 text-rose-600 border-rose-200":qe==="medium"&&(fe="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 ${xe} text-white flex items-center justify-center font-bold text-[12px] shrink-0`,children:te}),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:G[q]?.grade||_.grade||"",onChange:Fe=>H(Pe=>({...Pe,[q]:{...Pe[q],grade:Fe.target.value}})),readOnly:P!==q,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${P===q?"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:G[q]?.section||_.section||"",onChange:Fe=>H(Pe=>({...Pe,[q]:{...Pe[q],section:Fe.target.value}})),readOnly:P!==q,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${P===q?"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:`${oe} 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 ${fe}`,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:()=>re(P===q?null:q),className:`w-8 h-8 rounded-full flex items-center justify-center transition-colors ${P===q?"bg-purple-100 text-purple-600":"hover:bg-slate-200 text-slate-400"}`,children:e.jsx(ci,{className:"w-4 h-4"})})})]},q)})})]})})]})]})]})})}const Qa="ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789",Qo="school.mathpulse.local";function Go(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(""),[f,p]=u.useState(!1),[g,S]=u.useState(null),[N,j]=u.useState(null),[h,w]=u.useState(!1);u.useEffect(()=>{t&&(S(null),w(!1),p(!1),j(null),c((a?.email||ix(a)).trim()),m(Go()))},[t,a]);const C=u.useMemo(()=>a?[a.grade,a.section].filter(Boolean).join(" · ")||"Unassigned section":null,[a]),M=()=>{m(Go()),w(!1)},k=async()=>{try{const y=N?.temporaryPassword||d;if(!y)return;typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(y),w(!0),me.success("Temporary password copied. Share it with the student now — it will not be shown again."),window.setTimeout(()=>w(!1),2500)}catch(y){console.warn("Clipboard write failed:",y),me.error("Unable to copy password. Please copy it manually.")}},W=async()=>{if(!a)return;const y=l.trim();if(!lx(y)){S("Enter a valid email address before creating the account.");return}if(!d||d.length<8){S("Temporary password must be at least 8 characters.");return}if(!r){S("Missing teacher context. Please refresh and try again.");return}p(!0),S(null);try{const v=await Nm({name:a.name,lrn:a.lrn,email:y,grade:a.grade,section:a.section,classSectionId:a.classSectionId,adviserTeacherId:r,adviserTeacherName:o,schoolYear:n,temporaryPassword:d});j(v),i?.({...v,rosterId:a.rosterId}),me.success(`Account created for ${a.name}.`)}catch(v){const z=v instanceof Error?v.message:"Failed to create account.";S(z)}finally{p(!1)}},b=N?.temporaryPassword||d;return e.jsx(Mt,{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:()=>{f||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:y=>y.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(Ko,{size:22})}),e.jsxs("div",{children:[e.jsx("h2",{id:"create-student-account-modal-title",className:"text-[16px] font-bold text-[#0a1628]",children:N?"Account Created":"Create Student Account"}),e.jsx("p",{className:"text-[12px] text-[#5a6578] mt-0.5",children:N?"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:()=>{f||s()},className:"p-1.5 rounded-lg hover:bg-[#dde3eb] transition-colors","aria-label":"Close",children:e.jsx(ds,{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} · `:"",C]})]}),!N&&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:y=>c(y.target.value),disabled:f,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:M,disabled:f,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(Ls,{className:"w-4 h-4 text-[#475569]"})}),e.jsx("button",{type:"button",onClick:k,className:"p-2 rounded-xl border border-[#dde3eb] bg-white hover:bg-[#f1f5f9] transition-colors","aria-label":"Copy temporary password",children:h?e.jsx(Ot,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Dr,{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."})]}),g&&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:g})]})]}),N&&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:N.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:b}),e.jsx("button",{type:"button",onClick:k,className:"p-1.5 rounded-lg border border-emerald-200 bg-white hover:bg-emerald-100 transition-colors","aria-label":"Copy temporary password",children:h?e.jsx(Ot,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Dr,{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:N?e.jsx(ht,{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(ht,{type:"button",variant:"ghost",onClick:s,disabled:f,className:"text-[13px] font-semibold text-[#475569] rounded-xl px-4 py-2 hover:bg-[#dde3eb]",children:"Cancel"}),e.jsx(ht,{type:"button",onClick:W,disabled:f,className:"bg-indigo-600 hover:bg-indigo-700 text-white text-[13px] font-semibold rounded-xl px-5 py-2 disabled:opacity-60",children:f?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4 animate-spin"}),"Creating…"]}):"Create account"})]})})]})})})};function dx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=bt({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 Mr(t,s){const a=t.riskLevel.toLowerCase(),r=t.lastActive?nl(t.lastActive.toDate()):"Unknown",o=t.className||s||"Imported Class",n=cs(o),i=t.grade||n.grade,l=t.section||n.section,c=bt({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,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||xs(i)||void 0,classification:c.classification||aa(c.gradeLevel||i)||void 0,strand:c.strand||ra(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 mx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=bt({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 ux(t){const s=(t.riskLevel||"Low").toLowerCase(),a=bt({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||cs(r).grade,gradeLevel:a.gradeLevel||xs(a.grade||cs(r).grade)||void 0,classification:a.classification||aa(a.gradeLevel||a.grade)||void 0,strand:a.strand||ra(r,a.section||t.section)||void 0,section:a.section||cs(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 xx(t,s,a){return t<60||s<75||a<55?"high":t<75||s<85||a<70?"medium":"low"}function px(t,s,a,r){const o=bt({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),f=t.unknownFields?.weakestTopic||t.unknownFields?.topic||"Foundational Skills",p=xx(l,c,d),g=t.studentId||t.lrn||t.email||t.name||Math.random().toString(36).slice(2);return{id:`upload-${i}-${g}`,lrn:t.lrn,name:t.name,avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:l,riskLevel:p,weakestTopic:f,classroomId:i,className:n,grade:o.grade||cs(n).grade,gradeLevel:o.gradeLevel||xs(o.grade||cs(n).grade)||void 0,classification:o.classification||aa(o.gradeLevel||o.grade)||void 0,strand:o.strand||ra(n,o.section)||void 0,section:o.section||cs(n).section,classSectionId:i,classMetadata:o,managerId:o.managerId||void 0,managerName:o.managerName||void 0,lastActive:"Recently imported",struggles:[f],engagementScore:d,attendance:c,assignmentCompletion:m}}function nl(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 rt(t){return(t||"").trim().toLowerCase()}function Uo(t){const s=rt(t.classSectionId);if(s)return`section:${s}`;const a=(t.id||"").trim().toLowerCase();return a?`id:${a}`:`name:${(t.name||"").trim().toLowerCase()}`}function Vo(t,s){const a=new Map;return t.forEach(r=>{a.set(Uo(r),r)}),s.forEach(r=>{const o=Uo(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=bt({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 ir(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=rt(t.classSectionId)||rt(t.classroomId),o=(t.id||"").trim().toLowerCase();return r&&o?`${r}|id:${o}`:`${r}|anonymous`}function Wr(t){const s=rt(t.classSectionId)||rt(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 Wo(t,s){const a=new Map;return t.forEach(r=>{a.set(ir(r),r)}),s.forEach(r=>{const o=ir(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=bt({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 fp=({onLogout:t,onOpenProfile:s,onOpenSettings:a})=>{const{currentUser:r,userProfile:o}=ms(),[n,i]=u.useState("dashboard"),[l,c]=u.useState(!1),[d,m]=u.useState(!1),[f,p]=u.useState(!1),[g,S]=u.useState(!1),[N,j]=u.useState(!1),[h,w]=u.useState(!1),[C,M]=u.useState(!1),k=["streak_reminder","daily_checkin","streak_milestone","achievement_unlocked","level_up","xp_earned","quiz_result"],{notifications:W}=ei(),b=W.filter(R=>!R.isRead&&!k.includes(R.type)).length,[y,v]=u.useState(null),[z,F]=u.useState(null),[I,V]=u.useState(!1),[Y,se]=u.useState(!1),[ie,ae]=u.useState(!1),[he,we]=u.useState(!1),[O,J]=u.useState([]),[A,Z]=u.useState([]),[ne,$e]=u.useState([]),[Me,We]=u.useState(""),[P,re]=u.useState(!0),[T,G]=u.useState(!1),[H,ce]=u.useState(0),[_,Q]=u.useState([]),[q,E]=u.useState(!1),[te,de]=u.useState(null),[xe,oe]=u.useState(null),fe=o?.name||"Teacher",qe=u.useRef(new Map);u.useEffect(()=>{const R=()=>S(window.innerWidth<1024);return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]),u.useEffect(()=>{if(!r)return;const R=r.uid;let ee=!0,ze;return(async()=>{re(!0);try{const Ge=await Wi(R);let je=Ge.map(dx);const gt=await ym(R).catch(()=>[]),nt=new Map;gt.forEach(L=>{const K=rt(L.classSectionId);K&&nt.set(K,L)}),je=je.map(L=>{const K=nt.get(rt(L.classSectionId));if(!K)return L;const ke=bt({metadata:L.classMetadata,classSectionId:K.classSectionId||L.classSectionId,className:K.className||L.name,grade:K.grade||L.classMetadata?.grade,gradeLevel:K.gradeLevel||L.classMetadata?.gradeLevel,classification:K.classification||L.classMetadata?.classification,strand:K.strand||L.classMetadata?.strand,section:K.section||L.classMetadata?.section,schoolYear:K.schoolYear||L.classMetadata?.schoolYear,ownerTeacherId:K.ownerTeacherId||L.classMetadata?.ownerTeacherId,ownerTeacherName:K.ownerTeacherName||L.classMetadata?.ownerTeacherName,managerId:K.managerId||L.classMetadata?.managerId,managerName:K.managerName||L.classMetadata?.managerName});return{...L,name:ke.className||L.name,classSectionId:ke.classSectionId||L.classSectionId,classMetadata:ke,gradeLevel:ke.gradeLevel||L.gradeLevel,classification:ke.classification||L.classification,strand:ke.strand||L.strand,managerId:ke.managerId||L.managerId,managerName:ke.managerName||L.managerName}});const Ce=new Map,ps=new Map;Ge.forEach(L=>{const K=bt({metadata:L.classMetadata,classSectionId:L.classSectionId,className:L.name,grade:L.grade,gradeLevel:L.gradeLevel,classification:L.classification,strand:L.strand,section:L.section,schoolYear:L.schoolYear,ownerTeacherId:L.ownerTeacherId||L.teacherId,ownerTeacherName:L.ownerTeacherName,adviserTeacherId:L.adviserTeacherId||L.teacherId,adviserTeacherName:L.adviserTeacherName,managerId:L.managerId,managerName:L.managerName});Ce.set(L.id,K.className||L.name),ps.set(L.id,K);const ke=rt(L.classSectionId);if(ke){const _e=nt.get(ke),Qt=bt({metadata:K,classSectionId:_e?.classSectionId||ke,className:_e?.className||K.className,grade:_e?.grade||K.grade,gradeLevel:_e?.gradeLevel||K.gradeLevel,classification:_e?.classification||K.classification,strand:_e?.strand||K.strand,section:_e?.section||K.section,schoolYear:_e?.schoolYear||K.schoolYear,ownerTeacherId:_e?.ownerTeacherId||K.ownerTeacherId,ownerTeacherName:_e?.ownerTeacherName||K.ownerTeacherName,managerId:_e?.managerId||K.managerId,managerName:_e?.managerName||K.managerName});Ce.set(ke,Qt.className||L.name),ps.set(ke,Qt)}});const Xt=L=>{const K=rt(L.classSectionId||L.classroomId);if(!K)return L;const ke=ps.get(K);if(!ke)return L;const _e=bt({metadata:ke,classSectionId:L.classSectionId||ke.classSectionId,className:L.className||ke.className,grade:L.grade||ke.grade,gradeLevel:L.gradeLevel||ke.gradeLevel,classification:L.classification||ke.classification,strand:L.strand||ke.strand,section:L.section||ke.section,managerId:L.managerId||ke.managerId,managerName:L.managerName||ke.managerName});return{...L,className:_e.className||L.className,grade:_e.grade||L.grade,gradeLevel:_e.gradeLevel||L.gradeLevel,classification:_e.classification||L.classification,strand:_e.strand||L.strand,section:_e.section||L.section,classSectionId:_e.classSectionId||L.classSectionId,classMetadata:_e,managerId:_e.managerId||L.managerId,managerName:_e.managerName||L.managerName}},Ms=(L,K,ke)=>Ce.get(L)||(K?Ce.get(K):void 0)||ke||"Unknown",La=Array.from(new Set([...gt.map(L=>L.classSectionId),...Ge.map(L=>L.classSectionId).filter(Boolean),...je.map(L=>L.classSectionId).filter(Boolean)].map(L=>(L||"").trim()).filter(L=>!!L))),[Jt,na]=await Promise.all([dn(R).catch(L=>(console.warn("[TeacherDashboard] managed-student fetch failed:",L),[])),bm(R,La).catch(L=>(console.warn("[TeacherDashboard] registered-student fetch failed:",L),[]))]);let oa=na;if(na.length===0&&Jt.length===0)try{const{collection:L,query:K,where:ke,getDocs:_e}=await Ar(async()=>{const{collection:Rt,query:He,where:ma,getDocs:ua}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{collection:Rt,query:He,where:ma,getDocs:ua}},__vite__mapDeps([2,3])),{db:Qt}=await Ar(async()=>{const{db:Rt}=await import("./index-BYG24j30.js").then(He=>He.b5);return{db:Rt}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),Ee=K(L(Qt,"users"),ke("role","==","student"));oa=(await _e(Ee)).docs.map(Rt=>{const He=Rt.data();return{uid:Rt.id,name:String(He.name||He.displayName||"").trim()||"Student",email:String(He.email||"").trim(),lrn:He.lrn?String(He.lrn).trim():void 0,photo:He.photo?String(He.photo).trim():He.photoURL?String(He.photoURL).trim():void 0,grade:He.grade?String(He.grade).trim():void 0,section:He.section?String(He.section).trim():void 0,classSectionId:He.classSectionId?String(He.classSectionId).trim():void 0,adviserTeacherId:He.adviserTeacherId?String(He.adviserTeacherId).trim():void 0,role:"student",createdAt:He.createdAt||void 0}}).filter(Rt=>Rt.name!=="Student"||Rt.email)}catch(L){console.warn("[TeacherDashboard] fallback all-students fetch failed:",L)}const hs=new Map,ia=new Map,la=new Map;Jt.forEach(L=>{hs.set(L.id,L),L.lrn&&ia.set(L.lrn.trim().toLowerCase(),L);const K=No(L.name),ke=rt(L.classSectionId||L.classroomId);K&&la.set(`${K}|${ke}`,L)});const Qs=new Set,pr=oa.map(L=>{const K=vm(L),ke=(L.lrn||"").trim().toLowerCase(),_e=No(L.name),Qt=rt(L.classSectionId);let Ee;if(hs.has(L.uid))Ee=hs.get(L.uid);else if(ke&&ia.has(ke))Ee=ia.get(ke);else if(_e){const He=`${_e}|${Qt}`;Ee=la.get(He)}if(Ee){Qs.add(Ee.id);const He={...K,id:L.uid,accountUid:L.uid,email:K.email||Ee.email,lrn:K.lrn||Ee.lrn,name:K.name||Ee.name,avatar:K.avatar||Ee.avatar,riskLevel:Ee.riskLevel||K.riskLevel,avgQuizScore:Ee.avgQuizScore||K.avgQuizScore,engagementScore:Ee.engagementScore||K.engagementScore,attendance:Ee.attendance||K.attendance,assignmentCompletion:Ee.assignmentCompletion||K.assignmentCompletion,weakestTopic:Ee.weakestTopic||K.weakestTopic,struggles:Ee.struggles||K.struggles,lastActive:Ee.lastActive||K.lastActive,wri:Ee.wri??null,riskStatus:Ee.riskStatus??null,riskUpdatedAt:Ee.riskUpdatedAt??null,diagnosticScore:Ee.diagnosticScore??null,externalGradesAvg:Ee.externalGradesAvg??null,systemPerformanceAvg:Ee.systemPerformanceAvg??null,riskHistory:Ee.riskHistory,grade:K.grade||Ee.grade,gradeLevel:K.gradeLevel||Ee.gradeLevel,section:K.section||Ee.section,classSectionId:K.classSectionId||Ee.classSectionId,classroomId:K.classroomId||Ee.classroomId,classMetadata:Ee.classMetadata||K.classMetadata,hasRegisteredAccount:!0,source:"both"},ma=rt(He.classSectionId||He.classroomId),ua=Ms(He.classroomId||"",ma,He.className);return Xt(Mr(He,ua))}const Gs=rt(K.classSectionId||K.classroomId),Rt=Ms(K.classroomId||"",Gs,K.className);return Xt(Mr(K,Rt))}),hr=Jt.filter(L=>!Qs.has(L.id)).map(L=>{const K={...L,hasRegisteredAccount:!1,source:"import"},ke=rt(K.classSectionId||K.classroomId),_e=Ms(K.classroomId,ke,K.className);return Xt(Mr(K,_e))}),ca=[...pr,...hr];if(!ee)return;J(L=>je.length===0&&L.length>0?L:je),Z(L=>ca.length===0&&L.length>0?L:ca),it.getImportedClassOverview({limit:3e3,forceRefresh:H>0}).then(L=>{ee&&(L.warnings.length>0&&console.warn("Imported class overview warnings:",L.warnings.join(" ")),J(K=>Vo(K,L.classrooms.map(mx))),Z(K=>{if(K.length===0)return K;const ke=L.students.map(ux),_e=new Set;K.forEach(Ee=>_e.add(ir(Ee)));const Qt=ke.filter(Ee=>_e.has(ir(Ee)));return Qt.length===0?K:Wo(K,Qt)}))}).catch(L=>{console.warn("Imported class overview merge unavailable:",L)});const da=Ge.map(L=>L.id);da.length>0&&(ze=km(da,L=>{ee&&$e(L.map(K=>({id:K.id,student:K.studentName,action:K.action,topic:K.topic,time:nl(K.timestamp.toDate()),type:K.type})))}))}catch(Ge){console.error("Failed to load teacher data:",Ge),me.error("Failed to load dashboard data")}finally{re(!1)}})(),()=>{ee=!1,ze&&ze()}},[r,H]),u.useEffect(()=>{if(!r)return;let R=!0;return Sm("",80).then(ee=>{R&&Q(ee)}).catch(ee=>{console.warn("Failed to load teacher directory options:",ee)}),()=>{R=!1}},[r]),u.useEffect(()=>{if(A.length===0)return;(async()=>{if(A.length===0){We("");return}G(!0);try{const ee=A.map(Ne=>({name:Ne.name,engagementScore:Ne.engagementScore,avgQuizScore:Ne.avgScore,attendance:Ne.attendance,riskLevel:Ne.riskLevel})),ze=await it.getDailyInsight({students:ee});We(ze.insight)}catch{We(`${A.filter(ee=>ee.riskLevel==="high").length} students are at high risk of falling behind. Review their progress in the analytics view.`)}finally{G(!1)}})()},[A]);const Fe=O.reduce((R,ee)=>R+ee.studentCount,0),Pe=O.reduce((R,ee)=>R+ee.atRiskCount,0),tt=O.length>0?Math.round(O.reduce((R,ee)=>R+ee.avgScore,0)/O.length):0,Tt=[{name:"High Risk",value:A.filter(R=>R.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:A.filter(R=>R.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:A.filter(R=>R.riskLevel==="low").length,color:"#75D06A"}],dt={};A.forEach(R=>{R.weakestTopic&&R.weakestTopic!=="N/A"&&(dt[R.weakestTopic]||(dt[R.weakestTopic]={total:0,sum:0}),dt[R.weakestTopic].total+=1,dt[R.weakestTopic].sum+=R.avgScore)});const wt=Object.entries(dt).map(([R,ee])=>({topic:R,score:Math.round(ee.sum/ee.total)})).sort((R,ee)=>R.score-ee.score).slice(0,6),Lt=R=>{v(R),i("analytics")},B=R=>{F(R),i("intervention")},Ae=()=>{F(null),i("analytics")},Xe=()=>{v(null),F(null),i("dashboard")},Nt=async(R,ee)=>{if(!r){me.error("Unable to assign manager: teacher context is missing.");return}const ze=cs(R.classMetadata?.className||R.name),Ne=bt({metadata:R.classMetadata,classSectionId:R.classSectionId,className:R.name,grade:R.classMetadata?.grade||ze.grade,gradeLevel:R.classMetadata?.gradeLevel,classification:R.classMetadata?.classification,strand:R.classMetadata?.strand,section:R.classMetadata?.section||ze.section,schoolYear:R.classMetadata?.schoolYear||String(new Date().getFullYear()),ownerTeacherId:R.classMetadata?.ownerTeacherId||r.uid,ownerTeacherName:R.classMetadata?.ownerTeacherName||fe,adviserTeacherId:R.classMetadata?.adviserTeacherId||r.uid,adviserTeacherName:R.classMetadata?.adviserTeacherName||fe,managerId:ee.uid,managerName:ee.name}),Ge=Ne.classSectionId||Ht(Ne.grade||ze.grade,Ne.section||ze.section);if(!Ge){me.error("Unable to assign manager: missing class section ID.");return}E(!0);try{await qi({classSectionId:Ge,className:Ne.className||R.name,grade:Ne.grade||ze.grade,gradeLevel:Ne.gradeLevel||xs(Ne.grade||ze.grade)||Ne.grade||ze.grade,classification:Ne.classification||aa(Ne.gradeLevel||Ne.grade)||void 0,strand:Ne.strand||ra(Ne.className,Ne.section)||void 0,section:Ne.section||ze.section,schoolYear:Ne.schoolYear||String(new Date().getFullYear()),ownerTeacherId:Ne.ownerTeacherId||r.uid,ownerTeacherName:Ne.ownerTeacherName||fe,managerId:ee.uid,managerName:ee.name});const je=bt({metadata:Ne,classSectionId:Ge,managerId:ee.uid,managerName:ee.name}),gt=rt(Ge);J(nt=>nt.map(Ce=>rt(Ce.classSectionId)!==gt?Ce:{...Ce,name:je.className||Ce.name,classSectionId:je.classSectionId||Ce.classSectionId,classMetadata:je,gradeLevel:je.gradeLevel||Ce.gradeLevel,classification:je.classification||Ce.classification,strand:je.strand||Ce.strand,managerId:ee.uid,managerName:ee.name})),Z(nt=>nt.map(Ce=>{if(rt(Ce.classSectionId||Ce.classroomId)!==gt)return Ce;const Xt=bt({metadata:Ce.classMetadata,classSectionId:je.classSectionId||Ce.classSectionId,className:Ce.className||je.className,grade:Ce.grade||je.grade,gradeLevel:Ce.gradeLevel||je.gradeLevel,classification:Ce.classification||je.classification,strand:Ce.strand||je.strand,section:Ce.section||je.section,managerId:ee.uid,managerName:ee.name});return{...Ce,classMetadata:Xt,gradeLevel:Xt.gradeLevel||Ce.gradeLevel,classification:Xt.classification||Ce.classification,strand:Xt.strand||Ce.strand,managerId:ee.uid,managerName:ee.name}})),v(nt=>!nt||rt(nt.classSectionId)!==gt?nt:{...nt,classMetadata:je,managerId:ee.uid,managerName:ee.name,gradeLevel:je.gradeLevel||nt.gradeLevel,classification:je.classification||nt.classification,strand:je.strand||nt.strand}),me.success(`Assigned ${ee.name} as section manager.`)}catch(je){console.error("Failed to assign class manager:",je),me.error(je instanceof Error?je.message:"Failed to assign class manager")}finally{E(!1)}},Kt=u.useCallback(R=>{de({rosterId:R.id,name:R.name,lrn:R.lrn,email:R.email,grade:R.grade,section:R.section,classSectionId:R.classSectionId})},[]),Et=u.useCallback(R=>{Z(ee=>ee.map(ze=>ze.id===R.rosterId?{...ze,hasRegisteredAccount:!0,source:"both",accountUid:R.uid,email:R.email||ze.email}:ze)),ce(ee=>ee+1)},[]),Dt=u.useCallback(async(R,ee)=>{if(!r){me.error("Cannot reassign section without an authenticated teacher.");return}const ze=r.uid,Ne=(ee.classSectionId||"").trim();if(!Ne){me.error("Pick a target section first.");return}oe(R.id);try{await wm({studentId:R.accountUid||R.id,isRegisteredAccount:!!R.hasRegisteredAccount,newClassSectionId:Ne,newGrade:ee.grade,newSection:ee.section,previousClassSectionId:R.classSectionId,teacherId:ze,teacherName:fe,schoolYear:R.classMetadata?.schoolYear||String(new Date().getFullYear())}),Z(Ge=>Ge.map(je=>{if(je.id!==R.id)return je;const gt=bt({metadata:je.classMetadata,classSectionId:Ne,className:je.className,grade:ee.grade,section:ee.section});return{...je,grade:ee.grade,section:ee.section,classSectionId:Ne,classroomId:Ne,classMetadata:gt}})),me.success(`Moved ${R.name} to ${ee.grade} - ${ee.section}.`)}catch(Ge){console.error("Section reassignment failed:",Ge),me.error(Ge instanceof Error?Ge.message:"Failed to reassign section.")}finally{oe(null)}},[r,fe]);u.useEffect(()=>{const R=()=>{const ee=window.innerWidth<1024;S(ee),ee?c(!1):p(!1)};return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]),u.useEffect(()=>{g&&p(!1)},[n,g]);const $t=R=>{i(R),v(null),F(null)},_s=u.useMemo(()=>{if(!y)return;if(y.classMetadata?.classSectionId)return y.classMetadata.classSectionId||void 0;if(y.classSectionId)return y.classSectionId;const R=cs(y.classMetadata?.className||y.name);return Ht(R.grade,R.section)||void 0},[y]),at=u.useMemo(()=>y||null,[y]),za=u.useMemo(()=>{if(!at)return;const R=O.findIndex(ee=>ee.id===at.id);return nr[Math.max(0,R)%nr.length]},[at,O]),Ft=u.useMemo(()=>{if(!at)return A;const R=(at.id||"").trim().toLowerCase(),ee=rt(at.classSectionId),ze=(at.name||"").trim().toLowerCase();return A.filter(Ne=>{const Ge=rt(Ne.classroomId),je=rt(Ne.classSectionId),gt=(Ne.className||"").trim().toLowerCase();return ee&&(je===ee||Ge===ee)||R&&(Ge===R||je===R)||ze&>===ze})},[at,A]);return P?e.jsx(yl,{message:"Loading dashboard..."}):e.jsxs("div",{className:"relative flex h-screen w-full bg-background overflow-hidden",children:[g&&f&&e.jsx("button",{"aria-label":"Close navigation",className:"fixed inset-0 z-30 bg-slate-900/40 backdrop-blur-[1px]",onClick:()=>p(!1)}),e.jsxs(Re.aside,{initial:!1,animate:{width:g?280:l&&!d?80:280,x:g?f?0:-300:0},transition:{type:"spring",stiffness:360,damping:34},onMouseEnter:()=>!g&&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"})})]}),!g&&(!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(Ss,{size:20}):e.jsx(ks,{size:20})}),g&&e.jsx("button",{onClick:()=>p(!1),className:"p-2 hover:bg-[#dde3eb] rounded-lg transition-colors text-[#5a6578]","aria-label":"Close navigation",children:e.jsx(ds,{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(ys,{icon:zl,label:"Dashboard",active:n==="dashboard",collapsed:l&&!d,onClick:Xe,forceExpanded:g}),e.jsx(ys,{icon:$s,label:"Class Analytics",active:n==="analytics"||n==="intervention",collapsed:l&&!d,onClick:()=>$t("analytics"),forceExpanded:g})]})]}),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(ys,{icon:Ns,label:"Topic Mastery",active:n==="topic_mastery",collapsed:l&&!d,onClick:()=>$t("topic_mastery"),forceExpanded:g}),e.jsx(ys,{icon:is,label:"Competency",active:n==="competency",collapsed:l&&!d,onClick:()=>$t("competency"),forceExpanded:g})]})]}),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(ys,{icon:Ll,label:"Data Import",active:n==="import",collapsed:l&&!d,onClick:()=>i("import"),forceExpanded:g}),e.jsx(ys,{icon:ii,label:"AI Quiz Maker",active:n==="quiz_maker",collapsed:l&&!d,onClick:()=>i("quiz_maker"),forceExpanded:g}),e.jsx(ys,{icon:Vt,label:"Question Bank",active:n==="question_bank",collapsed:l&&!d,onClick:()=>i("question_bank"),forceExpanded:g}),e.jsx(ys,{icon:Ka,label:"Calendar",active:n==="calendar",collapsed:l&&!d,onClick:()=>i("calendar"),forceExpanded:g})]})]})]}),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(Dl,{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($l,{onClick:()=>j(!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:[g&&e.jsx("button",{onClick:()=>p(!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(Sl,{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, ${fe}`,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(is,{size:13,className:"text-[#9956DE]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#9956DE]",children:[Fe," 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(Js,{size:13,className:"text-[#F08386]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#C65E63]",children:[Pe," 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(Ea,{size:13,className:"text-[#75D06A]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#4D9F46]",children:[tt,"% avg"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:()=>{se(!0),V(!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(Fs,{size:18}),!I&&Me&&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"})]}),g&&n==="dashboard"&&e.jsx("button",{onClick:()=>we(R=>!R),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] ${he?"bg-[#818cf8] border-[#6366f1] text-white":"bg-white/60 hover:bg-white/80 border-white/50 text-[#64748b] hover:text-[#1e293b]"}`,"aria-label":he?"Close calendar panel":"Open calendar panel",title:he?"Close calendar":"View calendar",children:e.jsx(Ka,{size:18})}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>ae(!ie),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(er,{size:18}),b>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(Ml,{isOpen:ie,onClose:()=>ae(!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(fe)}&background=e0e7ff&color=4f46e5`,alt:"Profile",className:"w-full h-full object-cover"})}),e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:fe})]})]})]})}),e.jsx("main",{className:`flex-1 flex flex-col ${n==="intervention"||n==="analytics"?"overflow-hidden":"overflow-y-auto"}`,children:e.jsxs(Mt,{mode:"wait",children:[n==="dashboard"&&e.jsx(fx,{classes:O,liveActivity:ne,onViewClass:Lt,onViewAllClasses:()=>i("analytics"),onViewActivityStudent:R=>{const ee=A.find(ze=>ze.name===R);ee&&B(ee)},dailyInsight:Me,insightLoading:T,isInsightDismissed:I,onDismissInsight:()=>V(!0),onOpenInsightModal:()=>{se(!0),V(!0)},totalStudents:Fe,totalAtRisk:Pe,avgPerformance:tt,onCreateClass:()=>w(!0)}),n==="analytics"&&at&&e.jsx(vx,{selectedClass:at,students:Ft,allClasses:O,riskDistribution:Tt,topicPerformance:wt,onViewStudent:B,onCreateAccount:Kt,onReassignSection:Dt,reassignBusyId:xe,onBack:()=>v(null),teacherOptions:_,managerUpdating:q,onAssignManager:R=>Nt(at,R),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,classColor:za,insightDismissed:I,onOpenInsightModal:()=>se(!0),onAddStudents:()=>M(!0)}),n==="analytics"&&!at&&O.length>0&&e.jsx(zo,{classes:O,onSelectClass:Lt,onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:I,onOpenInsightModal:()=>se(!0),onCreateClass:()=>w(!0)}),n==="analytics"&&!at&&O.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($s,{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(ht,{onClick:()=>w(!0),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(Zs,{size:16,className:"mr-1.5"}),"Create Class"]})]})}),n==="intervention"&&z&&e.jsx(wx,{student:z,teacherId:r?.uid||"",teacherName:fe,initialCache:qe.current.get(z.id),onCacheUpdate:(R,ee)=>qe.current.set(R,ee),onStudentUpdated:R=>{const ee=z?Wr(z):null;F(R),Z(ze=>ze.map(Ne=>{const Ge=Wr(Ne),je=ee?Ge===ee:!1,gt=Ne.id===R.id&&rt(Ne.classSectionId)===rt(R.classSectionId);return je||gt?R:Ne}))},onBack:Ae,onNavigateToQuizMaker:R=>{i("quiz_maker"),R&&sessionStorage.setItem("quizMakerInitialTab",R)}}),n==="topic_mastery"&&e.jsx(Qm,{classSectionId:_s,onOpenNotifications:()=>i("notifications"),onOpenProfile:s}),n==="competency"&&at&&e.jsx(Wm,{classSectionId:_s,className:y?.name,fallbackStudents:A,onBack:()=>v(null),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:I,onOpenInsightModal:()=>se(!0)}),n==="competency"&&!at&&O.length>0&&e.jsx(zo,{classes:O,onSelectClass:R=>v(R),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:I,onOpenInsightModal:()=>se(!0),viewType:"competency"}),n==="competency"&&!at&&O.length===0&&e.jsx(hx,{icon:is,title:"Student Competency",description:"No classes available yet. Import class records to view competency breakdowns."}),n==="import"&&e.jsx(ox,{classSectionId:_s,className:y?.name,classMetadata:y?.classMetadata,students:A,classes:O.map(R=>({id:R.id,name:R.name,classSectionId:R.classSectionId})),teacherId:r?.uid||"",teacherName:fe,onStudentsUpdated:R=>Z(R),onBackToClasses:()=>i("dashboard"),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),V(!0)},userPhoto:o?.photo,onImportedClassRecords:R=>{const ee=R.students.map(Ce=>px(Ce,R.classSectionId,R.className,R.classMetadata)),ze=bt({metadata:R.classMetadata,classSectionId:R.classSectionId,className:R.className}),Ne=ze.classSectionId||"imported_class",Ge=ze.className||"Imported Class",je=ee.filter(Ce=>Ce.riskLevel==="high").length,gt=ee.length>0?Math.round(ee.reduce((Ce,ps)=>Ce+ps.avgScore,0)/ee.length):0,nt={id:Ne,name:Ge,classSectionId:Ne,classMetadata:{...ze,classSectionId:Ne,className:Ge},schedule:"Mon-Fri",studentCount:ee.length,avgScore:gt,atRiskCount:je,riskLevel:je>=5?"high":je>=2?"medium":"low"};Z(Ce=>Wo(Ce,ee)),J(Ce=>Vo(Ce,[nt]))},onDataChanged:()=>ce(R=>R+1)}),n==="notifications"&&e.jsx(Ym,{liveActivity:ne,atRiskStudents:A.filter(R=>R.riskLevel==="high").map(R=>({name:R.name,riskLevel:R.riskLevel,weakestTopic:R.weakestTopic})),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),V(!0)},userPhoto:o?.photo,teacherName:fe}),n==="calendar"&&e.jsx(cu,{classes:O,teacherId:r?.uid}),n==="quiz_maker"&&e.jsx(Yi,{onBack:()=>{const R=sessionStorage.getItem("quizMakerReturnTo");sessionStorage.removeItem("quizMakerReturnTo"),sessionStorage.removeItem("quizMakerInitialTab"),i(R==="intervention"?"intervention":"dashboard")},onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),V(!0)},userPhoto:o?.photo,teacherName:fe}),n==="question_bank"&&e.jsx(Pm,{onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),V(!0)},userPhoto:o?.photo,teacherName:fe})]})})]}),n==="dashboard"&&!g&&e.jsx(Yo,{onViewCalendar:()=>i("calendar"),onOpenProfile:s,userProfile:o,teacherName:fe,liveActivity:ne})]}),e.jsx(Mt,{children:g&&n==="dashboard"&&he&&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:()=>we(!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(Yo,{onViewCalendar:()=>{i("calendar"),we(!1)},onOpenProfile:()=>{s?.(),we(!1)},userProfile:o,teacherName:fe,liveActivity:ne})},"cal-drawer")]})}),e.jsx(Mt,{children:Y&&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(Fs,{size:16})}),e.jsx("h3",{className:"font-semibold text-slate-800",children:"Detailed AI Insight"})]}),e.jsx("button",{onClick:()=>{se(!1)},className:"p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(ds,{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:Me?.replace(/[*_]*\s*\(?Word\s*count\s*:\s*[*_]*\s*\d+\)?\s*[*_]*/gi,"").trim()||`**${Pe} students (${Fe>0?Math.round(Pe/Fe*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:()=>{se(!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(Tl,{isOpen:N,onClose:()=>j(!1),onConfirm:t,title:"Logout",message:"Are you sure you want to logout?",confirmText:"Logout",cancelText:"Cancel"}),e.jsx(Cm,{open:h,onClose:()=>w(!1),onCreated:()=>ce(R=>R+1),teacherName:fe}),e.jsx(Im,{open:C,onClose:()=>M(!1),onAdded:()=>ce(R=>R+1),grade:at?.gradeLevel||at?.classMetadata?.grade||"Grade 11",section:at?.classMetadata?.section||at?.name?.split(" - ")[1]||"",teacherName:fe,existingStudentUids:Ft.map(R=>R.id)}),e.jsx(cx,{isOpen:!!te,onClose:()=>de(null),seed:te,adviserTeacherId:r?.uid||"",adviserTeacherName:fe,schoolYear:te?A.find(R=>R.id===te.rosterId)?.classMetadata?.schoolYear||String(new Date().getFullYear()):void 0,onCreated:Et})]})},ys=({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}})]}),hx=({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})]})}),fx=({classes:t,liveActivity:s,onViewClass:a,onViewAllClasses:r,onViewActivityStudent:o,dailyInsight:n,insightLoading:i,isInsightDismissed:l,onDismissInsight:c,onOpenInsightModal:d,totalStudents:m,totalAtRisk:f,avgPerformance:p,onCreateClass:g})=>{const S=m>0?Math.round(f/m*100):0,N=m>0?Math.round((m-f)/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(Fs,{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:j=>{j.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:j=>{j.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(is,{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(Ns,{size:15})})]}),e.jsxs("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:"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(si,{size:15})})]}),e.jsxs("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:[N,"%"]}),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(N/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(lr,{size:15})})]}),e.jsx("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:f}),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:[S,"%"]})]})]})]}),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."}),g&&e.jsx("button",{onClick:g,className:"text-sm text-[#9956DE] font-semibold hover:underline",children:"+ Create a class"})]}),t.map((j,h)=>{const w=[{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]"}],C=w[h%w.length];return e.jsxs("div",{onClick:()=>a(j),className:`relative overflow-hidden flex items-center gap-3 p-[12px_13px] pl-[16px] border border-[#f1f5f9] rounded-[14px] cursor-pointer ${C.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] ${C.stripe}`}),e.jsx("div",{className:`w-[38px] h-[38px] rounded-[10px] flex items-center justify-center flex-shrink-0 text-[17px] ${C.bg} ${C.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:j.name}),e.jsx("div",{className:"text-[11px] text-[#94a3b8] mt-[1px]",children:j.classification||"High School"})]}),e.jsx("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[65px]",children:j.schedule||"Mon-Fri"}),e.jsxs("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[85px]",children:[j.studentCount," students"]}),e.jsx("span",{className:`text-[10px] font-semibold px-[9px] py-[3px] rounded-[6px] ${j.riskLevel==="high"?"bg-[#fee2e2] text-[#b91c1c] border border-[#fca5a5]":j.riskLevel==="medium"?"bg-[#fffbeb] text-[#b45309] border border-[#fcd34d]":"bg-[#ecfdf5] text-[#065f46] border border-[#6ee7b7]"}`,children:j.riskLevel==="high"?"High risk":j.riskLevel==="medium"?"Medium risk":"On track"}),e.jsx($r,{size:16,className:"text-[#cbd5e1] ml-auto hover:text-[#64748b]"})]},j.id)})]})]})]})},gx=ue.memo(({student:t,onViewStudent:s,onCreateAccount:a})=>{const o=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"},n=t.hasRegisteredAccount===!1&&t.source==="import",i=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] ${o.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 ${o.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 ${o.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}),i&&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(ea,{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 ${o.badge}`,children:[t.avgScore,"%"]})]}),n&&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:l=>{l.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 ${o.progress}`,style:{width:`${t.avgScore}%`}})})]})}),bx=({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 f=(m.classSectionId||m.id||"").trim();if(!f)return;const p=(m.classMetadata?.grade||"").trim(),g=(m.classMetadata?.section||"").trim();if(!p||!g)return;const S=m.name||`${p} - ${g}`;d.set(f,{classSectionId:f,grade:p,section:g,label:S})}),Array.from(d.values()).sort((m,f)=>m.label.localeCompare(f.label))},[s]),c=u.useMemo(()=>{const d=new Map,m=[];return t.forEach(f=>{const p=(f.classSectionId||"").trim();if(!p){m.push(f);return}const g=f.section||f.className||p,S=d.get(p)||{label:g,students:[]};S.students=[...S.students,f],d.set(p,S)}),{assigned:Array.from(d.entries()).map(([f,p])=>({sectionId:f,...p})).sort((f,p)=>f.label.localeCompare(p.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(_t,{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(qo,{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(qo,{student:d,sectionTargets:l,currentSectionId:a.classSectionId,onReassign:r,isBusy:o===d.id},`section-row-${d.id}`))})]})]})]})},qo=({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"})]})]})},vx=({selectedClass:t,students:s,allClasses:a,riskDistribution:r,topicPerformance:o,onViewStudent:n,onCreateAccount:i,onReassignSection:l,reassignBusyId:c,onBack:d,teacherOptions:m,managerUpdating:f,onAssignManager:p,onOpenNotifications:g,onOpenProfile:S,classColor:N,insightDismissed:j,onOpenInsightModal:h,onAddStudents:w})=>{const{currentUser:C,userProfile:M}=ms(),[k,W]=u.useState(""),[b,y]=u.useState(""),[v,z]=u.useState("All"),F=[{name:"High Risk",value:s.filter(O=>O.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:s.filter(O=>O.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:s.filter(O=>O.riskLevel==="low").length,color:"#75D06A"}];u.useEffect(()=>{y(t.classMetadata?.managerId||t.managerId||"")},[t]);const I=u.useMemo(()=>{const O=k.trim().toLowerCase();let J=s;return O&&(J=J.filter(A=>A.name.toLowerCase().includes(O)||(A.lrn||"").toLowerCase().includes(O)||(A.weakestTopic||"").toLowerCase().includes(O))),v==="Good"?J=J.filter(A=>A.avgScore>=85&&A.riskLevel!=="high"):v==="Risk"&&(J=J.filter(A=>A.riskLevel==="high"||A.avgScore<75)),J},[k,s,v]),V=u.useMemo(()=>{if(s.length===0)return 0;const O=s.reduce((J,A)=>J+(A.assignmentCompletion||0),0);return Math.round(O/s.length)},[s]),Y=u.useMemo(()=>{if(s.length===0)return 0;const O=s.reduce((A,Z)=>A+(Z.attendance||0),0)/s.length,J=s.reduce((A,Z)=>A+(Z.engagementScore||0),0)/s.length;return Math.round(O*.6+J*.4)},[s]),se=u.useMemo(()=>[...s].sort((O,J)=>J.avgScore-O.avgScore).slice(0,5),[s]),ie=u.useMemo(()=>[...s].filter(O=>O.riskLevel==="high"||O.avgScore<70||O.assignmentCompletion<65),[s]),ae=u.useMemo(()=>m.find(O=>O.uid===b),[m,b]),he=()=>{if(!ae){me.error("Select a teacher manager first.");return}p(ae)},we=[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(ks,{className:"w-4 h-4"}),"Back to Classes"]})}),e.jsxs("header",{style:{backgroundColor:N?.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:we.map((O,J)=>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:O},O))}),e.jsxs("p",{className:"text-[13px] text-white/80 font-medium",children:["Manager: ",t.classMetadata?.managerName||t.managerName||"Not assigned"]})]}),e.jsxs("div",{className:"bg-white/10 border border-white/20 rounded-[18px] p-[16px] backdrop-blur-md flex flex-col w-full md:w-auto shrink-0 relative z-10 shadow-inner",children:[e.jsx("label",{className:"text-[11px] font-bold text-white/90 uppercase tracking-wider mb-2 ml-1",children:"Section Manager"}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3",children:[e.jsxs("div",{className:"relative w-full md:w-[320px]",children:[e.jsxs("select",{value:b||"",onChange:O=>y(O.target.value),className:"appearance-none bg-white/20 border border-white/30 text-white text-[13px] font-bold rounded-xl pl-4 pr-10 py-2.5 outline-none focus:border-white/50 focus:ring-2 focus:ring-white/20 w-full shadow-sm cursor-pointer [&>option]:text-[#1e293b]",children:[e.jsx("option",{value:"",children:"Select teacher"}),m.map(O=>e.jsxs("option",{value:O.uid,children:[O.name," (",O.email,")"]},O.uid))]}),e.jsx(_t,{className:"w-4 h-4 text-white/70 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]}),e.jsx("button",{onClick:he,disabled:!b||f,className:"bg-white text-[#6366f1] hover:bg-white/90 text-[13px] font-bold rounded-full px-6 py-2.5 shadow-md transition-transform hover:scale-[1.02] whitespace-nowrap disabled:opacity-50 disabled:hover:scale-100",style:{color:N?.hex||"#6366f1"},children:f?"Updating...":"Assign"})]})]})]}),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(Ns,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[t.avgScore,"%"]})]}),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(Yr,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[V,"%"]})]}),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(is,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Y,"%"]})]}),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(Js,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[ie.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:["(",I.length,")"]})]}),e.jsx("button",{onClick:()=>w?.(),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(Bs,{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:k,onChange:O=>W(O.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:()=>z("All"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${v==="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:()=>z("Good"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${v==="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:()=>z("Risk"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${v==="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(Yd,{style:{height:"100%"},data:I,className:"no-scrollbar",itemContent:(O,J)=>e.jsx("div",{className:"py-[6px] px-[8px]",children:e.jsx(gx,{student:J,onViewStudent:n,onCreateAccount:i})}),computeItemKey:(O,J)=>Wr(J)})})]}),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($r,{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($n,{width:"100%",height:"100%",children:e.jsxs(Fn,{data:F,children:[e.jsx(On,{strokeDasharray:"4 4",stroke:"#f1f5f9",vertical:!1}),e.jsx(Bn,{dataKey:"name",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#475569",fontSize:11,fontWeight:600},dy:10}),e.jsx(Pn,{axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600}}),e.jsx(Hn,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(Qn,{dataKey:"value",radius:[6,6,0,0],barSize:80,children:F.map((O,J)=>{const A={"High Risk":"#f43f5e","Medium Risk":"#f59e0b","Low Risk":"#10b981"};return e.jsx(Gn,{fill:A[O.name]||O.color},`cell-${J}`)})})]})})})]}),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($r,{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($n,{width:"100%",height:"100%",children:e.jsxs(Fn,{data:o,layout:"vertical",margin:{top:0,right:10,left:40,bottom:0},children:[e.jsx(On,{strokeDasharray:"4 4",stroke:"#f1f5f9",horizontal:!1}),e.jsx(Bn,{type:"number",domain:[0,100],axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600},tickFormatter:O=>`${O}%`}),e.jsx(Pn,{dataKey:"topic",type:"category",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#1e293b",fontSize:11,fontWeight:600},dx:-10}),e.jsx(Hn,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(Qn,{dataKey:"score",radius:[0,6,6,0],barSize:28,children:o.map((O,J)=>{const A=["#6366f1","#a855f7","#10b981","#f59e0b","#ec4899"];return e.jsx(Gn,{fill:A[J%A.length]},`cell-${J}`)})})]})})})]})]}),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(Ea,{className:"w-4 h-4 text-emerald-500"}),"Top Performers"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[se.map(O=>e.jsxs("div",{onClick:()=>n(O),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:O.name}),e.jsxs("span",{className:"text-[13px] font-semibold text-emerald-600",children:[O.avgScore,"%"]})]},`top-${O.id}`)),se.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(Js,{className:"w-4 h-4 text-rose-500"}),"Needs Attention"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[ie.slice(0,4).map(O=>{const J=O.riskLevel==="high",A=J?"bg-rose-50/40 border-rose-50":"bg-amber-50/40 border-amber-50";return e.jsxs("div",{onClick:()=>n(O),className:`flex justify-between items-center p-3 rounded-[14px] border group hover:scale-[1.02] transition-transform cursor-pointer ${A}`,children:[e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:O.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] ${J?"text-rose-600":"text-amber-600"}`,children:J?"HIGH RISK":"MEDIUM RISK"})]},`attn-${O.id}`)}),ie.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No urgent students."})]})]})]})]})]}),e.jsx(bx,{students:s,allClasses:a,currentClass:t,onReassignSection:l,reassignBusyId:c})]})},wx=({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(()=>it.getImportGroundedRolloutFlags(),[]),[f,p]=u.useState(i?.learningPath||""),[g,S]=u.useState(!0),[N,j]=u.useState(i?.gradeDraft||t.grade||"Grade 11"),[h,w]=u.useState(i?.sectionDraft||t.section||"Section A"),[C,M]=u.useState(!1),[k,W]=u.useState(i?.lessonPlan??null),[b,y]=u.useState([]),[v,z]=u.useState(""),[F,I]=u.useState(!1),[V,Y]=u.useState(""),[se,ie]=u.useState("all"),[ae,he]=u.useState("all"),[we,O]=u.useState(!1),[J,A]=u.useState(!1),[Z,ne]=u.useState(null),[$e,Me]=u.useState(!1),[We,P]=u.useState(!1),[re,T]=u.useState(0),[G,H]=u.useState(!1),[ce,_]=u.useState("choose"),[Q,q]=u.useState([]),[E,te]=u.useState(!1),[de,xe]=u.useState(!1),[oe,fe]=u.useState(!1),[qe,Fe]=u.useState(!1);u.useEffect(()=>{j(t.grade||"Grade 11"),w(t.section||"Section A")},[t.grade,t.section]),u.useEffect(()=>{const B=Ae=>{if(Ae.key==="Escape"){if(qe){Fe(!1);return}if(de){oe?Fe(!0):xe(!1);return}G&&H(!1)}};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[de,G,oe,qe]),u.useEffect(()=>{if(de){const B=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=B}}},[de]),u.useEffect(()=>{l?.(t.id,{lessonPlan:k,learningPath:f,gradeDraft:N,sectionDraft:h})},[k,f,N,h,t.id,l]),u.useEffect(()=>{(async()=>{S(!0);try{let Ae="";try{Ae=await Cl(t.struggles.length>0?t.struggles:[t.weakestTopic],"general_math"),z(Ae)}catch{z("")}const Xe=await it.getLearningPath({weaknesses:t.struggles.length>0?t.struggles:[t.weakestTopic],gradeLevel:"High School",subject:"general_math"}),Nt=Ae?`${Xe.learningPath} +`);navigator.clipboard.writeText(x),dt(!0),setTimeout(()=>dt(!1),2e3)},dl=()=>{if(!oe)return;const x=new Blob([JSON.stringify(oe,null,2)],{type:"application/json"}),D=URL.createObjectURL(x),$=document.createElement("a");$.href=D,$.download=`quiz_${C.replace(/\s/g,"_")}_${Date.now()}.json`,$.click(),URL.revokeObjectURL(D)};b.length>0||Object.values(_e).flat().length>0;const hn=(x,D)=>{const $=D?.gradeLevel||C,ge=D?.topics||b,Oe=x.questions.map((Ye,Gt)=>({id:`q_${Date.now()}_${Gt}`,questionType:Ye.questionType||"identification",question:Ye.question,...Ye.options?{options:Ye.options}:{},correctAnswer:Ye.correctAnswer,bloomLevel:Ye.bloomLevel||"understand",difficulty:Ye.difficulty||"medium",topic:Ye.topic,subject:$,points:Ye.points,explanation:Ye.explanation}));return{title:`${$} Quiz – ${ge.length>0?ge.slice(0,2).join(", "):"Mixed Topics"}`,gradeLevel:$,questions:Oe,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"}},fn=u.useCallback(x=>{hs(D=>[x,...D.filter($=>$.id!==x.id)])},[]);async function gn(x,D){if(!p)return null;const $=hn(x,D),ge=await Tn($,p.uid,Ft?{documentId:Ft}:void 0);return R(ge),fn({id:ge,...$,teacherId:p.uid}),ge}const ml=async()=>{if(!oe){me.error("No quiz to save. Generate a quiz first.");return}if(!p){me.error("You must be signed in to save quizzes.");return}za(!0);try{const x=hn(oe),D=await Tn(x,p.uid,Ft?{documentId:Ft}:void 0);R(D),fn({id:D,...x,teacherId:p.uid}),me.success("Quiz saved to your library!"),m?.(D)}catch(x){me.error(x instanceof Error?x.message:"Failed to save quiz")}finally{za(!1)}},ul=async()=>{if(Ft){ze(!0);try{await Ol(Ft),hs(x=>x.map(D=>D.id===Ft?{...D,status:"published"}:D)),me.success("Quiz published to Quiz Bank!")}catch(x){me.error(x instanceof Error?x.message:"Failed to publish quiz")}finally{ze(!1)}}},gr=async x=>{const D=x??Ft;if(!D){me.error("Save the quiz first before assigning.");return}if(ca(D),Ge(!0),na(null),La(""),nt.length===0&&p){Xt(!0);try{const $=await dn(p.uid);Ce($)}catch{me.error("Failed to load students")}finally{Xt(!1)}}},xl=async()=>{const x=hr??Ft;if(!(!Jt||!x||!p)){gt(!0);try{await Bl(x,Jt,p.uid),hs(D=>D.map($=>$.id===x?{...$,status:"assigned",metadata:{...$.metadata,assignedTo:Jt}}:$)),me.success("Quiz assigned to student!"),Ge(!1),ca(null),N==="bank"&&br()}catch(D){me.error(D instanceof Error?D.message:"Failed to assign quiz")}finally{gt(!1)}}},br=u.useCallback(async()=>{if(p){la(!0);try{const x=await ai(p.uid);hs(x)}catch{me.error("Failed to load quiz bank")}finally{la(!1)}}},[p]);u.useEffect(()=>{N==="bank"&&br()},[N,br]);const pl=async x=>{try{await Fl(x),hs(D=>D.filter($=>$.id!==x)),me.success("Quiz deleted")}catch{me.error("Failed to delete quiz")}},bn=nt.filter(x=>x.name.toLowerCase().includes(Ms.toLowerCase())||x.email.toLowerCase().includes(Ms.toLowerCase())),vn=Qs==="all"?oa:oa.filter(x=>x.status===Qs),hl=x=>{const D=(x.metadata.topicsCovered||[]).reduce(($,ge)=>($[ge]=($[ge]||0)+1,$),{});return{questions:x.questions.map($=>({questionType:$.questionType,question:$.question,correctAnswer:$.correctAnswer,options:$.options??null,bloomLevel:$.bloomLevel,difficulty:$.difficulty,topic:$.topic,points:$.points,explanation:$.explanation})),totalPoints:x.totalPoints,metadata:{topicsCovered:D,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||[]}}},vr=x=>{R(x.id),fe(hl(x)),Fe(null),L(x.id),Dt("all"),_s("all"),Xe(null),w("results"),j("create")},wn={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"}},fl=(x,D,$)=>{const ge=Ae===D,Oe=wn[x.bloomLevel?.toLowerCase()]||wn.remember,Ye=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:D*.05},className:`border border-[#e2e8f0] rounded-[20px] overflow-hidden bg-white shadow-sm hover:shadow-md ${Ye} 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:()=>Xe(ge?null:D),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 ${Oe.card} text-white flex items-center justify-center font-bold text-[13px] shadow-sm`,children:["Q",D+1]}),e.jsx("span",{className:`px-2.5 py-1 rounded-md border text-[10px] font-bold uppercase tracking-wider shadow-sm ${Oe.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 ${Oe.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:ge?e.jsx(Na,{size:16,className:"text-[#64748b] transition-transform duration-300"}):e.jsx(_t,{size:16,className:"text-[#64748b]"})})]})]}),e.jsx(Mt,{children:ge&&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((Gt,Us)=>{const ot=Gt.includes(x.correctAnswer);return e.jsxs("div",{className:`rounded-[12px] p-4 text-[14px] font-medium transition-all cursor-pointer relative overflow-hidden ${ot?"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:[ot&&e.jsx("div",{className:"absolute left-0 top-0 w-1 h-full bg-emerald-500"}),e.jsx("span",{className:ot?"pl-2":"",children:Gt}),ot&&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(Ot,{size:13})})]},Us)})})]}),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(qr,{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(Fs,{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(vs,{size:14})," ",e.jsx("strong",{className:"text-[#1e293b]",children:"Type:"})," ",Oa[x.questionType]?.label||x.questionType]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(zr,{size:14})," ",e.jsx("strong",{className:"text-[#1e293b]",children:"Bloom:"})," ",x.bloomLevel]})]})]})})})]},D)},Nn=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:()=>j("create"),className:`px-6 py-2 rounded-full text-[13px] font-bold flex items-center gap-2 transition-all duration-300 ease-out ${N==="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(Fr,{size:16})," Create Quiz"]}),e.jsxs("button",{onClick:()=>j("bank"),className:`px-6 py-2 rounded-full text-[13px] font-bold flex items-center gap-2 transition-all duration-300 ease-out ${N==="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(tr,{size:16})," Quiz Bank"]})]})}),e.jsxs("div",{className:"w-full px-[24px] xl:px-[32px] pb-[32px] flex-1",children:[N==="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:()=>pr(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))}),ia?e.jsxs("div",{className:"flex items-center justify-center py-16",children:[e.jsx(mt,{size:24,className:"animate-spin text-sky-500"}),e.jsx("span",{className:"ml-2 text-sm text-[#5a6578]",children:"Loading quiz bank…"})]}):vn.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(tr,{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:vn.map(x=>e.jsxs(Re.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},onClick:()=>vr(x),role:"button",tabIndex:0,onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),vr(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 ${Dm[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(D=>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:D},D))}),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(Wl,{size:14})," ",x.questions.length," questions"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Zo,{size:14})," ",x.totalPoints," pts"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(is,{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:D=>{D.stopPropagation(),vr(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(ql,{size:14})," View"]}),e.jsxs("button",{onClick:D=>{D.stopPropagation(),gr(x.id)},className:"flex items-center gap-1.5 text-[13px] font-bold text-[#a855f7] hover:text-[#9333ea] transition-colors",children:[e.jsx(Da,{size:14})," Assign"]}),e.jsxs("button",{onClick:D=>{D.stopPropagation(),pl(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(ri,{size:14})," Delete"]})]})]},x.id))})]}),N==="create"&&e.jsxs(e.Fragment,{children:[Pe&&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(lr,{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:Pe})]}),e.jsx("button",{onClick:()=>tt(""),className:"ml-auto",children:e.jsx(ds,{size:14,className:"text-red-400"})})]})}),re&&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(mt,{size:20,className:"animate-spin text-[#a855f7]"}),"Generating Quiz in Background"]}),e.jsxs("span",{className:"text-[14px] font-extrabold text-[#9333ea]",children:[Q,"%"]})]}),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:`${Q}%`},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:E.replace(/_/g," ")})]}),e.jsx("p",{children:de}),ce&&e.jsxs("p",{className:"text-[11px] mt-3 opacity-60 font-mono",children:["Task ID: ",ce]})]})]}),e.jsxs("p",{className:"mt-8 text-[14px] font-medium text-[#64748b] flex items-center gap-2 animate-pulse",children:[e.jsx(mt,{size:16,className:"animate-spin"})," Generating quiz... Please wait."]})]}),!re&&h!=="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,D)=>{const ge=["setup","topics","style","preview"].indexOf(h),Oe=ge>D,Ye=ge===D;return e.jsxs("div",{className:`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl transition-all duration-500 ${Ye?"bg-purple-50/80 shadow-[0_1px_3px_rgba(168,85,247,0.1)]":Oe?"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 ${Ye?"bg-gradient-to-br from-[#a855f7] to-[#9333ea] text-white shadow-md":Oe?"bg-emerald-500 text-white shadow-sm":"bg-slate-100 text-[#64748b]"}`,children:Oe?e.jsx(Ot,{size:13,strokeWidth:3}):D+1}),e.jsx("span",{className:`text-[13px] font-bold whitespace-nowrap ${Ye?"text-[#9333ea]":Oe?"text-[#1e293b]":"text-[#64748b]"}`,children:x.label})]},x.id)})})}),h==="setup"&&!re&&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(ba,{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 ",pa," questions and ",ha," 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:C,onChange:x=>M(Cr(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:$m.map(x=>e.jsx("option",{value:x,children:x},x))}),e.jsx(_t,{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:()=>q(Math.max(1,k-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(En,{size:16})}),e.jsx("input",{id:"quiz-num-questions",type:"number",min:1,max:pa,value:k,onChange:x=>q(Math.min(pa,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:()=>q(Math.min(pa,k+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(Zs,{size:16})})]})]})]})]})]}),h==="topics"&&!re&&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 ",ha," 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:[b.filter(x=>!v.includes(x)).length," of ",ha," selected"]})]})]}),J?e.jsxs("div",{className:"flex items-center justify-center py-10 text-sm text-[#5a6578]",children:[e.jsx(mt,{size:24,className:"animate-spin text-[#9b51e0] mr-2"})," Loading topics..."]}):e.jsx("div",{className:"space-y-3",children:Object.entries(_e).map(([x,D])=>{const $=D.filter(Oe=>b.includes(Oe)&&!v.includes(Oe)).length,ge=Lt===x;return e.jsxs("div",{className:"border border-[#dde3eb] rounded-xl bg-white overflow-hidden shadow-sm",children:[e.jsxs("button",{onClick:()=>B(ge?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:[D.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:[$," selected"]}),ge?e.jsx(Na,{size:18,className:"text-slate-400"}):e.jsx(_t,{size:18,className:"text-slate-400"})]})]}),e.jsx(Mt,{children:ge&&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:D.map((Oe,Ye)=>{const Gt=b.includes(Oe),Us=v.includes(Oe),ot=Gt&&!Us;let Zt="Core";return Ye%3===0&&(Zt="Foundation"),Ye%3===2&&(Zt="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 ${ot?"bg-[#9b51e0] border-[#9b51e0]":"border-2 border-[#dde3eb] bg-white"}`,children:ot&&e.jsx(Ot,{size:14,className:"text-white"})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:ot,onChange:()=>He(Oe)}),e.jsx("span",{className:`text-sm font-semibold ${ot?"text-[#0a1628]":"text-[#5a6578]"}`,children:Oe})]}),e.jsx("span",{className:`border px-3 py-1 rounded-full text-[10px] uppercase font-bold tracking-wider ${Zt==="Advanced"?"bg-white text-slate-400 border-[#dde3eb]":"bg-purple-50 text-[#9b51e0] border-purple-100"}`,children:Zt})]},Oe)})})})})]},x)})})]}),h==="style"&&!re&&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(Oa).map(([x,D])=>{const $=F.includes(x);return e.jsxs("button",{onClick:()=>ma(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 ${$?"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:[$&&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(Ot,{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 ${$?"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:$?"text-[#a855f7]":"text-slate-500",children:D.icon})}),e.jsx("span",{className:`font-bold text-[12px] leading-tight ${$?"text-[#9333ea]":"text-slate-700"}`,children:D.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(yo).map(([x,D])=>{const $=W.includes(x);return e.jsx("button",{onClick:()=>ua(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 ${$?"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(ae).map(([x,D])=>{const $={easy:"bg-emerald-400",medium:"bg-amber-400",hard:"bg-rose-400"},ge={easy:"text-emerald-600",medium:"text-amber-500",hard:"text-rose-500"},Oe={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:${ge[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:`${D}%`},className:`h-full rounded-full transition-all duration-500 ease-out ${$[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 ${Oe[x]}`,children:[e.jsx("button",{onClick:()=>Rt(x,-5),className:`w-8 h-full flex items-center justify-center text-[#64748b] hover:bg-slate-50 hover:${ge[x]} rounded-lg transition-colors`,children:e.jsx(En,{className:"w-3.5 h-3.5"})}),e.jsx("input",{type:"text",value:`${D}%`,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:()=>Rt(x,5),className:`w-8 h-full flex items-center justify-center text-[#64748b] hover:bg-slate-50 hover:${ge[x]} rounded-lg transition-colors`,children:e.jsx(Zs,{className:"w-3.5 h-3.5"})})]})]},x)})})]})]}),h==="preview"&&!re&&!oe&&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($s,{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:k},{label:"Topics",value:b.filter(x=>!v.includes(x)).length},{label:"Level",value:C.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(ba,{size:18,className:"text-[#94a3b8] shrink-0 mt-0.5"}),e.jsxs("p",{children:[F.map(x=>Oa[x]?.label).join(" and ")," questions across"," ",e.jsxs("span",{className:"font-bold text-[#1e293b]",children:[b.filter(x=>!v.includes(x)).length," topics"]})," ","— aligned to ",e.jsx("span",{className:"font-semibold",children:W.map(x=>yo[x]?.label).join(", ")})," levels of Bloom's Taxonomy."," ",e.jsxs("span",{className:"font-semibold text-emerald-600",children:["Easy ",ae.easy,"%"]})," • ",e.jsxs("span",{className:"font-semibold text-amber-500",children:["Medium ",ae.medium,"%"]})," • ",e.jsxs("span",{className:"font-semibold text-rose-500",children:["Hard ",ae.hard,"%"]}),"."]})]})]})}),h==="results"&&oe&&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:cl,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:[Tt?e.jsx(Ot,{size:14,className:"text-green-500"}):e.jsx(Dr,{size:14}),Tt?"Copied!":"Copy All"]}),e.jsxs("button",{onClick:dl,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(Kl,{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(vs,{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:oe.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(Ns,{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:oe.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(oe.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(Ja,{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(oe.metadata.bloomTaxonomyDistribution).length}),e.jsx("span",{className:"text-[12px] font-bold text-white/90 uppercase tracking-widest relative z-10",children:"Bloom Levels"})]})]}),(oe.metadata.usedImportedTopics||(oe.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: ",oe.metadata.usedImportedTopics?"Yes":"No"," • ","Materials: ",oe.metadata.importedMaterialsCount??0," • ","Topics: ",oe.metadata.importedTopicCount??0]}),(oe.metadata.topicProvenance||[]).slice(0,5).map((x,D)=>e.jsxs("div",{className:"text-xs text-[#5a6578]",children:[x.title||"Untitled topic",x.sourceFile?` • ${x.sourceFile}`:""]},`${x.topicId||x.title||"topic"}_${D}`)),(Qt.length>0||Ee.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:Et,onChange:x=>Dt(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"}),Qt.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:$t,onChange:x=>_s(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"}),Ee.map(x=>e.jsx("option",{value:x,children:x},x))]})]})]}),e.jsxs("p",{className:"text-[11px] text-[#5a6578] mt-2",children:["Showing ",Gs.length," of ",oe.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($s,{size:14})," Difficulty"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(oe.metadata.difficultyBreakdown).map(([x,D])=>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 ${Bm[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:D})]},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(zr,{size:14})," Bloom's Taxonomy"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(oe.metadata.bloomTaxonomyDistribution).map(([x,D])=>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:D})]},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(Ja,{size:14})," Question Types"]}),e.jsx("div",{className:"space-y-3 text-[14px] font-medium text-[#475569]",children:Object.entries(oe.metadata.questionTypeBreakdown).map(([x,D])=>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:Oa[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:D})]},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(ba,{size:18,className:"text-[#9333ea]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-bold text-[#9333ea] mb-3",children:oe.metadata.supplementalPurpose||"This quiz is designed to supplement classroom instruction, not replace teacher-led learning."}),oe.metadata.recommendedTeacherActions&&oe.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:oe.metadata.recommendedTeacherActions.map((x,D)=>e.jsx("li",{children:x},D))})]})]})]})]}),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(li,{size:20,className:"text-[#a855f7]"})," Review Questions"]}),e.jsx("div",{className:"space-y-4",children:Gs.length>0?Gs.map((x,D)=>fl(x,D)):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."})})]})]})]})]}),N==="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:[h==="topics"&&!re&&e.jsx("button",{onClick:()=>{y([]),z([])},className:"text-[13px] font-semibold text-[#a855f7] hover:underline",children:"Clear all"}),(h==="style"||h==="preview")&&!re&&e.jsxs("button",{onClick:()=>w(h==="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(ks,{size:16})," Back"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[h==="setup"&&!re&&e.jsxs("button",{onClick:()=>w("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(Ss,{size:16})]}),h==="topics"&&!re&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>w("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(ks,{size:16})," Back"]}),e.jsxs("button",{onClick:()=>w("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(Ss,{size:16})]})]}),h==="style"&&!re&&e.jsxs("button",{onClick:()=>w("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(Ss,{size:16})]}),h==="preview"&&!re&&!oe&&e.jsxs("button",{onClick:ll,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(Ot,{size:16})," Generate Quiz"]}),re&&e.jsxs("div",{className:"flex items-center gap-3 text-slate-500 font-medium text-sm",children:[e.jsx(mt,{size:16,className:"animate-spin"})," Generating quiz... Please wait."]}),h==="results"&&(da?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{j("bank"),L(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:()=>gr(da),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(Da,{size:16})," Assign"]}),e.jsx("button",{onClick:pn,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:()=>{w("setup"),fe(null),Fe(null),R(null),L(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"}),Ft?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:ul,disabled:ee,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:[ee?e.jsx(mt,{size:16,className:"animate-spin"}):e.jsx(Ea,{size:16})," Publish"]}),e.jsxs("button",{onClick:()=>gr(),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(Da,{size:16})," Assign to Class"]})]}):e.jsxs("button",{onClick:ml,disabled:at,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:[at?e.jsx(mt,{size:16,className:"animate-spin"}):e.jsx(ni,{size:16})," Save to Library"]}),e.jsx("button",{onClick:pn,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(Lm,{isOpen:Nt,onClose:()=>Kt(!1)}),e.jsx(Mt,{children:Ne&&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:()=>Ge(!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(is,{size:18,className:"text-sky-600"}),"Assign to Student"]}),e.jsx("button",{onClick:()=>Ge(!1),className:"p-1 hover:bg-[#edf1f7] rounded-lg transition-colors",children:e.jsx(ds,{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(Bs,{size:14,className:"text-slate-500"}),e.jsx("input",{type:"text",placeholder:"Search students…",value:Ms,onChange:x=>La(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:ps?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(mt,{size:20,className:"animate-spin text-sky-500"})}):bn.length===0?e.jsx("p",{className:"text-center text-sm text-slate-500 py-10",children:"No students found"}):bn.map(x=>e.jsxs("button",{onClick:()=>na(x.id),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-left transition-colors ${Jt===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:Ga(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})]}),Jt===x.id&&e.jsx(Ot,{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:()=>Ge(!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:xl,disabled:!Jt||je,className:`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold transition-all ${Jt&&!je?"bg-gradient-to-r from-sky-600 to-sky-500 text-white shadow-sm":"bg-[#dde3eb] text-slate-500 cursor-not-allowed"}`,children:[je?e.jsx(mt,{size:14,className:"animate-spin"}):e.jsx(Da,{size:14}),"Assign"]})]})]})})})]});return d?e.jsx("div",{className:"w-full h-full flex flex-col overflow-hidden bg-white",children:Nn}):Nn},Pm=({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),[f,p]=u.useState(""),[g,S]=u.useState(11),[N,j]=u.useState("general_mathematics"),[h,w]=u.useState([]),[C,M]=u.useState(!1),[k,q]=u.useState(null),b=u.useCallback(async()=>{M(!0);try{const I=Ct(At(Ue,"question_bank",String(g),N,"questions","questions"),Xa(50));let Y=(await zt(I)).docs.map(se=>{const ie=se.data();return{id:se.id,question:ie.question||"",choices:ie.choices||[],correct_answer:ie.correct_answer||"",explanation:ie.explanation||"",topic:ie.topic||"",difficulty:ie.difficulty||"medium",grade_level:ie.grade_level||11}});if(Y.length===0){const se=Ct(At(Ue,"quizBattleQuestionBank"),Xa(50));Y=(await zt(se)).docs.map(ae=>{const he=ae.data();return{id:ae.id,question:he.question||"",choices:he.choices||[],correct_answer:he.correct_answer||"",explanation:he.explanation||"",topic:he.topic||"",difficulty:he.difficulty||"medium",grade_level:he.grade_level||11}})}w(Y)}catch(I){console.warn("[QuestionBankPanel] Failed to load questions:",I)}finally{M(!1)}},[g,N]);u.useEffect(()=>{b()},[b]);const y=u.useCallback(async()=>{c(!0);try{const I=await Sn("/api/quiz-battle/bank-status");i(I.pdfs)}catch(I){const W=I instanceof Ya?I.message:"Failed to load bank status";me.error(W)}finally{c(!1)}},[]);u.useEffect(()=>{y()},[y]);const v=async()=>{if(!f.trim()){me.error("Please enter a storage path");return}m(!0);try{await Sn("/api/quiz-battle/ingest-pdf",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storage_path:f.trim(),grade_level:g,topic:N.trim(),force_reingest:!1})}),me.success("PDF ingestion completed"),await y(),p("")}catch(I){const W=I instanceof Ya?I.message:"Ingestion failed";me.error(W)}finally{m(!1)}},z=n.reduce((I,W)=>I+W.question_count,0),F=n.filter(I=>I.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(vs,{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:z})]}),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(Ls,{size:16,className:"text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none",children:F})]})]}),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(Mn,{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(vs,{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:f,onChange:I=>p(I.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:g,onChange:I=>S(Number(I.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:N,onChange:I=>j(I.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:v,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(mt,{className:"w-4 h-4 animate-spin"}):e.jsx(Mn,{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:y,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(Ls,{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(I=>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 ${I.processed?"bg-indigo-50 text-indigo-500":"bg-amber-50 text-amber-500"}`,children:e.jsx(vs,{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:I.filename})]})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-semibold text-[#475569]",children:I.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:I.topic})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-bold text-[#1e293b] text-center",children:I.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 ${I.processed?"bg-emerald-50 text-emerald-600 border-emerald-200/50":"bg-amber-50 text-amber-600 border-amber-200/50"}`,children:[I.processed?e.jsx(Ls,{className:"w-3 h-3"}):e.jsx(mt,{className:"w-3 h-3 animate-spin"}),I.processed?"Completed":"Processing..."]})}),e.jsx("td",{className:"py-4 px-6 text-[13px] font-medium text-[#64748b]",children:I.timestamp?new Date(I.timestamp).toLocaleDateString():"-"})]},I.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(vs,{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 (",h.length,")"]}),e.jsx("button",{onClick:b,disabled:C,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(Ls,{className:`w-4 h-4 ${C?"animate-spin":""}`})})]}),C?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(mt,{className:"w-6 h-6 animate-spin text-[#9956DE]"})}):h.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:h.map(I=>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:()=>q(k===I.id?null:I.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:I.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 ",I.grade_level]}),e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-md bg-slate-100 text-slate-600 font-medium",children:I.topic}),e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-md font-semibold ${I.difficulty==="easy"?"bg-green-50 text-green-600":I.difficulty==="hard"?"bg-rose-50 text-rose-600":"bg-amber-50 text-amber-600"}`,children:I.difficulty})]})]}),k===I.id?e.jsx(Na,{size:16,className:"text-[#94a3b8] shrink-0"}):e.jsx(_t,{size:16,className:"text-[#94a3b8] shrink-0"})]}),k===I.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:I.choices.map((W,Y)=>e.jsxs("p",{className:`text-[12px] px-3 py-1.5 rounded-lg ${W===I.correct_answer?"bg-green-50 text-green-700 font-semibold border border-green-200":"bg-slate-50 text-[#475569]"}`,children:[String.fromCharCode(65+Y),". ",W]},Y))}),I.explanation&&e.jsxs("p",{className:"text-[12px] text-[#64748b] italic mt-2",children:["💡 ",I.explanation]})]})]},I.id))})]})]})]})},ko={totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:0},Hm={"gen-math":{label:"GEN MATH",color:"bg-sky-100 text-sky-700"},"stats-prob":{label:"STAT&PROB",color:"bg-sky-100 text-sky-700"},"pre-calc":{label:"PRE-CALC",color:"bg-orange-100 text-orange-700"},"basic-calc":{label:"BASIC CALC",color:"bg-red-100 text-red-700"}},Co={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"}},Io={needs_attention:0,on_track:1,no_data:2,mastered:3},Qm=({classSectionId:t,onOpenNotifications:s,onOpenProfile:a})=>{const{currentUser:r,userProfile:o}=ms(),[n,i]=u.useState([]),[l,c]=u.useState(ko),[d,m]=u.useState(!0),[f,p]=u.useState("all"),[g,S]=u.useState("all"),[N,j]=u.useState(""),[h,w]=u.useState("classAverage"),[C,M]=u.useState("asc"),k=An.map(A=>A.id),q=An.reduce((A,Z)=>(A[Z.id]=Z.name,A),{}),{isLoading:b,refetch:y}=ec();u.useEffect(()=>{b||(console.log("[TopicMasteryView] Curriculum ready"),y())},[b,y]);const[v,z]=u.useState(new Set),[F,I]=u.useState([]),W=Xl({queryKey:Nl.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 A=xt(Ue,"teachers",r.uid,"settings","quizSettings"),Z=await bs(A),ne=Z.exists()?Z.data()?.excludedTopics||[]:[],$e="https://deign86-mathpulse-api-v3test.hf.space",Me=new URLSearchParams({teacherId:r.uid});t&&Me.set("classSectionId",t);const We=await r.getIdToken(),P=await fetch(`${$e}/api/analytics/topic-mastery?${Me.toString()}`,{headers:{Authorization:`Bearer ${We}`}});if(!P.ok)return{excluded:ne,topics:[],summary:{totalTopicsTracked:0,masteredCount:0,needsAttentionCount:0,excludedCount:ne.length}};const re=await P.json(),T=(re.topics||[]).map(G=>({...G,isExcluded:ne.includes(G.topicName)}));return{excluded:ne,topics:T,summary:re.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(W.isLoading||W.isFetching),!W.data){I([]),i([]),c(ko),z(new Set);return}I(W.data.excluded),i(W.data.topics),c(W.data.summary)},[W.data,W.isFetching,W.isLoading]);const Y=async A=>{if(!r)return;const Z=F.includes(A)?F.filter(ne=>ne!==A):[...F,A];I(Z),i(ne=>ne.map($e=>$e.topicName===A?{...$e,isExcluded:!$e.isExcluded}:$e)),c(ne=>({...ne,excludedCount:Z.length}));try{const ne=xt(Ue,"teachers",r.uid,"settings","quizSettings");(await bs(ne)).exists()?await ls(ne,{excludedTopics:Z}):await ts(ne,{excludedTopics:Z})}catch{me.error("Failed to update excluded topics")}},se=async()=>{if(!r)return;const A=[...new Set([...F,...v])];I(A),i(Z=>Z.map(ne=>v.has(ne.topicName)?{...ne,isExcluded:!0}:ne)),c(Z=>({...Z,excludedCount:A.length})),z(new Set);try{const Z=xt(Ue,"teachers",r.uid,"settings","quizSettings");(await bs(Z)).exists()?await ls(Z,{excludedTopics:A}):await ts(Z,{excludedTopics:A}),me.success(`${v.size} topics excluded from quizzes`)}catch{me.error("Failed to update")}},ie=async()=>{if(!r)return;const A=F.filter(Z=>!v.has(Z));I(A),i(Z=>Z.map(ne=>v.has(ne.topicName)?{...ne,isExcluded:!1}:ne)),c(Z=>({...Z,excludedCount:A.length})),z(new Set);try{const Z=xt(Ue,"teachers",r.uid,"settings","quizSettings");(await bs(Z)).exists()?await ls(Z,{excludedTopics:A}):await ts(Z,{excludedTopics:A}),me.success(`${v.size} topics re-included in quizzes`)}catch{me.error("Failed to update")}},ae=A=>{h===A?M(Z=>Z==="asc"?"desc":"asc"):(w(A),M("asc"))},he=g==="all"?k:Jl(g);u.useEffect(()=>{f!=="all"&&(he.includes(f)||p("all"))},[he,f]);const we=n.filter(A=>!(f!=="all"&&A.subjectId!==f||!he.includes(A.subjectId)||N&&!A.topicName.toLowerCase().includes(N.toLowerCase()))).sort((A,Z)=>{const ne=C==="asc"?1:-1;switch(h){case"topicName":return ne*A.topicName.localeCompare(Z.topicName);case"classAverage":return ne*(A.classAverage-Z.classAverage);case"studentsAttempted":return ne*(A.studentsAttempted-Z.studentsAttempted);case"masteryStatus":return ne*((Io[A.masteryStatus]||0)-(Io[Z.masteryStatus]||0));default:return 0}}),O=()=>{v.size===we.length?z(new Set):z(new Set(we.map(A=>A.topicName)))},J=({field:A})=>h!==A?e.jsx(_t,{size:14,className:"text-white/40"}):C==="asc"?e.jsx(Na,{size:14,className:"text-white font-bold"}):e.jsx(_t,{size:14,className:"text-white font-bold"});return d?e.jsxs("div",{className:"flex items-center justify-center py-20",children:[e.jsx(mt,{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($s,{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(Yr,{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(Js,{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(Yl,{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(Bs,{size:16,className:"text-[#64748b] shrink-0 group-focus-within:text-[#4f46e5] transition-colors"}),e.jsx("input",{type:"text",placeholder:"Search topics...",value:N,onChange:A=>j(A.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:f,onChange:A=>p(A.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"}),he.map(A=>e.jsx("option",{value:A,children:q[A]||A},A))]}),e.jsx(_t,{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:g,onChange:A=>S(A.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"}),Zl.map(A=>e.jsx("option",{value:A,children:A},A))]}),e.jsx(_t,{size:16,className:"text-[#64748b] absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]})]}),e.jsx(Mt,{children:v.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:[v.size," topics selected"]}),e.jsx("button",{onClick:se,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:ie,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:()=>z(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:v.size===we.length&&we.length>0,onChange:O,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:()=>ae("topicName"),children:["TOPIC NAME ",e.jsx(J,{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:()=>ae("classAverage"),children:["CLASS AVG % ",e.jsx(J,{field:"classAverage"})]}),e.jsxs("div",{className:"col-span-2 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ae("studentsAttempted"),children:["STUDENTS ",e.jsx(J,{field:"studentsAttempted"})]}),e.jsxs("div",{className:"col-span-1 flex items-center gap-1 cursor-pointer hover:text-white/80 select-none",onClick:()=>ae("masteryStatus"),children:["STATUS ",e.jsx(J,{field:"masteryStatus"})]}),e.jsx("div",{className:"col-span-1 text-center",children:"EXCLUDE"})]}),e.jsx("div",{className:"flex flex-col",children:we.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($s,{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."})}):we.map(A=>{const Z=v.has(A.topicName),ne=Co[A.masteryStatus]||Co.no_data,$e=Hm[A.subjectId]||{label:A.subjectId.toUpperCase(),color:"bg-[#f8fafc] text-[#64748b]"},Me=A.classAverage<60?"bg-rose-500":A.classAverage<85?"bg-amber-500":"bg-emerald-500",We=A.isExcluded?"bg-slate-50/60 opacity-70":A.masteryStatus==="needs_attention"?"bg-rose-50/30":A.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 ${We} ${A.isExcluded?"line-through decoration-slate-400":""}`,children:[e.jsx("div",{className:"col-span-1 flex justify-center",children:e.jsx("input",{type:"checkbox",checked:Z,onChange:()=>{const P=new Set(v);Z?P.delete(A.topicName):P.add(A.topicName),z(P)},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:A.topicName}),e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded shrink-0 ${$e.color}`,children:$e.label})]}),e.jsx("div",{className:"col-span-2 text-[#475569] text-[13px] truncate pr-2",children:A.unit}),e.jsx("div",{className:"col-span-2",children:e.jsxs("span",{className:"font-bold text-[#1e293b] text-[14px]",children:[A.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:[A.studentsAttempted," / ",A.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 ${Me}`,style:{width:`${A.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:A.isExcluded,onChange:()=>Y(A.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:A.isExcluded?"Include in generation":"Exclude from generation"})]})]},A.topicName)})})]})})})]})]})};function Ki(t){return(t||"").trim().toLowerCase()}function To(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=Ki(t.classSectionId),n=(t.id||"").trim().toLowerCase();return o&&n?`${o}|id:${n}`:n?`id:${n}`:`${o}|anonymous`}function Gm(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 Um(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 Xi(t,s){const a=new Map,r=new Map,o=s?Ki(s):"all";return t.forEach(n=>{const i=Gm(n,o),l=i.map(m=>r.get(m)).find(Boolean)||i[0],c=a.get(l),d=c?Um(c,n):n;a.set(l,d),i.forEach(m=>r.set(m,l))}),Array.from(a.values())}function Eo(t,s){return Xi([...t,...s])}function Ws(t){return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function Vm(t){if(!t)return null;const s="gen-math",a=zn.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=zn.find(j=>j.modules.some(h=>h.id===i.id)),c=l?t?.subjects?.[l.id]?.modulesProgress?.[i.id]:null,d=Ws(c?.progress||0),m=i.lessons.length?i.lessons.reduce((j,h)=>{const w=o?.[h.id]?.score;if(typeof w=="number"&&Number.isFinite(w))return j+Ws(w);const C=!!c?.lessonsCompleted?.includes?.(h.id);return j+(C?100:0)},0)/i.lessons.length:0,f=i.quizzes.length?(c?.quizzesCompleted?.length||0)/i.quizzes.length*100:0,p=Ws(m),g=Ws(f),S=Ws(Math.min(100,(p+g*2)/1.5)),N=Ws(Math.min(100,40+d*.6));r.mastery+=d,r.concept+=p,r.application+=g,r.engagement+=S,r.consistency+=N});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 Ro={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"}},Tr=[{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"}],Wm=({classSectionId:t,className:s,fallbackStudents:a=[],onBack:r,onOpenNotifications:o,onOpenProfile:n,insightDismissed:i,onOpenInsightModal:l})=>{const{currentUser:c,userProfile:d}=ms(),m=u.useRef(0),[f,p]=u.useState([]),[g,S]=u.useState(!0),[N,j]=u.useState(""),[h,w]=u.useState("riskLevel"),[C,M]=u.useState("desc"),[k,q]=u.useState("all"),[b,y]=u.useState([]),[v,z]=u.useState(!1),[F,I]=u.useState(""),[W,Y]=u.useState(""),se=u.useCallback(T=>({id:T.id,lrn:T.lrn||void 0,name:T.name,email:T.email||"",avatar:Ga(T.gender),classSectionId:T.classSectionId??null,riskLevel:T.riskLevel||"Low",engagementScore:T.engagementScore,avgQuizScore:T.avgQuizScore,weakestTopic:T.weakestTopic||"Foundational Skills"}),[]),ie=u.useCallback(T=>({id:T.id,lrn:T.lrn,name:T.name,email:T.email||"",avatar:T.avatar&&!T.avatar.includes("ui-avatars.com")?T.avatar:Ga(T.gender),classSectionId:T.classSectionId??null,riskLevel:String(T.riskLevel).charAt(0).toUpperCase()+String(T.riskLevel).slice(1).toLowerCase(),engagementScore:T.engagementScore,avgQuizScore:Number(T.avgQuizScore??T.avgScore??0),weakestTopic:T.weakestTopic||"Foundational Skills"}),[]),ae=u.useCallback(async(T,G)=>{const H=new Map;T.forEach(_=>H.set(_.id,null));const ce=25;for(let _=0;_{try{const te=await kn(E.id);return{studentId:E.id,summary:Vm(te)}}catch{return{studentId:E.id,summary:null}}}))).forEach((E,te)=>{const de=Q[te]?.id;de&&(E.status==="fulfilled"?H.set(de,E.value.summary):H.set(de,null))})}m.current===G&&p(_=>_.map(Q=>H.has(Q.student.id)?{...Q,competencyMatrix:H.get(Q.student.id)??null,competencyMatrixLoading:!1}:Q))},[]),he=u.useCallback(async()=>{if(c?.uid){S(!0),Y("");try{let G=(await dn(c.uid)).map(Q=>({id:Q.id,name:Q.name,email:Q.email||"",avatar:Q.avatar&&!Q.avatar.includes("ui-avatars.com")?Q.avatar:Ga(Q.gender),classSectionId:Q.classSectionId??null,riskLevel:Q.riskLevel,engagementScore:Q.engagementScore,avgQuizScore:Q.avgQuizScore,weakestTopic:Q.weakestTopic||"Foundational Skills"}));a.length>0&&(G=Eo(G,a.map(ie))),t&&(G=G.filter(Q=>Q.classSectionId===t));const H=await it.getImportedClassOverview({classSectionId:t,limit:3e3});H.warnings.length>0&&Y(H.warnings.join(" ")),G=Eo(G,H.students.map(se));const ce=Xi(G,t),_=m.current+=1;p(ce.map((Q,U)=>({rowKey:`${To(Q)}|row:${U}`,student:Q,competency:null,competencyMatrix:null,competencyMatrixLoading:!0,loading:!1,expanded:!1}))),ae(ce,_)}catch(T){if(console.error("Failed to load students:",T),a.length>0){const G=a.map(ie).filter(H=>!t||H.classSectionId===t).map((H,ce)=>({rowKey:`${To(H)}|row:${ce}`,student:H,competency:null,competencyMatrix:null,competencyMatrixLoading:!1,loading:!1,expanded:!1}));p(G),Y("Showing recently imported students while backend roster sync catches up.")}else p([]),Y("Student competency roster is unavailable right now.")}finally{S(!1)}}},[t,c?.uid,a,ae,ie,se]);u.useEffect(()=>{he()},[he]),u.useEffect(()=>{(async()=>{if(!t){y([]),I("");return}z(!0),I("");try{const G=await it.getCourseMaterialTopics({classSectionId:t,limit:20}),H=(G.topics||[]).filter(ce=>ce.title?.trim());y(H),G.warnings.length>0&&I(G.warnings.join(" "))}catch{y([]),I("Imported topic context is unavailable right now.")}finally{z(!1)}})()},[t]);const we=async T=>{p(G=>G.map(H=>{if(H.rowKey!==T)return H;const ce=!H.expanded,_=H.student.id,Q={weakestTopic:H.student.weakestTopic,avgQuizScore:H.student.avgQuizScore};return ce&&!H.competency&&!H.loading?(O(T,_,Q),{...H,expanded:!0,loading:!0}):{...H,expanded:ce}}))},O=async(T,G,H)=>{try{const _=((await kn(G))?.quizAttempts??[]).map(U=>({topic:U.quizId,score:U.score,total:100,timeTaken:U.timeSpent})),Q=await it.getStudentCompetency(G,_.length>0?_:void 0);p(U=>U.map(E=>E.rowKey===T?{...E,competency:Q,loading:!1}:E))}catch{const _=H.avgQuizScore||50,Q={studentId:G,competencies:[{topic:H.weakestTopic||"Unknown",efficiencyScore:Math.max(15,_-20),competencyLevel:_<50?"beginner":"developing",perspective:`Student needs focused practice in ${H.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:[H.weakestTopic||"Review fundamentals"],excludeTopics:[]};p(U=>U.map(E=>E.rowKey===T?{...E,competency:Q,loading:!1}:E))}},J=T=>{h===T?M(G=>G==="asc"?"desc":"asc"):(w(T),M("asc"))},A={High:0,Medium:1,Low:2},Z=f.filter(T=>{if(k!=="all"&&T.student.riskLevel!==k)return!1;if(N){const G=N.toLowerCase();return T.student.name.toLowerCase().includes(G)||T.student.email.toLowerCase().includes(G)}return!0}).sort((T,G)=>{let H=0;switch(h){case"name":H=T.student.name.localeCompare(G.student.name);break;case"avgQuizScore":H=T.student.avgQuizScore-G.student.avgQuizScore;break;case"riskLevel":H=A[T.student.riskLevel]-A[G.student.riskLevel];break;case"engagementScore":H=T.student.engagementScore-G.student.engagementScore;break}return C==="asc"?H:-H}),ne=f.length,$e=f.filter(T=>T.student.riskLevel==="High").length,Me=ne>0?Math.round(f.reduce((T,G)=>T+G.student.avgQuizScore,0)/ne):0,We=ne>0?Math.round(f.reduce((T,G)=>T+G.student.engagementScore,0)/ne):0,P=Array.from(new Set(b.map(T=>T.title).filter(Boolean))).slice(0,10),re=({field:T})=>h!==T?e.jsx(_t,{size:14,className:"text-white/40"}):C==="asc"?e.jsx(Na,{size:14,className:"text-white font-bold"}):e.jsx(_t,{size:14,className:"text-white font-bold"});return g?e.jsxs("div",{className:"flex items-center justify-center py-20 p-6",children:[e.jsx(mt,{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(ks,{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(Cn,{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(Js,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:$e}),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($s,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:[Me,"%"]}),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(Ea,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[28px] font-bold relative z-10 leading-none mb-4",children:[We,"%"]}),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(Bs,{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:N,onChange:T=>j(T.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(T=>e.jsx("button",{onClick:()=>q(T),className:`px-4 py-1.5 text-[13px] font-semibold rounded-full whitespace-nowrap transition-colors shadow-md ${k===T?"bg-[#9956DE] text-white":"bg-white text-slate-500 hover:text-slate-700 hover:bg-slate-50"}`,children:T==="all"?"All":`${T} Risk`},T))})]}),e.jsxs("button",{onClick:he,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(Ls,{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}`:"",":"]}),v?e.jsx("span",{className:"text-[#8b5cf6] text-[13px]",children:"Loading class-scoped imported topics..."}):P.length>0?e.jsx("div",{className:"flex flex-wrap items-center gap-1.5 mt-1 sm:mt-0",children:P.map((T,G)=>e.jsxs(ue.Fragment,{children:[e.jsx("span",{className:"text-[#8b5cf6] text-[13px]",children:T}),GJ("name"),children:["Student ",e.jsx(re,{field:"name"})]}),e.jsxs("div",{className:"w-[120px] shrink-0 px-4 flex justify-center cursor-pointer hover:text-white/80 transition-colors",onClick:()=>J("riskLevel"),children:["Risk Level ",e.jsx(re,{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:()=>J("avgQuizScore"),children:["Avg. Score ",e.jsx(re,{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:()=>J("engagementScore"),children:["Engagement ",e.jsx(re,{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"}),Tr.map((T,G)=>e.jsx("div",{className:`w-[100px] shrink-0 px-2 flex justify-center ${G===Tr.length-1?"border-r border-transparent":""}`,children:T.header},T.key))]}),Z.length===0?e.jsxs("div",{className:"py-12 text-center text-slate-500",children:[e.jsx(Cn,{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:Z.map(T=>(T.student.riskLevel==="High"||T.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 we(T.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 ${T.expanded?"rotate-90":""}`,children:e.jsx(Ss,{className:"w-4 h-4 text-slate-400"})}),e.jsx("img",{src:T.student.avatar,alt:T.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:T.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 ${T.student.riskLevel==="High"?"bg-rose-50 text-rose-600 border-rose-200":T.student.riskLevel==="Medium"?"bg-amber-50 text-amber-600 border-amber-200":"bg-emerald-50 text-emerald-600 border-emerald-200"}`,children:T.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 ${T.student.avgQuizScore>=80?"bg-emerald-500":T.student.avgQuizScore>=60?"bg-amber-400":"bg-rose-500"}`,style:{width:`${T.student.avgQuizScore}%`}})}),e.jsxs("span",{className:"text-[13px] font-bold text-slate-800 w-8",children:[T.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:`${T.student.engagementScore}%`}})}),e.jsxs("span",{className:"text-[13px] font-bold text-slate-800 w-8",children:[T.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:T.student.weakestTopic})}),Tr.map(G=>{const H=T.competencyMatrix?.[G.key]??0;return e.jsx("div",{className:"w-[100px] shrink-0 px-2 flex justify-center",children:T.competencyMatrixLoading?e.jsx(mt,{size:12,className:"animate-spin text-muted-foreground"}):T.competencyMatrix?e.jsxs("span",{className:`text-[12px] font-medium px-2 rounded-full border ${H>=80?"text-emerald-600 bg-emerald-50 border-emerald-100":H>=60?"text-amber-600 bg-amber-50 border-amber-100":"text-rose-500 bg-rose-50 border-rose-100"}`,children:[H,"%"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})},G.key)})]}),e.jsx(Mt,{children:T.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:T.loading?e.jsxs("div",{className:"flex items-center py-4",children:[e.jsx(mt,{size:16,className:"animate-spin text-indigo-500 mr-2"}),e.jsx("span",{className:"text-sm text-slate-500",children:"Analyzing competency data..."})]}):T.competency?e.jsxs("div",{className:"space-y-4 max-w-4xl",children:[T.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:T.competency.recommendedTopics.map((G,H)=>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:G},H))})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.competency.competencies.map((G,H)=>e.jsx(qm,{competency:G},H))})]}):e.jsx("div",{className:"text-sm text-slate-500 py-4",children:"Failed to load competency details."})})]})})})]},T.rowKey)))})]})})]})},qm=({competency:t})=>{const s=Ro[t.competencyLevel]||Ro.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})]})},Ym=()=>{const{notifications:t,unreadCount:s,isLoading:a,markAsRead:r,markAllAsRead:o}=ei(),[n,i]=u.useState("all"),l=["streak_reminder","daily_checkin","streak_milestone","achievement_unlocked","level_up","xp_earned","quiz_result"],c=t.filter(S=>!S.isRead&&!l.includes(S.type)).length,d=S=>{switch(S){case"achievement_unlocked":case"achievement":return jl;case"message":return Al;case"grade":case"quiz_result":return Jo;case"reminder":case"streak_reminder":case"daily_checkin":return ea;case"risk_alert":return Js;case"sparkles":case"lesson_plan_ready":return Fs;case"users":case"student_import":return is;default:return er}},m=(S,N)=>{switch(S){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"}},f=S=>{switch(S){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)]"}},p=u.useMemo(()=>{let S=t.filter(N=>!l.includes(N.type));return n==="unread"&&(S=S.filter(N=>!N.isRead)),n==="important"&&(S=S.filter(N=>N.type==="risk_alert")),S},[t,n]),g=u.useMemo(()=>{const S=[],N=p.filter(w=>Vn(w.createdAt)),j=p.filter(w=>Wn(w.createdAt)),h=p.filter(w=>!Vn(w.createdAt)&&!Wn(w.createdAt));return N.length>0&&S.push({title:"Today",icon:ea,items:N}),j.length>0&&S.push({title:"Yesterday",icon:Rn,items:j}),h.length>0&&S.push({title:"Earlier",icon:Rn,items:h}),S},[p]);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(S=>S.type==="risk_alert"&&!S.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(ac,{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(mt,{className:"w-8 h-8 text-[#a855f7] animate-spin"}),e.jsx("p",{className:"text-[14px] font-medium text-[#64748b]",children:"Syncing notifications..."})]}):g.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(er,{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."})]}):g.map(S=>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(S.icon,{className:"w-4 h-4"})," ",S.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:S.items.map(N=>{const j=d(N.type),h=N.type==="risk_alert";return e.jsxs(Re.div,{layout:!0,onClick:()=>!N.isRead&&r(N.id),className:`relative p-5 flex gap-5 group cursor-pointer hover:bg-white transition-all duration-300 ${N.isRead?"opacity-80":m(N.type)}`,children:[e.jsx("div",{className:`absolute left-0 top-0 w-1.5 h-full transition-colors ${N.isRead?"bg-transparent":h?"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 ${f(N.type)}`,children:e.jsx(j,{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:[N.title,!N.isRead&&e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${h?"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 ${N.isRead?"text-[#94a3b8]":h?"text-rose-600":"text-[#a855f7]"}`,children:[rc(N.createdAt)," ago"]})]}),e.jsx("p",{className:"text-[14px] text-[#475569] font-medium leading-relaxed",children:N.message}),!N.isRead&&N.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 ${h?"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(fc,{size:18})})]},N.id)})})]},S.title))})]})})},Km=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)}},Xm=async(t,s)=>{const a=xt(At(Ue,"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 ts(a,{...r,createdAt:lt(),updatedAt:lt()}),r},Jm=async(t,s)=>{const a=xt(Ue,"calendarEvents",t);await ls(a,{...s,updatedAt:lt()})},Zm=async t=>{await _l(xt(Ue,"calendarEvents",t))},Ji=(t,s={},a,r)=>{if(!t)return a([]),()=>{};const{limitCount:o=500}=s,n=Ct(At(Ue,"calendarEvents"),St("userId","==",t),Xa(o));return ti(n,i=>{a(i.docs.map(l=>Km(l)))},i=>{console.error("Error subscribing to calendar events:",i),r?.(i)})};function eu({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:Xo("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 Ys=t=>String(t).padStart(2,"0"),As=t=>`${t.getFullYear()}-${Ys(t.getMonth()+1)}-${Ys(t.getDate())}`,Ur=t=>new Date(t.getFullYear(),t.getMonth(),1),_o=t=>new Date(t.getFullYear(),t.getMonth()+1,0),tu=t=>{const s=Ur(t),a=s.getDay(),r=new Date(s);return r.setDate(s.getDate()-a),r.setHours(0,0,0,0),r},su=(t,s)=>{const a=new Date(t);return a.setDate(a.getDate()+s),a},Mo=(t,s)=>t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate(),au=(t,s)=>t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth(),ru=t=>t.toLocaleDateString(void 0,{month:"long",year:"numeric"}),Ba=t=>t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),Ao=(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)},nu=["purple","blue","emerald","amber","rose"],Er=t=>{switch(t){case"blue":return"#3b82f6";case"emerald":return"#10b981";case"amber":return"#f59e0b";case"rose":return"#f43f5e";case"purple":default:return"#a855f7"}},ou=(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"}},iu=(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"}}},Rr=[{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 lu(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=Rr.find(i=>i.names.includes(r[1]))?.day,n=Rr.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 Rr.forEach(({names:o,day:n})=>{o.some(i=>s.includes(i))&&a.add(n)}),Array.from(a).sort((o,n)=>o-n)}const cu=({classes:t,teacherId:s})=>{const{currentUser:a}=ms(),[r,o]=u.useState([]),[n,i]=u.useState(!0),[l,c]=u.useState(""),[d,m]=u.useState(!0),[f,p]=u.useState(()=>{const E=new Date;return E.setHours(0,0,0,0),E}),[g,S]=u.useState(()=>{const E=new Date;return E.setHours(0,0,0,0),E}),[N,j]=u.useState(new Set),[h,w]=u.useState(!1),[C,M]=u.useState(null),[k,q]=u.useState(!1),[b,y]=u.useState(""),[v,z]=u.useState(""),[F,I]=u.useState(()=>As(new Date)),[W,Y]=u.useState("09:00"),[se,ie]=u.useState(""),[ae,he]=u.useState("purple"),[we,O]=u.useState(!1),[J,A]=u.useState(null);u.useEffect(()=>{if(!a?.uid){o([]),i(!1);return}c(""),i(!0);const E=Ji(a.uid,{limitCount:500},te=>{o(te),i(!1)},()=>{c("Unable to load calendar events right now."),i(!1)});return()=>E()},[a?.uid]);const Z=u.useMemo(()=>{const E=Ur(f);return E.setHours(0,0,0,0),E},[f]),ne=u.useMemo(()=>{const E=_o(f);return E.setHours(23,59,59,999),E},[f]),$e=u.useMemo(()=>{if(!t||t.length===0)return[];const E=[],te=Ur(f),de=_o(f),xe=new Date(te);for(;xe<=de;){const oe=xe.getDay();t.forEach(fe=>{if(lu(fe.schedule).includes(oe)){const Fe=`schedule-${fe.id}-${As(xe)}`;N.has(Fe)||E.push({id:Fe,userId:s||"",title:fe.name,startTime:new Date(xe),createdAt:new Date})}}),xe.setDate(xe.getDate()+1)}return E},[t,f,s,N]),Me=u.useMemo(()=>[...r,...$e],[r,$e]),We=u.useMemo(()=>Me.filter(E=>E.startTime>=Z&&E.startTime<=ne).sort((E,te)=>E.startTime.getTime()-te.startTime.getTime()),[Me,Z,ne]),P=u.useMemo(()=>{const E=new Map;for(const te of We){const de=As(te.startTime),xe=E.get(de)||[];xe.push(te),E.set(de,xe)}return E},[We]),re=u.useMemo(()=>As(g),[g]),T=u.useMemo(()=>[...P.get(re)||[]].sort((te,de)=>te.startTime.getTime()-de.startTime.getTime()),[P,re]),G=u.useMemo(()=>{const E=tu(f);return Array.from({length:42}).map((te,de)=>su(E,de))},[f]),H=E=>{const te=As(E);M(null),y(""),z(""),I(te),Y("09:00"),ie(""),he("purple"),w(!0)},ce=E=>{E.id.startsWith("schedule-")?(j(te=>new Set(te).add(E.id)),M(null)):M(E.id),y(E.title),z(E.description||""),I(As(E.startTime)),Y(Ys(E.startTime.getHours())+":"+Ys(E.startTime.getMinutes())),ie(E.endTime?Ys(E.endTime.getHours())+":"+Ys(E.endTime.getMinutes()):""),he(E.color||"purple"),O(!1),w(!0)},_=(E,te)=>{E.stopPropagation(),A(te),O(!0)},Q=async()=>{const E=a?.uid||s||"local-user";if(!b.trim()){c("Event title is required.");return}q(!0),c("");const te=Ao(F,W),de=se?Ao(F,se):void 0,xe={title:b.trim(),description:v.trim()?v.trim():void 0,startTime:te,endTime:de&&de.getTime()>te.getTime()?de:void 0,color:ae};try{if(C)o(oe=>oe.map(fe=>fe.id===C?{...fe,...xe}:fe)),await Jm(C,xe);else{const oe=`temp-${Date.now()}`;o(fe=>[...fe,{id:oe,userId:E,createdAt:new Date,...xe}]),await Xm(E,xe)}w(!1)}catch(oe){console.error(oe),w(!1)}finally{q(!1)}},U=async E=>{if(E.startsWith("schedule-")){j(te=>new Set(te).add(E)),J?.id===E&&O(!1);return}c(""),o(te=>te.filter(de=>de.id!==E)),J?.id===E&&O(!1);try{await Zm(E)}catch(te){console.error(te)}};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:()=>p(new Date(f.getFullYear(),f.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(ks,{className:"w-5 h-5"})}),e.jsx("h2",{className:"text-[22px] font-bold text-white w-44 text-center tracking-tight",children:ru(f)}),e.jsx("button",{onClick:()=>p(new Date(f.getFullYear(),f.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(Ss,{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:[We.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(kc,{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=>e.jsx("div",{className:"text-[12px] font-bold text-[#475569] uppercase tracking-widest",children:E},E))}),e.jsx("div",{className:"grid grid-cols-7 gap-2 pb-6 px-4",children:G.map(E=>{const te=As(E),de=P.get(te)||[],xe=Mo(E,g),oe=Mo(E,new Date),fe=au(E,f);return e.jsxs("div",{onClick:()=>S(new Date(E)),className:`group p-2 rounded-lg transition-all cursor-pointer border-2 flex flex-col relative min-h-[100px] xl:min-h-[120px] ${xe?"bg-purple-50/50 border-[#a855f7] shadow-sm z-10":oe?"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"} ${fe?"":"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 ${oe?"bg-gradient-to-br from-[#a855f7] to-[#9333ea] text-white shadow-md":xe?"text-[#9333ea]":"text-[#1e293b]"}`,children:E.getDate()})}),e.jsxs("div",{className:"mt-1 space-y-1",children:[de.slice(0,3).map(qe=>{const Fe=qe.id.startsWith("schedule-");return e.jsx("div",{onClick:Pe=>_(Pe,qe),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 ${ou(qe.color,Fe)}`,children:qe.title},qe.id)}),de.length>3&&e.jsxs("div",{className:"text-[10px] font-bold text-[#64748b] pl-1 pt-0.5",children:["+",de.length-3," more"]})]})]},te)})})]})]})}),e.jsx(Mt,{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:g.toLocaleDateString(void 0,{weekday:"long"})}),e.jsx("p",{className:"text-[13px] font-medium text-[#64748b]",children:g.toLocaleDateString(void 0,{day:"numeric",month:"long",year:"numeric"})})]}),e.jsx("button",{onClick:()=>H(g),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(Zs,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar pb-12",children:T.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center opacity-40",children:[e.jsx(wr,{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."})]}):T.map(E=>{const te=E.id.startsWith("schedule-"),de=iu(E.color,te);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 ${de.dot}`}),e.jsxs("div",{onClick:xe=>_(xe,E),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 ${de.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:E.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 ${de.time}`,children:[e.jsx(ea,{className:"w-3.5 h-3.5"})," ",e.jsxs("span",{children:[Ba(E.startTime),E.endTime?` - ${Ba(E.endTime)}`:""]})]}),E.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:E.description})]})]},E.id)})})]})})})]}),e.jsx(Ln,{open:h,onOpenChange:w,children:e.jsx(Dn,{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(nc,{className:"mb-6",children:[e.jsx(oc,{className:"text-[24px] font-bold text-[#1e293b] tracking-tight",children:C?"Edit Event":"Add New Event"}),e.jsx(ic,{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(js,{value:b,onChange:E=>y(E.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(js,{type:"date",value:F,onChange:E=>I(E.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(js,{type:"time",value:W,onChange:E=>Y(E.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(eu,{value:v,onChange:E=>z(E.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:nu.map(E=>e.jsx("button",{onClick:()=>he(E),className:`w-8 h-8 rounded-full flex items-center justify-center transition-all ${ae===E?"ring-2 ring-offset-2 ring-slate-800 scale-110 shadow-sm":"hover:scale-110 opacity-80 hover:opacity-100"}`,style:{backgroundColor:Er(E)},title:E,children:ae===E&&e.jsx(Ot,{className:"w-4 h-4 text-white"})},E))})]})]}),e.jsxs("div",{className:"flex gap-3 mt-8",children:[e.jsx(ht,{variant:"outline",onClick:()=>w(!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(ht,{onClick:Q,disabled:k,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:k?e.jsx(mt,{className:"w-5 h-5 animate-spin"}):"Save Event"})]})]})})}),e.jsx(Ln,{open:we,onOpenChange:O,children:e.jsx(Dn,{className:"sm:max-w-[400px] p-0 overflow-hidden rounded-[24px] border-none shadow-2xl [&>button]:hidden",children:J&&e.jsxs("div",{className:"p-8 bg-white relative",children:[e.jsx("button",{onClick:()=>O(!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(ds,{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:Er(J.color||"purple")+"20",color:Er(J.color||"purple")},children:J.id.startsWith("schedule-")?e.jsx(Ka,{size:24}):e.jsx(wr,{size:24})}),e.jsxs("div",{className:"pr-6",children:[e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] leading-tight mb-2",children:J.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(wr,{size:12}),J.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(ea,{size:12}),Ba(J.startTime),J.endTime?` - ${Ba(J.endTime)}`:""]})]})]})]}),J.description&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(mc,{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:J.description})]}),e.jsxs("div",{className:"flex gap-3 pt-2 border-t border-slate-100",children:[e.jsxs(ht,{variant:"outline",onClick:()=>U(J.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(ri,{className:"w-4 h-4 mr-2"})," Delete"]}),e.jsxs(ht,{onClick:()=>ce(J),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"]})]})]})})})]})},nr=[{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]"}],zo=({classes:t,onSelectClass:s,onOpenNotifications:a,onOpenProfile:r,insightDismissed:o,onOpenInsightModal:n,viewType:i="analytics",onCreateClass:l})=>{const{currentUser:c,userProfile:d}=ms(),[m,f]=u.useState(""),p=i==="competency",g=t.reduce((h,w)=>h+(w.studentCount||0),0),S=t.reduce((h,w)=>h+(w.atRiskCount||0),0),N=t.length>0?(t.reduce((h,w)=>h+(w.avgScore||0),0)/t.length).toFixed(1):0,j=t.filter(h=>h.name.toLowerCase().includes(m.toLowerCase())||(h.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(Bs,{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:h=>f(h.target.value),className:"bg-transparent border-none focus:outline-none ml-3 text-[13px] w-full text-[#475569] placeholder:text-[#94a3b8]"})]})})}),p?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(is,{className:"w-4 h-4 text-white"})})]}),e.jsx("div",{className:"text-[32px] font-bold relative z-10 leading-none mb-6",children:g}),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(Ns,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"text-[32px] font-bold relative z-10 leading-none mb-6",children:[N,"%"]}),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:"Vs. expected benchmark"}),e.jsx("span",{className:"text-[11px] font-bold bg-white/20 px-2 py-0.5 rounded-[4px] backdrop-blur-sm",children:"+1.4%"})]})]}),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(Ns,{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:"Attendance rate"}),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(is,{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:"94%"}),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:"Active participants"}),e.jsx("span",{className:"text-[11px] font-bold bg-white/20 px-2 py-0.5 rounded-[4px] backdrop-blur-sm",children:g>0?Math.round(g*.94):0})]})]}),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(Ns,{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:[N,"%"]}),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:"Vs. last month"}),e.jsx("span",{className:"text-[11px] font-bold bg-white/20 px-2 py-0.5 rounded-[4px] backdrop-blur-sm",children:"+2.1%"})]})]}),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(lr,{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:S}),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:[g>0?Math.round(S/g*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.jsx("span",{className:"text-[10px] font-bold text-[#9333ea] bg-white px-2 py-0.5 rounded-[4px]",children:"2 Pending"})]}),e.jsxs("div",{className:"space-y-[8px] flex-1 overflow-y-auto no-scrollbar relative z-10",children:[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(di,{className:"w-4 h-4"})}),e.jsxs("div",{className:"leading-snug text-white/90",children:[e.jsx("span",{className:"font-bold text-white",children:"Grade 11 - Section B"})," average dropped by 4% after the last quiz."]})]}),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(vs,{className:"w-4 h-4"})}),e.jsxs("div",{className:"leading-snug text-white/90",children:[e.jsx("span",{className:"font-bold text-white",children:"3 Lesson Plans"})," generated and awaiting your review."]})]})]})]})]}),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:p?"Select a Class":"My Classes"}),l&&!p&&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(Zs,{size:14}),"Create Class"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-[16px]",children:[j.map((h,w)=>{const C=nr[w%nr.length];let M=null;return h.riskLevel==="high"?M=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"}):h.riskLevel==="medium"?M=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"}):M=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(h),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] ${C.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] ${C.bg} flex items-center justify-center border ${C.border}`,children:e.jsx(Vt,{className:`w-5 h-5 ${C.text}`})}),e.jsxs("div",{children:[e.jsx("h4",{className:`font-bold text-[14px] text-[#1e293b] mb-0.5 transition-colors ${C.groupHover}`,children:h.name}),e.jsx("p",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider",children:h.gradeLevel||"Senior High"})]})]}),M]}),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:h.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:p?"Avg Competency":"Average"}),e.jsxs("span",{className:"font-semibold text-[#1e293b]",children:[h.avgScore,"%"]})]}),!p&&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:h.schedule||"Mon-Fri"})]})]})]})]},h.id)}),j.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."})]})]})]})})},Zi="PH_SHS_OFFICIAL_CLASS_RECORD",du=.85,Vr=.85,mu="2026.04.24",el=4,Wa=["INPUT DATA","SENIOR HIGH SCHOOL CLASS RECORD","LEARNERS NAMES","WRITTEN WORK","PERFORMANCE TASKS","QUARTERLY ASSESSMENT","REMARK","FINAL SEMESTRAL GRADES"],uu=[...Wa,"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"],xu=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],Aa=["WITH ATTACHMENTS","OFFICIALLY DROPPED","WITHDRAWN","UNOFFICIALLY DROPPED","TRANSFEREE","SHIFTER"],pu=["TOTAL","SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY","WEIGHT OF COMPONENTS"],hu={SECOND:["SECOND QUARTER","2ND QUARTER","Q2"]},qs={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"]},Ut={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"]},De={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 fu(t){return t==null?null:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:String(t)}function vt(t){return String(t??"").replace(/[\u00a0\t\r\n]+/g," ").replace(/[|]+/g," ").replace(/\s+/g," ").trim().toUpperCase()}function Lo(t){return vt(t).replace(/[^A-Z0-9]+/g,"")}function Se(t,s){const a=vt(t),r=vt(s);if(!a||!r)return!1;if(a.includes(r))return!0;const o=Lo(t),n=Lo(s);return!o||!n?!1:o.includes(n)}function qa(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 _r(t){return vt(t).toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,80)}function tl(t){const s={};return t.forEach(a=>{const r=Yt.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=Yt.encode_cell({r:o,c:n});s[i]=r}}),s}function gu(t,s,a){const o=(a||tl(t.merges))[s]||s;return t.cells[o]||t.cells[s]}const sl="A1:A1",Do=1200,$o=200,Fo=2e5;function bu(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>Do&&(r=s+Do-1),o-a+1>$o&&(o=a+$o-1);const n=r-s+1,i=o-a+1;if(n*i>Fo){const c=Math.max(1,Math.floor(Fo/i));r=s+Math.min(n,c)-1}return{s:{r:s,c:a},e:{r,c:o}}}function vu(t){try{return Yt.decode_range(t)}catch{return Yt.decode_range(sl)}}function wu(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=Yt.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 Nu(t){const s=vu(t.ref||sl),a=wu(t);return bu(a||s)}function ju(t,s){const a=Nu(s),r=`${Yt.encode_cell(a.s)}:${Yt.encode_cell(a.e)}`,o=tl(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 Rs(t,s){return st.endRow?"":(t.cells[s-t.startRow]||[]).map(r=>r?.normalizedText||"").filter(Boolean).join(" ").trim()}function fa(t){return Yt.encode_col(t)}function Pa(t){const s=String(t||"").trim().toUpperCase();if(!s||!/^[A-Z]+$/.test(s))return-1;try{return Yt.decode_col(s)}catch{return-1}}function yu(t){return`${Yt.encode_cell(t.s)}:${Yt.encode_cell(t.e)}`}function Su(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=Be(t,r,n);o.push(i?.displayValue??null)}a.push(o)}return a}function ku(t,s){const a=vt(t),r=vt(s);return!a||!r?0:a===r?1:a.includes(r)?.9:.75}function mn(t,s){const a=[];for(let r=0;r{Se(l.normalizedText,c)&&a.push({sheetName:t.sheetName,anchor:c,row:l.row,col:l.col,address:l.address,value:String(l.displayValue??""),confidence:ku(l.displayValue,c)})})}const o=t.startRow+r,n=Rs(t,o);n&&s.forEach(i=>{if(!Se(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 Cu(t,s){return Object.values(t).flatMap(a=>mn(a,s))}function jt(t,s){return mn(t,[s]).sort((a,r)=>a.row-r.row||a.col-r.col)}function al(t,s,a,r=6){for(let o=1;o<=r;o+=1){const i=Be(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=Be(t,s+o,a)?.displayValue;if(i!=null&&String(i).trim())return String(i).trim()}}function rl(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=Rs(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 Iu(t,s){const a=vt(t).toLowerCase(),r=o=>[...s].some(n=>Se(n,o));return qs.inputData.some(o=>a.includes(o))||r("INPUT DATA")?"inputData":qs.finalSemestral.some(o=>a.includes(o))||r("FINAL SEMESTRAL GRADES")||r("FINAL GRADES")?"finalSemestral":qs.firstQuarter.some(o=>a.includes(o))||r("FIRST QUARTER")?"firstQuarter":qs.secondQuarter.some(o=>a.includes(o))||r("SECOND QUARTER")?"secondQuarter":r("SENIOR HIGH SCHOOL CLASS RECORD")||r("WRITTEN WORK")&&r("PERFORMANCE TASKS")?"firstQuarter":qs.helper.some(o=>a.includes(o))||r("WEIGHT OF COMPONENTS")||r("ATTACHMENTS")||r("HELPER")?"helper":qs.lookup.some(o=>a.includes(o))||r("LOOK UP")?"lookup":"other"}function Tu(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 Eu(t){const s=Cu(t.matrices,uu),a=new Set,r=[];Wa.forEach(g=>{s.some(N=>Se(N.anchor,g))&&(a.add(g),r.push(`Found critical anchor: ${g}`))});const o=Wa.filter(g=>!a.has(g)),n=new Map;s.forEach(g=>{n.has(g.sheetName)||n.set(g.sheetName,new Set),n.get(g.sheetName)?.add(g.anchor)});const i=t.sheetNames.map(g=>{const S=n.get(g)||new Set,N=Iu(g,S),j=Math.min(1,.35+Math.min(.55,S.size*.08)),h=[`sheet:${g}`,`signals:${S.size}`,...[...S].slice(0,5)];return{sheetName:g,role:N,confidence:Number(j.toFixed(3)),evidence:h}}),l={firstQuarter:[],secondQuarter:[],finalSemestral:[],helper:[],lookup:[],other:[]};i.forEach(g=>{switch(g.role){case"inputData":l.inputData?l.other.push(g.sheetName):l.inputData=g.sheetName;break;case"firstQuarter":l.firstQuarter.push(g.sheetName);break;case"secondQuarter":l.secondQuarter.push(g.sheetName);break;case"finalSemestral":l.finalSemestral.push(g.sheetName);break;case"helper":l.helper.push(g.sheetName);break;case"lookup":l.lookup.push(g.sheetName);break;case"other":default:l.other.push(g.sheetName);break}});const c=(l.inputData?1:0)+l.firstQuarter.length+l.secondQuarter.length+l.finalSemestral.length+l.helper.length+l.lookup.length,d=Tu({criticalFound:a.size,criticalTotal:Wa.length,recognizedSheets:c,totalSheets:t.sheetNames.length,hasDepedAnchor:s.some(g=>Se(g.anchor,"Pursuant to DepEd Order 8 series of 2015"))}),m=l.firstQuarter.length>0||l.secondQuarter.length>0,f=!!l.inputData&&m&&l.finalSemestral.length>0,p=d>=.55&&f;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:Zi,isOfficialFormatLikely:p,confidence:d,evidence:r,missingCriticalAnchors:o,detectedSheets:l,anchorMatches:s}}function or(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 un(t){const s=vt(t);if(s.includes("FEMALE"))return"FEMALE";if(s.includes("MALE"))return"MALE"}function xn(t){const s=vt(t.rowText);return s?s==="MALE"||s==="FEMALE"?"sex-header":xu.some(a=>s.includes(a))?"signature":pu.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 Ru(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(o=>{a.push({role:r,name:String(Be(t,o.row,o.col+1)?.displayValue||"").trim()||void 0,sourceSheet:t.sheetName,sourceRow:o.row+1})})}),a}function _u(t){const s=[],a=jt(t,"LEARNERS NAMES")[0],r=a?rl(t,a.row,5):t.startRow,o=(j,h)=>jt(t,j).find(C=>Math.abs(C.row-r)<=2)?.col??h,n=o(De.learnerNo[0],t.startCol),i=o(De.learnerName[0],t.startCol+1),l=o(De.firstQuarter[0],i+1),c=o(De.secondQuarter[0],l+1),d=o(De.firstSemester[0],c+1),m=o(De.finalGrades[0],d+1),f=o(De.remark[0],m+1),p=o(De.additionalRemarks[0],f+1),g=[];let S="UNKNOWN",N=0;for(let j=r+1;j<=t.endRow;j+=1){const h=Rs(t,j),w=xn({rowText:h,hasLearnerNumber:/\b\d{1,2}\b/.test(h),hasLearnerName:/[A-Z]{2,}/.test(h)});if(w==="sex-header"){S=un(h)||S;continue}if(w==="signature"||w==="helper")break;if(w==="blank"){if(N+=1,N>=el)break;continue}if(w!=="learner")continue;N=0;const C=or(Be(t,j,n)?.displayValue),M=String(Be(t,j,i)?.displayValue||"").trim();if(!M&&C===void 0)continue;const k=Be(t,j,l)?.displayValue??null,q=Be(t,j,c)?.displayValue??null,b=Be(t,j,d)?.displayValue??null,y=Be(t,j,m)?.displayValue??null,v=Be(t,j,f)?.displayValue??null;let z=Be(t,j,p)?.displayValue??null;const F=Aa.filter(I=>Se(h,I));F.length>0&&(z=[z,F.join("; ")].filter(Boolean).join("; ")||null),!M&&C!==void 0&&s.push(`Row ${j+1} has learner number ${C} but empty learner name.`),g.push({learnerNo:C,fullName:M||`Unnamed Learner ${C||j+1}`,sex:S,firstQuarter:k,secondQuarter:q,firstSemester:b,finalGrades:y,remark:v,additionalRemarks:z,sourceRow:j+1})}return{sheetName:t.sheetName,learnerGrades:g,signatures:Ru(t),warnings:s}}function es(t,s){for(const a of s){const r=jt(t,a);for(const o of r){const n=al(t,o.row,o.col,8);if(n&&n.trim())return n.trim()}}}function Mu(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(n=>{const i=al(t,n.row,n.col,10);a.push({role:r,name:i,sourceSheet:t.sheetName,sourceRow:n.row+1})})}),a}function Au(t){const s=jt(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 f=Rs(t,m),p=xn({rowText:f,hasLearnerNumber:!!or(Be(t,m,o)?.displayValue),hasLearnerName:!!String(Be(t,m,r)?.displayValue||"").trim()});if(p==="sex-header"){c=un(f)||c,d=0;continue}if(p==="signature"||p==="helper")break;if(p!=="learner"){if(p==="blank"&&(d+=1),d>=5)break;continue}d=0;const g=or(Be(t,m,o)?.displayValue),S=String(Be(t,m,r)?.displayValue||"").trim(),N=String(Be(t,m,n)?.displayValue||"").trim()||void 0,j=String(Be(t,m,i)?.displayValue||"").trim()||void 0,h=Aa.filter(w=>Se(f,w));!S&&g===void 0||l.push({learnerNo:g,sex:c,fullName:S||`Unnamed Learner ${g||m}`,sourceSheet:t.sheetName,sourceRow:m+1,remarks:N,additionalRemarks:j,statuses:h.length>0?h:void 0})}return l}function zu(t){const s=[],a=[];for(let r=t.startRow;r<=t.endRow;r+=1){const o=Rs(t,r);if(o){if(Aa.some(n=>Se(o,n))){s.push(o);continue}(Se(o,"IMPORTANT")||Se(o,"NOTE")||Se(o,"ATTACHMENT")||Se(o,"LOOK UP"))&&a.push(o)}}return{attachmentRules:Array.from(new Set(s)),helperNotes:Array.from(new Set(a))}}function Lu(t){const s=[],a={region:es(t,Ut.region),division:es(t,Ut.division),schoolName:es(t,Ut.schoolName),schoolId:es(t,Ut.schoolId),schoolYear:es(t,Ut.schoolYear),gradeSection:es(t,Ut.gradeSection),semester:es(t,Ut.semester),track:es(t,Ut.track),subjectCode:es(t,Ut.subjectCode),subjectName:es(t,Ut.subjectName),teacherName:es(t,Ut.teacherName)},r=Au(t),o=Mu(t),{attachmentRules:n,helperNotes:i}=zu(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."),mn(t,Object.values(Ut).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 Du(t){const s=vt(t.sheetName);return hu.SECOND.some(a=>Se(s,a))?"SECOND":"FIRST"}function $u(t,s){const a=[],r=[],o=[];let n,i="NONE";for(let l=t.startCol;l<=t.endCol;l+=1){const c=Be(t,s,l),d=vt(c?.displayValue||""),m=Be(t,s+1,l),f=String(m?.displayValue||c?.displayValue||"").trim();if(!d&&!f)continue;if(Se(d,De.writtenWork[0])){i="WW";continue}if(Se(d,De.performanceTasks[0])){i="PT";continue}if(Se(d,De.quarterlyAssessment[0])){n={key:_r(f||"quarterly_assessment"),label:f||"Quarterly Assessment",column:fa(l)},i="DERIVED";continue}if(Se(d,De.initialGrade[0])||Se(d,De.quarterlyGrade[0])||Se(d,De.remark[0])||Se(d,De.additionalRemarks[0])||Se(d,De.firstQuarter[0])||Se(d,De.secondQuarter[0])||Se(d,De.firstSemester[0])||Se(d,De.finalGrades[0])||Se(d,De.ps[0])||Se(d,De.ws[0])||Se(d,De.total[0])){i="DERIVED",o.push({key:_r(f||d),label:f||d,column:fa(l)});continue}const p={key:_r(f||d||fa(l)),label:f||d||fa(l),maxScore:qa(m?.displayValue),column:fa(l)};i==="WW"?a.push(p):i==="PT"?r.push(p):i==="DERIVED"&&o.push(p)}return{writtenWorks:a,performanceTasks:r,quarterlyAssessment:n,derived:o}}function Fu(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(o=>{const n=Be(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 Oo(t,s,a){for(let r=t.startCol;r<=t.endCol;r+=1){const o=vt(Be(t,s,r)?.displayValue||""),n=vt(Be(t,s+1,r)?.displayValue||"");if(a.some(i=>Se(o,i)||Se(n,i)))return r}}function Ou(t,s,a,r){const o={learnerNo:or(Be(t,s,r.numberCol)?.displayValue),fullName:String(Be(t,s,r.nameCol)?.displayValue||"").trim(),sourceRow:s+1},n={};a.writtenWorks.forEach(d=>{const m=d.column?Pa(d.column):-1;if(m<0)return;const f=Be(t,s,m)?.displayValue;n[d.key]=f??null}),Object.keys(n).length>0&&(o.writtenWorks=n);const i={};if(a.performanceTasks.forEach(d=>{const m=d.column?Pa(d.column):-1;if(m<0)return;const f=Be(t,s,m)?.displayValue;i[d.key]=f??null}),Object.keys(i).length>0&&(o.performanceTasks=i),a.quarterlyAssessment?.column){const d=Pa(a.quarterlyAssessment.column);o.quarterlyAssessment=Be(t,s,d)?.displayValue??null}const l=a.derived||[],c={};return l.forEach(d=>{if(!d.column)return;const m=Pa(d.column);if(m<0)return;const f=Be(t,s,m)?.displayValue??null;c[d.key]=f,Se(d.label,De.initialGrade[0])&&(o.initialGrade=f),Se(d.label,De.quarterlyGrade[0])&&(o.quarterlyGrade=f),Se(d.label,De.firstQuarter[0])&&(o.firstQuarter=f),Se(d.label,De.secondQuarter[0])&&(o.secondQuarter=f),Se(d.label,De.firstSemester[0])&&(o.firstSemester=f),Se(d.label,De.finalGrades[0])&&(o.finalGrades=f),Se(d.label,De.remark[0])&&(o.remark=f!==null?String(f):null),Se(d.label,De.additionalRemarks[0])&&(o.additionalRemarks=f!==null?String(f):null)}),Object.keys(c).length>0&&(o.totals=c),o}function Bu(t){const s=Du(t),a=[],r=jt(t,De.learnerName[0])[0]||jt(t,De.learnerName[1])[0],o=r?rl(t,r.row,4):t.startRow,n=$u(t,o),i=Oo(t,o,De.learnerNo)??t.startCol,l=Oo(t,o,De.learnerName)??Math.min(t.endCol,i+1),c=[];let d="UNKNOWN",m=0;for(let S=o+1;S<=t.endRow;S+=1){const N=Rs(t,S),j=xn({rowText:N,hasLearnerNumber:/\b\d{1,2}\b/.test(N),hasLearnerName:/[A-Z]{2,}/.test(N)});if(j==="sex-header"){d=un(N)||d;continue}if(j==="signature"||j==="helper")break;if(j==="blank"){if(m+=1,m>=el)break;continue}if(j!=="learner")continue;m=0;const h=Ou(t,S,n,{numberCol:i,nameCol:l});if(h.sex=d,!h.fullName&&h.learnerNo===void 0)continue;const w=Aa.filter(C=>Se(N,C));w.length>0&&!h.additionalRemarks&&(h.additionalRemarks=w.join("; ")),!h.fullName&&h.learnerNo!==void 0&&(a.push(`Row ${S+1} has learner number ${h.learnerNo} but empty name.`),h.fullName=`Unnamed Learner ${h.learnerNo}`),c.push(h)}n.writtenWorks.length===0&&n.performanceTasks.length===0&&a.push(`No detailed assessment columns detected in ${t.sheetName}.`);const f=qa(jt(t,"WRITTEN WORK %")[0]?.value||jt(t,"WRITTEN WORK")[0]?.value),p=qa(jt(t,"PERFORMANCE TASKS %")[0]?.value||jt(t,"PERFORMANCE TASKS")[0]?.value),g=qa(jt(t,"QUARTERLY ASSESSMENT %")[0]?.value||jt(t,"QUARTERLY ASSESSMENT")[0]?.value);return{sheetName:t.sheetName,quarter:s,gradingWeights:{writtenWork:f,performanceTasks:p,quarterlyAssessment:g},assessmentColumns:n,learnerGrades:c,signatures:Fu(t),warnings:a}}function Pu(t){const s=["SUBMITTED BY","CHECKED BY","VERIFIED BY","RECOMMENDED BY","APPROVED BY"],a=[];return s.forEach(r=>{jt(t,r).forEach(o=>{a.push({role:r,name:String(Be(t,o.row,o.col+1)?.displayValue||"").trim()||void 0,sourceSheet:t.sheetName,sourceRow:o.row+1})})}),a}function Hu(t){const s=[];let a=!1;for(let r=t.startRow;r<=t.endRow;r+=1){const o=Rs(t,r);if(!o){if(a&&s.length>0)break;continue}if(Se(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=Be(t,r,i)?.displayValue;l==null||String(l).trim()===""||(n[`c${i}`]=l)}Object.keys(n).length>2&&s.push(n)}return s}function Qu(t){const s=[],a=[],r=[],o=[],n=[];return t.forEach(i=>{Pu(i).forEach(l=>a.push(l)),Hu(i).forEach(l=>r.push({...l,sourceSheet:i.sheetName}));for(let l=i.startRow;l<=i.endRow;l+=1){const c=Rs(i,l);if(c){if(Aa.some(d=>Se(c,d))){o.push(`${i.sheetName}: ${c}`);continue}(Se(c,"HELPER")||Se(c,"LOOK UP")||Se(c,"IMPORTANT")||Se(c,"REFERENCE")||Se(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 Gu(t,s,a){const r=new Map,o=n=>{const i=`${vt(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 Uu(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=`${vt(i.role)}|${vt(i.name||"")}|${i.sourceSheet}`;n.set(l,i)}),Array.from(n.values())}function Vu(t){const s=Gu(t.inputData.learners,t.quarterSheets,t.finalSheets);return{format:Zi,version:mu,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:Uu(t.inputData,t.quarterSheets,t.finalSheets,t.references),unclassifiedBlocks:t.unclassifiedBlocks},validation:t.validation,raw:t.workbook.raw}}function Wu(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 qu(t){const s={ref:t["!ref"],merges:Wu(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 Yu(t,s){const a=cc(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=qu(i);o[n]=l,r[n]=ju(n,l)}),{fileName:t,sheetNames:a.SheetNames,raw:{sheets:o},matrices:r}}async function Ku(t){const s=await t.arrayBuffer();return Yu(t.name,s)}class Xu{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=Be(o,l,c);if(!(m&&m.displayValue!==null&&m.displayValue!==void 0&&String(m.displayValue).trim())){n.add(d);continue}const p=this.collectComponent(o,l,c,i,n);p&&r.push({sheetName:o.sheetName,range:yu(p),purposeGuess:a,raw2D:Su(o,p)})}}),r}collectComponent(s,a,r,o,n){const i=[{row:a,col:r}];let l=a,c=a,d=r,m=r,f=!1;for(;i.length>0;){const p=i.shift();if(!p)break;const g=`${p.row}:${p.col}`;if(n.has(g)||o.has(g))continue;n.add(g);const S=Be(s,p.row,p.col);S&&S.displayValue!==null&&S.displayValue!==void 0&&String(S.displayValue).trim()&&(f=!0,l=Math.min(l,p.row),c=Math.max(c,p.row),d=Math.min(d,p.col),m=Math.max(m,p.col),[{row:p.row-1,col:p.col},{row:p.row+1,col:p.col},{row:p.row,col:p.col-1},{row:p.row,col:p.col+1}].forEach(j=>{j.rows.endRow||j.cols.endCol||i.push(j)}))}return f?{s:{r:l,c:d},e:{r:c,c:m}}:null}}function Ju(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 Zu(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 ex(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 tx(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 sx(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(", ")}.`),Zu(t.inputData.learners).forEach(n=>s.push(n)),ex(t.quarterSheets).forEach(n=>s.push(n)),tx(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 Bo=1500;function Po(t){return t?Object.values(t.matrices).reduce((s,a)=>s+a.rowCount*a.colCount,0):0}function Ho(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>=Bo){console.warn(`${s} slow=true threshold=${Bo}ms`);return}}function zs(t,s){t?.onProgress?.(s)}function rx(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 ga(t,s,a,r){rx(a,s).forEach(o=>{t.markRange(s.sheetName,{s:{r:o,c:s.startCol},e:{r:o,c:s.endCol}},r)})}async function nx(t,s){const a=s?.confidenceThreshold??du,r=Date.now();let o=null;try{if(zs(s,{stage:"reading",message:"Reading workbook structure and raw sheets..."}),o=await Ku(t),!o)throw new Error("Workbook read returned null");zs(s,{stage:"detecting-format",message:"Detecting DepEd SHS workbook format..."});const n=Eu(o);zs(s,{stage:"extracting",message:"Extracting metadata, learners, grades, and references..."});const i=n.detectedSheets.inputData||o.sheetNames[0],l=o.matrices[i],c=l?Lu(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(C=>o.matrices[C]).filter(C=>!!C).map(C=>Bu(C)),f=(n.detectedSheets.finalSemestral||[]).map(C=>o.matrices[C]).filter(C=>!!C).map(C=>_u(C)),p=[...n.detectedSheets.helper||[],...n.detectedSheets.lookup||[]].map(C=>o.matrices[C]).filter(C=>!!C),g=Qu(p),S=new Xu;n.anchorMatches.forEach(C=>{const M=o.matrices[C.sheetName];M&&ga(S,M,[C.row],`Anchor match: ${C.anchor}`)}),[c.sheetName].forEach(C=>{const M=o.matrices[C];if(!M)return;const k=Array.from({length:Math.min(14,M.rowCount)},(y,v)=>M.startRow+v),q=c.learners.map(y=>y.sourceRow-1),b=c.signatures.map(y=>y.sourceRow).filter(y=>typeof y=="number").map(y=>y-1);ga(S,M,[...k,...q,...b],"Input Data parsed rows")}),m.forEach(C=>{const M=o.matrices[C.sheetName];if(!M)return;const k=C.learnerGrades.map(y=>y.sourceRow-1),q=C.signatures.map(y=>y.sourceRow).filter(y=>typeof y=="number").map(y=>y-1),b=k.length>0?Math.max(M.startRow,Math.min(...k)-2):M.startRow;ga(S,M,[b,b+1,...k,...q],"Quarter sheet parsed rows")}),f.forEach(C=>{const M=o.matrices[C.sheetName];if(!M)return;const k=C.learnerGrades.map(y=>y.sourceRow-1),q=C.signatures.map(y=>y.sourceRow).filter(y=>typeof y=="number").map(y=>y-1),b=k.length>0?Math.max(M.startRow,Math.min(...k)-2):M.startRow;ga(S,M,[b,b+1,...k,...q],"Final semestral parsed rows")}),p.forEach(C=>{const M=g.componentWeights.filter(b=>b.sourceSheet===C.sheetName).map(b=>b.sourceRow).filter(b=>typeof b=="number").map(b=>b-1),k=g.signatures?.filter(b=>b.sourceSheet===C.sheetName).map(b=>b.sourceRow).filter(b=>typeof b=="number").map(b=>b-1)||[],q=M.length===0&&k.length===0?[C.startRow,C.startRow+1,C.startRow+2]:[];ga(S,C,[...M,...k,...q],"Reference/helper parsed rows")});const N=S.getUnmappedBlocks(o.matrices);zs(s,{stage:"validating",message:"Validating completeness and structural integrity..."});const j=sx({detection:n,inputData:c,quarterSheets:m,finalSheets:f,mappedCellRegions:S.getMappedRegionCount(),unmappedCellRegions:N.length,totalSheets:o.sheetNames.length});zs(s,{stage:"normalizing",message:"Normalizing parsed workbook and creating entity mapping..."});const h=Vu({workbook:o,detection:n,inputData:c,quarterSheets:m,finalSheets:f,references:g,validation:j,unclassifiedBlocks:N});h.validation.confidence_.trim().toLowerCase().replace(/\s+/g," "),he=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;const Q=Number(String(_??"").replace(/[^0-9.-]+/g,""));return Number.isFinite(Q)?Q:null},we=(_,Q)=>{const U=Number.isFinite(_)?_:Q;return Math.max(0,Math.min(100,U))},O=_=>{const Q=String(_??"");return/[",\n]/.test(Q)?`"${Q.replace(/"/g,'""')}"`:Q},J=(_,Q)=>{const U=new Map,E=["quarterlyGrade","finalGrades","firstSemester","firstQuarter","secondQuarter","initialGrade"];_.mapping.gradeEntities.forEach(Pe=>{const tt=ae(Pe.fullName||"");if(!tt)return;const Tt=E.map(wt=>he(Pe[wt])).filter(wt=>wt!==null);if(Tt.length===0)return;const dt=U.get(tt)||[];U.set(tt,dt.concat(Tt))});const te=_.mapping.studentEntities||[];if(te.length===0)return null;const de=(_.imported.schoolContext.semester||_.imported.schoolContext.schoolYear||"First Semester").trim(),xe=(_.imported.schoolContext.subjectName||"Class Record Import").trim(),oe=(t||s||"import").replace(/[^a-zA-Z0-9]+/g,"").toUpperCase().slice(0,12)||"IMPORT",qe=[["name","lrn","email","engagementScore","avgQuizScore","attendance","assignmentCompletion","term","assessmentName"].join(",")];if(te.forEach((Pe,tt)=>{const Tt=ae(Pe.fullName||""),dt=U.get(Tt)||[],wt=dt.length>0?dt.reduce((Dt,$t)=>Dt+$t,0)/dt.length:75,Lt=we(wt,75),B=we(Lt+5,85),Ae=we(Lt*.7+B*.3,80),Xe=we(B*.6+Lt*.4,82),Nt=Pe.learnerNo||tt+1,Kt=`IMP-${oe}-${String(Nt).padStart(4,"0")}`,Et=Pe.fullName||`Learner ${tt+1}`;qe.push([O(Et),O(Kt),O(""),O(Number(Ae.toFixed(1))),O(Number(Lt.toFixed(1))),O(Number(B.toFixed(1))),O(Number(Xe.toFixed(1))),O(de),O(xe)].join(","))}),qe.length<=1)return null;const Fe=Q.replace(/\.(xlsx|xls)$/i,"");return new File([qe.join(` +`)],`${Fe}-normalized.csv`,{type:"text/csv"})},A=async _=>{y(!0),I(""),Y(null);let Q=_;if(/\.(xlsx|xls)$/i.test(_.name))try{const U=await nx(_,{confidenceThreshold:Vr});w(U);const E=J(U,_.name);E&&(Q=E)}catch{w(null)}else w(null);try{const U=await it.uploadClassRecords(Q,{classSectionId:t,className:s,datasetIntent:"synthetic_student_records"}),E=U.students.length,de=((xe,oe,fe,qe)=>({classSectionId:xe.classSectionId||oe||"imported_class",className:xe.className||fe||"Imported Class",classMetadata:xe.classMetadata||qe}))(U,t,s,a);E>0&&l?.({students:U.students,classSectionId:de.classSectionId,className:de.className,classMetadata:de.classMetadata}),U.success?(me.success(`Successfully imported ${E} student records.`),Y({datasetIntent:U.datasetIntent,summary:U.interpretationSummary,columns:U.columnInterpretations?.map(xe=>({columnName:xe.columnName,mappedField:xe.mappedField,usagePolicy:xe.usagePolicy,confidenceBand:xe.confidenceBand,domainSignals:xe.domainSignals}))||[]}),c?.()):me.error("Import completed but no usable student rows were detected. Check required columns and retry.")}catch(U){me.error(U instanceof Error?U.message:"Upload failed")}finally{y(!1)}},Z=async _=>{z(!0);try{const Q=await it.uploadCourseMaterials(_,{classSectionId:t,className:s});if(Q.success){const U=Q.topics?.length??0;me.success(`Course material imported (${U} topics extracted).`),c?.()}}catch(Q){me.error(Q instanceof Error?Q.message:"Course material upload failed")}finally{z(!1)}},[ne,$e]=u.useState(r),[Me,We]=u.useState(!1),[P,re]=u.useState(null),T=u.useMemo(()=>{let _=ne;if(o.length>0){const Q=new Set(o.map(U=>gs(U.classSectionId||U.id)));_=_.filter(U=>Q.has(gs(U.classSectionId))||Q.has(gs(U.classroomId)))}else return[];return t&&(_=_.filter(Q=>gs(Q.classSectionId)===gs(t)||gs(Q.classroomId)===gs(t))),_},[ne,t,o]);u.useEffect(()=>{$e(r),H(Object.fromEntries(r.map(_=>[Ha(_),{grade:_.grade||"",section:_.section||""}])))},[r]);const[G,H]=u.useState({}),ce=async()=>{We(!0);let _=0,Q=0;try{for(const E of T){const te=G[Ha(E)],de=te?.grade||E.grade,xe=te?.section||E.section;try{n&&(de!==E.grade||xe!==E.section)&&(await xr(E.id,de,xe,n,new Date().getFullYear().toString(),i),await Vi(E.id,de,xe),_++)}catch(oe){console.warn(`[EditRecords] Failed to save ${E.name}:`,oe),Q++}}const U=ne.map(E=>{const te=G[Ha(E)];if(!te)return E;const de=bt({metadata:E.classMetadata,classSectionId:E.classSectionId,className:[te.grade,te.section].filter(Boolean).join(" - "),grade:te.grade,section:te.section});return{...E,grade:te.grade,section:te.section,className:de.className||[te.grade,te.section].filter(Boolean).join(" - "),classSectionId:de.classSectionId||E.classSectionId,classMetadata:de}});$e(U),m?.(U),Q>0?me.warning(`Saved ${_} records, ${Q} failed`):me.success("Records saved successfully")}catch{me.error("Failed to save changes")}finally{We(!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:[N==="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(Ja,{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(_t,{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(),M(!0)},onDragLeave:()=>M(!1),onDrop:_=>{_.preventDefault(),M(!1);const Q=_.dataTransfer.files[0];Q&&A(Q)},onClick:()=>se.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] ${C?"border-[#1FA7E1] bg-[#1FA7E1]/10":"border-[#1FA7E1]/30 hover:border-[#1FA7E1] bg-white hover:bg-[#1FA7E1]/5"}`,children:[e.jsx("input",{ref:se,type:"file",accept:".csv,.xlsx,.xls",onChange:_=>{const Q=_.target.files?.[0];Q&&A(Q)},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:b?e.jsx("span",{className:"animate-spin text-[#1FA7E1]",children:"..."}):e.jsx(zc,{className:"w-8 h-8 text-[#1FA7E1]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:b?"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(),q(!0)},onDragLeave:()=>q(!1),onDrop:_=>{_.preventDefault(),q(!1);const Q=_.dataTransfer.files[0];Q&&Z(Q)},onClick:()=>ie.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] ${k?"border-[#9956DE] bg-[#9956DE]/10":"border-[#9956DE]/30 hover:border-[#9956DE] bg-white hover:bg-[#9956DE]/5"}`,children:[e.jsx("input",{ref:ie,type:"file",accept:".pdf,.docx,.txt",onChange:_=>{const Q=_.target.files?.[0];Q&&Z(Q)},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:v?e.jsx("span",{className:"animate-spin text-[#9956DE]",children:"..."}):e.jsx(vs,{className:"w-8 h-8 text-[#9956DE]"})}),e.jsx("h3",{className:"text-[18px] font-bold text-[#1e293b] mb-2",children:v?"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(Mc,{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(di,{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(Fs,{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(qr,{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:()=>j("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(Ic,{className:"w-4 h-4"})," Edit Class Records"]}),e.jsx("button",{onClick:()=>j("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:()=>j("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(Nc,{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."})]})]})]})]}),N==="mapping-logs"&&e.jsxs("div",{className:"space-y-[16px]",children:[e.jsx("div",{className:"shrink-0 mb-2",children:e.jsxs("button",{onClick:()=>j("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(Za,{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:W?e.jsx("div",{className:"space-y-3",children:W.columns.map((_,Q)=>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"})]},Q))}):e.jsx("p",{className:"text-slate-500 text-sm",children:"No recent mapping logs to display."})})]})]}),N==="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:()=>j("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(Za,{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:()=>j("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:ce,disabled:Me,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:Me?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(ni,{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(ba,{className:"w-4 h-4"})," Click on any field to edit"]}),e.jsxs("span",{children:["Showing ",T.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:T.map((_,Q)=>{const U=Ha(_),E=_.name.split(" "),te=E.length>1?`${E[0][0]}${E[E.length-1][0]}`.toUpperCase():_.name.substring(0,2).toUpperCase(),de=["bg-[#be185d]","bg-[#3b82f6]","bg-[#f43f5e]","bg-[#2563eb]","bg-[#059669]","bg-[#d946ef]"],xe=de[Q%de.length],oe=(_.avgScore??0)>=75?"text-emerald-500":(_.avgScore??0)>=60?"text-orange-500":"text-rose-500";let fe="bg-slate-50 text-slate-600 border-slate-200";const qe=(_.riskLevel||"").toLowerCase();return qe==="low"?fe="bg-emerald-50 text-emerald-600 border-emerald-200":qe==="high"?fe="bg-rose-50 text-rose-600 border-rose-200":qe==="medium"&&(fe="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 ${xe} text-white flex items-center justify-center font-bold text-[12px] shrink-0`,children:te}),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:G[U]?.grade||_.grade||"",onChange:Fe=>H(Pe=>({...Pe,[U]:{...Pe[U],grade:Fe.target.value}})),readOnly:P!==U,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${P===U?"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:G[U]?.section||_.section||"",onChange:Fe=>H(Pe=>({...Pe,[U]:{...Pe[U],section:Fe.target.value}})),readOnly:P!==U,className:`outline-none px-4 py-1.5 rounded-full text-[13px] font-medium text-slate-600 w-full transition-all text-center ${P===U?"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:`${oe} 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 ${fe}`,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:()=>re(P===U?null:U),className:`w-8 h-8 rounded-full flex items-center justify-center transition-colors ${P===U?"bg-purple-100 text-purple-600":"hover:bg-slate-200 text-slate-400"}`,children:e.jsx(ci,{className:"w-4 h-4"})})})]},U)})})]})})]})]})]})})}const Qa="ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789",Qo="school.mathpulse.local";function Go(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(""),[f,p]=u.useState(!1),[g,S]=u.useState(null),[N,j]=u.useState(null),[h,w]=u.useState(!1);u.useEffect(()=>{t&&(S(null),w(!1),p(!1),j(null),c((a?.email||ix(a)).trim()),m(Go()))},[t,a]);const C=u.useMemo(()=>a?[a.grade,a.section].filter(Boolean).join(" · ")||"Unassigned section":null,[a]),M=()=>{m(Go()),w(!1)},k=async()=>{try{const y=N?.temporaryPassword||d;if(!y)return;typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(y),w(!0),me.success("Temporary password copied. Share it with the student now — it will not be shown again."),window.setTimeout(()=>w(!1),2500)}catch(y){console.warn("Clipboard write failed:",y),me.error("Unable to copy password. Please copy it manually.")}},q=async()=>{if(!a)return;const y=l.trim();if(!lx(y)){S("Enter a valid email address before creating the account.");return}if(!d||d.length<8){S("Temporary password must be at least 8 characters.");return}if(!r){S("Missing teacher context. Please refresh and try again.");return}p(!0),S(null);try{const v=await Nm({name:a.name,lrn:a.lrn,email:y,grade:a.grade,section:a.section,classSectionId:a.classSectionId,adviserTeacherId:r,adviserTeacherName:o,schoolYear:n,temporaryPassword:d});j(v),i?.({...v,rosterId:a.rosterId}),me.success(`Account created for ${a.name}.`)}catch(v){const z=v instanceof Error?v.message:"Failed to create account.";S(z)}finally{p(!1)}},b=N?.temporaryPassword||d;return e.jsx(Mt,{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:()=>{f||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:y=>y.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(Ko,{size:22})}),e.jsxs("div",{children:[e.jsx("h2",{id:"create-student-account-modal-title",className:"text-[16px] font-bold text-[#0a1628]",children:N?"Account Created":"Create Student Account"}),e.jsx("p",{className:"text-[12px] text-[#5a6578] mt-0.5",children:N?"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:()=>{f||s()},className:"p-1.5 rounded-lg hover:bg-[#dde3eb] transition-colors","aria-label":"Close",children:e.jsx(ds,{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} · `:"",C]})]}),!N&&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:y=>c(y.target.value),disabled:f,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:M,disabled:f,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(Ls,{className:"w-4 h-4 text-[#475569]"})}),e.jsx("button",{type:"button",onClick:k,className:"p-2 rounded-xl border border-[#dde3eb] bg-white hover:bg-[#f1f5f9] transition-colors","aria-label":"Copy temporary password",children:h?e.jsx(Ot,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Dr,{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."})]}),g&&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:g})]})]}),N&&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:N.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:b}),e.jsx("button",{type:"button",onClick:k,className:"p-1.5 rounded-lg border border-emerald-200 bg-white hover:bg-emerald-100 transition-colors","aria-label":"Copy temporary password",children:h?e.jsx(Ot,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Dr,{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:N?e.jsx(ht,{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(ht,{type:"button",variant:"ghost",onClick:s,disabled:f,className:"text-[13px] font-semibold text-[#475569] rounded-xl px-4 py-2 hover:bg-[#dde3eb]",children:"Cancel"}),e.jsx(ht,{type:"button",onClick:q,disabled:f,className:"bg-indigo-600 hover:bg-indigo-700 text-white text-[13px] font-semibold rounded-xl px-5 py-2 disabled:opacity-60",children:f?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4 animate-spin"}),"Creating…"]}):"Create account"})]})})]})})})};function dx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=bt({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 Mr(t,s){const a=t.riskLevel.toLowerCase(),r=t.lastActive?nl(t.lastActive.toDate()):"Unknown",o=t.className||s||"Imported Class",n=cs(o),i=t.grade||n.grade,l=t.section||n.section,c=bt({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,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||xs(i)||void 0,classification:c.classification||aa(c.gradeLevel||i)||void 0,strand:c.strand||ra(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 mx(t){const s=t.atRiskCount>=5?"high":t.atRiskCount>=2?"medium":"low",a=bt({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 ux(t){const s=(t.riskLevel||"Low").toLowerCase(),a=bt({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||cs(r).grade,gradeLevel:a.gradeLevel||xs(a.grade||cs(r).grade)||void 0,classification:a.classification||aa(a.gradeLevel||a.grade)||void 0,strand:a.strand||ra(r,a.section||t.section)||void 0,section:a.section||cs(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 xx(t,s,a){return t<60||s<75||a<55?"high":t<75||s<85||a<70?"medium":"low"}function px(t,s,a,r){const o=bt({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),f=t.unknownFields?.weakestTopic||t.unknownFields?.topic||"Foundational Skills",p=xx(l,c,d),g=t.studentId||t.lrn||t.email||t.name||Math.random().toString(36).slice(2);return{id:`upload-${i}-${g}`,lrn:t.lrn,name:t.name,avatar:`https://ui-avatars.com/api/?name=${encodeURIComponent(t.name)}&background=random`,avgScore:l,riskLevel:p,weakestTopic:f,classroomId:i,className:n,grade:o.grade||cs(n).grade,gradeLevel:o.gradeLevel||xs(o.grade||cs(n).grade)||void 0,classification:o.classification||aa(o.gradeLevel||o.grade)||void 0,strand:o.strand||ra(n,o.section)||void 0,section:o.section||cs(n).section,classSectionId:i,classMetadata:o,managerId:o.managerId||void 0,managerName:o.managerName||void 0,lastActive:"Recently imported",struggles:[f],engagementScore:d,attendance:c,assignmentCompletion:m}}function nl(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 rt(t){return(t||"").trim().toLowerCase()}function Uo(t){const s=rt(t.classSectionId);if(s)return`section:${s}`;const a=(t.id||"").trim().toLowerCase();return a?`id:${a}`:`name:${(t.name||"").trim().toLowerCase()}`}function Vo(t,s){const a=new Map;return t.forEach(r=>{a.set(Uo(r),r)}),s.forEach(r=>{const o=Uo(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=bt({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 ir(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=rt(t.classSectionId)||rt(t.classroomId),o=(t.id||"").trim().toLowerCase();return r&&o?`${r}|id:${o}`:`${r}|anonymous`}function Wr(t){const s=rt(t.classSectionId)||rt(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 Wo(t,s){const a=new Map;return t.forEach(r=>{a.set(ir(r),r)}),s.forEach(r=>{const o=ir(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=bt({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 fp=({onLogout:t,onOpenProfile:s,onOpenSettings:a})=>{const{currentUser:r,userProfile:o}=ms(),[n,i]=u.useState("dashboard"),[l,c]=u.useState(!1),[d,m]=u.useState(!1),[f,p]=u.useState(!1),[g,S]=u.useState(!1),[N,j]=u.useState(!1),[h,w]=u.useState(!1),[C,M]=u.useState(!1),k=["streak_reminder","daily_checkin","streak_milestone","achievement_unlocked","level_up","xp_earned","quiz_result"],{notifications:q}=ei(),b=q.filter(R=>!R.isRead&&!k.includes(R.type)).length,[y,v]=u.useState(null),[z,F]=u.useState(null),[I,W]=u.useState(!1),[Y,se]=u.useState(!1),[ie,ae]=u.useState(!1),[he,we]=u.useState(!1),[O,J]=u.useState([]),[A,Z]=u.useState([]),[ne,$e]=u.useState([]),[Me,We]=u.useState(""),[P,re]=u.useState(!0),[T,G]=u.useState(!1),[H,ce]=u.useState(0),[_,Q]=u.useState([]),[U,E]=u.useState(!1),[te,de]=u.useState(null),[xe,oe]=u.useState(null),fe=o?.name||"Teacher",qe=u.useRef(new Map);u.useEffect(()=>{const R=()=>S(window.innerWidth<1024);return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]),u.useEffect(()=>{if(!r)return;const R=r.uid;let ee=!0,ze;return(async()=>{re(!0);try{const Ge=await Wi(R);let je=Ge.map(dx);const gt=await ym(R).catch(()=>[]),nt=new Map;gt.forEach(L=>{const K=rt(L.classSectionId);K&&nt.set(K,L)}),je=je.map(L=>{const K=nt.get(rt(L.classSectionId));if(!K)return L;const ke=bt({metadata:L.classMetadata,classSectionId:K.classSectionId||L.classSectionId,className:K.className||L.name,grade:K.grade||L.classMetadata?.grade,gradeLevel:K.gradeLevel||L.classMetadata?.gradeLevel,classification:K.classification||L.classMetadata?.classification,strand:K.strand||L.classMetadata?.strand,section:K.section||L.classMetadata?.section,schoolYear:K.schoolYear||L.classMetadata?.schoolYear,ownerTeacherId:K.ownerTeacherId||L.classMetadata?.ownerTeacherId,ownerTeacherName:K.ownerTeacherName||L.classMetadata?.ownerTeacherName,managerId:K.managerId||L.classMetadata?.managerId,managerName:K.managerName||L.classMetadata?.managerName});return{...L,name:ke.className||L.name,classSectionId:ke.classSectionId||L.classSectionId,classMetadata:ke,gradeLevel:ke.gradeLevel||L.gradeLevel,classification:ke.classification||L.classification,strand:ke.strand||L.strand,managerId:ke.managerId||L.managerId,managerName:ke.managerName||L.managerName}});const Ce=new Map,ps=new Map;Ge.forEach(L=>{const K=bt({metadata:L.classMetadata,classSectionId:L.classSectionId,className:L.name,grade:L.grade,gradeLevel:L.gradeLevel,classification:L.classification,strand:L.strand,section:L.section,schoolYear:L.schoolYear,ownerTeacherId:L.ownerTeacherId||L.teacherId,ownerTeacherName:L.ownerTeacherName,adviserTeacherId:L.adviserTeacherId||L.teacherId,adviserTeacherName:L.adviserTeacherName,managerId:L.managerId,managerName:L.managerName});Ce.set(L.id,K.className||L.name),ps.set(L.id,K);const ke=rt(L.classSectionId);if(ke){const _e=nt.get(ke),Qt=bt({metadata:K,classSectionId:_e?.classSectionId||ke,className:_e?.className||K.className,grade:_e?.grade||K.grade,gradeLevel:_e?.gradeLevel||K.gradeLevel,classification:_e?.classification||K.classification,strand:_e?.strand||K.strand,section:_e?.section||K.section,schoolYear:_e?.schoolYear||K.schoolYear,ownerTeacherId:_e?.ownerTeacherId||K.ownerTeacherId,ownerTeacherName:_e?.ownerTeacherName||K.ownerTeacherName,managerId:_e?.managerId||K.managerId,managerName:_e?.managerName||K.managerName});Ce.set(ke,Qt.className||L.name),ps.set(ke,Qt)}});const Xt=L=>{const K=rt(L.classSectionId||L.classroomId);if(!K)return L;const ke=ps.get(K);if(!ke)return L;const _e=bt({metadata:ke,classSectionId:L.classSectionId||ke.classSectionId,className:L.className||ke.className,grade:L.grade||ke.grade,gradeLevel:L.gradeLevel||ke.gradeLevel,classification:L.classification||ke.classification,strand:L.strand||ke.strand,section:L.section||ke.section,managerId:L.managerId||ke.managerId,managerName:L.managerName||ke.managerName});return{...L,className:_e.className||L.className,grade:_e.grade||L.grade,gradeLevel:_e.gradeLevel||L.gradeLevel,classification:_e.classification||L.classification,strand:_e.strand||L.strand,section:_e.section||L.section,classSectionId:_e.classSectionId||L.classSectionId,classMetadata:_e,managerId:_e.managerId||L.managerId,managerName:_e.managerName||L.managerName}},Ms=(L,K,ke)=>Ce.get(L)||(K?Ce.get(K):void 0)||ke||"Unknown",La=Array.from(new Set([...gt.map(L=>L.classSectionId),...Ge.map(L=>L.classSectionId).filter(Boolean),...je.map(L=>L.classSectionId).filter(Boolean)].map(L=>(L||"").trim()).filter(L=>!!L))),[Jt,na]=await Promise.all([dn(R).catch(L=>(console.warn("[TeacherDashboard] managed-student fetch failed:",L),[])),bm(R,La).catch(L=>(console.warn("[TeacherDashboard] registered-student fetch failed:",L),[]))]);let oa=na;if(na.length===0&&Jt.length===0)try{const{collection:L,query:K,where:ke,getDocs:_e}=await Ar(async()=>{const{collection:Rt,query:He,where:ma,getDocs:ua}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{collection:Rt,query:He,where:ma,getDocs:ua}},__vite__mapDeps([2,3])),{db:Qt}=await Ar(async()=>{const{db:Rt}=await import("./index-CR5aYAL9.js").then(He=>He.b5);return{db:Rt}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])),Ee=K(L(Qt,"users"),ke("role","==","student"));oa=(await _e(Ee)).docs.map(Rt=>{const He=Rt.data();return{uid:Rt.id,name:String(He.name||He.displayName||"").trim()||"Student",email:String(He.email||"").trim(),lrn:He.lrn?String(He.lrn).trim():void 0,photo:He.photo?String(He.photo).trim():He.photoURL?String(He.photoURL).trim():void 0,grade:He.grade?String(He.grade).trim():void 0,section:He.section?String(He.section).trim():void 0,classSectionId:He.classSectionId?String(He.classSectionId).trim():void 0,adviserTeacherId:He.adviserTeacherId?String(He.adviserTeacherId).trim():void 0,role:"student",createdAt:He.createdAt||void 0}}).filter(Rt=>Rt.name!=="Student"||Rt.email)}catch(L){console.warn("[TeacherDashboard] fallback all-students fetch failed:",L)}const hs=new Map,ia=new Map,la=new Map;Jt.forEach(L=>{hs.set(L.id,L),L.lrn&&ia.set(L.lrn.trim().toLowerCase(),L);const K=No(L.name),ke=rt(L.classSectionId||L.classroomId);K&&la.set(`${K}|${ke}`,L)});const Qs=new Set,pr=oa.map(L=>{const K=vm(L),ke=(L.lrn||"").trim().toLowerCase(),_e=No(L.name),Qt=rt(L.classSectionId);let Ee;if(hs.has(L.uid))Ee=hs.get(L.uid);else if(ke&&ia.has(ke))Ee=ia.get(ke);else if(_e){const He=`${_e}|${Qt}`;Ee=la.get(He)}if(Ee){Qs.add(Ee.id);const He={...K,id:L.uid,accountUid:L.uid,email:K.email||Ee.email,lrn:K.lrn||Ee.lrn,name:K.name||Ee.name,avatar:K.avatar||Ee.avatar,riskLevel:Ee.riskLevel||K.riskLevel,avgQuizScore:Ee.avgQuizScore||K.avgQuizScore,engagementScore:Ee.engagementScore||K.engagementScore,attendance:Ee.attendance||K.attendance,assignmentCompletion:Ee.assignmentCompletion||K.assignmentCompletion,weakestTopic:Ee.weakestTopic||K.weakestTopic,struggles:Ee.struggles||K.struggles,lastActive:Ee.lastActive||K.lastActive,wri:Ee.wri??null,riskStatus:Ee.riskStatus??null,riskUpdatedAt:Ee.riskUpdatedAt??null,diagnosticScore:Ee.diagnosticScore??null,externalGradesAvg:Ee.externalGradesAvg??null,systemPerformanceAvg:Ee.systemPerformanceAvg??null,riskHistory:Ee.riskHistory,grade:K.grade||Ee.grade,gradeLevel:K.gradeLevel||Ee.gradeLevel,section:K.section||Ee.section,classSectionId:K.classSectionId||Ee.classSectionId,classroomId:K.classroomId||Ee.classroomId,classMetadata:Ee.classMetadata||K.classMetadata,hasRegisteredAccount:!0,source:"both"},ma=rt(He.classSectionId||He.classroomId),ua=Ms(He.classroomId||"",ma,He.className);return Xt(Mr(He,ua))}const Gs=rt(K.classSectionId||K.classroomId),Rt=Ms(K.classroomId||"",Gs,K.className);return Xt(Mr(K,Rt))}),hr=Jt.filter(L=>!Qs.has(L.id)).map(L=>{const K={...L,hasRegisteredAccount:!1,source:"import"},ke=rt(K.classSectionId||K.classroomId),_e=Ms(K.classroomId,ke,K.className);return Xt(Mr(K,_e))}),ca=[...pr,...hr];if(!ee)return;J(L=>je.length===0&&L.length>0?L:je),Z(L=>ca.length===0&&L.length>0?L:ca),it.getImportedClassOverview({limit:3e3,forceRefresh:H>0}).then(L=>{ee&&(L.warnings.length>0&&console.warn("Imported class overview warnings:",L.warnings.join(" ")),J(K=>Vo(K,L.classrooms.map(mx))),Z(K=>{if(K.length===0)return K;const ke=L.students.map(ux),_e=new Set;K.forEach(Ee=>_e.add(ir(Ee)));const Qt=ke.filter(Ee=>_e.has(ir(Ee)));return Qt.length===0?K:Wo(K,Qt)}))}).catch(L=>{console.warn("Imported class overview merge unavailable:",L)});const da=Ge.map(L=>L.id);da.length>0&&(ze=km(da,L=>{ee&&$e(L.map(K=>({id:K.id,student:K.studentName,action:K.action,topic:K.topic,time:nl(K.timestamp.toDate()),type:K.type})))}))}catch(Ge){console.error("Failed to load teacher data:",Ge),me.error("Failed to load dashboard data")}finally{re(!1)}})(),()=>{ee=!1,ze&&ze()}},[r,H]),u.useEffect(()=>{if(!r)return;let R=!0;return Sm("",80).then(ee=>{R&&Q(ee)}).catch(ee=>{console.warn("Failed to load teacher directory options:",ee)}),()=>{R=!1}},[r]),u.useEffect(()=>{if(A.length===0)return;(async()=>{if(A.length===0){We("");return}G(!0);try{const ee=A.map(Ne=>({name:Ne.name,engagementScore:Ne.engagementScore,avgQuizScore:Ne.avgScore,attendance:Ne.attendance,riskLevel:Ne.riskLevel})),ze=await it.getDailyInsight({students:ee});We(ze.insight)}catch{We(`${A.filter(ee=>ee.riskLevel==="high").length} students are at high risk of falling behind. Review their progress in the analytics view.`)}finally{G(!1)}})()},[A]);const Fe=O.reduce((R,ee)=>R+ee.studentCount,0),Pe=O.reduce((R,ee)=>R+ee.atRiskCount,0),tt=O.length>0?Math.round(O.reduce((R,ee)=>R+ee.avgScore,0)/O.length):0,Tt=[{name:"High Risk",value:A.filter(R=>R.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:A.filter(R=>R.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:A.filter(R=>R.riskLevel==="low").length,color:"#75D06A"}],dt={};A.forEach(R=>{R.weakestTopic&&R.weakestTopic!=="N/A"&&(dt[R.weakestTopic]||(dt[R.weakestTopic]={total:0,sum:0}),dt[R.weakestTopic].total+=1,dt[R.weakestTopic].sum+=R.avgScore)});const wt=Object.entries(dt).map(([R,ee])=>({topic:R,score:Math.round(ee.sum/ee.total)})).sort((R,ee)=>R.score-ee.score).slice(0,6),Lt=R=>{v(R),i("analytics")},B=R=>{F(R),i("intervention")},Ae=()=>{F(null),i("analytics")},Xe=()=>{v(null),F(null),i("dashboard")},Nt=async(R,ee)=>{if(!r){me.error("Unable to assign manager: teacher context is missing.");return}const ze=cs(R.classMetadata?.className||R.name),Ne=bt({metadata:R.classMetadata,classSectionId:R.classSectionId,className:R.name,grade:R.classMetadata?.grade||ze.grade,gradeLevel:R.classMetadata?.gradeLevel,classification:R.classMetadata?.classification,strand:R.classMetadata?.strand,section:R.classMetadata?.section||ze.section,schoolYear:R.classMetadata?.schoolYear||String(new Date().getFullYear()),ownerTeacherId:R.classMetadata?.ownerTeacherId||r.uid,ownerTeacherName:R.classMetadata?.ownerTeacherName||fe,adviserTeacherId:R.classMetadata?.adviserTeacherId||r.uid,adviserTeacherName:R.classMetadata?.adviserTeacherName||fe,managerId:ee.uid,managerName:ee.name}),Ge=Ne.classSectionId||Ht(Ne.grade||ze.grade,Ne.section||ze.section);if(!Ge){me.error("Unable to assign manager: missing class section ID.");return}E(!0);try{await qi({classSectionId:Ge,className:Ne.className||R.name,grade:Ne.grade||ze.grade,gradeLevel:Ne.gradeLevel||xs(Ne.grade||ze.grade)||Ne.grade||ze.grade,classification:Ne.classification||aa(Ne.gradeLevel||Ne.grade)||void 0,strand:Ne.strand||ra(Ne.className,Ne.section)||void 0,section:Ne.section||ze.section,schoolYear:Ne.schoolYear||String(new Date().getFullYear()),ownerTeacherId:Ne.ownerTeacherId||r.uid,ownerTeacherName:Ne.ownerTeacherName||fe,managerId:ee.uid,managerName:ee.name});const je=bt({metadata:Ne,classSectionId:Ge,managerId:ee.uid,managerName:ee.name}),gt=rt(Ge);J(nt=>nt.map(Ce=>rt(Ce.classSectionId)!==gt?Ce:{...Ce,name:je.className||Ce.name,classSectionId:je.classSectionId||Ce.classSectionId,classMetadata:je,gradeLevel:je.gradeLevel||Ce.gradeLevel,classification:je.classification||Ce.classification,strand:je.strand||Ce.strand,managerId:ee.uid,managerName:ee.name})),Z(nt=>nt.map(Ce=>{if(rt(Ce.classSectionId||Ce.classroomId)!==gt)return Ce;const Xt=bt({metadata:Ce.classMetadata,classSectionId:je.classSectionId||Ce.classSectionId,className:Ce.className||je.className,grade:Ce.grade||je.grade,gradeLevel:Ce.gradeLevel||je.gradeLevel,classification:Ce.classification||je.classification,strand:Ce.strand||je.strand,section:Ce.section||je.section,managerId:ee.uid,managerName:ee.name});return{...Ce,classMetadata:Xt,gradeLevel:Xt.gradeLevel||Ce.gradeLevel,classification:Xt.classification||Ce.classification,strand:Xt.strand||Ce.strand,managerId:ee.uid,managerName:ee.name}})),v(nt=>!nt||rt(nt.classSectionId)!==gt?nt:{...nt,classMetadata:je,managerId:ee.uid,managerName:ee.name,gradeLevel:je.gradeLevel||nt.gradeLevel,classification:je.classification||nt.classification,strand:je.strand||nt.strand}),me.success(`Assigned ${ee.name} as section manager.`)}catch(je){console.error("Failed to assign class manager:",je),me.error(je instanceof Error?je.message:"Failed to assign class manager")}finally{E(!1)}},Kt=u.useCallback(R=>{de({rosterId:R.id,name:R.name,lrn:R.lrn,email:R.email,grade:R.grade,section:R.section,classSectionId:R.classSectionId})},[]),Et=u.useCallback(R=>{Z(ee=>ee.map(ze=>ze.id===R.rosterId?{...ze,hasRegisteredAccount:!0,source:"both",accountUid:R.uid,email:R.email||ze.email}:ze)),ce(ee=>ee+1)},[]),Dt=u.useCallback(async(R,ee)=>{if(!r){me.error("Cannot reassign section without an authenticated teacher.");return}const ze=r.uid,Ne=(ee.classSectionId||"").trim();if(!Ne){me.error("Pick a target section first.");return}oe(R.id);try{await wm({studentId:R.accountUid||R.id,isRegisteredAccount:!!R.hasRegisteredAccount,newClassSectionId:Ne,newGrade:ee.grade,newSection:ee.section,previousClassSectionId:R.classSectionId,teacherId:ze,teacherName:fe,schoolYear:R.classMetadata?.schoolYear||String(new Date().getFullYear())}),Z(Ge=>Ge.map(je=>{if(je.id!==R.id)return je;const gt=bt({metadata:je.classMetadata,classSectionId:Ne,className:je.className,grade:ee.grade,section:ee.section});return{...je,grade:ee.grade,section:ee.section,classSectionId:Ne,classroomId:Ne,classMetadata:gt}})),me.success(`Moved ${R.name} to ${ee.grade} - ${ee.section}.`)}catch(Ge){console.error("Section reassignment failed:",Ge),me.error(Ge instanceof Error?Ge.message:"Failed to reassign section.")}finally{oe(null)}},[r,fe]);u.useEffect(()=>{const R=()=>{const ee=window.innerWidth<1024;S(ee),ee?c(!1):p(!1)};return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]),u.useEffect(()=>{g&&p(!1)},[n,g]);const $t=R=>{i(R),v(null),F(null)},_s=u.useMemo(()=>{if(!y)return;if(y.classMetadata?.classSectionId)return y.classMetadata.classSectionId||void 0;if(y.classSectionId)return y.classSectionId;const R=cs(y.classMetadata?.className||y.name);return Ht(R.grade,R.section)||void 0},[y]),at=u.useMemo(()=>y||null,[y]),za=u.useMemo(()=>{if(!at)return;const R=O.findIndex(ee=>ee.id===at.id);return nr[Math.max(0,R)%nr.length]},[at,O]),Ft=u.useMemo(()=>{if(!at)return A;const R=(at.id||"").trim().toLowerCase(),ee=rt(at.classSectionId),ze=(at.name||"").trim().toLowerCase();return A.filter(Ne=>{const Ge=rt(Ne.classroomId),je=rt(Ne.classSectionId),gt=(Ne.className||"").trim().toLowerCase();return ee&&(je===ee||Ge===ee)||R&&(Ge===R||je===R)||ze&>===ze})},[at,A]);return P?e.jsx(yl,{message:"Loading dashboard..."}):e.jsxs("div",{className:"relative flex h-screen w-full bg-background overflow-hidden",children:[g&&f&&e.jsx("button",{"aria-label":"Close navigation",className:"fixed inset-0 z-30 bg-slate-900/40 backdrop-blur-[1px]",onClick:()=>p(!1)}),e.jsxs(Re.aside,{initial:!1,animate:{width:g?280:l&&!d?80:280,x:g?f?0:-300:0},transition:{type:"spring",stiffness:360,damping:34},onMouseEnter:()=>!g&&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"})})]}),!g&&(!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(Ss,{size:20}):e.jsx(ks,{size:20})}),g&&e.jsx("button",{onClick:()=>p(!1),className:"p-2 hover:bg-[#dde3eb] rounded-lg transition-colors text-[#5a6578]","aria-label":"Close navigation",children:e.jsx(ds,{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(ys,{icon:zl,label:"Dashboard",active:n==="dashboard",collapsed:l&&!d,onClick:Xe,forceExpanded:g}),e.jsx(ys,{icon:$s,label:"Class Analytics",active:n==="analytics"||n==="intervention",collapsed:l&&!d,onClick:()=>$t("analytics"),forceExpanded:g})]})]}),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(ys,{icon:Ns,label:"Topic Mastery",active:n==="topic_mastery",collapsed:l&&!d,onClick:()=>$t("topic_mastery"),forceExpanded:g}),e.jsx(ys,{icon:is,label:"Competency",active:n==="competency",collapsed:l&&!d,onClick:()=>$t("competency"),forceExpanded:g})]})]}),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(ys,{icon:Ll,label:"Data Import",active:n==="import",collapsed:l&&!d,onClick:()=>i("import"),forceExpanded:g}),e.jsx(ys,{icon:ii,label:"AI Quiz Maker",active:n==="quiz_maker",collapsed:l&&!d,onClick:()=>i("quiz_maker"),forceExpanded:g}),e.jsx(ys,{icon:Vt,label:"Question Bank",active:n==="question_bank",collapsed:l&&!d,onClick:()=>i("question_bank"),forceExpanded:g}),e.jsx(ys,{icon:Ka,label:"Calendar",active:n==="calendar",collapsed:l&&!d,onClick:()=>i("calendar"),forceExpanded:g})]})]})]}),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(Dl,{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($l,{onClick:()=>j(!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:[g&&e.jsx("button",{onClick:()=>p(!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(Sl,{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, ${fe}`,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(is,{size:13,className:"text-[#9956DE]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#9956DE]",children:[Fe," 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(Js,{size:13,className:"text-[#F08386]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#C65E63]",children:[Pe," 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(Ea,{size:13,className:"text-[#75D06A]"}),e.jsxs("span",{className:"text-xs font-display font-semibold text-[#4D9F46]",children:[tt,"% avg"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:()=>{se(!0),W(!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(Fs,{size:18}),!I&&Me&&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"})]}),g&&n==="dashboard"&&e.jsx("button",{onClick:()=>we(R=>!R),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] ${he?"bg-[#818cf8] border-[#6366f1] text-white":"bg-white/60 hover:bg-white/80 border-white/50 text-[#64748b] hover:text-[#1e293b]"}`,"aria-label":he?"Close calendar panel":"Open calendar panel",title:he?"Close calendar":"View calendar",children:e.jsx(Ka,{size:18})}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>ae(!ie),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(er,{size:18}),b>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(Ml,{isOpen:ie,onClose:()=>ae(!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(fe)}&background=e0e7ff&color=4f46e5`,alt:"Profile",className:"w-full h-full object-cover"})}),e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:fe})]})]})]})}),e.jsx("main",{className:`flex-1 flex flex-col ${n==="intervention"||n==="analytics"?"overflow-hidden":"overflow-y-auto"}`,children:e.jsxs(Mt,{mode:"wait",children:[n==="dashboard"&&e.jsx(fx,{classes:O,liveActivity:ne,onViewClass:Lt,onViewAllClasses:()=>i("analytics"),onViewActivityStudent:R=>{const ee=A.find(ze=>ze.name===R);ee&&B(ee)},dailyInsight:Me,insightLoading:T,isInsightDismissed:I,onDismissInsight:()=>W(!0),onOpenInsightModal:()=>{se(!0),W(!0)},totalStudents:Fe,totalAtRisk:Pe,avgPerformance:tt,onCreateClass:()=>w(!0)}),n==="analytics"&&at&&e.jsx(vx,{selectedClass:at,students:Ft,allClasses:O,riskDistribution:Tt,topicPerformance:wt,onViewStudent:B,onCreateAccount:Kt,onReassignSection:Dt,reassignBusyId:xe,onBack:()=>v(null),teacherOptions:_,managerUpdating:U,onAssignManager:R=>Nt(at,R),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,classColor:za,insightDismissed:I,onOpenInsightModal:()=>se(!0),onAddStudents:()=>M(!0)}),n==="analytics"&&!at&&O.length>0&&e.jsx(zo,{classes:O,onSelectClass:Lt,onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:I,onOpenInsightModal:()=>se(!0),onCreateClass:()=>w(!0)}),n==="analytics"&&!at&&O.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($s,{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(ht,{onClick:()=>w(!0),className:"bg-[#9956DE] hover:bg-[#7c3aed] text-white",children:[e.jsx(Zs,{size:16,className:"mr-1.5"}),"Create Class"]})]})}),n==="intervention"&&z&&e.jsx(wx,{student:z,teacherId:r?.uid||"",teacherName:fe,initialCache:qe.current.get(z.id),onCacheUpdate:(R,ee)=>qe.current.set(R,ee),onStudentUpdated:R=>{const ee=z?Wr(z):null;F(R),Z(ze=>ze.map(Ne=>{const Ge=Wr(Ne),je=ee?Ge===ee:!1,gt=Ne.id===R.id&&rt(Ne.classSectionId)===rt(R.classSectionId);return je||gt?R:Ne}))},onBack:Ae,onNavigateToQuizMaker:R=>{i("quiz_maker"),R&&sessionStorage.setItem("quizMakerInitialTab",R)}}),n==="topic_mastery"&&e.jsx(Qm,{classSectionId:_s,onOpenNotifications:()=>i("notifications"),onOpenProfile:s}),n==="competency"&&at&&e.jsx(Wm,{classSectionId:_s,className:y?.name,fallbackStudents:A,onBack:()=>v(null),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:I,onOpenInsightModal:()=>se(!0)}),n==="competency"&&!at&&O.length>0&&e.jsx(zo,{classes:O,onSelectClass:R=>v(R),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,insightDismissed:I,onOpenInsightModal:()=>se(!0),viewType:"competency"}),n==="competency"&&!at&&O.length===0&&e.jsx(hx,{icon:is,title:"Student Competency",description:"No classes available yet. Import class records to view competency breakdowns."}),n==="import"&&e.jsx(ox,{classSectionId:_s,className:y?.name,classMetadata:y?.classMetadata,students:A,classes:O.map(R=>({id:R.id,name:R.name,classSectionId:R.classSectionId})),teacherId:r?.uid||"",teacherName:fe,onStudentsUpdated:R=>Z(R),onBackToClasses:()=>i("dashboard"),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),W(!0)},userPhoto:o?.photo,onImportedClassRecords:R=>{const ee=R.students.map(Ce=>px(Ce,R.classSectionId,R.className,R.classMetadata)),ze=bt({metadata:R.classMetadata,classSectionId:R.classSectionId,className:R.className}),Ne=ze.classSectionId||"imported_class",Ge=ze.className||"Imported Class",je=ee.filter(Ce=>Ce.riskLevel==="high").length,gt=ee.length>0?Math.round(ee.reduce((Ce,ps)=>Ce+ps.avgScore,0)/ee.length):0,nt={id:Ne,name:Ge,classSectionId:Ne,classMetadata:{...ze,classSectionId:Ne,className:Ge},schedule:"Mon-Fri",studentCount:ee.length,avgScore:gt,atRiskCount:je,riskLevel:je>=5?"high":je>=2?"medium":"low"};Z(Ce=>Wo(Ce,ee)),J(Ce=>Vo(Ce,[nt]))},onDataChanged:()=>ce(R=>R+1)}),n==="notifications"&&e.jsx(Ym,{liveActivity:ne,atRiskStudents:A.filter(R=>R.riskLevel==="high").map(R=>({name:R.name,riskLevel:R.riskLevel,weakestTopic:R.weakestTopic})),onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),W(!0)},userPhoto:o?.photo,teacherName:fe}),n==="calendar"&&e.jsx(cu,{classes:O,teacherId:r?.uid}),n==="quiz_maker"&&e.jsx(Yi,{onBack:()=>{const R=sessionStorage.getItem("quizMakerReturnTo");sessionStorage.removeItem("quizMakerReturnTo"),sessionStorage.removeItem("quizMakerInitialTab"),i(R==="intervention"?"intervention":"dashboard")},onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),W(!0)},userPhoto:o?.photo,teacherName:fe}),n==="question_bank"&&e.jsx(Pm,{onOpenNotifications:()=>i("notifications"),onOpenProfile:s,onOpenInsightModal:()=>{se(!0),W(!0)},userPhoto:o?.photo,teacherName:fe})]})})]}),n==="dashboard"&&!g&&e.jsx(Yo,{onViewCalendar:()=>i("calendar"),onOpenProfile:s,userProfile:o,teacherName:fe,liveActivity:ne})]}),e.jsx(Mt,{children:g&&n==="dashboard"&&he&&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:()=>we(!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(Yo,{onViewCalendar:()=>{i("calendar"),we(!1)},onOpenProfile:()=>{s?.(),we(!1)},userProfile:o,teacherName:fe,liveActivity:ne})},"cal-drawer")]})}),e.jsx(Mt,{children:Y&&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(Fs,{size:16})}),e.jsx("h3",{className:"font-semibold text-slate-800",children:"Detailed AI Insight"})]}),e.jsx("button",{onClick:()=>{se(!1)},className:"p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(ds,{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:Me?.replace(/[*_]*\s*\(?Word\s*count\s*:\s*[*_]*\s*\d+\)?\s*[*_]*/gi,"").trim()||`**${Pe} students (${Fe>0?Math.round(Pe/Fe*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:()=>{se(!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(Tl,{isOpen:N,onClose:()=>j(!1),onConfirm:t,title:"Logout",message:"Are you sure you want to logout?",confirmText:"Logout",cancelText:"Cancel"}),e.jsx(Cm,{open:h,onClose:()=>w(!1),onCreated:()=>ce(R=>R+1),teacherName:fe}),e.jsx(Im,{open:C,onClose:()=>M(!1),onAdded:()=>ce(R=>R+1),grade:at?.gradeLevel||at?.classMetadata?.grade||"Grade 11",section:at?.classMetadata?.section||at?.name?.split(" - ")[1]||"",teacherName:fe,existingStudentUids:Ft.map(R=>R.id)}),e.jsx(cx,{isOpen:!!te,onClose:()=>de(null),seed:te,adviserTeacherId:r?.uid||"",adviserTeacherName:fe,schoolYear:te?A.find(R=>R.id===te.rosterId)?.classMetadata?.schoolYear||String(new Date().getFullYear()):void 0,onCreated:Et})]})},ys=({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}})]}),hx=({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})]})}),fx=({classes:t,liveActivity:s,onViewClass:a,onViewAllClasses:r,onViewActivityStudent:o,dailyInsight:n,insightLoading:i,isInsightDismissed:l,onDismissInsight:c,onOpenInsightModal:d,totalStudents:m,totalAtRisk:f,avgPerformance:p,onCreateClass:g})=>{const S=m>0?Math.round(f/m*100):0,N=m>0?Math.round((m-f)/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(Fs,{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:j=>{j.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:j=>{j.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(is,{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(Ns,{size:15})})]}),e.jsxs("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:"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(si,{size:15})})]}),e.jsxs("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:[N,"%"]}),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(N/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(lr,{size:15})})]}),e.jsx("div",{className:"relative z-10 text-[18px] sm:text-[26px] font-semibold tracking-tight",children:f}),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:[S,"%"]})]})]})]}),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."}),g&&e.jsx("button",{onClick:g,className:"text-sm text-[#9956DE] font-semibold hover:underline",children:"+ Create a class"})]}),t.map((j,h)=>{const w=[{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]"}],C=w[h%w.length];return e.jsxs("div",{onClick:()=>a(j),className:`relative overflow-hidden flex items-center gap-3 p-[12px_13px] pl-[16px] border border-[#f1f5f9] rounded-[14px] cursor-pointer ${C.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] ${C.stripe}`}),e.jsx("div",{className:`w-[38px] h-[38px] rounded-[10px] flex items-center justify-center flex-shrink-0 text-[17px] ${C.bg} ${C.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:j.name}),e.jsx("div",{className:"text-[11px] text-[#94a3b8] mt-[1px]",children:j.classification||"High School"})]}),e.jsx("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[65px]",children:j.schedule||"Mon-Fri"}),e.jsxs("div",{className:"hidden sm:block text-[12px] text-[#64748b] min-w-[85px]",children:[j.studentCount," students"]}),e.jsx("span",{className:`text-[10px] font-semibold px-[9px] py-[3px] rounded-[6px] ${j.riskLevel==="high"?"bg-[#fee2e2] text-[#b91c1c] border border-[#fca5a5]":j.riskLevel==="medium"?"bg-[#fffbeb] text-[#b45309] border border-[#fcd34d]":"bg-[#ecfdf5] text-[#065f46] border border-[#6ee7b7]"}`,children:j.riskLevel==="high"?"High risk":j.riskLevel==="medium"?"Medium risk":"On track"}),e.jsx($r,{size:16,className:"text-[#cbd5e1] ml-auto hover:text-[#64748b]"})]},j.id)})]})]})]})},gx=ue.memo(({student:t,onViewStudent:s,onCreateAccount:a})=>{const o=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"},n=t.hasRegisteredAccount===!1&&t.source==="import",i=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] ${o.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 ${o.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 ${o.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}),i&&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(ea,{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 ${o.badge}`,children:[t.avgScore,"%"]})]}),n&&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:l=>{l.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 ${o.progress}`,style:{width:`${t.avgScore}%`}})})]})}),bx=({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 f=(m.classSectionId||m.id||"").trim();if(!f)return;const p=(m.classMetadata?.grade||"").trim(),g=(m.classMetadata?.section||"").trim();if(!p||!g)return;const S=m.name||`${p} - ${g}`;d.set(f,{classSectionId:f,grade:p,section:g,label:S})}),Array.from(d.values()).sort((m,f)=>m.label.localeCompare(f.label))},[s]),c=u.useMemo(()=>{const d=new Map,m=[];return t.forEach(f=>{const p=(f.classSectionId||"").trim();if(!p){m.push(f);return}const g=f.section||f.className||p,S=d.get(p)||{label:g,students:[]};S.students=[...S.students,f],d.set(p,S)}),{assigned:Array.from(d.entries()).map(([f,p])=>({sectionId:f,...p})).sort((f,p)=>f.label.localeCompare(p.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(_t,{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(qo,{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(qo,{student:d,sectionTargets:l,currentSectionId:a.classSectionId,onReassign:r,isBusy:o===d.id},`section-row-${d.id}`))})]})]})]})},qo=({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"})]})]})},vx=({selectedClass:t,students:s,allClasses:a,riskDistribution:r,topicPerformance:o,onViewStudent:n,onCreateAccount:i,onReassignSection:l,reassignBusyId:c,onBack:d,teacherOptions:m,managerUpdating:f,onAssignManager:p,onOpenNotifications:g,onOpenProfile:S,classColor:N,insightDismissed:j,onOpenInsightModal:h,onAddStudents:w})=>{const{currentUser:C,userProfile:M}=ms(),[k,q]=u.useState(""),[b,y]=u.useState(""),[v,z]=u.useState("All"),F=[{name:"High Risk",value:s.filter(O=>O.riskLevel==="high").length,color:"#FF8B8B"},{name:"Medium Risk",value:s.filter(O=>O.riskLevel==="medium").length,color:"#F08386"},{name:"Low Risk",value:s.filter(O=>O.riskLevel==="low").length,color:"#75D06A"}];u.useEffect(()=>{y(t.classMetadata?.managerId||t.managerId||"")},[t]);const I=u.useMemo(()=>{const O=k.trim().toLowerCase();let J=s;return O&&(J=J.filter(A=>A.name.toLowerCase().includes(O)||(A.lrn||"").toLowerCase().includes(O)||(A.weakestTopic||"").toLowerCase().includes(O))),v==="Good"?J=J.filter(A=>A.avgScore>=85&&A.riskLevel!=="high"):v==="Risk"&&(J=J.filter(A=>A.riskLevel==="high"||A.avgScore<75)),J},[k,s,v]),W=u.useMemo(()=>{if(s.length===0)return 0;const O=s.reduce((J,A)=>J+(A.assignmentCompletion||0),0);return Math.round(O/s.length)},[s]),Y=u.useMemo(()=>{if(s.length===0)return 0;const O=s.reduce((A,Z)=>A+(Z.attendance||0),0)/s.length,J=s.reduce((A,Z)=>A+(Z.engagementScore||0),0)/s.length;return Math.round(O*.6+J*.4)},[s]),se=u.useMemo(()=>[...s].sort((O,J)=>J.avgScore-O.avgScore).slice(0,5),[s]),ie=u.useMemo(()=>[...s].filter(O=>O.riskLevel==="high"||O.avgScore<70||O.assignmentCompletion<65),[s]),ae=u.useMemo(()=>m.find(O=>O.uid===b),[m,b]),he=()=>{if(!ae){me.error("Select a teacher manager first.");return}p(ae)},we=[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(ks,{className:"w-4 h-4"}),"Back to Classes"]})}),e.jsxs("header",{style:{backgroundColor:N?.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:we.map((O,J)=>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:O},O))}),e.jsxs("p",{className:"text-[13px] text-white/80 font-medium",children:["Manager: ",t.classMetadata?.managerName||t.managerName||"Not assigned"]})]}),e.jsxs("div",{className:"bg-white/10 border border-white/20 rounded-[18px] p-[16px] backdrop-blur-md flex flex-col w-full md:w-auto shrink-0 relative z-10 shadow-inner",children:[e.jsx("label",{className:"text-[11px] font-bold text-white/90 uppercase tracking-wider mb-2 ml-1",children:"Section Manager"}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3",children:[e.jsxs("div",{className:"relative w-full md:w-[320px]",children:[e.jsxs("select",{value:b||"",onChange:O=>y(O.target.value),className:"appearance-none bg-white/20 border border-white/30 text-white text-[13px] font-bold rounded-xl pl-4 pr-10 py-2.5 outline-none focus:border-white/50 focus:ring-2 focus:ring-white/20 w-full shadow-sm cursor-pointer [&>option]:text-[#1e293b]",children:[e.jsx("option",{value:"",children:"Select teacher"}),m.map(O=>e.jsxs("option",{value:O.uid,children:[O.name," (",O.email,")"]},O.uid))]}),e.jsx(_t,{className:"w-4 h-4 text-white/70 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"})]}),e.jsx("button",{onClick:he,disabled:!b||f,className:"bg-white text-[#6366f1] hover:bg-white/90 text-[13px] font-bold rounded-full px-6 py-2.5 shadow-md transition-transform hover:scale-[1.02] whitespace-nowrap disabled:opacity-50 disabled:hover:scale-100",style:{color:N?.hex||"#6366f1"},children:f?"Updating...":"Assign"})]})]})]}),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(Ns,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[t.avgScore,"%"]})]}),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(Yr,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[W,"%"]})]}),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(is,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[Y,"%"]})]}),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(Js,{size:14})})]}),e.jsxs("div",{className:"relative z-10 text-[22px] sm:text-[26px] font-semibold tracking-tight",children:[ie.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:["(",I.length,")"]})]}),e.jsx("button",{onClick:()=>w?.(),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(Bs,{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:k,onChange:O=>q(O.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:()=>z("All"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${v==="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:()=>z("Good"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${v==="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:()=>z("Risk"),className:`px-3 py-1.5 text-[11px] font-semibold rounded-[14px] whitespace-nowrap transition-all hover:scale-[1.02] ${v==="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(Yd,{style:{height:"100%"},data:I,className:"no-scrollbar",itemContent:(O,J)=>e.jsx("div",{className:"py-[6px] px-[8px]",children:e.jsx(gx,{student:J,onViewStudent:n,onCreateAccount:i})}),computeItemKey:(O,J)=>Wr(J)})})]}),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($r,{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($n,{width:"100%",height:"100%",children:e.jsxs(Fn,{data:F,children:[e.jsx(On,{strokeDasharray:"4 4",stroke:"#f1f5f9",vertical:!1}),e.jsx(Bn,{dataKey:"name",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#475569",fontSize:11,fontWeight:600},dy:10}),e.jsx(Pn,{axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600}}),e.jsx(Hn,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(Qn,{dataKey:"value",radius:[6,6,0,0],barSize:80,children:F.map((O,J)=>{const A={"High Risk":"#f43f5e","Medium Risk":"#f59e0b","Low Risk":"#10b981"};return e.jsx(Gn,{fill:A[O.name]||O.color},`cell-${J}`)})})]})})})]}),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($r,{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($n,{width:"100%",height:"100%",children:e.jsxs(Fn,{data:o,layout:"vertical",margin:{top:0,right:10,left:40,bottom:0},children:[e.jsx(On,{strokeDasharray:"4 4",stroke:"#f1f5f9",horizontal:!1}),e.jsx(Bn,{type:"number",domain:[0,100],axisLine:!1,tickLine:!1,tick:{fill:"#64748b",fontSize:10,fontWeight:600},tickFormatter:O=>`${O}%`}),e.jsx(Pn,{dataKey:"topic",type:"category",axisLine:{stroke:"#cbd5e1",strokeWidth:2},tickLine:!1,tick:{fill:"#1e293b",fontSize:11,fontWeight:600},dx:-10}),e.jsx(Hn,{cursor:{fill:"#f8fafc"},contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),e.jsx(Qn,{dataKey:"score",radius:[0,6,6,0],barSize:28,children:o.map((O,J)=>{const A=["#6366f1","#a855f7","#10b981","#f59e0b","#ec4899"];return e.jsx(Gn,{fill:A[J%A.length]},`cell-${J}`)})})]})})})]})]}),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(Ea,{className:"w-4 h-4 text-emerald-500"}),"Top Performers"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[se.map(O=>e.jsxs("div",{onClick:()=>n(O),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:O.name}),e.jsxs("span",{className:"text-[13px] font-semibold text-emerald-600",children:[O.avgScore,"%"]})]},`top-${O.id}`)),se.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(Js,{className:"w-4 h-4 text-rose-500"}),"Needs Attention"]})}),e.jsxs("div",{className:"space-y-[8px]",children:[ie.slice(0,4).map(O=>{const J=O.riskLevel==="high",A=J?"bg-rose-50/40 border-rose-50":"bg-amber-50/40 border-amber-50";return e.jsxs("div",{onClick:()=>n(O),className:`flex justify-between items-center p-3 rounded-[14px] border group hover:scale-[1.02] transition-transform cursor-pointer ${A}`,children:[e.jsx("span",{className:"text-[13px] font-semibold text-[#1e293b]",children:O.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] ${J?"text-rose-600":"text-amber-600"}`,children:J?"HIGH RISK":"MEDIUM RISK"})]},`attn-${O.id}`)}),ie.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No urgent students."})]})]})]})]})]}),e.jsx(bx,{students:s,allClasses:a,currentClass:t,onReassignSection:l,reassignBusyId:c})]})},wx=({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(()=>it.getImportGroundedRolloutFlags(),[]),[f,p]=u.useState(i?.learningPath||""),[g,S]=u.useState(!0),[N,j]=u.useState(i?.gradeDraft||t.grade||"Grade 11"),[h,w]=u.useState(i?.sectionDraft||t.section||"Section A"),[C,M]=u.useState(!1),[k,q]=u.useState(i?.lessonPlan??null),[b,y]=u.useState([]),[v,z]=u.useState(""),[F,I]=u.useState(!1),[W,Y]=u.useState(""),[se,ie]=u.useState("all"),[ae,he]=u.useState("all"),[we,O]=u.useState(!1),[J,A]=u.useState(!1),[Z,ne]=u.useState(null),[$e,Me]=u.useState(!1),[We,P]=u.useState(!1),[re,T]=u.useState(0),[G,H]=u.useState(!1),[ce,_]=u.useState("choose"),[Q,U]=u.useState([]),[E,te]=u.useState(!1),[de,xe]=u.useState(!1),[oe,fe]=u.useState(!1),[qe,Fe]=u.useState(!1);u.useEffect(()=>{j(t.grade||"Grade 11"),w(t.section||"Section A")},[t.grade,t.section]),u.useEffect(()=>{const B=Ae=>{if(Ae.key==="Escape"){if(qe){Fe(!1);return}if(de){oe?Fe(!0):xe(!1);return}G&&H(!1)}};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[de,G,oe,qe]),u.useEffect(()=>{if(de){const B=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=B}}},[de]),u.useEffect(()=>{l?.(t.id,{lessonPlan:k,learningPath:f,gradeDraft:N,sectionDraft:h})},[k,f,N,h,t.id,l]),u.useEffect(()=>{(async()=>{S(!0);try{let Ae="";try{Ae=await Cl(t.struggles.length>0?t.struggles:[t.weakestTopic],"general_math"),z(Ae)}catch{z("")}const Xe=await it.getLearningPath({weaknesses:t.struggles.length>0?t.struggles:[t.weakestTopic],gradeLevel:"High School",subject:"general_math"}),Nt=Ae?`${Xe.learningPath} -${Ae}`:Xe.learningPath;p(Nt)}catch{p("Unable to generate learning path. Please try again later."),z("")}finally{S(!1)}})()},[t]);const Pe=u.useCallback(async()=>{I(!0),Y("");try{const B=t.classSectionId||Ht(N||"Grade 11",h||"Section A"),Ae=t.struggles.length>0?t.struggles[0]:t.weakestTopic,Xe=await Rm({gradeLevel:N||t.grade||"Grade 11",subject:"general_math",quarter:1,moduleUnit:[N,h].filter(Boolean).join(" - ")||t.className,lessonTitle:`Grounded Lesson: ${Ae}`,learningCompetency:Ae,learnerLevel:t.avgScore<60?"support":t.avgScore<80?"developing":"advanced",classSectionId:B,className:[N,h].filter(Boolean).join(" - ")||t.className,focusTopics:t.struggles.length>0?t.struggles:[t.weakestTopic],topicCount:5,preferImportedTopics:m.lessonEnabled,allowReviewSources:we,allowUnverifiedLesson:J},!0);W(Xe),y(Xe.curriculumSources||[]),ne(null),it.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:B,className:[N,h].filter(Boolean).join(" - ")||t.className,metadata:{usedImportedTopics:Xe.usedImportedTopics,importedTopicCount:Xe.importedTopicCount,blockCount:Xe.blocks.length,publishReady:Xe.publishReady,sourceLegitimacyStatus:Xe.sourceLegitimacy.status,selfValidationPassed:Xe.selfValidation.passed,importGroundingEnabled:m.lessonEnabled}})}catch(B){let Ae=B instanceof Error?B.message:"Unable to generate lesson plan at this time.";if(B instanceof Ya&&B.status===422)try{const Nt=JSON.parse(B.responseBody)?.detail;Nt?.message&&(Ae=Nt.message);const Kt=Nt?.sourceLegitimacy?.issues||[],Et=Nt?.selfValidation?.issues||[],Dt=[...Kt,...Et].filter(Boolean).slice(0,3);Dt.length>0&&(Ae=`${Ae} ${Dt.join(" ")}`)}catch{}Y(Ae),W(null),y([]),it.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:t.classSectionId||Ht(N||"Grade 11",h||"Section A"),className:[N,h].filter(Boolean).join(" - ")||t.className,metadata:{error:Ae,allowReviewSources:we,allowUnverifiedLesson:J,importGroundingEnabled:m.lessonEnabled}})}finally{I(!1)}},[t,N,h,m.lessonEnabled,we,J]),tt=u.useCallback(async()=>{if(!k)return me.error("Generate a lesson plan first."),null;Me(!0);try{const B=await Tm(k,s,{teacherName:a,studentId:t.id,studentName:t.name});return ne(B),me.success("Lesson plan saved as draft."),B}catch(B){return console.error("Failed to save lesson draft:",B),me.error(B instanceof Error?B.message:"Failed to save lesson draft."),null}finally{Me(!1)}},[k,s,a,t.id,t.name]),Tt=u.useCallback(async()=>{if(!k){me.error("Generate a lesson plan first.");return}if(!k.publishReady){const B=[...k.sourceLegitimacy.issues,...k.selfValidation.issues].filter(Boolean).slice(0,2).join(" ");me.error(B||"Lesson is not publish-ready. Resolve legitimacy and validation checks first.");return}P(!0);try{let B=Z;if(B||(B=await tt()),!B)return;await Em(B),me.success("Lesson plan published to class content."),it.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:k.classSectionId||t.classSectionId,className:k.className||t.className,metadata:{action:"publish_lesson_plan",lessonPlanId:B,publishReady:k.publishReady,sourceLegitimacyStatus:k.sourceLegitimacy.status,selfValidationPassed:k.selfValidation.passed}})}catch(B){console.error("Failed to publish lesson plan:",B),me.error(B instanceof Error?B.message:"Failed to publish lesson plan."),it.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:k.classSectionId||t.classSectionId,className:k.className||t.className,metadata:{action:"publish_lesson_plan",error:B instanceof Error?B.message:"Failed to publish lesson plan."}})}finally{P(!1)}},[k,Z,tt,t.className,t.classSectionId]);u.useEffect(()=>{Pe()},[re]),u.useEffect(()=>{T(B=>B+1)},[t.id]),u.useEffect(()=>{ie("all"),he("all")},[k]),u.useMemo(()=>k?Array.from(new Set(k.blocks.map(B=>B.provenance?.sourceFile?.trim()).filter(B=>!!B))).sort((B,Ae)=>B.localeCompare(Ae)):[],[k]),u.useMemo(()=>k?Array.from(new Set(k.blocks.map(B=>B.provenance?.materialId?.trim()).filter(B=>!!B))).sort((B,Ae)=>B.localeCompare(Ae)):[],[k]);const dt=u.useMemo(()=>k?k.blocks.filter(B=>{const Ae=se==="all"||(B.provenance?.sourceFile||"").trim()===se,Xe=ae==="all"||(B.provenance?.materialId||"").trim()===ae;return Ae&&Xe}):[],[k,se,ae]),wt=[{id:1,type:"video",title:`${t.weakestTopic} Fundamentals`,duration:"8 mins",icon:Un},{id:2,type:"quiz",title:`${t.weakestTopic} Practice`,questions:10,icon:ii},{id:3,type:"assessment",title:"Final Check",questions:5,icon:Yr}],Lt=async()=>{if(!s){me.error("Unable to update section: teacher context missing");return}M(!0);try{await xr(t.id,N,h,s,new Date().getFullYear().toString(),a),await Vi(t.id,N,h);const B={...t,grade:N,section:h,className:[N,h].filter(Boolean).join(" - "),classSectionId:Ht(N,h)};r(B),me.success("Student section assignment updated")}catch(B){console.error("Failed to update student section assignment:",B),me.error("Failed to update section assignment")}finally{M(!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(Za,{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(In,{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(In,{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"]})]})]}),v&&e.jsx(jo,{sources:b,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(Ea,{className:"w-3.5 h-3.5"})," Learning Strengths"]}),e.jsx("p",{className:"text-[13px] text-[#475569] leading-relaxed pl-2",children: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(Ns,{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:t.struggles.length>0?t.struggles.map((B,Ae)=>e.jsxs("li",{children:["Must continue strengthening ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:B}),"."]},Ae)):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("button",{disabled:g,onClick:()=>T(B=>B+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(Ls,{className:"w-3 h-3"})," Regenerate"]})]}),e.jsxs(wo,{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:"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Interactive"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Video"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Practice"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Quiz"})]}),e.jsx("div",{className:"relative border-l-2 border-[#e2e8f0] ml-[20px] space-y-[28px] pb-4",children:wt.map((B,Ae)=>{let Xe=e.jsx(Un,{className:"w-4 h-4"}),Nt="bg-[#8b5cf6] shadow-[0_4px_10px_rgba(139,92,246,0.3)]",Kt="text-purple-600",Et="group-hover:border-purple-200",Dt="hover:bg-[#4f46e5]",$t=e.jsx(Pl,{className:"w-4 h-4 ml-0.5"});return B.type==="quiz"?(Xe=e.jsx(Hl,{className:"w-4 h-4"}),Nt="bg-sky-500 shadow-[0_4px_10px_rgba(14,165,233,0.3)]",Kt="text-sky-600",Et="group-hover:border-sky-200",Dt="hover:bg-sky-500",$t=e.jsx(Ss,{className:"w-4 h-4"})):B.type==="assessment"&&(Xe=e.jsx(qr,{className:"w-4 h-4"}),Nt="bg-emerald-500 shadow-[0_4px_10px_rgba(16,185,129,0.3)]",Kt="text-emerald-600",Et="group-hover:bg-emerald-50"),e.jsxs(Re.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:Ae*.1},className:"relative pl-[32px] group",children:[e.jsx("div",{className:`absolute -left-[17px] top-1 w-8 h-8 rounded-full ${Nt} text-white flex items-center justify-center ring-4 ring-white group-hover:scale-110 transition-transform`,children:Xe}),e.jsxs("div",{className:`${B.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 ${Et}`,children:[e.jsxs("div",{children:[e.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wider mb-1 block ${Kt}`,children:["Step ",Ae+1," • ",B.type==="video"?"Video Lesson":B.type==="quiz"?"Practice":"Assessment"]}),e.jsx("p",{className:"font-semibold text-[#1e293b] text-[13px] mb-0.5",children:B.title}),e.jsxs("p",{className:"text-[#64748b] text-[11px] flex items-center gap-1.5",children:[B.type==="video"&&e.jsxs(e.Fragment,{children:[e.jsx(ea,{className:"w-3 h-3"})," ",B.duration]}),B.type==="quiz"&&e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"w-3 h-3"})," ",B.questions," questions"]}),B.type==="assessment"&&e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"w-3 h-3"})," ",B.questions," assessment questions"]})]})]}),B.type==="assessment"?e.jsx(Zo,{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] ${Dt} hover:text-white transition-colors border border-[#e2e8f0]`,children:$t})]})]},B.id)})})]})]}),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-2",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Targeted Lesson Generation"}),e.jsx(ht,{onClick:()=>T(B=>B+1),disabled:F,className:"bg-[#4f46e5] hover:bg-[#3730a3] text-white h-8 text-[11px] rounded-full px-4",children:F?"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(ba,{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:we,onChange:B=>O(B.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:J,onChange:B=>A(B.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(wo,{name:"teacher-intervention-lesson-plan",loading:!1,fixture:null,fallback:null,children:[V&&e.jsx("div",{className:"bg-[#FF8B8B]/14 border border-[#FF8B8B]/35 rounded-xl p-3 text-sm text-[#D66A6A] mb-4",children:V}),k&&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(jo,{sources:b})}),e.jsx("p",{className:"text-[14px] font-semibold text-[#1e293b]",children:k.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:"})," ",k.usedImportedTopics?"Yes":"No"," (",k.importedTopicCount,")"]}),e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:[e.jsx("span",{className:"font-semibold text-[#475569]",children:"Subject:"})," ",k.subject||"General Math"," (Q",k.quarter||1,")"]})]}),k.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: ",k.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 ${k.publishReady?"text-emerald-600":"text-rose-500"}`,children:k.publishReady?"Ready":"Blocked"})]})}),k.warnings.length>0&&e.jsx("p",{className:"text-[11px] text-amber-600 mt-2 bg-amber-50 px-2 py-1.5 rounded",children:k.warnings.join(" ")})]}),k.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:k.lessonObjective})]}),k.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:k.realWorldHook})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 mt-4",children:dt.map(B=>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:B.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] mt-1",children:[B.estimatedMinutes," mins "," • "," ",B.strategy]}),e.jsx("p",{className:"text-[12px] text-[#475569] mt-2 bg-[#f8fafc] p-2 rounded-lg",children:B.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"}),B.activities.slice(0,2).map((Ae,Xe)=>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:Ae})]},Xe))]})]},B.blockId))}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-4",children:[e.jsx(ht,{variant:"outline",onClick:()=>void tt(),disabled:$e||!k,className:"border-[#cbd5e1] text-[#475569] hover:bg-[#f8fafc] text-[12px] h-9 rounded-full px-5",children:$e?e.jsx(_n,{className:"h-4 w-16"}):"Save Draft"}),e.jsx(ht,{onClick:()=>void Tt(),disabled:We||!k||!k.publishReady,className:"bg-[#10b981] hover:bg-[#059669] text-white text-[12px] h-9 rounded-full px-5",children:We?e.jsx(_n,{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 ${t.riskLevel==="high"?"text-rose-600 bg-rose-50 border-rose-100":t.riskLevel==="medium"?"text-amber-600 bg-amber-50 border-amber-100":"text-emerald-600 bg-emerald-50 border-emerald-100"}`,children: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:[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:t.avgScore>80?"High":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: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:t.weakestTopic,children:t.weakestTopic})]})]}),e.jsx("div",{className:"w-full flex flex-col gap-[10px]",children:e.jsxs("button",{onClick:async()=>{_("choose"),H(!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(Rc,{className:"w-4 h-4"})," Export Materials"]})}),G&&Lr.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center p-4",onClick:()=>H(!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:B=>B.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:[ce==="bank"&&e.jsx("button",{onClick:()=>_("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(ks,{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(Fr,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-bold text-white leading-tight",children:ce==="choose"?"Export Materials":"Choose a Quiz"}),e.jsx("p",{className:"text-[11px] text-white/70 font-medium",children:ce==="choose"?`For ${t.name}`:"Select a quiz from your bank"})]})]}),e.jsx("button",{onClick:()=>H(!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(ds,{className:"w-4 h-4"})})]})}),e.jsx("div",{className:"p-6",children:ce==="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()=>{te(!0),_("bank");try{const B=await ai(s);q(B)}catch{q([])}finally{te(!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(tr,{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:()=>{H(!1),fe(!1),xe(!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(Fs,{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:E?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..."})]}):Q.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(tr,{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:Q.map(B=>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:B.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] font-medium mt-0.5",children:[B.questions?.length??0," questions",B.gradeLevel?` · ${B.gradeLevel}`:"",B.metadata?.topicsCovered?.[0]?` · ${B.metadata.topicsCovered[0]}`:""]})]}),e.jsx("button",{onClick:()=>{H(!1),me.success(`"${B.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"})]},B.id))})})})]})]}),document.body),de&&Lr.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm",onClick:()=>{oe?Fe(!0):xe(!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:()=>{oe?Fe(!0):xe(!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(Za,{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(Fr,{className:"w-3.5 h-3.5 text-white"})}),e.jsx("span",{className:"text-[14px] font-bold text-[#1e293b]",children:"AI Quiz Maker"})]}),oe&&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(Yi,{onBack:()=>xe(!1),drawerMode:!0,gradeLevel:t.grade,onQuizGenerating:()=>fe(!0),onQuizSaved:B=>{fe(!1),me.success("Quiz saved! Close this panel or create another.",{action:{label:"Close Panel",onClick:()=>xe(!1)}})}})})]}),qe&&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:()=>Fe(!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(lr,{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:()=>Fe(!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:()=>{Fe(!1),xe(!1),fe(!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:` +${Ae}`:Xe.learningPath;p(Nt)}catch{p("Unable to generate learning path. Please try again later."),z("")}finally{S(!1)}})()},[t]);const Pe=u.useCallback(async()=>{I(!0),Y("");try{const B=t.classSectionId||Ht(N||"Grade 11",h||"Section A"),Ae=t.struggles.length>0?t.struggles[0]:t.weakestTopic,Xe=await Rm({gradeLevel:N||t.grade||"Grade 11",subject:"general_math",quarter:1,moduleUnit:[N,h].filter(Boolean).join(" - ")||t.className,lessonTitle:`Grounded Lesson: ${Ae}`,learningCompetency:Ae,learnerLevel:t.avgScore<60?"support":t.avgScore<80?"developing":"advanced",classSectionId:B,className:[N,h].filter(Boolean).join(" - ")||t.className,focusTopics:t.struggles.length>0?t.struggles:[t.weakestTopic],topicCount:5,preferImportedTopics:m.lessonEnabled,allowReviewSources:we,allowUnverifiedLesson:J},!0);q(Xe),y(Xe.curriculumSources||[]),ne(null),it.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:B,className:[N,h].filter(Boolean).join(" - ")||t.className,metadata:{usedImportedTopics:Xe.usedImportedTopics,importedTopicCount:Xe.importedTopicCount,blockCount:Xe.blocks.length,publishReady:Xe.publishReady,sourceLegitimacyStatus:Xe.sourceLegitimacy.status,selfValidationPassed:Xe.selfValidation.passed,importGroundingEnabled:m.lessonEnabled}})}catch(B){let Ae=B instanceof Error?B.message:"Unable to generate lesson plan at this time.";if(B instanceof Ya&&B.status===422)try{const Nt=JSON.parse(B.responseBody)?.detail;Nt?.message&&(Ae=Nt.message);const Kt=Nt?.sourceLegitimacy?.issues||[],Et=Nt?.selfValidation?.issues||[],Dt=[...Kt,...Et].filter(Boolean).slice(0,3);Dt.length>0&&(Ae=`${Ae} ${Dt.join(" ")}`)}catch{}Y(Ae),q(null),y([]),it.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:t.classSectionId||Ht(N||"Grade 11",h||"Section A"),className:[N,h].filter(Boolean).join(" - ")||t.className,metadata:{error:Ae,allowReviewSources:we,allowUnverifiedLesson:J,importGroundingEnabled:m.lessonEnabled}})}finally{I(!1)}},[t,N,h,m.lessonEnabled,we,J]),tt=u.useCallback(async()=>{if(!k)return me.error("Generate a lesson plan first."),null;Me(!0);try{const B=await Tm(k,s,{teacherName:a,studentId:t.id,studentName:t.name});return ne(B),me.success("Lesson plan saved as draft."),B}catch(B){return console.error("Failed to save lesson draft:",B),me.error(B instanceof Error?B.message:"Failed to save lesson draft."),null}finally{Me(!1)}},[k,s,a,t.id,t.name]),Tt=u.useCallback(async()=>{if(!k){me.error("Generate a lesson plan first.");return}if(!k.publishReady){const B=[...k.sourceLegitimacy.issues,...k.selfValidation.issues].filter(Boolean).slice(0,2).join(" ");me.error(B||"Lesson is not publish-ready. Resolve legitimacy and validation checks first.");return}P(!0);try{let B=Z;if(B||(B=await tt()),!B)return;await Em(B),me.success("Lesson plan published to class content."),it.reportImportGroundedFeedback({flow:"lesson",status:"success",classSectionId:k.classSectionId||t.classSectionId,className:k.className||t.className,metadata:{action:"publish_lesson_plan",lessonPlanId:B,publishReady:k.publishReady,sourceLegitimacyStatus:k.sourceLegitimacy.status,selfValidationPassed:k.selfValidation.passed}})}catch(B){console.error("Failed to publish lesson plan:",B),me.error(B instanceof Error?B.message:"Failed to publish lesson plan."),it.reportImportGroundedFeedback({flow:"lesson",status:"failed",classSectionId:k.classSectionId||t.classSectionId,className:k.className||t.className,metadata:{action:"publish_lesson_plan",error:B instanceof Error?B.message:"Failed to publish lesson plan."}})}finally{P(!1)}},[k,Z,tt,t.className,t.classSectionId]);u.useEffect(()=>{Pe()},[re]),u.useEffect(()=>{T(B=>B+1)},[t.id]),u.useEffect(()=>{ie("all"),he("all")},[k]),u.useMemo(()=>k?Array.from(new Set(k.blocks.map(B=>B.provenance?.sourceFile?.trim()).filter(B=>!!B))).sort((B,Ae)=>B.localeCompare(Ae)):[],[k]),u.useMemo(()=>k?Array.from(new Set(k.blocks.map(B=>B.provenance?.materialId?.trim()).filter(B=>!!B))).sort((B,Ae)=>B.localeCompare(Ae)):[],[k]);const dt=u.useMemo(()=>k?k.blocks.filter(B=>{const Ae=se==="all"||(B.provenance?.sourceFile||"").trim()===se,Xe=ae==="all"||(B.provenance?.materialId||"").trim()===ae;return Ae&&Xe}):[],[k,se,ae]),wt=[{id:1,type:"video",title:`${t.weakestTopic} Fundamentals`,duration:"8 mins",icon:Un},{id:2,type:"quiz",title:`${t.weakestTopic} Practice`,questions:10,icon:ii},{id:3,type:"assessment",title:"Final Check",questions:5,icon:Yr}],Lt=async()=>{if(!s){me.error("Unable to update section: teacher context missing");return}M(!0);try{await xr(t.id,N,h,s,new Date().getFullYear().toString(),a),await Vi(t.id,N,h);const B={...t,grade:N,section:h,className:[N,h].filter(Boolean).join(" - "),classSectionId:Ht(N,h)};r(B),me.success("Student section assignment updated")}catch(B){console.error("Failed to update student section assignment:",B),me.error("Failed to update section assignment")}finally{M(!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(Za,{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(In,{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(In,{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"]})]})]}),v&&e.jsx(jo,{sources:b,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(Ea,{className:"w-3.5 h-3.5"})," Learning Strengths"]}),e.jsx("p",{className:"text-[13px] text-[#475569] leading-relaxed pl-2",children: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(Ns,{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:t.struggles.length>0?t.struggles.map((B,Ae)=>e.jsxs("li",{children:["Must continue strengthening ",e.jsx("span",{className:"font-semibold text-[#1e293b]",children:B}),"."]},Ae)):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("button",{disabled:g,onClick:()=>T(B=>B+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(Ls,{className:"w-3 h-3"})," Regenerate"]})]}),e.jsxs(wo,{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:"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Interactive"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Video"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Practice"}),e.jsx("span",{className:"px-3 py-1 bg-[#f8fafc] text-[#475569] text-[11px] font-semibold rounded-full border border-[#e2e8f0]",children:"Quiz"})]}),e.jsx("div",{className:"relative border-l-2 border-[#e2e8f0] ml-[20px] space-y-[28px] pb-4",children:wt.map((B,Ae)=>{let Xe=e.jsx(Un,{className:"w-4 h-4"}),Nt="bg-[#8b5cf6] shadow-[0_4px_10px_rgba(139,92,246,0.3)]",Kt="text-purple-600",Et="group-hover:border-purple-200",Dt="hover:bg-[#4f46e5]",$t=e.jsx(Pl,{className:"w-4 h-4 ml-0.5"});return B.type==="quiz"?(Xe=e.jsx(Hl,{className:"w-4 h-4"}),Nt="bg-sky-500 shadow-[0_4px_10px_rgba(14,165,233,0.3)]",Kt="text-sky-600",Et="group-hover:border-sky-200",Dt="hover:bg-sky-500",$t=e.jsx(Ss,{className:"w-4 h-4"})):B.type==="assessment"&&(Xe=e.jsx(qr,{className:"w-4 h-4"}),Nt="bg-emerald-500 shadow-[0_4px_10px_rgba(16,185,129,0.3)]",Kt="text-emerald-600",Et="group-hover:bg-emerald-50"),e.jsxs(Re.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:Ae*.1},className:"relative pl-[32px] group",children:[e.jsx("div",{className:`absolute -left-[17px] top-1 w-8 h-8 rounded-full ${Nt} text-white flex items-center justify-center ring-4 ring-white group-hover:scale-110 transition-transform`,children:Xe}),e.jsxs("div",{className:`${B.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 ${Et}`,children:[e.jsxs("div",{children:[e.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wider mb-1 block ${Kt}`,children:["Step ",Ae+1," • ",B.type==="video"?"Video Lesson":B.type==="quiz"?"Practice":"Assessment"]}),e.jsx("p",{className:"font-semibold text-[#1e293b] text-[13px] mb-0.5",children:B.title}),e.jsxs("p",{className:"text-[#64748b] text-[11px] flex items-center gap-1.5",children:[B.type==="video"&&e.jsxs(e.Fragment,{children:[e.jsx(ea,{className:"w-3 h-3"})," ",B.duration]}),B.type==="quiz"&&e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"w-3 h-3"})," ",B.questions," questions"]}),B.type==="assessment"&&e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"w-3 h-3"})," ",B.questions," assessment questions"]})]})]}),B.type==="assessment"?e.jsx(Zo,{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] ${Dt} hover:text-white transition-colors border border-[#e2e8f0]`,children:$t})]})]},B.id)})})]})]}),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-2",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[#1e293b]",children:"Targeted Lesson Generation"}),e.jsx(ht,{onClick:()=>T(B=>B+1),disabled:F,className:"bg-[#4f46e5] hover:bg-[#3730a3] text-white h-8 text-[11px] rounded-full px-4",children:F?"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(ba,{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:we,onChange:B=>O(B.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:J,onChange:B=>A(B.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(wo,{name:"teacher-intervention-lesson-plan",loading:!1,fixture:null,fallback:null,children:[W&&e.jsx("div",{className:"bg-[#FF8B8B]/14 border border-[#FF8B8B]/35 rounded-xl p-3 text-sm text-[#D66A6A] mb-4",children:W}),k&&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(jo,{sources:b})}),e.jsx("p",{className:"text-[14px] font-semibold text-[#1e293b]",children:k.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:"})," ",k.usedImportedTopics?"Yes":"No"," (",k.importedTopicCount,")"]}),e.jsxs("p",{className:"text-[11px] text-[#64748b]",children:[e.jsx("span",{className:"font-semibold text-[#475569]",children:"Subject:"})," ",k.subject||"General Math"," (Q",k.quarter||1,")"]})]}),k.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: ",k.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 ${k.publishReady?"text-emerald-600":"text-rose-500"}`,children:k.publishReady?"Ready":"Blocked"})]})}),k.warnings.length>0&&e.jsx("p",{className:"text-[11px] text-amber-600 mt-2 bg-amber-50 px-2 py-1.5 rounded",children:k.warnings.join(" ")})]}),k.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:k.lessonObjective})]}),k.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:k.realWorldHook})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 mt-4",children:dt.map(B=>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:B.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] mt-1",children:[B.estimatedMinutes," mins "," • "," ",B.strategy]}),e.jsx("p",{className:"text-[12px] text-[#475569] mt-2 bg-[#f8fafc] p-2 rounded-lg",children:B.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"}),B.activities.slice(0,2).map((Ae,Xe)=>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:Ae})]},Xe))]})]},B.blockId))}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-4",children:[e.jsx(ht,{variant:"outline",onClick:()=>void tt(),disabled:$e||!k,className:"border-[#cbd5e1] text-[#475569] hover:bg-[#f8fafc] text-[12px] h-9 rounded-full px-5",children:$e?e.jsx(_n,{className:"h-4 w-16"}):"Save Draft"}),e.jsx(ht,{onClick:()=>void Tt(),disabled:We||!k||!k.publishReady,className:"bg-[#10b981] hover:bg-[#059669] text-white text-[12px] h-9 rounded-full px-5",children:We?e.jsx(_n,{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 ${t.riskLevel==="high"?"text-rose-600 bg-rose-50 border-rose-100":t.riskLevel==="medium"?"text-amber-600 bg-amber-50 border-amber-100":"text-emerald-600 bg-emerald-50 border-emerald-100"}`,children: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:[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:t.avgScore>80?"High":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: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:t.weakestTopic,children:t.weakestTopic})]})]}),e.jsx("div",{className:"w-full flex flex-col gap-[10px]",children:e.jsxs("button",{onClick:async()=>{_("choose"),H(!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(Rc,{className:"w-4 h-4"})," Export Materials"]})}),G&&Lr.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center p-4",onClick:()=>H(!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:B=>B.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:[ce==="bank"&&e.jsx("button",{onClick:()=>_("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(ks,{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(Fr,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-bold text-white leading-tight",children:ce==="choose"?"Export Materials":"Choose a Quiz"}),e.jsx("p",{className:"text-[11px] text-white/70 font-medium",children:ce==="choose"?`For ${t.name}`:"Select a quiz from your bank"})]})]}),e.jsx("button",{onClick:()=>H(!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(ds,{className:"w-4 h-4"})})]})}),e.jsx("div",{className:"p-6",children:ce==="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()=>{te(!0),_("bank");try{const B=await ai(s);U(B)}catch{U([])}finally{te(!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(tr,{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:()=>{H(!1),fe(!1),xe(!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(Fs,{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:E?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..."})]}):Q.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(tr,{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:Q.map(B=>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:B.title}),e.jsxs("p",{className:"text-[11px] text-[#64748b] font-medium mt-0.5",children:[B.questions?.length??0," questions",B.gradeLevel?` · ${B.gradeLevel}`:"",B.metadata?.topicsCovered?.[0]?` · ${B.metadata.topicsCovered[0]}`:""]})]}),e.jsx("button",{onClick:()=>{H(!1),me.success(`"${B.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"})]},B.id))})})})]})]}),document.body),de&&Lr.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm",onClick:()=>{oe?Fe(!0):xe(!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:()=>{oe?Fe(!0):xe(!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(Za,{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(Fr,{className:"w-3.5 h-3.5 text-white"})}),e.jsx("span",{className:"text-[14px] font-bold text-[#1e293b]",children:"AI Quiz Maker"})]}),oe&&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(Yi,{onBack:()=>xe(!1),drawerMode:!0,gradeLevel:t.grade,onQuizGenerating:()=>fe(!0),onQuizSaved:B=>{fe(!1),me.success("Quiz saved! Close this panel or create another.",{action:{label:"Close Panel",onClick:()=>xe(!1)}})}})})]}),qe&&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:()=>Fe(!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(lr,{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:()=>Fe(!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:()=>{Fe(!1),xe(!1),fe(!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; } } - `})]}),document.body),e.jsxs("div",{className:"w-full bg-white/80 rounded-[18px] p-[20px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white mt-auto",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[#1e293b] mb-4",children:"Section Assignment"}),e.jsxs("div",{className:"space-y-[12px]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5 block ml-1",children:"Grade Level"}),e.jsx("div",{className:"relative",children:e.jsx(js,{value:N,onChange:B=>j(B.target.value),placeholder:"Grade",className:"appearance-none w-full bg-[#f8fafc] border border-[#e2e8f0] text-[#475569] text-[13px] font-medium rounded-[14px] px-4 py-2.5 outline-none focus:border-[#a855f7] focus:ring-1 focus:ring-[#a855f7] h-auto"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5 block ml-1",children:"Section"}),e.jsx("div",{className:"relative",children:e.jsx(js,{value:h,onChange:B=>w(B.target.value),placeholder:"Section",className:"appearance-none w-full bg-[#f8fafc] border border-[#e2e8f0] text-[#475569] text-[13px] font-medium rounded-[14px] px-4 py-2.5 outline-none focus:border-[#a855f7] focus:ring-1 focus:ring-[#a855f7] h-auto"})})]}),e.jsx("button",{onClick:Lt,disabled:C||!N.trim()||!h.trim(),className:"w-full bg-white hover:bg-[#f8fafc] disabled:opacity-50 text-[#4f46e5] border border-[#e0e7ff] text-[13px] font-semibold rounded-[14px] px-4 py-2.5 transition-colors shadow-[0_1px_4px_rgba(0,0,0,0.02)] mt-2",children:C?"Updating...":"Update Assignment"})]})]})]})})]})},Yo=({onViewCalendar:t,onOpenProfile:s,userProfile:a,teacherName:r,liveActivity:o=[]})=>{const{currentUser:n}=ms(),[i,l]=u.useState(new Date),[c,d]=u.useState("pulse"),[m,f]=u.useState([]),[p,g]=u.useState(!1);u.useEffect(()=>{if(!n?.uid)return;const v=Ji(n.uid,{limitCount:100},z=>f(z),()=>{});return()=>v()},[n?.uid]);const S=v=>new Date(v.getFullYear(),v.getMonth()+1,0).getDate(),N=v=>new Date(v.getFullYear(),v.getMonth(),1).getDay(),j=()=>i.toLocaleDateString(void 0,{month:"long",year:"numeric"}),h=()=>l(new Date(i.getFullYear(),i.getMonth()-1)),w=()=>l(new Date(i.getFullYear(),i.getMonth()+1)),C=()=>{const v=S(i),z=N(i),F=[];for(let I=z-1;I>=0;I--)F.unshift(null);for(let I=1;I<=v;I++)F.push(I);return F},M=v=>{if(!v)return!1;const z=new Date;return v===z.getDate()&&i.getMonth()===z.getMonth()&&i.getFullYear()===z.getFullYear()},k=C(),W=["Mo","Tu","We","Th","Fr","Sa","Su"],b=v=>{if(!v)return!1;const z=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(v).padStart(2,"0")}`;return m.some(F=>{const I=new Date(F.startTime);return`${I.getFullYear()}-${String(I.getMonth()+1).padStart(2,"0")}-${String(I.getDate()).padStart(2,"0")}`===z})},y=v=>{if(!v)return;const z=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(v).padStart(2,"0")}`,F=m.filter(I=>{const V=new Date(I.startTime);return`${V.getFullYear()}-${String(V.getMonth()+1).padStart(2,"0")}-${String(V.getDate()).padStart(2,"0")}`===z});if(F.length!==0)return F.map(I=>`• ${I.title}`).join(` -`)};return e.jsxs("aside",{className:"w-[280px] bg-white border-l border-[#e2e8f0] flex flex-col flex-shrink-0 overflow-hidden",children:[e.jsxs("div",{className:"p-[22px_16px_10px] border-b border-[#f1f5f9] flex flex-col items-center gap-[5px]",children:[e.jsx("div",{className:"w-[48px] h-[48px] rounded-full bg-[#e0e7ff] flex items-center justify-center text-[22px] text-[#4f46e5] shadow-[0_0_0_3px_#c7d2fe] flex-shrink-0",children:e.jsx(kl,{src:a?.photo,name:r,className:"w-full h-full rounded-full"})}),e.jsx("div",{className:"text-[13.5px] font-semibold text-[#1e293b] mt-1",children:r}),e.jsx("div",{className:"text-[11px] text-[#94a3b8]",children:"Teacher"}),e.jsx("button",{onClick:s,className:"mt-[4px] py-[6px] px-[22px] bg-[#818cf8] hover:bg-[#6366f1] text-white rounded-full text-[11.5px] font-medium transition-colors",children:"Profile"})]}),e.jsxs("div",{className:"border-b border-[#f1f5f9]",children:[e.jsxs("div",{className:"p-[10px_16px_8px] flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:v=>{v.stopPropagation(),h()},className:"w-6 h-6 flex items-center justify-center bg-white border border-[#e2e8f0] rounded-[7px] text-[#64748b] hover:bg-[#f8fafc] cursor-pointer text-[14px] z-10",children:e.jsx(ks,{size:14})}),e.jsx("span",{className:"text-[12px] font-semibold text-[#1e293b] hover:text-[#4f46e5] transition-colors cursor-pointer",onClick:t,children:j()}),e.jsx("button",{onClick:v=>{v.stopPropagation(),w()},className:"w-6 h-6 flex items-center justify-center bg-white border border-[#e2e8f0] rounded-[7px] text-[#64748b] hover:bg-[#f8fafc] cursor-pointer text-[14px] z-10",children:e.jsx(Ss,{size:14})})]}),e.jsx("button",{onClick:()=>g(v=>!v),className:"w-6 h-6 flex items-center justify-center rounded-[7px] text-[#94a3b8] hover:bg-[#f1f5f9] hover:text-[#64748b] transition-colors",title:p?"Show calendar":"Hide calendar","aria-label":p?"Expand calendar":"Collapse calendar",children:e.jsx(_t,{size:14,className:`transition-transform duration-200 ${p?"":"rotate-180"}`})})]}),e.jsx(Mt,{initial:!1,children:!p&&e.jsx(Re.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.22,ease:"easeInOut"},className:"overflow-hidden",children:e.jsx("div",{className:"px-[16px] pb-[10px] cursor-pointer hover:bg-slate-50 transition-colors group/cal",onClick:t,children:e.jsxs("div",{className:"grid grid-cols-7 gap-[2px] text-center mb-1",children:[W.map(v=>e.jsx("div",{className:"text-[10px] font-semibold text-[#94a3b8] p-[2px_0_4px]",children:v},v)),k.map((v,z)=>e.jsxs("div",{className:"relative flex flex-col items-center justify-center h-[28px]",title:y(v),children:[e.jsx("div",{className:`text-[11px] leading-[22px] w-[22px] h-[22px] flex items-center justify-center rounded-full transition-all ${v===null?"text-[#cbd5e1]":M(v)?"bg-[#818cf8] text-white font-semibold":"text-[#475569] group-hover/cal:bg-slate-100"}`,children:v}),v!==null&&b(v)&&e.jsx("div",{className:`absolute bottom-0 w-1 h-1 rounded-full ${M(v)?"bg-white":"bg-[#a855f7]"}`})]},`${i.getMonth()}-${z}`))]})})},"cal-grid")})]}),e.jsxs("div",{className:"flex gap-[18px] p-[12px_16px_0] border-b border-[#f1f5f9] flex-shrink-0",children:[e.jsx("button",{onClick:()=>d("pulse"),className:`text-[11.5px] font-semibold pb-[9px] border-b-[2.5px] transition-colors ${c==="pulse"?"text-[#10b981] border-[#10b981]":"text-[#94a3b8] border-transparent"}`,children:"Live pulse"}),e.jsx("button",{onClick:()=>d("reminders"),className:`text-[11.5px] font-semibold pb-[9px] border-b-[2.5px] transition-colors ${c==="reminders"?"text-[#10b981] border-[#10b981]":"text-[#94a3b8] border-transparent"}`,children:"Reminders"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-[14px_16px]",children:[c==="pulse"&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-[10px] font-bold text-[#64748b] uppercase tracking-wider",children:"Live Activity Stream"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),e.jsx("span",{className:"text-[9px] font-bold text-emerald-600",children:"LIVE"})]})]}),o.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center opacity-40",children:[e.jsx(si,{size:32,className:"text-slate-300 mb-2"}),e.jsx("p",{className:"text-[11px] font-bold text-[#1e293b]",children:"No recent activity"})]}):e.jsx("div",{className:"space-y-4",children:o.slice(0,5).map(v=>e.jsxs("div",{className:"relative pl-5 before:absolute before:left-1.5 before:top-2 before:bottom-[-16px] before:w-[1px] before:bg-slate-100 last:before:hidden",children:[e.jsx("div",{className:"absolute left-0 top-1.5 w-3 h-3 rounded-full border-2 border-white bg-indigo-500 shadow-sm z-10"}),e.jsxs("div",{className:"bg-white border border-[#f1f5f9] rounded-xl p-3 shadow-sm hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex justify-between items-start mb-1",children:[e.jsx("span",{className:"text-[12px] font-bold text-[#1e293b] truncate",children:v.student}),e.jsx("span",{className:"text-[9px] font-medium text-[#94a3b8] shrink-0",children:v.time})]}),e.jsxs("p",{className:"text-[11px] text-[#64748b] leading-snug",children:[v.action," ",e.jsx("span",{className:"font-bold text-[#4f46e5]",children:v.topic})]})]})]},v.id))})]}),c==="reminders"&&e.jsxs("div",{className:"space-y-3",children:[m.filter(v=>{const z=new Date;return z.setHours(0,0,0,0),new Date(v.startTime).getTime()>=z.getTime()}).sort((v,z)=>new Date(v.startTime).getTime()-new Date(z.startTime).getTime()).slice(0,5).map(v=>{const z=new Date(v.startTime).toDateString()===new Date().toDateString();return e.jsxs("div",{onClick:t,className:"flex items-start gap-3 p-3 border border-[#f1f5f9] rounded-[14px] cursor-pointer hover:bg-slate-50 transition-colors group",children:[e.jsx("div",{className:`p-2 rounded-xl border border-[#f1f5f9] bg-white text-[14px] flex-shrink-0 shadow-sm transition-transform group-hover:scale-105 ${z?"text-rose-500":"text-[#4f46e5]"}`,children:e.jsx(Ka,{size:14})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] font-bold text-[#1e293b] mb-0.5 truncate",children:v.title}),e.jsxs("div",{className:`text-[10px] font-medium ${z?"text-rose-500 font-bold":"text-[#94a3b8]"}`,children:[z?"Today, ":"",new Date(v.startTime).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]},v.id)}),m.filter(v=>new Date(v.startTime).getTime()>=new Date().setHours(0,0,0,0)).length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center opacity-40",children:[e.jsx(er,{size:32,className:"text-slate-300 mb-2"}),e.jsx("p",{className:"text-[11px] font-bold text-[#1e293b]",children:"No upcoming tasks"})]})]})]})]})};export{fp as default}; + `})]}),document.body),e.jsxs("div",{className:"w-full bg-white/80 rounded-[18px] p-[20px] shadow-[0_1px_4px_rgba(0,0,0,0.02)] border border-white mt-auto",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[#1e293b] mb-4",children:"Section Assignment"}),e.jsxs("div",{className:"space-y-[12px]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5 block ml-1",children:"Grade Level"}),e.jsx("div",{className:"relative",children:e.jsx(js,{value:N,onChange:B=>j(B.target.value),placeholder:"Grade",className:"appearance-none w-full bg-[#f8fafc] border border-[#e2e8f0] text-[#475569] text-[13px] font-medium rounded-[14px] px-4 py-2.5 outline-none focus:border-[#a855f7] focus:ring-1 focus:ring-[#a855f7] h-auto"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold text-[#64748b] uppercase tracking-wider mb-1.5 block ml-1",children:"Section"}),e.jsx("div",{className:"relative",children:e.jsx(js,{value:h,onChange:B=>w(B.target.value),placeholder:"Section",className:"appearance-none w-full bg-[#f8fafc] border border-[#e2e8f0] text-[#475569] text-[13px] font-medium rounded-[14px] px-4 py-2.5 outline-none focus:border-[#a855f7] focus:ring-1 focus:ring-[#a855f7] h-auto"})})]}),e.jsx("button",{onClick:Lt,disabled:C||!N.trim()||!h.trim(),className:"w-full bg-white hover:bg-[#f8fafc] disabled:opacity-50 text-[#4f46e5] border border-[#e0e7ff] text-[13px] font-semibold rounded-[14px] px-4 py-2.5 transition-colors shadow-[0_1px_4px_rgba(0,0,0,0.02)] mt-2",children:C?"Updating...":"Update Assignment"})]})]})]})})]})},Yo=({onViewCalendar:t,onOpenProfile:s,userProfile:a,teacherName:r,liveActivity:o=[]})=>{const{currentUser:n}=ms(),[i,l]=u.useState(new Date),[c,d]=u.useState("pulse"),[m,f]=u.useState([]),[p,g]=u.useState(!1);u.useEffect(()=>{if(!n?.uid)return;const v=Ji(n.uid,{limitCount:100},z=>f(z),()=>{});return()=>v()},[n?.uid]);const S=v=>new Date(v.getFullYear(),v.getMonth()+1,0).getDate(),N=v=>new Date(v.getFullYear(),v.getMonth(),1).getDay(),j=()=>i.toLocaleDateString(void 0,{month:"long",year:"numeric"}),h=()=>l(new Date(i.getFullYear(),i.getMonth()-1)),w=()=>l(new Date(i.getFullYear(),i.getMonth()+1)),C=()=>{const v=S(i),z=N(i),F=[];for(let I=z-1;I>=0;I--)F.unshift(null);for(let I=1;I<=v;I++)F.push(I);return F},M=v=>{if(!v)return!1;const z=new Date;return v===z.getDate()&&i.getMonth()===z.getMonth()&&i.getFullYear()===z.getFullYear()},k=C(),q=["Mo","Tu","We","Th","Fr","Sa","Su"],b=v=>{if(!v)return!1;const z=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(v).padStart(2,"0")}`;return m.some(F=>{const I=new Date(F.startTime);return`${I.getFullYear()}-${String(I.getMonth()+1).padStart(2,"0")}-${String(I.getDate()).padStart(2,"0")}`===z})},y=v=>{if(!v)return;const z=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(v).padStart(2,"0")}`,F=m.filter(I=>{const W=new Date(I.startTime);return`${W.getFullYear()}-${String(W.getMonth()+1).padStart(2,"0")}-${String(W.getDate()).padStart(2,"0")}`===z});if(F.length!==0)return F.map(I=>`• ${I.title}`).join(` +`)};return e.jsxs("aside",{className:"w-[280px] bg-white border-l border-[#e2e8f0] flex flex-col flex-shrink-0 overflow-hidden",children:[e.jsxs("div",{className:"p-[22px_16px_10px] border-b border-[#f1f5f9] flex flex-col items-center gap-[5px]",children:[e.jsx("div",{className:"w-[48px] h-[48px] rounded-full bg-[#e0e7ff] flex items-center justify-center text-[22px] text-[#4f46e5] shadow-[0_0_0_3px_#c7d2fe] flex-shrink-0",children:e.jsx(kl,{src:a?.photo,name:r,className:"w-full h-full rounded-full"})}),e.jsx("div",{className:"text-[13.5px] font-semibold text-[#1e293b] mt-1",children:r}),e.jsx("div",{className:"text-[11px] text-[#94a3b8]",children:"Teacher"}),e.jsx("button",{onClick:s,className:"mt-[4px] py-[6px] px-[22px] bg-[#818cf8] hover:bg-[#6366f1] text-white rounded-full text-[11.5px] font-medium transition-colors",children:"Profile"})]}),e.jsxs("div",{className:"border-b border-[#f1f5f9]",children:[e.jsxs("div",{className:"p-[10px_16px_8px] flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:v=>{v.stopPropagation(),h()},className:"w-6 h-6 flex items-center justify-center bg-white border border-[#e2e8f0] rounded-[7px] text-[#64748b] hover:bg-[#f8fafc] cursor-pointer text-[14px] z-10",children:e.jsx(ks,{size:14})}),e.jsx("span",{className:"text-[12px] font-semibold text-[#1e293b] hover:text-[#4f46e5] transition-colors cursor-pointer",onClick:t,children:j()}),e.jsx("button",{onClick:v=>{v.stopPropagation(),w()},className:"w-6 h-6 flex items-center justify-center bg-white border border-[#e2e8f0] rounded-[7px] text-[#64748b] hover:bg-[#f8fafc] cursor-pointer text-[14px] z-10",children:e.jsx(Ss,{size:14})})]}),e.jsx("button",{onClick:()=>g(v=>!v),className:"w-6 h-6 flex items-center justify-center rounded-[7px] text-[#94a3b8] hover:bg-[#f1f5f9] hover:text-[#64748b] transition-colors",title:p?"Show calendar":"Hide calendar","aria-label":p?"Expand calendar":"Collapse calendar",children:e.jsx(_t,{size:14,className:`transition-transform duration-200 ${p?"":"rotate-180"}`})})]}),e.jsx(Mt,{initial:!1,children:!p&&e.jsx(Re.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.22,ease:"easeInOut"},className:"overflow-hidden",children:e.jsx("div",{className:"px-[16px] pb-[10px] cursor-pointer hover:bg-slate-50 transition-colors group/cal",onClick:t,children:e.jsxs("div",{className:"grid grid-cols-7 gap-[2px] text-center mb-1",children:[q.map(v=>e.jsx("div",{className:"text-[10px] font-semibold text-[#94a3b8] p-[2px_0_4px]",children:v},v)),k.map((v,z)=>e.jsxs("div",{className:"relative flex flex-col items-center justify-center h-[28px]",title:y(v),children:[e.jsx("div",{className:`text-[11px] leading-[22px] w-[22px] h-[22px] flex items-center justify-center rounded-full transition-all ${v===null?"text-[#cbd5e1]":M(v)?"bg-[#818cf8] text-white font-semibold":"text-[#475569] group-hover/cal:bg-slate-100"}`,children:v}),v!==null&&b(v)&&e.jsx("div",{className:`absolute bottom-0 w-1 h-1 rounded-full ${M(v)?"bg-white":"bg-[#a855f7]"}`})]},`${i.getMonth()}-${z}`))]})})},"cal-grid")})]}),e.jsxs("div",{className:"flex gap-[18px] p-[12px_16px_0] border-b border-[#f1f5f9] flex-shrink-0",children:[e.jsx("button",{onClick:()=>d("pulse"),className:`text-[11.5px] font-semibold pb-[9px] border-b-[2.5px] transition-colors ${c==="pulse"?"text-[#10b981] border-[#10b981]":"text-[#94a3b8] border-transparent"}`,children:"Live pulse"}),e.jsx("button",{onClick:()=>d("reminders"),className:`text-[11.5px] font-semibold pb-[9px] border-b-[2.5px] transition-colors ${c==="reminders"?"text-[#10b981] border-[#10b981]":"text-[#94a3b8] border-transparent"}`,children:"Reminders"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-[14px_16px]",children:[c==="pulse"&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-[10px] font-bold text-[#64748b] uppercase tracking-wider",children:"Live Activity Stream"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),e.jsx("span",{className:"text-[9px] font-bold text-emerald-600",children:"LIVE"})]})]}),o.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center opacity-40",children:[e.jsx(si,{size:32,className:"text-slate-300 mb-2"}),e.jsx("p",{className:"text-[11px] font-bold text-[#1e293b]",children:"No recent activity"})]}):e.jsx("div",{className:"space-y-4",children:o.slice(0,5).map(v=>e.jsxs("div",{className:"relative pl-5 before:absolute before:left-1.5 before:top-2 before:bottom-[-16px] before:w-[1px] before:bg-slate-100 last:before:hidden",children:[e.jsx("div",{className:"absolute left-0 top-1.5 w-3 h-3 rounded-full border-2 border-white bg-indigo-500 shadow-sm z-10"}),e.jsxs("div",{className:"bg-white border border-[#f1f5f9] rounded-xl p-3 shadow-sm hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex justify-between items-start mb-1",children:[e.jsx("span",{className:"text-[12px] font-bold text-[#1e293b] truncate",children:v.student}),e.jsx("span",{className:"text-[9px] font-medium text-[#94a3b8] shrink-0",children:v.time})]}),e.jsxs("p",{className:"text-[11px] text-[#64748b] leading-snug",children:[v.action," ",e.jsx("span",{className:"font-bold text-[#4f46e5]",children:v.topic})]})]})]},v.id))})]}),c==="reminders"&&e.jsxs("div",{className:"space-y-3",children:[m.filter(v=>{const z=new Date;return z.setHours(0,0,0,0),new Date(v.startTime).getTime()>=z.getTime()}).sort((v,z)=>new Date(v.startTime).getTime()-new Date(z.startTime).getTime()).slice(0,5).map(v=>{const z=new Date(v.startTime).toDateString()===new Date().toDateString();return e.jsxs("div",{onClick:t,className:"flex items-start gap-3 p-3 border border-[#f1f5f9] rounded-[14px] cursor-pointer hover:bg-slate-50 transition-colors group",children:[e.jsx("div",{className:`p-2 rounded-xl border border-[#f1f5f9] bg-white text-[14px] flex-shrink-0 shadow-sm transition-transform group-hover:scale-105 ${z?"text-rose-500":"text-[#4f46e5]"}`,children:e.jsx(Ka,{size:14})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] font-bold text-[#1e293b] mb-0.5 truncate",children:v.title}),e.jsxs("div",{className:`text-[10px] font-medium ${z?"text-rose-500 font-bold":"text-[#94a3b8]"}`,children:[z?"Today, ":"",new Date(v.startTime).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]},v.id)}),m.filter(v=>new Date(v.startTime).getTime()>=new Date().setHours(0,0,0,0)).length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center opacity-40",children:[e.jsx(er,{size:32,className:"text-slate-300 mb-2"}),e.jsx("p",{className:"text-[11px] font-bold text-[#1e293b]",children:"No upcoming tasks"})]})]})]})]})};export{fp as default}; diff --git a/assets/XPNotification-B3gCYXcz.js b/assets/XPNotification-BWSMGDCy.js similarity index 92% rename from assets/XPNotification-B3gCYXcz.js rename to assets/XPNotification-BWSMGDCy.js index 5c615f3f1517cdc9e55a6ed6a33b401425ef784e..c9a96e4c4983f88f3e93bfd2958bc0d1db14aac0 100644 --- a/assets/XPNotification-B3gCYXcz.js +++ b/assets/XPNotification-BWSMGDCy.js @@ -1 +1 @@ -import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{h as n,m as i,a5 as m}from"./index-BYG24j30.js";import{S as c}from"./sparkles-DiaNugT9.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const b=({xp:r,message:a,show:t,onComplete:s})=>(l.useEffect(()=>{if(t){const o=setTimeout(()=>{s()},3e3);return()=>clearTimeout(o)}},[t,s]),e.jsx(n,{children:t&&e.jsx(i.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-50",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(i.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(c,{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:["+",r," XP"]})]})]})})}));export{b as default}; +import{r as l,j as e}from"./vendor-react-B4AQeu28.js";import{h as n,m as i,a5 as m}from"./index-CR5aYAL9.js";import{S as c}from"./sparkles-Df420Y_c.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const b=({xp:r,message:a,show:t,onComplete:s})=>(l.useEffect(()=>{if(t){const o=setTimeout(()=>{s()},3e3);return()=>clearTimeout(o)}},[t,s]),e.jsx(n,{children:t&&e.jsx(i.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-50",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(i.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(c,{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:["+",r," XP"]})]})]})})}));export{b as default}; diff --git a/assets/automationService-Cn_PZsKR.js b/assets/automationService-BUinEhr-.js similarity index 98% rename from assets/automationService-Cn_PZsKR.js rename to assets/automationService-BUinEhr-.js index c4a17d63d2f838db063600995d560e363d7f1b35..159365686ee7932772347beb2537a4e70d6bc2bc 100644 --- a/assets/automationService-Cn_PZsKR.js +++ b/assets/automationService-BUinEhr-.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 C,writeBatch as Q}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as r,b3 as $}from"./index-BYG24j30.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-BPuEd8FG.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 E(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 M(e,n,o="Grade 11",u,i="iar_only",t="initial_assessment"){if(t==="followup_diagnostic"){const s=a(r,"deepDiagnosticAssignments"),d=b(s,z("lrn","==",e)),f=await A(d);if(!f.empty){const p=Q(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,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 x(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 N(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 W(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 G(e){const n=g(r,"curriculumContent",e.contentId);return e.action==="delete"?await C(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{E as getPendingDeepDiagnosticCount,G as triggerContentUpdated,W as triggerDataImported,M as triggerDiagnosticCompleted,x as triggerQuizSubmitted,N 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 C,writeBatch as Q}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as r,b3 as $}from"./index-CR5aYAL9.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-BPuEd8FG.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 E(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 M(e,n,o="Grade 11",u,i="iar_only",t="initial_assessment"){if(t==="followup_diagnostic"){const s=a(r,"deepDiagnosticAssignments"),d=b(s,z("lrn","==",e)),f=await A(d);if(!f.empty){const p=Q(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,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 x(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 N(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 W(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 G(e){const n=g(r,"curriculumContent",e.contentId);return e.action==="delete"?await C(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{E as getPendingDeepDiagnosticCount,G as triggerContentUpdated,W as triggerDataImported,M as triggerDiagnosticCompleted,x as triggerQuizSubmitted,N as triggerStudentEnrolled}; diff --git a/assets/bell-CJfHcVLS.js b/assets/bell-DVzATilo.js similarity index 91% rename from assets/bell-CJfHcVLS.js rename to assets/bell-DVzATilo.js index 32737bff65b856edc0e864ff9db8e37d038660a1..a8761ac99151c28b928cb2dd003412d4ec23c96e 100644 --- a/assets/bell-CJfHcVLS.js +++ b/assets/bell-DVzATilo.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/button-LR_FKM7p.js b/assets/button-CbtAHv27.js similarity index 97% rename from assets/button-LR_FKM7p.js rename to assets/button-CbtAHv27.js index 188eea9299bd168214ae9750b90c16e3068e85c1..a2b4da71e2855345ccac74fdf85efa6e986ed041 100644 --- a/assets/button-LR_FKM7p.js +++ b/assets/button-CbtAHv27.js @@ -1 +1 @@ -import{j as y}from"./vendor-react-B4AQeu28.js";import{S as k}from"./vendor-radix-BPuEd8FG.js";import{c as V}from"./vendor-charts-CAmziV1y.js";import{n as p}from"./index-BYG24j30.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-BPuEd8FG.js";import{c as V}from"./vendor-charts-CAmziV1y.js";import{n as p}from"./index-CR5aYAL9.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-BOgIfbES.js b/assets/chart-column-nZ0JrvMi.js similarity index 89% rename from assets/chart-column-BOgIfbES.js rename to assets/chart-column-nZ0JrvMi.js index 59152df98f0ae474eb73c6e137126fbb2baad3a4..7925e8bd75d8c0b9d95f3609b46c794f41dceb51 100644 --- a/assets/chart-column-BOgIfbES.js +++ b/assets/chart-column-nZ0JrvMi.js @@ -1,4 +1,4 @@ -import{e as t}from"./index-BYG24j30.js";/** +import{e as t}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chatService-CczfDdTB.js b/assets/chatService-BdLPo3Lt.js similarity index 97% rename from assets/chatService-CczfDdTB.js rename to assets/chatService-BdLPo3Lt.js index a9f0ab80037ddc311c47336ad39d4939ee7fd37c..2b36d610ea512dbe0463df246c4ca64fede511f7 100644 --- a/assets/chatService-CczfDdTB.js +++ b/assets/chatService-BdLPo3Lt.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-BYG24j30.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-BPuEd8FG.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-CR5aYAL9.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-BPuEd8FG.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-C-Jb6xS0.js b/assets/check-MAu_C8ty.js similarity index 85% rename from assets/check-C-Jb6xS0.js rename to assets/check-MAu_C8ty.js index 41800324d14b18d915d65adf528965010b96ce4b..c52c0506d835d13126b489746b71bf9a98ef1ca2 100644 --- a/assets/check-C-Jb6xS0.js +++ b/assets/check-MAu_C8ty.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BYG24j30.js";/** +import{e as c}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chevron-left-CIE_NDv7.js b/assets/chevron-left-Buq4JTY_.js similarity index 86% rename from assets/chevron-left-CIE_NDv7.js rename to assets/chevron-left-Buq4JTY_.js index 6e4633086a51758359e883af81cef3269a23d4c8..b2dadf77d1522134bf8fb6e36962646b54c97e3e 100644 --- a/assets/chevron-left-CIE_NDv7.js +++ b/assets/chevron-left-Buq4JTY_.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chevron-right-CF79oTk8.js b/assets/chevron-right-d9v3XH9Z.js similarity index 85% rename from assets/chevron-right-CF79oTk8.js rename to assets/chevron-right-d9v3XH9Z.js index 9bbccce3da95dd2916e452f52315e846dab1abd0..a8aadc838ebb83b45c6a565f4d8d14b9a0333204 100644 --- a/assets/chevron-right-CF79oTk8.js +++ b/assets/chevron-right-d9v3XH9Z.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BYG24j30.js";/** +import{e as o}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/chevron-up-vEHTl-in.js b/assets/chevron-up-BrrK8Cng.js similarity index 92% rename from assets/chevron-up-vEHTl-in.js rename to assets/chevron-up-BrrK8Cng.js index ead04415534adc8d8355839844b9fa9ec948f78c..26bf3a37af0c875ad45e48c1086d91a5615ab4a1 100644 --- a/assets/chevron-up-vEHTl-in.js +++ b/assets/chevron-up-BrrK8Cng.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BYG24j30.js";/** +import{e as o}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-alert-D1BZWAsh.js b/assets/circle-alert-CSWToxPb.js similarity index 90% rename from assets/circle-alert-D1BZWAsh.js rename to assets/circle-alert-CSWToxPb.js index 294f069a27369c5fca94fb7a76176e3ffc50a3bc..e8ef4839a7f9d1e70f11b3278becfd203c7281da 100644 --- a/assets/circle-alert-D1BZWAsh.js +++ b/assets/circle-alert-CSWToxPb.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-check-_6J4FrSd.js b/assets/circle-check--_-gyncR.js similarity index 87% rename from assets/circle-check-_6J4FrSd.js rename to assets/circle-check--_-gyncR.js index 7e86e66c30bcdc40686a408fd8fae74cdf96c8dd..fa40bef86ffa260904addc0f1aba4f297f5fc4d5 100644 --- a/assets/circle-check-_6J4FrSd.js +++ b/assets/circle-check--_-gyncR.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BYG24j30.js";/** +import{e as c}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-check-big-uJgj_456.js b/assets/circle-check-big-CWD8eO1a.js similarity index 88% rename from assets/circle-check-big-uJgj_456.js rename to assets/circle-check-big-CWD8eO1a.js index dd7c81ebdb6ae61a1822deb5e817645f9fc88230..1057170e9954dce1eddf3fac9b401eac5c1f2e4b 100644 --- a/assets/circle-check-big-uJgj_456.js +++ b/assets/circle-check-big-CWD8eO1a.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BYG24j30.js";/** +import{e as c}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/circle-help-BYya03qM.js b/assets/circle-help-CS95sLmI.js similarity index 89% rename from assets/circle-help-BYya03qM.js rename to assets/circle-help-CS95sLmI.js index 83f30064f2821feabf6a9ca78622dd10fbf9bf05..543ac18048775242cc1f5e577467fb5d073684d7 100644 --- a/assets/circle-help-BYya03qM.js +++ b/assets/circle-help-CS95sLmI.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BYG24j30.js";/** +import{e as c}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/clipboard-check-CC5IRbh7.js b/assets/clipboard-check-B4PuSMw1.js similarity index 91% rename from assets/clipboard-check-CC5IRbh7.js rename to assets/clipboard-check-B4PuSMw1.js index 01bb2ebc42fe57523d8c2adbdcaa44948cc70d28..cc0b06742e6483f9f382d8b3893e5e40a83eb912 100644 --- a/assets/clipboard-check-CC5IRbh7.js +++ b/assets/clipboard-check-B4PuSMw1.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/clock-CGFFx3Yv.js b/assets/clock-BF2L28Gg.js similarity index 87% rename from assets/clock-CGFFx3Yv.js rename to assets/clock-BF2L28Gg.js index 83ff7171a0c0426b1670a4e500c3c8cb2760ac94..a4219fac67b01ab890a74f99e5b8d4a02d9ed573 100644 --- a/assets/clock-CGFFx3Yv.js +++ b/assets/clock-BF2L28Gg.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BYG24j30.js";/** +import{e as c}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/diagnosticService-DGOeuGMt.js b/assets/diagnosticService-C3w1VDru.js similarity index 93% rename from assets/diagnosticService-DGOeuGMt.js rename to assets/diagnosticService-C3w1VDru.js index 9f3e38ccaca6810ea353beca08b8c109cc29df20..468da4229a0ab851a26fe9674d1229118cf3ac07 100644 --- a/assets/diagnosticService-DGOeuGMt.js +++ b/assets/diagnosticService-C3w1VDru.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BYG24j30.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); -import{_ as w}from"./index-BYG24j30.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-BYG24j30.js").then(a=>a.b5);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-BYG24j30.js").then(r=>r.b5);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-CR5aYAL9.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/index-DoBeoF6g.css"])))=>i.map(i=>d[i]); +import{_ as w}from"./index-CR5aYAL9.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-CR5aYAL9.js").then(a=>a.b5);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-CR5aYAL9.js").then(r=>r.b5);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-H4V35jbm.js b/assets/dialog-BhXeykx9.js similarity index 96% rename from assets/dialog-H4V35jbm.js rename to assets/dialog-BhXeykx9.js index 0a238c8690814492b565050e875c9fab4bda187a..75b1541343a1bd5c18dae06101dc300540d0866c 100644 --- a/assets/dialog-H4V35jbm.js +++ b/assets/dialog-BhXeykx9.js @@ -1,4 +1,4 @@ -import{e as g,n as s}from"./index-BYG24j30.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-BPuEd8FG.js";import{X as x}from"./x-DU8WEZ6X.js";/** +import{e as g,n as s}from"./index-CR5aYAL9.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-BPuEd8FG.js";import{X as x}from"./x-DiyyYv8Q.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/dollar-sign-CFYvEMYD.js b/assets/dollar-sign-a1mi5_q1.js similarity index 89% rename from assets/dollar-sign-CFYvEMYD.js rename to assets/dollar-sign-a1mi5_q1.js index 2ff2fa6f5d18f61a26e4f260ceec5ac2b0c78d3e..fe47a8779ae6d14f5817726ffb782d401771853d 100644 --- a/assets/dollar-sign-CFYvEMYD.js +++ b/assets/dollar-sign-a1mi5_q1.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/download-DRtqT_j8.js b/assets/download-teQqHQmt.js similarity index 89% rename from assets/download-DRtqT_j8.js rename to assets/download-teQqHQmt.js index f940f0a6e1ea16a6af67ad398f4173fff5af93ff..5334c6367e9f49d326b55d5794a4b566dabbb543 100644 --- a/assets/download-DRtqT_j8.js +++ b/assets/download-teQqHQmt.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BYG24j30.js";/** +import{e as o}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/eye-Cjs8eHiG.js b/assets/eye-BuiZU-wn.js similarity index 96% rename from assets/eye-Cjs8eHiG.js rename to assets/eye-BuiZU-wn.js index a47134e4c260bb22a01f05c3a1958fb3d9db2701..4b46bbc93026c5c04766840c06d9c37851f14898 100644 --- a/assets/eye-Cjs8eHiG.js +++ b/assets/eye-BuiZU-wn.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/formatDistanceToNow-C9WeR9GV.js b/assets/formatDistanceToNow-B4dD00jc.js similarity index 99% rename from assets/formatDistanceToNow-C9WeR9GV.js rename to assets/formatDistanceToNow-B4dD00jc.js index bcc3fdd658d1fe7899efdc6e3085372da9fcd064..723fa276eaba873175cf30608a5fcec182270382 100644 --- a/assets/formatDistanceToNow-C9WeR9GV.js +++ b/assets/formatDistanceToNow-B4dD00jc.js @@ -1,4 +1,4 @@ -import{e as W,t as u,a8 as S}from"./index-BYG24j30.js";/** +import{e as W,t as u,a8 as S}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/funnel-CkgPZM71.js b/assets/funnel-nXEzWYRv.js similarity index 90% rename from assets/funnel-CkgPZM71.js rename to assets/funnel-nXEzWYRv.js index dba4d64c58c6cceafcc928a71cf68d226d13ac52..e10b50a2e576b36ab331b1c177360a1c6e342076 100644 --- a/assets/funnel-CkgPZM71.js +++ b/assets/funnel-nXEzWYRv.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/index-BYG24j30.js b/assets/index-CR5aYAL9.js similarity index 98% rename from assets/index-BYG24j30.js rename to assets/index-CR5aYAL9.js index fa039a164682e643f5451ddd9722fef4bba7cc82..690391b43d455a155960b698875bd8fbdcdbfb7c 100644 --- a/assets/index-BYG24j30.js +++ b/assets/index-CR5aYAL9.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/automationService-Cn_PZsKR.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/chatService-CczfDdTB.js","assets/trackingService-MJBRfiN7.js","assets/LoginPage-DKWs9ixZ.js","assets/button-LR_FKM7p.js","assets/input-CtjqQUbX.js","assets/sparkles-DiaNugT9.js","assets/mail-B8qfL-UK.js","assets/eye-Cjs8eHiG.js","assets/shield-check-CoyMgFec.js","assets/TeacherDashboard-Uxc_axO7.js","assets/ConfirmModal-BDSADafu.js","assets/x-DU8WEZ6X.js","assets/trash-2-Bz07bxtW.js","assets/log-out-7LnFvNg-.js","assets/search-qXpo6Bz-.js","assets/check-C-Jb6xS0.js","assets/plus-C5IM0tm0.js","assets/NotificationDropdown-vpdHjkTB.js","assets/formatDistanceToNow-C9WeR9GV.js","assets/bell-CJfHcVLS.js","assets/circle-check-_6J4FrSd.js","assets/circle-alert-D1BZWAsh.js","assets/LogoutActionButton-U0Q7JjxX.js","assets/quizService-Dg-FcCkj.js","assets/tooltip-B8dZx5CM.js","assets/circle-help-BYya03qM.js","assets/send-Cs_bBaZx.js","assets/chevron-up-vEHTl-in.js","assets/minus-sZ1MmK-H.js","assets/chart-column-BOgIfbES.js","assets/skeleton-9NZnc9sp.js","assets/download-DRtqT_j8.js","assets/chevron-left-CIE_NDv7.js","assets/chevron-right-CF79oTk8.js","assets/save-DidAD_jg.js","assets/upload-z5a73neo.js","assets/useQuery-C5wg1Gx-.js","assets/subjects-CnMsFeDX.js","assets/useCurriculum-BCsJVZ1p.js","assets/circle-check-big-uJgj_456.js","assets/ChatMarkdown-Dn0t_isr.js","assets/clock-CGFFx3Yv.js","assets/dialog-H4V35jbm.js","assets/vendor-xlsx-uZelXSz_.js","assets/clipboard-check-CC5IRbh7.js","assets/AdminDashboard-BGOkExie.js","assets/Sidebar-DAee_vGE.js","assets/shirt-DhJu64M2.js","assets/select-DM5m46Pk.js","assets/dollar-sign-CFYvEMYD.js","assets/switch-CqM6p44O.js","assets/useSubjectAvailability-CNwO6mr3.js","assets/HeroBanner--aQVgKP1.js","assets/RightSidebar-BF7n5nEK.js","assets/quiz_battle_avatar-BXHPSput.js","assets/XPNotification-B3gCYXcz.js","assets/index-BVqK5_Xi.js","assets/megaphone-DX0jSVq2.js","assets/SupplementalBanner-DptF9mye.js","assets/SupplementalPillCarousel-BucFK7HK.js","assets/LearningPath-6C1pnB-M.js","assets/ModuleFolderCard-7StF4eM7.js","assets/CompetencyRadarChart-wJLEa8V5.js","assets/ModulesPage-Dw5f2_tQ.js","assets/ScientificCalculator-Ba2j64OY.js","assets/volume-x-WJgblgWN.js","assets/lightbulb-C6VPAE81.js","assets/confetti.module-C94ZD2ww.js","assets/funnel-CkgPZM71.js","assets/AIChatPage-6rPaXTro.js","assets/GradesPage-DFzgWMGj.js","assets/LeaderboardPage-BhhK2vnv.js","assets/useFeatureAccess-BqmsqlKE.js","assets/QuizBattlePage-B59IiVNM.js","assets/CompositeAvatar-Col05lJc.js","assets/avatarData-BuQSOXo3.js","assets/AvatarShop-CiwigxhN.js","assets/FloatingAITutor-C6E9qFVh.js","assets/maximize-2-7OlWKBmu.js","assets/RewardsModal-vFV0nluD.js","assets/ProfileModal-BujeMrz5.js","assets/ProfilePictureUploader-C40Uwtje.js","assets/SettingsModal-BlqFNEeQ.js","assets/InitialAssessmentModal-BXrHaNxu.js","assets/diagnosticService-DGOeuGMt.js","assets/AssessmentPage-BRsvq8VI.js","assets/DiagnosticBreakdown-DMdwTTKX.js","assets/testResetService-3LGLpyer.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/automationService-BUinEhr-.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-BPuEd8FG.js","assets/vendor-charts-CAmziV1y.js","assets/vendor-markdown-yqZQ_iQm.js","assets/vendor-markdown-CfVKi3_s.css","assets/chatService-BdLPo3Lt.js","assets/trackingService-BGfVSr6K.js","assets/LoginPage-BLe3Cr5c.js","assets/button-CbtAHv27.js","assets/input-DgZjxAsx.js","assets/sparkles-Df420Y_c.js","assets/mail-sfPSTvMi.js","assets/eye-BuiZU-wn.js","assets/shield-check-CuuwgPnV.js","assets/TeacherDashboard-D7do0AjP.js","assets/ConfirmModal-BVHZuXaM.js","assets/x-DiyyYv8Q.js","assets/trash-2-BtGasoad.js","assets/log-out-BT_ShBSM.js","assets/search-1a4wCp_r.js","assets/check-MAu_C8ty.js","assets/plus-Cp5Q-YTc.js","assets/NotificationDropdown-DBksmA1S.js","assets/formatDistanceToNow-B4dD00jc.js","assets/bell-DVzATilo.js","assets/circle-check--_-gyncR.js","assets/circle-alert-CSWToxPb.js","assets/LogoutActionButton-tEi5DIaj.js","assets/quizService-83ZGYTl6.js","assets/tooltip-COrnGY4E.js","assets/circle-help-CS95sLmI.js","assets/send-B1wbvsc_.js","assets/chevron-up-BrrK8Cng.js","assets/minus-D8MfEHLl.js","assets/chart-column-nZ0JrvMi.js","assets/skeleton-nK8OdpwJ.js","assets/download-teQqHQmt.js","assets/chevron-left-Buq4JTY_.js","assets/chevron-right-d9v3XH9Z.js","assets/save-BpEMiY1d.js","assets/upload-Dv-dcZHV.js","assets/useQuery-CFyiy_x4.js","assets/subjects-CruSaBwq.js","assets/useCurriculum-BQeS3LyA.js","assets/circle-check-big-CWD8eO1a.js","assets/ChatMarkdown-kQBhTXf0.js","assets/clock-BF2L28Gg.js","assets/dialog-BhXeykx9.js","assets/vendor-xlsx-uZelXSz_.js","assets/clipboard-check-B4PuSMw1.js","assets/AdminDashboard-DY4v_Yug.js","assets/Sidebar-DPdujCJv.js","assets/shirt-DT9OZcT1.js","assets/select-DMAe8pN9.js","assets/dollar-sign-a1mi5_q1.js","assets/switch-DI6PCkYC.js","assets/useSubjectAvailability-SVKjmUD3.js","assets/HeroBanner-DGWA0f42.js","assets/RightSidebar-DY3YTL-R.js","assets/quiz_battle_avatar-BXHPSput.js","assets/XPNotification-BWSMGDCy.js","assets/index-CvXxFcEI.js","assets/megaphone-D_BUBJZ4.js","assets/SupplementalBanner-BLQPu9lu.js","assets/SupplementalPillCarousel-BmES_4dd.js","assets/LearningPath-BkBmgh8H.js","assets/ModuleFolderCard-DaH-e6Ze.js","assets/CompetencyRadarChart-DMNMZ6Ga.js","assets/ModulesPage-BVHCL2m4.js","assets/ScientificCalculator-CLa3avU-.js","assets/volume-x-FcYe0Ron.js","assets/lightbulb-CRrzx6iX.js","assets/confetti.module-C94ZD2ww.js","assets/funnel-nXEzWYRv.js","assets/AIChatPage-BP31m_mb.js","assets/GradesPage-D7AMuxL8.js","assets/LeaderboardPage-DIBnra9H.js","assets/useFeatureAccess-DCme1VYw.js","assets/QuizBattlePage-Cm-cnqCP.js","assets/CompositeAvatar-Col05lJc.js","assets/avatarData-BuQSOXo3.js","assets/AvatarShop-1g2VJnfQ.js","assets/FloatingAITutor-DpWLWA30.js","assets/maximize-2-DtyTSFtD.js","assets/RewardsModal-e7BnIl6w.js","assets/ProfileModal-BpvupEPF.js","assets/ProfilePictureUploader-CZ4lHPeL.js","assets/SettingsModal-Bj9L7UBt.js","assets/InitialAssessmentModal-BXyrazRg.js","assets/diagnosticService-C3w1VDru.js","assets/AssessmentPage-DhcG3TWJ.js","assets/DiagnosticBreakdown-lTfPVQ3_.js","assets/testResetService-BuCuwryb.js"])))=>i.map(i=>d[i]); import{r as h,j as b,d as I,c as Tp,f as Pp}from"./vendor-react-B4AQeu28.js";import{initializeFirestore as _p,memoryLocalCache as Ep,setDoc as $e,doc as q,serverTimestamp as ce,getDoc as ve,getDocFromServer as Zo,onSnapshot as Yt,query as Ot,limit as ks,orderBy as vn,collection as Xe,getDocs as zn,updateDoc as dt,arrayUnion as Lu,increment as fs,where as Mt,deleteDoc as yr,Timestamp as Dn,runTransaction as Cp}from"./vendor-firebase-firestore-CNv3xXal.js";import{U as Ap,V as Rp,Y as Mp,Z as Ip,$ as Dp,a0 as Op,a1 as Lp,a2 as zp,a3 as jp}from"./vendor-firebase-core-D7GXCeNu.js";import{browserLocalPersistence as Ha,initializeAuth as Za,browserSessionPersistence as Np,inMemoryPersistence as Ka,GoogleAuthProvider as $p,createUserWithEmailAndPassword as Fp,updateProfile as Vp,signInWithEmailAndPassword as Bp,signOut as Up,onAuthStateChanged as qp,updatePassword as Gp,updateEmail as Wp,deleteUser as Hp,EmailAuthProvider as Zp,reauthenticateWithCredential as Kp}from"./vendor-firebase-auth-T_wvTOvf.js";import{g as Qp}from"./vendor-firebase-storage-Bi7H_66d.js";import{g as Xp}from"./vendor-firebase-analytics-rHarj5hR.js";import{R as Yp,I as Jp,F as em}from"./vendor-radix-BPuEd8FG.js";import{c as tm}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 Nr=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(){}},nm=class extends Nr{#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"}},zu=new nm,sm={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},rm=class{#e=sm;#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)}},Ko=new rm;function om(e){setTimeout(e,0)}var im=typeof window>"u"||"Deno"in globalThis;function St(){}function am(e,t){return typeof e=="function"?e(t):e}function cm(e){return typeof e=="number"&&e>=0&&e!==1/0}function lm(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Qo(e,t){return typeof e=="function"?e(t):e}function um(e,t){return typeof e=="function"?e(t):e}function Qa(e,t){const{type:n="all",exact:s,fetchStatus:r,predicate:o,queryKey:i,stale:a}=e;if(i){if(s){if(t.queryHash!==Ni(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 Xa(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 Ni(e,t){return(t?.queryKeyHashFn||hs)(e)}function hs(e){return JSON.stringify(e,(t,n)=>Xo(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 dm=Object.prototype.hasOwnProperty;function ju(e,t,n=0){if(e===t)return e;if(n>500)return t;const s=Ya(e)&&Ya(t);if(!s&&!(Xo(e)&&Xo(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{Ko.setTimeout(t,e)})}function hm(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ju(e,t):t}function pm(e,t,n=0){const s=[...e,t];return n&&s.length>n?s.slice(1):s}function mm(e,t,n=0){const s=[t,...e];return n&&s.length>n?s.slice(0,-1):s}var $i=Symbol();function Nu(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===$i?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function SR(e,t){return typeof e=="function"?e(...t):!!e}function gm(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 $u=(()=>{let e=()=>im;return{isServer(){return e()},setIsServer(t){e=t}}})();function ym(){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 bm=om;function vm(){let e=[],t=0,n=a=>{a()},s=a=>{a()},r=bm;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 Ze=vm(),wm=class extends Nr{#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}},br=new wm;function xm(e){return Math.min(1e3*2**e,3e4)}function Fu(e){return(e??"online")==="online"?br.isOnline():!0}var Yo=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Vu(e){let t=!1,n=0,s;const r=ym(),o=()=>r.status!=="pending",i=g=>{if(!o()){const y=new Yo(g);f(y),e.onCancel?.(y)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>zu.isFocused()&&(e.networkMode==="always"||br.isOnline())&&e.canRun(),d=()=>Fu(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??($u.isServer()?0:3),S=e.retryDelay??xm,x=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 Bu=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),cm(this.gcTime)&&(this.#e=Ko.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??($u.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Ko.clearTimeout(this.#e),this.#e=void 0)}};function Sm(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=>{gm(m,()=>t.signal,()=>d=!0)},f=Nu(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 P={client:t.client,queryKey:t.queryKey,pageParam:g,direction:y?"backward":"forward",meta:t.options.meta};return l(P),P})(),S=await f(k),{maxPages:x}=t.options,T=y?mm:pm;return{pages:T(m.pages,S,x),pageParams:T(m.pageParams,g,x)}};if(r&&o.length){const m=r==="backward",g=m?km:ec,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:ec(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 ec(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 km(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Tm=class extends Bu{#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=nc(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=nc(this.options);t.data!==void 0&&(this.setState(tc(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){const n=hm(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(St).catch(St):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=>um(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$i||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Qo(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:!lm(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=Nu(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"?Sm(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=Vu({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:c=>{c instanceof Yo&&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 Yo){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,...Pm(n.data,this.options),fetchMeta:e.meta??null};case"success":const s={...n,...tc(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),Ze.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Pm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Fu(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function tc(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function nc(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 _m=class extends Bu{#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||Em(),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=Vu({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),Ze.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function Em(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Cm=class extends Nr{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 _m({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=Ns(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=Ns(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=Ns(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=Ns(e);return typeof t=="string"?this.#t.get(t)?.find(s=>s!==e&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Ze.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=>Xa(t,n))}findAll(e={}){return this.getAll().filter(t=>Xa(e,t))}notify(e){Ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Ze.batch(()=>Promise.all(e.map(t=>t.continue().catch(St))))}};function Ns(e){return e.options.scope?.id}var Am=class extends Nr{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const s=t.queryKey,r=t.queryHash??Ni(s,t);let o=this.get(r);return o||(o=new Tm({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(){Ze.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=>Qa(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Qa(e,n)):t}notify(e){Ze.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Ze.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ze.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Rm=class{#e;#t;#n;#r;#o;#s;#c;#i;constructor(e={}){this.#e=e.queryCache||new Am,this.#t=e.mutationCache||new Cm,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#c=zu.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=br.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(Qo(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=am(t,o);if(i!==void 0)return this.#e.build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return Ze.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;Ze.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Ze.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},s=Ze.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(s).then(St).catch(St)}invalidateQueries(e,t={}){return Ze.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=Ze.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(St)),r.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(s).then(St)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Qo(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(St).catch(St)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(St).catch(St)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return br.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=Ni(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===$i&&(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()}},Uu=h.createContext(void 0),kR=e=>{const t=h.useContext(Uu);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Mm=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),b.jsx(Uu.Provider,{value:e,children:t}));/** * react-router v7.14.2 * @@ -221,11 +221,11 @@ Please change the parent to k(f,S,x)};let o;const i=Mr,a=!th.jitless,u=a&&lS.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?ph([],m,f,p,l,e):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f)}});function Fl(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=>!In(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=>xn(i,s,wn())))}),t)}const B1=E("$ZodUnion",(e,t)=>{De.init(e,t),de(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),de(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=>_a(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=>Fl(c,r,e,o)):Fl(a,r,e,o)}}),U1=E("$ZodIntersection",(e,t)=>{De.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])=>Vl(n,c,u)):Vl(n,o,i)}});function Ci(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=Ci(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}),In(e))return e;const i=Ci(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 q1=E("$ZodEnum",(e,t)=>{De.init(e,t);const n=nh(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(r=>uS.has(typeof r)).map(r=>typeof r=="string"?Hr(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}}),G1=E("$ZodTransform",(e,t)=>{De.init(e,t),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new eh(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 Ln;return n.value=r,n}});function Bl(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const mh=E("$ZodOptional",(e,t)=>{De.init(e,t),e._zod.optin="optional",e._zod.optout="optional",de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),de(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${_a(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=>Bl(o,n.value)):Bl(r,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,s)}}),W1=E("$ZodExactOptional",(e,t)=>{mh.init(e,t),de(e._zod,"values",()=>t.innerType._zod.values),de(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,s)=>t.innerType._zod.run(n,s)}),H1=E("$ZodNullable",(e,t)=>{De.init(e,t),de(e._zod,"optin",()=>t.innerType._zod.optin),de(e._zod,"optout",()=>t.innerType._zod.optout),de(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${_a(n.source)}|null)$`):void 0}),de(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)}),Z1=E("$ZodDefault",(e,t)=>{De.init(e,t),e._zod.optin="optional",de(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=>Ul(o,t)):Ul(r,t)}});function Ul(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const K1=E("$ZodPrefault",(e,t)=>{De.init(e,t),e._zod.optin="optional",de(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))}),Q1=E("$ZodNonOptional",(e,t)=>{De.init(e,t),de(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=>ql(o,e)):ql(r,e)}});function ql(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 X1=E("$ZodCatch",(e,t)=>{De.init(e,t),de(e._zod,"optin",()=>t.innerType._zod.optin),de(e._zod,"optout",()=>t.innerType._zod.optout),de(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=>xn(i,s,wn()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(o=>xn(o,s,wn()))},input:n.value}),n.issues=[]),n)}}),Y1=E("$ZodPipe",(e,t)=>{De.init(e,t),de(e._zod,"values",()=>t.in._zod.values),de(e._zod,"optin",()=>t.in._zod.optin),de(e._zod,"optout",()=>t.out._zod.optout),de(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=>Hs(i,t.in,s)):Hs(o,t.in,s)}const r=t.in._zod.run(n,s);return r instanceof Promise?r.then(o=>Hs(o,t.out,s)):Hs(r,t.out,s)}});function Hs(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const J1=E("$ZodReadonly",(e,t)=>{De.init(e,t),de(e._zod,"propValues",()=>t.innerType._zod.propValues),de(e._zod,"values",()=>t.innerType._zod.values),de(e._zod,"optin",()=>t.innerType?._zod?.optin),de(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(Gl):Gl(r)}});function Gl(e){return e.value=Object.freeze(e.value),e}const ek=E("$ZodCustom",(e,t)=>{Nt.init(e,t),De.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=>Wl(o,n,s,e));Wl(r,n,s,e)}});function Wl(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 Hl;class tk{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 nk(){return new tk}(Hl=globalThis).__zod_globalRegistry??(Hl.__zod_globalRegistry=nk());const as=globalThis.__zod_globalRegistry;function sk(e,t){return new e({type:"string",...Q(t)})}function rk(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Q(t)})}function Zl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Q(t)})}function ok(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Q(t)})}function ik(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Q(t)})}function ak(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Q(t)})}function ck(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Q(t)})}function lk(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Q(t)})}function uk(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Q(t)})}function dk(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Q(t)})}function fk(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Q(t)})}function hk(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Q(t)})}function pk(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Q(t)})}function mk(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Q(t)})}function gk(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Q(t)})}function yk(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Q(t)})}function bk(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Q(t)})}function vk(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Q(t)})}function wk(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Q(t)})}function xk(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Q(t)})}function Sk(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Q(t)})}function kk(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Q(t)})}function Tk(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Q(t)})}function Pk(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Q(t)})}function _k(e,t){return new e({type:"string",format:"date",check:"string_format",...Q(t)})}function Ek(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Q(t)})}function Ck(e,t){return new e({type:"string",format:"duration",check:"string_format",...Q(t)})}function Ak(e){return new e({type:"unknown"})}function Rk(e,t){return new e({type:"never",...Q(t)})}function gh(e,t){return new e1({check:"max_length",...Q(t),maximum:e})}function Dr(e,t){return new t1({check:"min_length",...Q(t),minimum:e})}function yh(e,t){return new n1({check:"length_equals",...Q(t),length:e})}function Mk(e,t){return new s1({check:"string_format",format:"regex",...Q(t),pattern:e})}function Ik(e){return new r1({check:"string_format",format:"lowercase",...Q(e)})}function Dk(e){return new o1({check:"string_format",format:"uppercase",...Q(e)})}function Ok(e,t){return new i1({check:"string_format",format:"includes",...Q(t),includes:e})}function Lk(e,t){return new a1({check:"string_format",format:"starts_with",...Q(t),prefix:e})}function zk(e,t){return new c1({check:"string_format",format:"ends_with",...Q(t),suffix:e})}function qn(e){return new l1({check:"overwrite",tx:e})}function jk(e){return qn(t=>t.normalize(e))}function Nk(){return qn(e=>e.trim())}function $k(){return qn(e=>e.toLowerCase())}function Fk(){return qn(e=>e.toUpperCase())}function Vk(){return qn(e=>cS(e))}function Bk(e,t,n){return new e({type:"array",element:t,...Q(n)})}function Uk(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Q(n)})}function qk(e){const t=Gk(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 Gk(e,t){const n=new Nt({check:"custom",...Q(t)});return n._zod.check=e,n}function bh(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 qe(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),qe(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"&&He(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 vh(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 wh(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:Or(t,"input",e.processors),output:Or(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function He(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 He(s.element,n);if(s.type==="set")return He(s.valueType,n);if(s.type==="lazy")return He(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 He(s.innerType,n);if(s.type==="intersection")return He(s.left,n)||He(s.right,n);if(s.type==="record"||s.type==="map")return He(s.keyType,n)||He(s.valueType,n);if(s.type==="pipe")return He(s.in,n)||He(s.out,n);if(s.type==="object"){for(const r in s.shape)if(He(s.shape[r],n))return!0;return!1}if(s.type==="union"){for(const r of s.options)if(He(r,n))return!0;return!1}if(s.type==="tuple"){for(const r of s.items)if(He(r,n))return!0;return!!(s.rest&&He(s.rest,n))}return!1}const Wk=(e,t={})=>n=>{const s=bh({...n,processors:t});return qe(e,s),vh(s,e),wh(s,e)},Or=(e,t,n={})=>s=>{const{libraryOptions:r,target:o}=s??{},i=bh({...r??{},target:o,io:t,processors:n});return qe(e,i),vh(i,e),wh(i,e)},Hk={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Zk=(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=Hk[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}))])}},Kk=(e,t,n,s)=>{n.not={}},Qk=(e,t,n,s)=>{},Xk=(e,t,n,s)=>{const r=e._zod.def,o=nh(r.entries);o.every(i=>typeof i=="number")&&(n.type="number"),o.every(i=>typeof i=="string")&&(n.type="string"),n.enum=o},Yk=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Jk=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},eT=(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=qe(o.element,t,{...s,path:[...s.path,"items"]})},tT=(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]=qe(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=qe(o.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},nT=(e,t,n,s)=>{const r=e._zod.def,o=r.inclusive===!1,i=r.options.map((a,c)=>qe(a,t,{...s,path:[...s.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=i:n.anyOf=i},sT=(e,t,n,s)=>{const r=e._zod.def,o=qe(r.left,t,{...s,path:[...s.path,"allOf",0]}),i=qe(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},rT=(e,t,n,s)=>{const r=e._zod.def,o=qe(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"}]},oT=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},iT=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},aT=(e,t,n,s)=>{const r=e._zod.def;qe(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)))},cT=(e,t,n,s)=>{const r=e._zod.def;qe(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},lT=(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;qe(o,t,s);const i=t.seen.get(e);i.ref=o},uT=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},xh=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},dT=E("ZodISODateTime",(e,t)=>{k1.init(e,t),ke.init(e,t)});function fT(e){return Pk(dT,e)}const hT=E("ZodISODate",(e,t)=>{T1.init(e,t),ke.init(e,t)});function pT(e){return _k(hT,e)}const mT=E("ZodISOTime",(e,t)=>{P1.init(e,t),ke.init(e,t)});function gT(e){return Ek(mT,e)}const yT=E("ZodISODuration",(e,t)=>{_1.init(e,t),ke.init(e,t)});function bT(e){return Ck(yT,e)}const vT=(e,t)=>{ah.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>wS(e,n)},flatten:{value:n=>vS(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ei,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ei,2)}},isEmpty:{get(){return e.issues.length===0}}})},ht=E("ZodError",vT,{Parent:Error}),wT=Ca(ht),xT=Aa(ht),ST=Zr(ht),kT=Kr(ht),TT=kS(ht),PT=TS(ht),_T=PS(ht),ET=_S(ht),CT=ES(ht),AT=CS(ht),RT=AS(ht),MT=RS(ht),Oe=E("ZodType",(e,t)=>(De.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Or(e,"input"),output:Or(e,"output")}}),e.toJSONSchema=Wk(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(nn(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)=>sn(e,n,s),e.brand=()=>e,e.register=((n,s)=>(n.add(e,s),e)),e.parse=(n,s)=>wT(e,n,s,{callee:e.parse}),e.safeParse=(n,s)=>ST(e,n,s),e.parseAsync=async(n,s)=>xT(e,n,s,{callee:e.parseAsync}),e.safeParseAsync=async(n,s)=>kT(e,n,s),e.spa=e.safeParseAsync,e.encode=(n,s)=>TT(e,n,s),e.decode=(n,s)=>PT(e,n,s),e.encodeAsync=async(n,s)=>_T(e,n,s),e.decodeAsync=async(n,s)=>ET(e,n,s),e.safeEncode=(n,s)=>CT(e,n,s),e.safeDecode=(n,s)=>AT(e,n,s),e.safeEncodeAsync=async(n,s)=>RT(e,n,s),e.safeDecodeAsync=async(n,s)=>MT(e,n,s),e.refine=(n,s)=>e.check(TP(n,s)),e.superRefine=n=>e.check(PP(n)),e.overwrite=n=>e.check(qn(n)),e.optional=()=>Xl(e),e.exactOptional=()=>dP(e),e.nullable=()=>Yl(e),e.nullish=()=>Xl(Yl(e)),e.nonoptional=n=>yP(e,n),e.array=()=>eP(e),e.or=n=>rP([e,n]),e.and=n=>iP(e,n),e.transform=n=>Jl(e,lP(n)),e.default=n=>pP(e,n),e.prefault=n=>gP(e,n),e.catch=n=>vP(e,n),e.pipe=n=>Jl(e,n),e.readonly=()=>SP(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)),Sh=E("_ZodString",(e,t)=>{Ra.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(s,r,o)=>Zk(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(Mk(...s)),e.includes=(...s)=>e.check(Ok(...s)),e.startsWith=(...s)=>e.check(Lk(...s)),e.endsWith=(...s)=>e.check(zk(...s)),e.min=(...s)=>e.check(Dr(...s)),e.max=(...s)=>e.check(gh(...s)),e.length=(...s)=>e.check(yh(...s)),e.nonempty=(...s)=>e.check(Dr(1,...s)),e.lowercase=s=>e.check(Ik(s)),e.uppercase=s=>e.check(Dk(s)),e.trim=()=>e.check(Nk()),e.normalize=(...s)=>e.check(jk(...s)),e.toLowerCase=()=>e.check($k()),e.toUpperCase=()=>e.check(Fk()),e.slugify=()=>e.check(Vk())}),IT=E("ZodString",(e,t)=>{Ra.init(e,t),Sh.init(e,t),e.email=n=>e.check(rk(DT,n)),e.url=n=>e.check(lk(OT,n)),e.jwt=n=>e.check(Tk(KT,n)),e.emoji=n=>e.check(uk(LT,n)),e.guid=n=>e.check(Zl(Kl,n)),e.uuid=n=>e.check(ok(Zs,n)),e.uuidv4=n=>e.check(ik(Zs,n)),e.uuidv6=n=>e.check(ak(Zs,n)),e.uuidv7=n=>e.check(ck(Zs,n)),e.nanoid=n=>e.check(dk(zT,n)),e.guid=n=>e.check(Zl(Kl,n)),e.cuid=n=>e.check(fk(jT,n)),e.cuid2=n=>e.check(hk(NT,n)),e.ulid=n=>e.check(pk($T,n)),e.base64=n=>e.check(xk(WT,n)),e.base64url=n=>e.check(Sk(HT,n)),e.xid=n=>e.check(mk(FT,n)),e.ksuid=n=>e.check(gk(VT,n)),e.ipv4=n=>e.check(yk(BT,n)),e.ipv6=n=>e.check(bk(UT,n)),e.cidrv4=n=>e.check(vk(qT,n)),e.cidrv6=n=>e.check(wk(GT,n)),e.e164=n=>e.check(kk(ZT,n)),e.datetime=n=>e.check(fT(n)),e.date=n=>e.check(pT(n)),e.time=n=>e.check(gT(n)),e.duration=n=>e.check(bT(n))});function kh(e){return sk(IT,e)}const ke=E("ZodStringFormat",(e,t)=>{xe.init(e,t),Sh.init(e,t)}),DT=E("ZodEmail",(e,t)=>{p1.init(e,t),ke.init(e,t)}),Kl=E("ZodGUID",(e,t)=>{f1.init(e,t),ke.init(e,t)}),Zs=E("ZodUUID",(e,t)=>{h1.init(e,t),ke.init(e,t)}),OT=E("ZodURL",(e,t)=>{m1.init(e,t),ke.init(e,t)}),LT=E("ZodEmoji",(e,t)=>{g1.init(e,t),ke.init(e,t)}),zT=E("ZodNanoID",(e,t)=>{y1.init(e,t),ke.init(e,t)}),jT=E("ZodCUID",(e,t)=>{b1.init(e,t),ke.init(e,t)}),NT=E("ZodCUID2",(e,t)=>{v1.init(e,t),ke.init(e,t)}),$T=E("ZodULID",(e,t)=>{w1.init(e,t),ke.init(e,t)}),FT=E("ZodXID",(e,t)=>{x1.init(e,t),ke.init(e,t)}),VT=E("ZodKSUID",(e,t)=>{S1.init(e,t),ke.init(e,t)}),BT=E("ZodIPv4",(e,t)=>{E1.init(e,t),ke.init(e,t)}),UT=E("ZodIPv6",(e,t)=>{C1.init(e,t),ke.init(e,t)}),qT=E("ZodCIDRv4",(e,t)=>{A1.init(e,t),ke.init(e,t)}),GT=E("ZodCIDRv6",(e,t)=>{R1.init(e,t),ke.init(e,t)}),WT=E("ZodBase64",(e,t)=>{M1.init(e,t),ke.init(e,t)}),HT=E("ZodBase64URL",(e,t)=>{D1.init(e,t),ke.init(e,t)}),ZT=E("ZodE164",(e,t)=>{O1.init(e,t),ke.init(e,t)}),KT=E("ZodJWT",(e,t)=>{z1.init(e,t),ke.init(e,t)}),QT=E("ZodUnknown",(e,t)=>{j1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Qk()});function Ql(){return Ak(QT)}const XT=E("ZodNever",(e,t)=>{N1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Kk(e,n,s)});function YT(e){return Rk(XT,e)}const JT=E("ZodArray",(e,t)=>{$1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>eT(e,n,s,r),e.element=t.element,e.min=(n,s)=>e.check(Dr(n,s)),e.nonempty=n=>e.check(Dr(1,n)),e.max=(n,s)=>e.check(gh(n,s)),e.length=(n,s)=>e.check(yh(n,s)),e.unwrap=()=>e.element});function eP(e,t){return Bk(JT,e,t)}const tP=E("ZodObject",(e,t)=>{V1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>tT(e,n,s,r),de(e,"shape",()=>t.shape),e.keyof=()=>aP(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ql()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ql()}),e.strict=()=>e.clone({...e._zod.def,catchall:YT()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>pS(e,n),e.safeExtend=n=>mS(e,n),e.merge=n=>gS(e,n),e.pick=n=>fS(e,n),e.omit=n=>hS(e,n),e.partial=(...n)=>yS(Th,e,n[0]),e.required=(...n)=>bS(Ph,e,n[0])});function nP(e,t){const n={type:"object",shape:e??{},...Q(t)};return new tP(n)}const sP=E("ZodUnion",(e,t)=>{B1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>nT(e,n,s,r),e.options=t.options});function rP(e,t){return new sP({type:"union",options:e,...Q(t)})}const oP=E("ZodIntersection",(e,t)=>{U1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>sT(e,n,s,r)});function iP(e,t){return new oP({type:"intersection",left:e,right:t})}const Ai=E("ZodEnum",(e,t)=>{q1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(s,r,o)=>Xk(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 Ai({...t,checks:[],...Q(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 Ai({...t,checks:[],...Q(r),entries:o})}});function aP(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Ai({type:"enum",entries:n,...Q(t)})}const cP=E("ZodTransform",(e,t)=>{G1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Jk(e,n),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new eh(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 lP(e){return new cP({type:"transform",transform:e})}const Th=E("ZodOptional",(e,t)=>{mh.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>xh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Xl(e){return new Th({type:"optional",innerType:e})}const uP=E("ZodExactOptional",(e,t)=>{W1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>xh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function dP(e){return new uP({type:"optional",innerType:e})}const fP=E("ZodNullable",(e,t)=>{H1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>rT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Yl(e){return new fP({type:"nullable",innerType:e})}const hP=E("ZodDefault",(e,t)=>{Z1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>iT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function pP(e,t){return new hP({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():rh(t)}})}const mP=E("ZodPrefault",(e,t)=>{K1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>aT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function gP(e,t){return new mP({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():rh(t)}})}const Ph=E("ZodNonOptional",(e,t)=>{Q1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>oT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function yP(e,t){return new Ph({type:"nonoptional",innerType:e,...Q(t)})}const bP=E("ZodCatch",(e,t)=>{X1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>cT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function vP(e,t){return new bP({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const wP=E("ZodPipe",(e,t)=>{Y1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>lT(e,n,s,r),e.in=t.in,e.out=t.out});function Jl(e,t){return new wP({type:"pipe",in:e,out:t})}const xP=E("ZodReadonly",(e,t)=>{J1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>uT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function SP(e){return new xP({type:"readonly",innerType:e})}const kP=E("ZodCustom",(e,t)=>{ek.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Yk(e,n)});function TP(e,t={}){return Uk(kP,e,t)}function PP(e){return qk(e)}const _P=/[<>]/;function EP(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 CP=/^\+?[0-9 ()\-.]{7,20}$/,AP=kh().trim().min(1,"Full name is required").max(100,"Full name must be 100 characters or fewer").refine(e=>!_P.test(e),{message:"Full name cannot contain < or > characters"}),RP=kh().trim().max(20,"Phone number must be 20 characters or fewer").refine(e=>e.length===0||CP.test(e),{message:"Phone number must contain only digits and + ( ) - . spaces"}),MP=nP({name:AP,phone:RP.optional()});function _R(e){const t=MP.safeParse({name:e.name??"",phone:e.phone??""});return t.success?null:t.error.issues[0]?.message??"Invalid profile data"}new $p;const Ri="mathpulse.pendingAuthRole",_h="mathpulse.lastAuthRole",IP=e=>{if(e==="admin")throw new Error("Admin account creation is restricted. Please contact an existing administrator.")},Ma=(e,t)=>{const n=e,s=new Error(n.message||t);return n.code&&(s.code=n.code),s},ER=e=>{try{localStorage.setItem(Ri,e),localStorage.setItem(_h,e)}catch{}},DP=()=>{try{const e=localStorage.getItem(Ri);return localStorage.removeItem(Ri),e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},OP=()=>{try{const e=localStorage.getItem(_h);return e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},CR=async(e,t,n,s,r={})=>{try{IP(s);const i=(await Fp(ye,e,t)).user;return await Vp(i,{displayName:n}),await Eh(i,s,r)}catch(o){const i=o;throw console.error("[ERROR] Error signing up:",{code:i.code,message:i.message,fullError:o}),Ma(o,"Failed to create account")}},AR=async(e,t)=>{try{await Bp(ye,e,t)}catch(n){const s=n;throw console.error("[ERROR] Error signing in:",{code:s.code,message:s.message,fullError:n}),Ma(n,"Failed to sign in")}},eu=async()=>{try{await Up(ye)}catch(e){throw console.error("Error signing out:",e),Ma(e,"Failed to sign out")}},Eh=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:ce(),updatedAt:ce()},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 $e(q(N,"users",e.uid),i),i},Ia=async e=>{try{const t=q(N,"users",e),n=await ve(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.error("Error getting user profile:",t),null}},LP=async e=>{try{const t=q(N,"users",e),n=await Zo(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.warn("[getUserProfileFromServer] Server read failed, falling back to cache:",t),Ia(e)}},zP=async(e,t)=>{try{const n=await Ia(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=q(N,"users",e);await $e(a,{...i,updatedAt:ce()},{merge:!0})}catch(n){throw console.error("Error updating user profile:",n),n}},Ch=h.createContext({currentUser:null,userProfile:null,loading:!0,isLoggedIn:!1,userRole:"student",refreshProfile:async()=>{}}),Ms=()=>{const e=h.useContext(Ch);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e},jP=({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=DP()||OP()||u(p.email)||"student",g=m==="admin"?"student":m;let y=await Ia(p.uid);if(!y&&p.email){const v=g,k=p.displayName||"User";try{y=await Eh(p,v,{name:k}),v==="student"&&oe(async()=>{const{triggerStudentEnrolled:S}=await import("./automationService-Cn_PZsKR.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)}}y?(c(y.role),r(y)):(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 LP(t.uid);f&&r(f)}},l={currentUser:t,userProfile:s,loading:o,isLoggedIn:!!t,userRole:s?.role||a,refreshProfile:d};return b.jsx(Ch.Provider,{value:l,children:e})},NP=({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=q(N,"users",t.uid);return Yt(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 oe(async()=>{const{getDoc:v}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{getDoc:v}},__vite__mapDeps([1,2])),y=await g(q(N,"users",m));if(y.exists()){const v=y.data();a(EP(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(Ix,{className:"animate-spin text-slate-400",size:32})}):b.jsx(Nf,{mode:"wait",children:n?b.jsx(On.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(Ox,{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(Ti,{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(On.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e},"content")})},$P=/(```[\s\S]*?```|`[^`\n]+`)/g,FP=/(\$\$[\s\S]*?\$\$|\$[^$\n]+\$|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]|\[(?![^[]*\]\()[^\]]+\]|(?]*>[\s\S]*?<\s*\/\s*think\s*>/gi,UP=/<\s*\/?\s*think\b[^>]*>/gi,qP=/<\s*\/\s*think\s*>/gi,GP=/<\s*(\/?)\s*think\b([\s\S]*?)>/gi,WP=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,HP=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,ZP=/\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,KP=/^\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 Ah(e){return e.replace(GP,(t,n,s)=>`<${n?"/":""}think${s}>`)}function QP(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 XP(e){const t=Ah(e);if(/<\s*think\b/i.test(t))return"";const n=QP(t,qP);return n===-1?"":t.slice(n).trim()}function YP(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 wh(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:Or(t,"input",e.processors),output:Or(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function He(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 He(s.element,n);if(s.type==="set")return He(s.valueType,n);if(s.type==="lazy")return He(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 He(s.innerType,n);if(s.type==="intersection")return He(s.left,n)||He(s.right,n);if(s.type==="record"||s.type==="map")return He(s.keyType,n)||He(s.valueType,n);if(s.type==="pipe")return He(s.in,n)||He(s.out,n);if(s.type==="object"){for(const r in s.shape)if(He(s.shape[r],n))return!0;return!1}if(s.type==="union"){for(const r of s.options)if(He(r,n))return!0;return!1}if(s.type==="tuple"){for(const r of s.items)if(He(r,n))return!0;return!!(s.rest&&He(s.rest,n))}return!1}const Wk=(e,t={})=>n=>{const s=bh({...n,processors:t});return qe(e,s),vh(s,e),wh(s,e)},Or=(e,t,n={})=>s=>{const{libraryOptions:r,target:o}=s??{},i=bh({...r??{},target:o,io:t,processors:n});return qe(e,i),vh(i,e),wh(i,e)},Hk={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Zk=(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=Hk[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}))])}},Kk=(e,t,n,s)=>{n.not={}},Qk=(e,t,n,s)=>{},Xk=(e,t,n,s)=>{const r=e._zod.def,o=nh(r.entries);o.every(i=>typeof i=="number")&&(n.type="number"),o.every(i=>typeof i=="string")&&(n.type="string"),n.enum=o},Yk=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Jk=(e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},eT=(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=qe(o.element,t,{...s,path:[...s.path,"items"]})},tT=(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]=qe(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=qe(o.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},nT=(e,t,n,s)=>{const r=e._zod.def,o=r.inclusive===!1,i=r.options.map((a,c)=>qe(a,t,{...s,path:[...s.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=i:n.anyOf=i},sT=(e,t,n,s)=>{const r=e._zod.def,o=qe(r.left,t,{...s,path:[...s.path,"allOf",0]}),i=qe(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},rT=(e,t,n,s)=>{const r=e._zod.def,o=qe(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"}]},oT=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},iT=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},aT=(e,t,n,s)=>{const r=e._zod.def;qe(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)))},cT=(e,t,n,s)=>{const r=e._zod.def;qe(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},lT=(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;qe(o,t,s);const i=t.seen.get(e);i.ref=o},uT=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},xh=(e,t,n,s)=>{const r=e._zod.def;qe(r.innerType,t,s);const o=t.seen.get(e);o.ref=r.innerType},dT=E("ZodISODateTime",(e,t)=>{k1.init(e,t),ke.init(e,t)});function fT(e){return Pk(dT,e)}const hT=E("ZodISODate",(e,t)=>{T1.init(e,t),ke.init(e,t)});function pT(e){return _k(hT,e)}const mT=E("ZodISOTime",(e,t)=>{P1.init(e,t),ke.init(e,t)});function gT(e){return Ek(mT,e)}const yT=E("ZodISODuration",(e,t)=>{_1.init(e,t),ke.init(e,t)});function bT(e){return Ck(yT,e)}const vT=(e,t)=>{ah.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>wS(e,n)},flatten:{value:n=>vS(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ei,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ei,2)}},isEmpty:{get(){return e.issues.length===0}}})},ht=E("ZodError",vT,{Parent:Error}),wT=Ca(ht),xT=Aa(ht),ST=Zr(ht),kT=Kr(ht),TT=kS(ht),PT=TS(ht),_T=PS(ht),ET=_S(ht),CT=ES(ht),AT=CS(ht),RT=AS(ht),MT=RS(ht),Oe=E("ZodType",(e,t)=>(De.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Or(e,"input"),output:Or(e,"output")}}),e.toJSONSchema=Wk(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(nn(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)=>sn(e,n,s),e.brand=()=>e,e.register=((n,s)=>(n.add(e,s),e)),e.parse=(n,s)=>wT(e,n,s,{callee:e.parse}),e.safeParse=(n,s)=>ST(e,n,s),e.parseAsync=async(n,s)=>xT(e,n,s,{callee:e.parseAsync}),e.safeParseAsync=async(n,s)=>kT(e,n,s),e.spa=e.safeParseAsync,e.encode=(n,s)=>TT(e,n,s),e.decode=(n,s)=>PT(e,n,s),e.encodeAsync=async(n,s)=>_T(e,n,s),e.decodeAsync=async(n,s)=>ET(e,n,s),e.safeEncode=(n,s)=>CT(e,n,s),e.safeDecode=(n,s)=>AT(e,n,s),e.safeEncodeAsync=async(n,s)=>RT(e,n,s),e.safeDecodeAsync=async(n,s)=>MT(e,n,s),e.refine=(n,s)=>e.check(TP(n,s)),e.superRefine=n=>e.check(PP(n)),e.overwrite=n=>e.check(qn(n)),e.optional=()=>Xl(e),e.exactOptional=()=>dP(e),e.nullable=()=>Yl(e),e.nullish=()=>Xl(Yl(e)),e.nonoptional=n=>yP(e,n),e.array=()=>eP(e),e.or=n=>rP([e,n]),e.and=n=>iP(e,n),e.transform=n=>Jl(e,lP(n)),e.default=n=>pP(e,n),e.prefault=n=>gP(e,n),e.catch=n=>vP(e,n),e.pipe=n=>Jl(e,n),e.readonly=()=>SP(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)),Sh=E("_ZodString",(e,t)=>{Ra.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(s,r,o)=>Zk(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(Mk(...s)),e.includes=(...s)=>e.check(Ok(...s)),e.startsWith=(...s)=>e.check(Lk(...s)),e.endsWith=(...s)=>e.check(zk(...s)),e.min=(...s)=>e.check(Dr(...s)),e.max=(...s)=>e.check(gh(...s)),e.length=(...s)=>e.check(yh(...s)),e.nonempty=(...s)=>e.check(Dr(1,...s)),e.lowercase=s=>e.check(Ik(s)),e.uppercase=s=>e.check(Dk(s)),e.trim=()=>e.check(Nk()),e.normalize=(...s)=>e.check(jk(...s)),e.toLowerCase=()=>e.check($k()),e.toUpperCase=()=>e.check(Fk()),e.slugify=()=>e.check(Vk())}),IT=E("ZodString",(e,t)=>{Ra.init(e,t),Sh.init(e,t),e.email=n=>e.check(rk(DT,n)),e.url=n=>e.check(lk(OT,n)),e.jwt=n=>e.check(Tk(KT,n)),e.emoji=n=>e.check(uk(LT,n)),e.guid=n=>e.check(Zl(Kl,n)),e.uuid=n=>e.check(ok(Zs,n)),e.uuidv4=n=>e.check(ik(Zs,n)),e.uuidv6=n=>e.check(ak(Zs,n)),e.uuidv7=n=>e.check(ck(Zs,n)),e.nanoid=n=>e.check(dk(zT,n)),e.guid=n=>e.check(Zl(Kl,n)),e.cuid=n=>e.check(fk(jT,n)),e.cuid2=n=>e.check(hk(NT,n)),e.ulid=n=>e.check(pk($T,n)),e.base64=n=>e.check(xk(WT,n)),e.base64url=n=>e.check(Sk(HT,n)),e.xid=n=>e.check(mk(FT,n)),e.ksuid=n=>e.check(gk(VT,n)),e.ipv4=n=>e.check(yk(BT,n)),e.ipv6=n=>e.check(bk(UT,n)),e.cidrv4=n=>e.check(vk(qT,n)),e.cidrv6=n=>e.check(wk(GT,n)),e.e164=n=>e.check(kk(ZT,n)),e.datetime=n=>e.check(fT(n)),e.date=n=>e.check(pT(n)),e.time=n=>e.check(gT(n)),e.duration=n=>e.check(bT(n))});function kh(e){return sk(IT,e)}const ke=E("ZodStringFormat",(e,t)=>{xe.init(e,t),Sh.init(e,t)}),DT=E("ZodEmail",(e,t)=>{p1.init(e,t),ke.init(e,t)}),Kl=E("ZodGUID",(e,t)=>{f1.init(e,t),ke.init(e,t)}),Zs=E("ZodUUID",(e,t)=>{h1.init(e,t),ke.init(e,t)}),OT=E("ZodURL",(e,t)=>{m1.init(e,t),ke.init(e,t)}),LT=E("ZodEmoji",(e,t)=>{g1.init(e,t),ke.init(e,t)}),zT=E("ZodNanoID",(e,t)=>{y1.init(e,t),ke.init(e,t)}),jT=E("ZodCUID",(e,t)=>{b1.init(e,t),ke.init(e,t)}),NT=E("ZodCUID2",(e,t)=>{v1.init(e,t),ke.init(e,t)}),$T=E("ZodULID",(e,t)=>{w1.init(e,t),ke.init(e,t)}),FT=E("ZodXID",(e,t)=>{x1.init(e,t),ke.init(e,t)}),VT=E("ZodKSUID",(e,t)=>{S1.init(e,t),ke.init(e,t)}),BT=E("ZodIPv4",(e,t)=>{E1.init(e,t),ke.init(e,t)}),UT=E("ZodIPv6",(e,t)=>{C1.init(e,t),ke.init(e,t)}),qT=E("ZodCIDRv4",(e,t)=>{A1.init(e,t),ke.init(e,t)}),GT=E("ZodCIDRv6",(e,t)=>{R1.init(e,t),ke.init(e,t)}),WT=E("ZodBase64",(e,t)=>{M1.init(e,t),ke.init(e,t)}),HT=E("ZodBase64URL",(e,t)=>{D1.init(e,t),ke.init(e,t)}),ZT=E("ZodE164",(e,t)=>{O1.init(e,t),ke.init(e,t)}),KT=E("ZodJWT",(e,t)=>{z1.init(e,t),ke.init(e,t)}),QT=E("ZodUnknown",(e,t)=>{j1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Qk()});function Ql(){return Ak(QT)}const XT=E("ZodNever",(e,t)=>{N1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Kk(e,n,s)});function YT(e){return Rk(XT,e)}const JT=E("ZodArray",(e,t)=>{$1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>eT(e,n,s,r),e.element=t.element,e.min=(n,s)=>e.check(Dr(n,s)),e.nonempty=n=>e.check(Dr(1,n)),e.max=(n,s)=>e.check(gh(n,s)),e.length=(n,s)=>e.check(yh(n,s)),e.unwrap=()=>e.element});function eP(e,t){return Bk(JT,e,t)}const tP=E("ZodObject",(e,t)=>{V1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>tT(e,n,s,r),de(e,"shape",()=>t.shape),e.keyof=()=>aP(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ql()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ql()}),e.strict=()=>e.clone({...e._zod.def,catchall:YT()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>pS(e,n),e.safeExtend=n=>mS(e,n),e.merge=n=>gS(e,n),e.pick=n=>fS(e,n),e.omit=n=>hS(e,n),e.partial=(...n)=>yS(Th,e,n[0]),e.required=(...n)=>bS(Ph,e,n[0])});function nP(e,t){const n={type:"object",shape:e??{},...Q(t)};return new tP(n)}const sP=E("ZodUnion",(e,t)=>{B1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>nT(e,n,s,r),e.options=t.options});function rP(e,t){return new sP({type:"union",options:e,...Q(t)})}const oP=E("ZodIntersection",(e,t)=>{U1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>sT(e,n,s,r)});function iP(e,t){return new oP({type:"intersection",left:e,right:t})}const Ai=E("ZodEnum",(e,t)=>{q1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(s,r,o)=>Xk(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 Ai({...t,checks:[],...Q(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 Ai({...t,checks:[],...Q(r),entries:o})}});function aP(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Ai({type:"enum",entries:n,...Q(t)})}const cP=E("ZodTransform",(e,t)=>{G1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Jk(e,n),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new eh(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 lP(e){return new cP({type:"transform",transform:e})}const Th=E("ZodOptional",(e,t)=>{mh.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>xh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Xl(e){return new Th({type:"optional",innerType:e})}const uP=E("ZodExactOptional",(e,t)=>{W1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>xh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function dP(e){return new uP({type:"optional",innerType:e})}const fP=E("ZodNullable",(e,t)=>{H1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>rT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Yl(e){return new fP({type:"nullable",innerType:e})}const hP=E("ZodDefault",(e,t)=>{Z1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>iT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function pP(e,t){return new hP({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():rh(t)}})}const mP=E("ZodPrefault",(e,t)=>{K1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>aT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function gP(e,t){return new mP({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():rh(t)}})}const Ph=E("ZodNonOptional",(e,t)=>{Q1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>oT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function yP(e,t){return new Ph({type:"nonoptional",innerType:e,...Q(t)})}const bP=E("ZodCatch",(e,t)=>{X1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>cT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function vP(e,t){return new bP({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const wP=E("ZodPipe",(e,t)=>{Y1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>lT(e,n,s,r),e.in=t.in,e.out=t.out});function Jl(e,t){return new wP({type:"pipe",in:e,out:t})}const xP=E("ZodReadonly",(e,t)=>{J1.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>uT(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function SP(e){return new xP({type:"readonly",innerType:e})}const kP=E("ZodCustom",(e,t)=>{ek.init(e,t),Oe.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Yk(e,n)});function TP(e,t={}){return Uk(kP,e,t)}function PP(e){return qk(e)}const _P=/[<>]/;function EP(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 CP=/^\+?[0-9 ()\-.]{7,20}$/,AP=kh().trim().min(1,"Full name is required").max(100,"Full name must be 100 characters or fewer").refine(e=>!_P.test(e),{message:"Full name cannot contain < or > characters"}),RP=kh().trim().max(20,"Phone number must be 20 characters or fewer").refine(e=>e.length===0||CP.test(e),{message:"Phone number must contain only digits and + ( ) - . spaces"}),MP=nP({name:AP,phone:RP.optional()});function _R(e){const t=MP.safeParse({name:e.name??"",phone:e.phone??""});return t.success?null:t.error.issues[0]?.message??"Invalid profile data"}new $p;const Ri="mathpulse.pendingAuthRole",_h="mathpulse.lastAuthRole",IP=e=>{if(e==="admin")throw new Error("Admin account creation is restricted. Please contact an existing administrator.")},Ma=(e,t)=>{const n=e,s=new Error(n.message||t);return n.code&&(s.code=n.code),s},ER=e=>{try{localStorage.setItem(Ri,e),localStorage.setItem(_h,e)}catch{}},DP=()=>{try{const e=localStorage.getItem(Ri);return localStorage.removeItem(Ri),e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},OP=()=>{try{const e=localStorage.getItem(_h);return e==="student"||e==="teacher"||e==="admin"?e:null}catch{return null}},CR=async(e,t,n,s,r={})=>{try{IP(s);const i=(await Fp(ye,e,t)).user;return await Vp(i,{displayName:n}),await Eh(i,s,r)}catch(o){const i=o;throw console.error("[ERROR] Error signing up:",{code:i.code,message:i.message,fullError:o}),Ma(o,"Failed to create account")}},AR=async(e,t)=>{try{await Bp(ye,e,t)}catch(n){const s=n;throw console.error("[ERROR] Error signing in:",{code:s.code,message:s.message,fullError:n}),Ma(n,"Failed to sign in")}},eu=async()=>{try{await Up(ye)}catch(e){throw console.error("Error signing out:",e),Ma(e,"Failed to sign out")}},Eh=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:ce(),updatedAt:ce()},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 $e(q(N,"users",e.uid),i),i},Ia=async e=>{try{const t=q(N,"users",e),n=await ve(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.error("Error getting user profile:",t),null}},LP=async e=>{try{const t=q(N,"users",e),n=await Zo(t);return n.exists()?{...n.data(),uid:n.id}:null}catch(t){return console.warn("[getUserProfileFromServer] Server read failed, falling back to cache:",t),Ia(e)}},zP=async(e,t)=>{try{const n=await Ia(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=q(N,"users",e);await $e(a,{...i,updatedAt:ce()},{merge:!0})}catch(n){throw console.error("Error updating user profile:",n),n}},Ch=h.createContext({currentUser:null,userProfile:null,loading:!0,isLoggedIn:!1,userRole:"student",refreshProfile:async()=>{}}),Ms=()=>{const e=h.useContext(Ch);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e},jP=({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=DP()||OP()||u(p.email)||"student",g=m==="admin"?"student":m;let y=await Ia(p.uid);if(!y&&p.email){const v=g,k=p.displayName||"User";try{y=await Eh(p,v,{name:k}),v==="student"&&oe(async()=>{const{triggerStudentEnrolled:S}=await import("./automationService-BUinEhr-.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)}}y?(c(y.role),r(y)):(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 LP(t.uid);f&&r(f)}},l={currentUser:t,userProfile:s,loading:o,isLoggedIn:!!t,userRole:s?.role||a,refreshProfile:d};return b.jsx(Ch.Provider,{value:l,children:e})},NP=({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=q(N,"users",t.uid);return Yt(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 oe(async()=>{const{getDoc:v}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{getDoc:v}},__vite__mapDeps([1,2])),y=await g(q(N,"users",m));if(y.exists()){const v=y.data();a(EP(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(Ix,{className:"animate-spin text-slate-400",size:32})}):b.jsx(Nf,{mode:"wait",children:n?b.jsx(On.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(Ox,{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(Ti,{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(On.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e},"content")})},$P=/(```[\s\S]*?```|`[^`\n]+`)/g,FP=/(\$\$[\s\S]*?\$\$|\$[^$\n]+\$|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]|\[(?![^[]*\]\()[^\]]+\]|(?]*>[\s\S]*?<\s*\/\s*think\s*>/gi,UP=/<\s*\/?\s*think\b[^>]*>/gi,qP=/<\s*\/\s*think\s*>/gi,GP=/<\s*(\/?)\s*think\b([\s\S]*?)>/gi,WP=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,HP=/(?:<\s*\/?\s*t(?:h(?:i(?:n(?:k)?)?)?)?)\s*$/i,ZP=/\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,KP=/^\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 Ah(e){return e.replace(GP,(t,n,s)=>`<${n?"/":""}think${s}>`)}function QP(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 XP(e){const t=Ah(e);if(/<\s*think\b/i.test(t))return"";const n=QP(t,qP);return n===-1?"":t.slice(n).trim()}function YP(e){const t=e.replace(/\r\n?/g,` `).trim();if(!t)return"";const n=ZP.exec(t);return n&&typeof n.index=="number"?t.slice(n.index).trim():t.split(` `).map(o=>o.trim()).filter(o=>o&&KP.test(o)).length>=2?"":t}function Mi(e,t={}){if(!e||typeof e!="string")return"";let n=Ah(e),s="";for(;n!==s;)s=n,n=n.replace(BP,"");if(!t.preserveUnclosedThinkBlocks){const r=n.toLowerCase(),o=r.lastIndexOf("");o!==-1&&o>i&&(n=n.slice(0,o))}return n=n.replace(UP,""),t.streamingSafeTail&&(n=n.replace(WP,"").replace(HP,"")),n}function JP(e){return Mi(e,{streamingSafeTail:!0}).trim()}function vt(e){const t=XP(e);if(t)return t;const n=Mi(e,{streamingSafeTail:!0}).trim();if(n)return n;const s=Mi(e,{streamingSafeTail:!0,preserveUnclosedThinkBlocks:!0}).trim();return YP(s)}function e_(e){return e.replace(VP,t=>`$${t}$`)}function t_(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 n_(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 s_(e){if(!e||typeof e!="string")return"";const n=vt(e).replace(/\r\n?/g,` `);return n_(n).split($P).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(FP).map((f,p)=>p%2===1?t_(f):e_(f)).join("")).join("")}const r_=80;function Io(e,t=r_){if(!e||typeof e!="string")return"";const n=s_(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 o_=/^\s*(?:hi|hello|hey|good\s+(?:morning|afternoon|evening))\b/i,i_=/\b(?:thanks|thank\s+you|thank\s+u|ty)\b/i,Rh=["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."],Mh=["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."],tu=["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."],a_=["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"],c_=[/\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+/],l_=new Set(["go","continue","yes","ok","next","more"]),u_=[/\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],nu="I can continue once I know which math problem you mean. Please share the problem again or tell me which step to continue.";function Ks(e){return e.length===0?"":e[Math.floor(Math.random()*e.length)]??e[0]}function d_(e){const t=(e??"").trim().toLowerCase();return t?a_.some(n=>t.includes(n))?!0:c_.some(n=>n.test(t)):!1}function f_(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function Ih(e){const t=f_(e);return t?l_.has(t):!1}function su(e){const t=(e??"").trim();return t?d_(t)?null:o_.test(t)?Ks(Rh):i_.test(t)?Ks(Mh):Ks(tu):Ks(tu)}function h_(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 p_(e){const t=h_(e);return t?u_.some(n=>n.test(t)):!1}function m_(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"&&!Ih(o))return o}return null}function g_(e){return Rh.includes(e)||Mh.includes(e)}function Dh(e,t){const n=su(e);if(n===null)return null;if(!Ih(e))return n;if(p_(t))return null;const s=m_(t);if(!s)return nu;const r=su(s);return r===null?null:g_(r)?nu:r}const y_=2166136261,b_=16777619,Da=e=>(e||"").trim().toLowerCase().replace(/\s+/g," "),ru=e=>{let t=y_;for(let n=0;n>>0).toString(36)},RR={modules:(e,t=[])=>["modules",e??"all",...t],topicMastery:(e,t)=>["topic-mastery",e,t??"all"],masteryHeatmap:()=>["mastery-heatmap"],avatarInventory:()=>["avatar-inventory"]},Oa="mathpulse:chat-hint-cache:v1",v_=1200*1e3,Bt=new Map,La=()=>typeof window<"u",za=()=>Date.now(),Ii=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),w_=e=>Ii(e)&&typeof e.value=="string"&&typeof e.expiresAt=="number"&&Number.isFinite(e.expiresAt),x_=()=>{if(!La())return{entries:{}};try{const e=sessionStorage.getItem(Oa);if(!e)return{entries:{}};const t=JSON.parse(e);if(!Ii(t)||!Ii(t.entries))return{entries:{}};const n={};for(const[s,r]of Object.entries(t.entries)){if(!w_(r))continue;const o=r.value.trim();o&&(n[s]={value:o,expiresAt:r.expiresAt})}return{entries:n}}catch{return{entries:{}}}},Lr=e=>{if(La())try{const t={entries:e};sessionStorage.setItem(Oa,JSON.stringify(t))}catch{}},S_=e=>{const t=za(),n={};for(const[s,r]of Object.entries(e))r.expiresAt>t&&r.value.trim()&&(n[s]=r);return n},k_=e=>{Bt.clear();for(const[t,n]of Object.entries(e))Bt.set(t,n)},Oh=()=>{try{const e=x_(),t=S_(e.entries);k_(t),Lr(t)}catch{Bt.clear(),Lr({})}},T_=e=>e.slice(-4).map(n=>`${n.role}:${Da(n.content)}`).join("|"),P_=e=>{const t=Da(e);return t?/\b(hint|clue|nudge|guide me|without giving( me)? the answer|step by step|next step)\b/.test(t):!1},__=({userId:e,prompt:t,history:n=[]})=>{const s=Da(t),r=T_(n);return["chat-hint",e,ru(s),ru(r||"no-history")].join(":")},E_=e=>{Oh();const t=Bt.get(e);return t?t.expiresAt<=za()?(Bt.delete(e),Lr(Object.fromEntries(Bt.entries())),null):t.value:null},C_=(e,t,n=v_)=>{const s=(t||"").trim();if(!s)return;Oh();const r={value:s,expiresAt:za()+Math.max(1e3,n)};Bt.set(e,r),Lr(Object.fromEntries(Bt.entries()))},A_=()=>{if(Bt.clear(),!!La())try{sessionStorage.removeItem(Oa)}catch{}},Lh=h.createContext(void 0);let Do=null,Oo=null;const ou=()=>(Do||(Do=oe(()=>Promise.resolve().then(()=>ZE),void 0)),Do),un=()=>(Oo||(Oo=oe(()=>import("./chatService-CczfDdTB.js"),__vite__mapDeps([11,1,2,3,4,5,6,7,8,9,10]))),Oo),R_=new Set(["go","continue","next","more","yes","ok"]),M_=[/\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 I_(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function zh(e){const t=I_(e);return t?R_.has(t):!1}function D_(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&&!zh(s))return s}return null}function O_(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(FP).map((f,p)=>p%2===1?t_(f):e_(f)).join("")).join("")}const r_=80;function Io(e,t=r_){if(!e||typeof e!="string")return"";const n=s_(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 o_=/^\s*(?:hi|hello|hey|good\s+(?:morning|afternoon|evening))\b/i,i_=/\b(?:thanks|thank\s+you|thank\s+u|ty)\b/i,Rh=["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."],Mh=["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."],tu=["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."],a_=["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"],c_=[/\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+/],l_=new Set(["go","continue","yes","ok","next","more"]),u_=[/\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],nu="I can continue once I know which math problem you mean. Please share the problem again or tell me which step to continue.";function Ks(e){return e.length===0?"":e[Math.floor(Math.random()*e.length)]??e[0]}function d_(e){const t=(e??"").trim().toLowerCase();return t?a_.some(n=>t.includes(n))?!0:c_.some(n=>n.test(t)):!1}function f_(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function Ih(e){const t=f_(e);return t?l_.has(t):!1}function su(e){const t=(e??"").trim();return t?d_(t)?null:o_.test(t)?Ks(Rh):i_.test(t)?Ks(Mh):Ks(tu):Ks(tu)}function h_(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 p_(e){const t=h_(e);return t?u_.some(n=>n.test(t)):!1}function m_(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"&&!Ih(o))return o}return null}function g_(e){return Rh.includes(e)||Mh.includes(e)}function Dh(e,t){const n=su(e);if(n===null)return null;if(!Ih(e))return n;if(p_(t))return null;const s=m_(t);if(!s)return nu;const r=su(s);return r===null?null:g_(r)?nu:r}const y_=2166136261,b_=16777619,Da=e=>(e||"").trim().toLowerCase().replace(/\s+/g," "),ru=e=>{let t=y_;for(let n=0;n>>0).toString(36)},RR={modules:(e,t=[])=>["modules",e??"all",...t],topicMastery:(e,t)=>["topic-mastery",e,t??"all"],masteryHeatmap:()=>["mastery-heatmap"],avatarInventory:()=>["avatar-inventory"]},Oa="mathpulse:chat-hint-cache:v1",v_=1200*1e3,Bt=new Map,La=()=>typeof window<"u",za=()=>Date.now(),Ii=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),w_=e=>Ii(e)&&typeof e.value=="string"&&typeof e.expiresAt=="number"&&Number.isFinite(e.expiresAt),x_=()=>{if(!La())return{entries:{}};try{const e=sessionStorage.getItem(Oa);if(!e)return{entries:{}};const t=JSON.parse(e);if(!Ii(t)||!Ii(t.entries))return{entries:{}};const n={};for(const[s,r]of Object.entries(t.entries)){if(!w_(r))continue;const o=r.value.trim();o&&(n[s]={value:o,expiresAt:r.expiresAt})}return{entries:n}}catch{return{entries:{}}}},Lr=e=>{if(La())try{const t={entries:e};sessionStorage.setItem(Oa,JSON.stringify(t))}catch{}},S_=e=>{const t=za(),n={};for(const[s,r]of Object.entries(e))r.expiresAt>t&&r.value.trim()&&(n[s]=r);return n},k_=e=>{Bt.clear();for(const[t,n]of Object.entries(e))Bt.set(t,n)},Oh=()=>{try{const e=x_(),t=S_(e.entries);k_(t),Lr(t)}catch{Bt.clear(),Lr({})}},T_=e=>e.slice(-4).map(n=>`${n.role}:${Da(n.content)}`).join("|"),P_=e=>{const t=Da(e);return t?/\b(hint|clue|nudge|guide me|without giving( me)? the answer|step by step|next step)\b/.test(t):!1},__=({userId:e,prompt:t,history:n=[]})=>{const s=Da(t),r=T_(n);return["chat-hint",e,ru(s),ru(r||"no-history")].join(":")},E_=e=>{Oh();const t=Bt.get(e);return t?t.expiresAt<=za()?(Bt.delete(e),Lr(Object.fromEntries(Bt.entries())),null):t.value:null},C_=(e,t,n=v_)=>{const s=(t||"").trim();if(!s)return;Oh();const r={value:s,expiresAt:za()+Math.max(1e3,n)};Bt.set(e,r),Lr(Object.fromEntries(Bt.entries()))},A_=()=>{if(Bt.clear(),!!La())try{sessionStorage.removeItem(Oa)}catch{}},Lh=h.createContext(void 0);let Do=null,Oo=null;const ou=()=>(Do||(Do=oe(()=>Promise.resolve().then(()=>ZE),void 0)),Do),un=()=>(Oo||(Oo=oe(()=>import("./chatService-BdLPo3Lt.js"),__vite__mapDeps([11,1,2,3,4,5,6,7,8,9,10]))),Oo),R_=new Set(["go","continue","next","more","yes","ok"]),M_=[/\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 I_(e){return(e??"").trim().toLowerCase().replace(/\s+/g," ").replace(/[\p{P}]+$/gu,"")}function zh(e){const t=I_(e);return t?R_.has(t):!1}function D_(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&&!zh(s))return s}return null}function O_(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 L_(e){const t=(e??"").trim();if(!t)return null;for(const n of M_){const s=n.exec(t);if(!s)continue;const r=Is(s[2]);if(r)return r}return null}function z_(e,t){const n=Is(t);return n?e.toLowerCase().includes(n.toLowerCase()):!1}function Di(e,t,n,s){return n&&!z_(t,n)?!0:s?N_(e,t):!1}function j_(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 N_(e,t){const n=t.trim(),s=e.toLowerCase();if(!n||j_(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 En(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 Qs(e,t){const n=e.trim(),s=t.trim();if(!n)return En(s);if(!s)return En(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 En(`${n}${s.slice(o)}`.trim())}return n.endsWith(s)?En(n):s.startsWith(n)?En(s):En(`${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 MR=()=>{const e=h.useContext(Lh);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},V_=({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 un(),P=await T.getUserChatSessions(t.uid),_=await Promise.all(P.map(async w=>{const A=(await T.getSessionMessages(w.id,t.uid)).map(B=>({id:B.id,sender:B.role==="user"?"user":"ai",text:B.role==="assistant"?vt(B.content):B.content,timestamp:B.timestamp instanceof Date?B.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):new Date(B.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}));return{id:w.id,title:w.title,date:w.updatedAt instanceof Date?w.updatedAt.toLocaleDateString():new Date(w.updatedAt).toLocaleDateString(),messageCount:A.length,preview:A.length>0&&Io(A[A.length-1].text)||"No messages yet",topics:[],messages:A,createdAt:w.createdAt instanceof Date?w.createdAt:new Date(w.createdAt),updatedAt:w.updatedAt instanceof Date?w.updatedAt:new Date(w.updatedAt)}}));s(_)}catch(T){console.error("Error loading chat sessions:",T)}finally{l(!0)}})()},[t]);const p=x=>{if(x.length===0)return"New Chat";const T=x.find(w=>w.sender==="user")?.text||"",P=T.toLowerCase();if(P.includes("quadratic")||P.includes("ax² + bx + c"))return"Quadratic Equations Help";if(P.includes("derivative")||P.includes("calculus"))return"Derivatives & Calculus";if(P.includes("pythagor")||P.includes("right triangle"))return"Pythagorean Theorem";if(P.includes("trig")||P.includes("sin")||P.includes("cos"))return"Trigonometry Help";if(P.includes("area")||P.includes("perimeter"))return"Geometry - Area & Perimeter";if(P.includes("algebra")||P.includes("solve")&&P.includes("x"))return"Algebra Problem Solving";if(P.includes("factor"))return"Factoring Practice";if(P.includes("graph")||P.includes("plot"))return"Graphing Functions";if(P.includes("matrix")||P.includes("matrices"))return"Matrix Operations";if(P.includes("integral")||P.includes("integrate"))return"Integration Problems";if(P.includes("limit"))return"Limits in Calculus";if(P.includes("statistic")||P.includes("probability"))return"Statistics & Probability";const _=T.slice(0,40);return _.length{const T=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),P=new Date,_={id:T,title:x?p([x]):"New Chat",date:"Just now",messageCount:x?1:0,preview:x&&Io(x.text)||"Start a new conversation...",topics:[],messages:x?[x]:[],createdAt:P,updatedAt:P};if(s(w=>[_,...w]),t){const w=x?p([x]):"New Chat",R=un().then(async A=>{const B=await A.createChatSession(t.uid,w);return oe(async()=>{const{logChatSession:F}=await import("./trackingService-MJBRfiN7.js");return{logChatSession:F}},__vite__mapDeps([12,1,2,3,4,5,6,7,8,9,10])).then(({logChatSession:F})=>F(t.uid,B.id,x?1:0).catch(()=>{})),x&&await A.addMessageToSession(B.id,x.sender==="user"?"user":"assistant",x.text),B.id}).catch(A=>(console.error("Error creating Firebase session:",A),T));f.current.set(T,R)}return T},[t]),g=h.useCallback((x,T)=>{s(_=>_.map(w=>{if(w.id===x){const R=[...w.messages,T];return{...w,messages:R,messageCount:R.length,preview:Io(T.text)||w.preview,updatedAt:new Date,title:R.length===2?p(R):w.title}}return w}));const P=async _=>{const w=f.current.get(_);return w?await w:_};P(x).then(async _=>{await(await un()).addMessageToSession(_,T.sender==="user"?"user":"assistant",T.text)}).catch(_=>console.error("Error persisting message:",_)),s(_=>{const w=_.find(R=>R.id===x);if(w&&w.messages.length===2){const R=p(w.messages);P(x).then(async A=>{await(await un()).updateSessionTitle(A,R)}).catch(A=>console.error("Error updating title:",A))}return _})},[]),y=h.useCallback(async(x,T)=>{const P=T.trim(),_={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),sender:"user",text:P,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,_),u(x),a(!0);try{let w=null,R=null;const A=n.find(Z=>Z.id===x),F=[...A?.messages||[],_].map(Z=>({role:Z.sender==="user"?"user":"assistant",content:Z.text})),H=zh(P)?D_(F):null,se=H?O_(H):P,te=H??P,V=P_(P)?__({userId:t?.uid||"anonymous",prompt:P,history:F}):null,ie=Z=>{if(!V)return;const O=vt(Z).trim();O&&C_(V,O)},re=Dh(P,{history:F});if(re){const Z={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:re,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,Z);return}if(V){const Z=E_(V);if(Z){const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:Z,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,O);return}}try{const Z=await ou();w=Z.apiService,R=Z.ApiTimeoutError}catch(Z){console.error("Failed to load API service for chat:",Z);const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:Xs(te),timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,O);return}const ue=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});let D="",he=null;const st=$_(P),X=F_(P),U=L_(P),G=X||!!U,J={sessionId:x,...U?{expectedEndMarker:U,completionMode:"marker"}:{}},we=Z=>Di(P,Z,U,X),ae=Z=>{Z.trim()&&s(O=>O.map(ee=>{if(ee.id!==x)return ee;if(!he){he=`stream-${typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString()}-${Math.random().toString(36).slice(2,8)}`;const ge={id:he,sender:"ai",text:Z,timestamp:ue},K=[...ee.messages,ge];return{...ee,messages:K,messageCount:K.length,updatedAt:new Date}}return{...ee,messages:ee.messages.map(ge=>ge.id===he?{...ge,text:Z}:ge),updatedAt:new Date}}))},le=()=>{if(!he)return;const Z=he;s(O=>O.map(ee=>{if(ee.id!==x)return ee;const ge=ee.messages.filter(K=>K.id!==Z);return{...ee,messages:ge,messageCount:ge.length,updatedAt:new Date}}))};try{const{response:Z}=await w.chat(se,F,K=>{D+=K,st&&ae(JP(D))},J);let O=vt(Z||D).trim();if(G&&O&&we(O)){try{const K=await w.chatSafe(iu(P,O,U),F,J),Ye=vt(K.data.response).trim();O=Qs(O,Ye)}catch(K){console.warn("Streaming completion repair failed:",K)}if(G&&O&&we(O))try{const K=await w.chatSafe(au(P,O,U),F,J),Ye=vt(K.data.response).trim();O=Qs(O,Ye)}catch(K){console.warn("Streaming plain continuation repair failed:",K)}if(G&&O&&we(O))try{const K=await w.chatSafe(cu(P,U),F,J),Ye=vt(K.data.response).trim();Ye&&(O=lu(P,O,Ye,U,X))}catch(K){console.warn("Streaming full completion repair failed:",K)}}const ee=we(O);(!O||ee&&!G)&&(O=Xs(te,F)),ie(O),he&&le();const ge={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ue};g(x,ge)}catch(Z){R&&Z instanceof R?console.warn(`Streaming timed out after ${Z.timeoutMs}ms, falling back to non-streaming chat.`,Z):console.warn("Streaming failed, falling back to non-streaming chat:",Z),he&&le();let O="";try{const K=w??(await ou()).apiService,{data:Ye}=await K.chatSafe(se,F,J);if(O=vt(Ye.response).trim(),G&&O&&we(O))try{const Le=await K.chatSafe(iu(P,O,U),F,J),Je=vt(Le.data.response).trim();O=Qs(O,Je)}catch(Le){console.warn("Non-stream completion repair failed:",Le)}if(G&&O&&we(O))try{const Le=await K.chatSafe(au(P,O,U),F,J),Je=vt(Le.data.response).trim();O=Qs(O,Je)}catch(Le){console.warn("Non-stream plain continuation repair failed:",Le)}if(G&&O&&we(O))try{const Le=await K.chatSafe(cu(P,U),F,J),Je=vt(Le.data.response).trim();Je&&(O=lu(P,O,Je,U,X))}catch(Le){console.warn("Non-stream full completion repair failed:",Le)}}catch(K){console.warn("Chat request failed, using local fallback response:",K),O=Xs(te,F)}const ee=we(O);(!O||ee&&!G)&&(O=Xs(te,F)),ie(O);const ge={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ue};g(x,ge)}if(A&&A.messages.length===1){const Z=n.find(O=>O.id===x);if(Z&&Z.messages.length>1){const O=p(Z.messages),ee=f.current.get(x);(ee||Promise.resolve(x)).then(async K=>{await(await un()).updateSessionTitle(K,O)}).catch(K=>console.error("Error updating title:",K))}}}finally{a(!1),u(null)}},[n,g,t]),v=h.useCallback((x,T)=>{s(w=>w.map(R=>R.id===x?{...R,title:T}:R));const P=f.current.get(x);(P||Promise.resolve(x)).then(async w=>{await(await un()).updateSessionTitle(w,T)}).catch(w=>console.error("Error updating session title:",w))},[]),k=h.useCallback(x=>{s(_=>_.filter(w=>w.id!==x)),r===x&&o(null);const T=f.current.get(x);(T||Promise.resolve(x)).then(async _=>{await(await un()).deleteSession(_)}).catch(_=>console.error("Error deleting session:",_)),f.current.delete(x)},[r]),S=h.useCallback(()=>n.find(x=>x.id===r)||null,[n,r]);return b.jsx(Lh.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})},B_=[{id:"first_lesson",title:"First Steps",description:"Complete your first lesson",icon:Mo,iconColor:"text-yellow-500",xpReward:50,condition:"lesson_complete",threshold:1,category:"learning"},{id:"lesson_10",title:"Dedicated Learner",description:"Complete 10 lessons",icon:Mo,iconColor:"text-blue-500",xpReward:200,condition:"lesson_complete",threshold:10,category:"learning"},{id:"lesson_50",title:"Knowledge Seeker",description:"Complete 50 lessons",icon:Rl,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:Ol,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:Il,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:Pi,iconColor:"text-orange-500",xpReward:100,condition:"speed_quiz",category:"learning"},{id:"quiz_10",title:"Quiz Enthusiast",description:"Complete 10 quizzes",icon:bx,iconColor:"text-cyan-500",xpReward:200,condition:"quiz_complete",threshold:10,category:"learning"},{id:"quiz_50",title:"Quiz Champion",description:"Complete 50 quizzes",icon:Mo,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:Vx,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:mr,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:Gs,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:Gs,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:Gs,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:Ml,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:Pi,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:Nx,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:pr,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:Ml,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:Ux,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:Gs,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:mr,iconColor:"text-orange-500",xpReward:500,condition:"mastery_10",threshold:10,category:"mastery"},{id:"mastery_level",title:"Rising Star",description:"Reach level 5",icon:pr,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:Dl,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:Rl,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:Ex,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:Il,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:pr,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:Cl,iconColor:"text-amber-400",xpReward:1e3,condition:"social_xp",category:"mastery"},{id:"explore_profile",title:"Identity Set",description:"Complete your user profile",icon:Xx,iconColor:"text-blue-400",xpReward:50,condition:"explore_profile_complete",category:"exploration"},{id:"explore_first_friend",title:"Socialite",description:"Add your first friend",icon:Ll,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:Al,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:Jx,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:kx,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:Rx,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:Dl,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:Ll,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:Cl,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:Ol,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:mr,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:Al,iconColor:"text-violet-400",xpReward:200,condition:"social_daily_return",threshold:7,category:"social"}];new Map(B_.map(e=>[e.id,e]));const Lo=async(e,t,n,s)=>{try{const r=q(N,"users",e),o=await ve(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 x=0;for(let T=1;T<=m;T++)x+=Math.floor(100*Math.pow(1.5,T-1));if(f>=x)m++,y=!0;else break}const v={currentXP:l,totalXP:f,level:m,updatedAt:ce()};u!==1&&(v.xpMultiplier=1),await dt(r,v);const k=q(Xe(N,"xpActivities"));return await $e(k,{activityId:k.id,userId:e,type:n,xpEarned:t,description:s,timestamp:ce()}),{newLevel:m,leveledUp:y,xp:l,addedXp:t}}catch(r){throw console.error("Error awarding XP:",r),r}},IR=async(e,t=!1,n="all",s=10)=>{try{const r=Ot(Xe(N,"leaderboard"),vn("totalXP","desc"),ks(s)),o=await zn(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),[]}},DR=(e,t,n=!1,s="all",r=10)=>{const o=Ot(Xe(N,"leaderboard"),vn("totalXP","desc"),ks(r));return Yt(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([])})},OR=async e=>{try{const t=await ve(q(N,"achievements",e));return t.exists()?t.data().achievements||[]:[]}catch(t){return console.error("Error getting user achievements:",t),[]}},LR=async(e,t,n)=>{try{const s=q(N,"users",e),r=await ve(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=q(N,"users",e),s=await ve(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:Lu(t),updatedAt:ce()}),{success:!0,message:"Avatar item unlocked!"})}catch(n){return console.error("Error unlocking avatar item:",n),{success:!1,message:"Failed to unlock item"}}},Xr=3e4,jh=3,Nh=1e3;class Dt 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 bn 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 zr extends Error{endpoint;originalError;constructor(t,n){super(`Network error on ${t}: ${n.message}`),this.name="ApiNetworkError",this.endpoint=t,this.originalError=n}}class je extends Error{endpoint;details;constructor(t,n){super(`Validation error before calling ${t}: ${n}`),this.name="ApiValidationError",this.endpoint=t,this.details=n}}const U_=new Set([408,429,500,502,503,504]);function q_(e){return U_.has(e)}function ja(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 Rt(e,t,n,s){ja({timestamp:new Date().toISOString(),level:"info",endpoint:e,method:t,message:n,details:s})}function Oi(e,t,n,s){ja({timestamp:new Date().toISOString(),level:"warn",endpoint:e,method:t,message:n,details:s})}function Ne(e,t,n,s){ja({timestamp:new Date().toISOString(),level:"error",endpoint:e,method:t,message:n,details:s})}function G_(e,t,n=Xr){const s=new AbortController,r=setTimeout(()=>s.abort(),n);return{promise:fetch(e,{...t,signal:s.signal}).finally(()=>clearTimeout(r)),abort:()=>s.abort()}}let W_=e=>new Promise(t=>setTimeout(t,e));function uu(e){return W_(e)}function H_(e,t=Nh){const n=t*Math.pow(2,e),s=Math.random()*t;return Math.min(n+s,3e4)}async function du(e,t={},n={}){const{maxRetries:s=jh,timeoutMs:r=Xr,baseBackoffMs:o=Nh}=n,i=(t.method??"GET").toUpperCase();let a;for(let c=0;c<=s;c++){const u=Date.now();try{c>0&&Rt(e,i,`Retry attempt ${c}/${s}`);const{promise:d}=G_(e,t,r),l=await d,f=Date.now()-u;if(l.ok)return Rt(e,i,`${l.status} in ${f}ms`,{attempt:c}),await l.json();const p=await l.text().catch(()=>"Unable to read response body"),m=q_(l.status),g=new Dt({status:l.status,statusText:l.statusText,endpoint:e,responseBody:p,retryable:m,requestId:l.headers.get("x-request-id")??void 0});if(Ne(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){Oi(e,i,`Rate limited. Waiting ${v}s (Retry-After header)`),await uu(v*1e3),a=g;continue}}}a=g}catch(d){const l=Date.now()-u;if(d instanceof Dt&&!d.retryable)throw d;if(d instanceof DOMException&&d.name==="AbortError"){const f=new bn(e,r);Ne(e,i,`Timeout after ${l}ms`,{attempt:c,timeoutMs:r}),a=f}else if(d instanceof TypeError&&d.message.includes("fetch")){const f=new zr(e,d);Ne(e,i,`Network error after ${l}ms: ${d.message}`,{attempt:c}),a=f}else d instanceof Dt?a=d:(a=d instanceof Error?d:new Error(String(d)),Ne(e,i,`Unexpected error: ${a.message}`,{attempt:c}))}if(cs==null||s==="").map(([s])=>s);if(n.length>0)throw new je(e,`Missing required fields: ${n.join(", ")}`)}function Re(e,t,n,s,r){if(typeof n!="number"||isNaN(n)||nr)throw new je(e,`${t} must be a number between ${s} and ${r}, got ${n}`)}function Z_(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 K_=e=>{switch(e){case"success":return Y_;case"info":return eE;case"warning":return J_;case"error":return tE;default:return null}},Q_=Array(12).fill(0),X_=({visible:e,className:t})=>I.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},I.createElement("div",{className:"sonner-spinner"},Q_.map((n,s)=>I.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),Y_=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"})),J_=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"})),eE=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"})),tE=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"})),nE=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"})),sE=()=>{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 Li=1;class rE{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:Li++,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(iE(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||Li++;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 nt=new rE,oE=(e,t)=>{const n=t?.id||Li++;return nt.addToast({title:e,...t,id:n}),n},iE=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",aE=oE,cE=()=>nt.toasts,lE=()=>nt.getActiveToasts(),ct=Object.assign(aE,{success:nt.success,info:nt.info,warning:nt.warning,error:nt.error,custom:nt.custom,message:nt.message,promise:nt.promise,dismiss:nt.dismiss,loading:nt.loading},{getHistory:cE,getToasts:lE});Z_("[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 Ys(e){return e.label!==void 0}const uE=3,dE="24px",fE="16px",fu=4e3,hE=356,pE=14,mE=45,gE=200;function _t(...e){return e.filter(Boolean).join(" ")}function yE(e){const[t,n]=e.split("-"),s=[];return t&&s.push(t),n&&s.push(n),s}const bE=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:x,defaultRichColors:T,closeButton:P,style:_,cancelButtonStyle:w,actionButtonStyle:R,className:A="",descriptionClassName:B="",duration:F,position:H,gap:se,expandByDefault:te,classNames:V,icons:ie,closeButtonAriaLabel:re="Close toast"}=e,[ue,D]=I.useState(null),[he,st]=I.useState(null),[X,U]=I.useState(!1),[G,J]=I.useState(!1),[we,ae]=I.useState(!1),[le,Z]=I.useState(!1),[O,ee]=I.useState(!1),[ge,K]=I.useState(0),[Ye,Le]=I.useState(0),Je=I.useRef(l.duration||F||fu),on=I.useRef(null),pt=I.useRef(null),Ds=v===0,Os=v+1<=g,Ge=l.type,it=l.dismissible!==!1,$t=l.className||"",eo=l.descriptionClassName||"",Ft=I.useMemo(()=>y.findIndex(Y=>Y.toastId===l.id)||0,[y,l.id]),an=I.useMemo(()=>{var Y;return(Y=l.closeButton)!=null?Y:P},[l.closeButton,P]),Wn=I.useMemo(()=>l.duration||F||fu,[l.duration,F]),Tn=I.useRef(0),rt=I.useRef(0),Wt=I.useRef(0),mt=I.useRef(null),[to,Hn]=H.split("-"),Ls=I.useMemo(()=>y.reduce((Y,Ee,ze)=>ze>=Ft?Y:Y+Ee.height,0),[y,Ft]),Zn=sE(),no=l.invert||d,Kn=Ge==="loading";rt.current=I.useMemo(()=>Ft*se+Ls,[Ft,Ls]),I.useEffect(()=>{Je.current=Wn},[Wn]),I.useEffect(()=>{U(!0)},[]),I.useEffect(()=>{const Y=pt.current;if(Y){const Ee=Y.getBoundingClientRect().height;return Le(Ee),m(ze=>[{toastId:l.id,height:Ee,position:l.position},...ze]),()=>m(ze=>ze.filter(Te=>Te.toastId!==l.id))}},[m,l.id]),I.useLayoutEffect(()=>{if(!X)return;const Y=pt.current,Ee=Y.style.height;Y.style.height="auto";const ze=Y.getBoundingClientRect().height;Y.style.height=Ee,Le(ze),m(Te=>Te.find(_e=>_e.toastId===l.id)?Te.map(_e=>_e.toastId===l.id?{..._e,height:ze}:_e):[{toastId:l.id,height:ze,position:l.position},...Te])},[X,l.title,l.description,m,l.id,l.jsx,l.action,l.cancel]);const at=I.useCallback(()=>{J(!0),K(rt.current),m(Y=>Y.filter(Ee=>Ee.toastId!==l.id)),setTimeout(()=>{x(l)},gE)},[l,x,m,rt]);I.useEffect(()=>{if(l.promise&&Ge==="loading"||l.duration===1/0||l.type==="loading")return;let Y;return S||p||Zn?(()=>{if(Wt.current{Je.current!==1/0&&(Tn.current=new Date().getTime(),Y=setTimeout(()=>{l.onAutoClose==null||l.onAutoClose.call(l,l),at()},Je.current))})(),()=>clearTimeout(Y)},[S,p,l,Ge,Zn,at]),I.useEffect(()=>{l.delete&&(at(),l.onDismiss==null||l.onDismiss.call(l,l))},[at,l.delete]);function Qn(){var Y;if(ie?.loading){var Ee;return I.createElement("div",{className:_t(V?.loader,l==null||(Ee=l.classNames)==null?void 0:Ee.loader,"sonner-loader"),"data-visible":Ge==="loading"},ie.loading)}return I.createElement(X_,{className:_t(V?.loader,l==null||(Y=l.classNames)==null?void 0:Y.loader),visible:Ge==="loading"})}const so=l.icon||ie?.[Ge]||K_(Ge);var Xn,cn;return I.createElement("li",{tabIndex:0,ref:pt,className:_t(A,$t,V?.toast,l==null||(t=l.classNames)==null?void 0:t.toast,V?.default,V?.[Ge],l==null||(n=l.classNames)==null?void 0:n[Ge]),"data-sonner-toast":"","data-rich-colors":(Xn=l.richColors)!=null?Xn:T,"data-styled":!(l.jsx||l.unstyled||f),"data-mounted":X,"data-promise":!!l.promise,"data-swiped":O,"data-removed":G,"data-visible":Os,"data-y-position":to,"data-x-position":Hn,"data-index":v,"data-front":Ds,"data-swiping":we,"data-dismissible":it,"data-type":Ge,"data-invert":no,"data-swipe-out":le,"data-swipe-direction":he,"data-expanded":!!(S||te&&X),"data-testid":l.testId,style:{"--index":v,"--toasts-before":v,"--z-index":k.length-v,"--offset":`${G?ge:rt.current}px`,"--initial-height":te?"auto":`${Ye}px`,..._,...l.style},onDragEnd:()=>{ae(!1),D(null),mt.current=null},onPointerDown:Y=>{Y.button!==2&&(Kn||!it||(on.current=new Date,K(rt.current),Y.target.setPointerCapture(Y.pointerId),Y.target.tagName!=="BUTTON"&&(ae(!0),mt.current={x:Y.clientX,y:Y.clientY})))},onPointerUp:()=>{var Y,Ee,ze;if(le||!it)return;mt.current=null;const Te=Number(((Y=pt.current)==null?void 0:Y.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Pt=Number(((Ee=pt.current)==null?void 0:Ee.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),_e=new Date().getTime()-((ze=on.current)==null?void 0:ze.getTime()),Fe=ue==="x"?Te:Pt,Pn=Math.abs(Fe)/_e;if(Math.abs(Fe)>=mE||Pn>.11){K(rt.current),l.onDismiss==null||l.onDismiss.call(l,l),st(ue==="x"?Te>0?"right":"left":Pt>0?"down":"up"),at(),Z(!0);return}else{var et,Ve;(et=pt.current)==null||et.style.setProperty("--swipe-amount-x","0px"),(Ve=pt.current)==null||Ve.style.setProperty("--swipe-amount-y","0px")}ee(!1),ae(!1),D(null)},onPointerMove:Y=>{var Ee,ze,Te;if(!mt.current||!it||((Ee=window.getSelection())==null?void 0:Ee.toString().length)>0)return;const _e=Y.clientY-mt.current.y,Fe=Y.clientX-mt.current.x;var Pn;const et=(Pn=e.swipeDirections)!=null?Pn:yE(H);!ue&&(Math.abs(Fe)>1||Math.abs(_e)>1)&&D(Math.abs(Fe)>Math.abs(_e)?"x":"y");let Ve={x:0,y:0};const Yn=gt=>1/(1.5+Math.abs(gt)/20);if(ue==="y"){if(et.includes("top")||et.includes("bottom"))if(et.includes("top")&&_e<0||et.includes("bottom")&&_e>0)Ve.y=_e;else{const gt=_e*Yn(_e);Ve.y=Math.abs(gt)0)Ve.x=Fe;else{const gt=Fe*Yn(Fe);Ve.x=Math.abs(gt)0||Math.abs(Ve.y)>0)&&ee(!0),(ze=pt.current)==null||ze.style.setProperty("--swipe-amount-x",`${Ve.x}px`),(Te=pt.current)==null||Te.style.setProperty("--swipe-amount-y",`${Ve.y}px`)}},an&&!l.jsx&&Ge!=="loading"?I.createElement("button",{"aria-label":re,"data-disabled":Kn,"data-close-button":!0,onClick:Kn||!it?()=>{}:()=>{at(),l.onDismiss==null||l.onDismiss.call(l,l)},className:_t(V?.closeButton,l==null||(s=l.classNames)==null?void 0:s.closeButton)},(cn=ie?.close)!=null?cn:nE):null,(Ge||l.icon||l.promise)&&l.icon!==null&&(ie?.[Ge]!==null||l.icon)?I.createElement("div",{"data-icon":"",className:_t(V?.icon,l==null||(r=l.classNames)==null?void 0:r.icon)},l.promise||l.type==="loading"&&!l.icon?l.icon||Qn():null,l.type!=="loading"?so:null):null,I.createElement("div",{"data-content":"",className:_t(V?.content,l==null||(o=l.classNames)==null?void 0:o.content)},I.createElement("div",{"data-title":"",className:_t(V?.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(B,eo,V?.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&&Ys(l.cancel)?I.createElement("button",{"data-button":!0,"data-cancel":!0,style:l.cancelButtonStyle||w,onClick:Y=>{Ys(l.cancel)&&it&&(l.cancel.onClick==null||l.cancel.onClick.call(l.cancel,Y),at())},className:_t(V?.cancelButton,l==null||(c=l.classNames)==null?void 0:c.cancelButton)},l.cancel.label):null,I.isValidElement(l.action)?l.action:l.action&&Ys(l.action)?I.createElement("button",{"data-button":!0,"data-action":!0,style:l.actionButtonStyle||R,onClick:Y=>{Ys(l.action)&&(l.action.onClick==null||l.action.onClick.call(l.action,Y),!Y.defaultPrevented&&at())},className:_t(V?.actionButton,l==null||(u=l.classNames)==null?void 0:u.actionButton)},l.action.label):null)};function hu(){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 vE(e,t){const n={};return[e,t].forEach((s,r)=>{const o=r===1,i=o?"--mobile-offset":"--offset",a=o?fE:dE;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 zo=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=uE,toastOptions:v,dir:k=hu(),gap:S=pE,icons:x,containerAriaLabel:T="Notifications"}=t,[P,_]=I.useState([]),w=I.useMemo(()=>s?P.filter(X=>X.toasterId===s):P.filter(X=>!X.toasterId),[P,s]),R=I.useMemo(()=>Array.from(new Set([o].concat(w.filter(X=>X.position).map(X=>X.position)))),[w,o]),[A,B]=I.useState([]),[F,H]=I.useState(!1),[se,te]=I.useState(!1),[V,ie]=I.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),re=I.useRef(null),ue=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),D=I.useRef(null),he=I.useRef(!1),st=I.useCallback(X=>{_(U=>{var G;return(G=U.find(J=>J.id===X.id))!=null&&G.delete||nt.dismiss(X.id),U.filter(({id:J})=>J!==X.id)})},[]);return I.useEffect(()=>nt.subscribe(X=>{if(X.dismiss){requestAnimationFrame(()=>{_(U=>U.map(G=>G.id===X.id?{...G,delete:!0}:G))});return}setTimeout(()=>{Tp.flushSync(()=>{_(U=>{const G=U.findIndex(J=>J.id===X.id);return G!==-1?[...U.slice(0,G),{...U[G],...X},...U.slice(G+1)]:[X,...U]})})})}),[P]),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:U})=>{ie(U?"dark":"light")})}catch{X.addListener(({matches:G})=>{try{ie(G?"dark":"light")}catch(J){console.error(J)}})}},[f]),I.useEffect(()=>{P.length<=1&&H(!1)},[P]),I.useEffect(()=>{const X=U=>{var G;if(i.every(ae=>U[ae]||U.code===ae)){var we;H(!0),(we=re.current)==null||we.focus()}U.code==="Escape"&&(document.activeElement===re.current||(G=re.current)!=null&&G.contains(document.activeElement))&&H(!1)};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[i]),I.useEffect(()=>{if(re.current)return()=>{D.current&&(D.current.focus({preventScroll:!0}),D.current=null,he.current=!1)}},[re.current]),I.createElement("section",{ref:n,"aria-label":`${T} ${ue}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},R.map((X,U)=>{var G;const[J,we]=X.split("-");return w.length?I.createElement("ol",{key:X,dir:k==="auto"?hu():k,tabIndex:-1,ref:re,className:u,"data-sonner-toaster":!0,"data-sonner-theme":V,"data-y-position":J,"data-x-position":we,style:{"--front-toast-height":`${((G=A[0])==null?void 0:G.height)||0}px`,"--width":`${hE}px`,"--gap":`${S}px`,...g,...vE(d,l)},onBlur:ae=>{he.current&&!ae.currentTarget.contains(ae.relatedTarget)&&(he.current=!1,D.current&&(D.current.focus({preventScroll:!0}),D.current=null))},onFocus:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||he.current||(he.current=!0,D.current=ae.relatedTarget)},onMouseEnter:()=>H(!0),onMouseMove:()=>H(!0),onMouseLeave:()=>{se||H(!1)},onDragEnd:()=>H(!1),onPointerDown:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||te(!0)},onPointerUp:()=>te(!1)},w.filter(ae=>!ae.position&&U===0||ae.position===X).map((ae,le)=>{var Z,O;return I.createElement(bE,{key:ae.id,icons:x,index:le,toast:ae,defaultRichColors:p,duration:(Z=v?.duration)!=null?Z:m,className:v?.className,descriptionClassName:v?.descriptionClassName,invert:r,visibleToasts:y,closeButton:(O=v?.closeButton)!=null?O:c,interacting:se,position:X,style:v?.style,unstyled:v?.unstyled,classNames:v?.classNames,cancelButtonStyle:v?.cancelButtonStyle,actionButtonStyle:v?.actionButtonStyle,closeButtonAriaLabel:v?.closeButtonAriaLabel,removeToast:st,toasts:w.filter(ee=>ee.position==ae.position),heights:A.filter(ee=>ee.position==ae.position),setHeights:B,expandByDefault:a,gap:S,expanded:F,swipeDirections:t.swipeDirections})})):null}))});function wE(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 xE(e,t){const n=ye.currentUser;if(n)try{const s=q(N,"_analytics/rateLimitHits",n.uid);await $e(s,{uid:n.uid,endpoint:e,retryAfter:t,timestamp:ce()},{merge:!0})}catch(s){console.warn("Failed to log rate limit hit:",s)}}const jo=new Map;function SE(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=jo.get(e);r&&clearInterval(r.timerId);const o=window.setInterval(()=>{Math.ceil((s-Date.now())/1e3)<=0&&(clearInterval(o),jo.delete(e),ct.dismiss(n))},1e3);jo.set(e,{endpoint:e,endsAt:s,timerId:o})}async function kE(e,t){if(e.status!==429)return!1;const n=wE(e);return await xE(t,n),SE(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",Yr=(e,t)=>t,$h=(e,t)=>t,No=Yr(void 0,!0),pu=Yr(void 0,!0),mu=Yr(void 0,!0),gu=Yr(void 0,!0),yu=$h(void 0,9e4),$o=$h(void 0,9e5);let Fo=!0,bu=0;const TE=6e4;async function PE(){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 _E(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 EE(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 CE(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 Ct={maxRetries:jh,timeoutMs:Xr,baseBackoffMs:1e3},Qt={...Ct,timeoutMs:6e4},AE={...Qt,maxRetries:1,timeoutMs:45e3,baseBackoffMs:750},RE={...Ct,maxRetries:1,timeoutMs:2e4,baseBackoffMs:500},rs={maxRetries:2,timeoutMs:12e4,baseBackoffMs:2e3},ME={maxRetries:0,timeoutMs:8e3,baseBackoffMs:500};let Js=null;async function IE(){return Js||(Js=(async()=>{try{Rt("/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?(Rt("/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}})(),Js)}async function z(e,t,n=Ct){const s=`${Ss}${e}`,r=t?.method??"GET";Rt(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){Ne(e,r,"Failed to acquire Firebase ID token",d)}return{...t,headers:c}};let i=await o(!1);try{const a=await du(s,i,n);return Rt(e,r,"Request succeeded"),a}catch(a){if(a instanceof Dt&&a.status===401&&ye.currentUser)try{Rt(e,r,"401 received, refreshing Firebase token and retrying once"),i=await o(!0);const c=await du(s,i,n);return Rt(e,r,"Request succeeded after token refresh"),c}catch(c){throw c instanceof Dt?Ne(e,r,`HTTP ${c.status}: ${c.responseBody.slice(0,300)}`):c instanceof bn?Ne(e,r,`Timeout after ${c.timeoutMs}ms`):c instanceof zr?Ne(e,r,`Network error: ${c.originalError.message}`):Ne(e,r,`Unexpected: ${c instanceof Error?c.message:String(c)}`),c}throw a instanceof Dt?(Ne(e,r,`HTTP ${a.status}: ${a.responseBody.slice(0,300)}`),a.status===429&&await kE(new Response(a.responseBody,{status:429,headers:{"retry-after":"60"}}),e)):a instanceof bn?Ne(e,r,`Timeout after ${a.timeoutMs}ms`):a instanceof zr?Ne(e,r,`Network error: ${a.originalError.message}`):Ne(e,r,`Unexpected: ${a instanceof Error?a.message:String(a)}`),a}}async function vu(e,t,n=Xr){const s=`${Ss}${e}`,r=t?.method??"GET";Rt(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){Ne(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 Dt({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 Dt&&i.status===401&&ye.currentUser)return Rt(e,r,"401 received for blob request, refreshing Firebase token and retrying once"),o(!0);throw i}}const DE={response:"Sorry, the AI tutor is temporarily unavailable. Please try again in a moment."},OE={riskLevel:"Medium",confidence:0,analysis:{labels:[],scores:[]},risk_level:"medium",risk_score:0,top_factors:["Fallback risk response due to temporary service unavailability"]},LE={learningPath:"Unable to generate a learning path right now. Please try again later."},zE={insight:"Daily insight is temporarily unavailable. Please refresh later."},jE={expression:"",result:"Error: calculation service unavailable",steps:[],simplified:null,latex:null};function NE(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.riskLevel=="string"&&typeof t.confidence=="number"}function wu(e){if(typeof e!="object"||e===null)return!1;const t=e;return Array.isArray(t.questions)&&typeof t.totalPoints=="number"}const $E=e=>new Promise(t=>setTimeout(t,e));function FE(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 wt={getImportGroundedRolloutFlags(){return{quizEnabled:No,lessonEnabled:pu,feedbackEnabled:mu}},async reportImportGroundedFeedback(e){return mu?z("/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 z("/health",void 0,{...Ct,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"),yu)};u=setTimeout(()=>d("total"),$o);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){Ne("/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 P=await y.text().catch(()=>"Unable to read response body");throw new Error(`Streaming request failed (${y.status}): ${P.slice(0,300)}`)}g=y.body.getReader();const v=new TextDecoder;let k="",S="",x=!1;const T=P=>{const _=P.indexOf(` +What would you like to learn about?`}const MR=()=>{const e=h.useContext(Lh);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},V_=({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 un(),P=await T.getUserChatSessions(t.uid),_=await Promise.all(P.map(async w=>{const A=(await T.getSessionMessages(w.id,t.uid)).map(B=>({id:B.id,sender:B.role==="user"?"user":"ai",text:B.role==="assistant"?vt(B.content):B.content,timestamp:B.timestamp instanceof Date?B.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):new Date(B.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}));return{id:w.id,title:w.title,date:w.updatedAt instanceof Date?w.updatedAt.toLocaleDateString():new Date(w.updatedAt).toLocaleDateString(),messageCount:A.length,preview:A.length>0&&Io(A[A.length-1].text)||"No messages yet",topics:[],messages:A,createdAt:w.createdAt instanceof Date?w.createdAt:new Date(w.createdAt),updatedAt:w.updatedAt instanceof Date?w.updatedAt:new Date(w.updatedAt)}}));s(_)}catch(T){console.error("Error loading chat sessions:",T)}finally{l(!0)}})()},[t]);const p=x=>{if(x.length===0)return"New Chat";const T=x.find(w=>w.sender==="user")?.text||"",P=T.toLowerCase();if(P.includes("quadratic")||P.includes("ax² + bx + c"))return"Quadratic Equations Help";if(P.includes("derivative")||P.includes("calculus"))return"Derivatives & Calculus";if(P.includes("pythagor")||P.includes("right triangle"))return"Pythagorean Theorem";if(P.includes("trig")||P.includes("sin")||P.includes("cos"))return"Trigonometry Help";if(P.includes("area")||P.includes("perimeter"))return"Geometry - Area & Perimeter";if(P.includes("algebra")||P.includes("solve")&&P.includes("x"))return"Algebra Problem Solving";if(P.includes("factor"))return"Factoring Practice";if(P.includes("graph")||P.includes("plot"))return"Graphing Functions";if(P.includes("matrix")||P.includes("matrices"))return"Matrix Operations";if(P.includes("integral")||P.includes("integrate"))return"Integration Problems";if(P.includes("limit"))return"Limits in Calculus";if(P.includes("statistic")||P.includes("probability"))return"Statistics & Probability";const _=T.slice(0,40);return _.length{const T=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),P=new Date,_={id:T,title:x?p([x]):"New Chat",date:"Just now",messageCount:x?1:0,preview:x&&Io(x.text)||"Start a new conversation...",topics:[],messages:x?[x]:[],createdAt:P,updatedAt:P};if(s(w=>[_,...w]),t){const w=x?p([x]):"New Chat",R=un().then(async A=>{const B=await A.createChatSession(t.uid,w);return oe(async()=>{const{logChatSession:F}=await import("./trackingService-BGfVSr6K.js");return{logChatSession:F}},__vite__mapDeps([12,1,2,3,4,5,6,7,8,9,10])).then(({logChatSession:F})=>F(t.uid,B.id,x?1:0).catch(()=>{})),x&&await A.addMessageToSession(B.id,x.sender==="user"?"user":"assistant",x.text),B.id}).catch(A=>(console.error("Error creating Firebase session:",A),T));f.current.set(T,R)}return T},[t]),g=h.useCallback((x,T)=>{s(_=>_.map(w=>{if(w.id===x){const R=[...w.messages,T];return{...w,messages:R,messageCount:R.length,preview:Io(T.text)||w.preview,updatedAt:new Date,title:R.length===2?p(R):w.title}}return w}));const P=async _=>{const w=f.current.get(_);return w?await w:_};P(x).then(async _=>{await(await un()).addMessageToSession(_,T.sender==="user"?"user":"assistant",T.text)}).catch(_=>console.error("Error persisting message:",_)),s(_=>{const w=_.find(R=>R.id===x);if(w&&w.messages.length===2){const R=p(w.messages);P(x).then(async A=>{await(await un()).updateSessionTitle(A,R)}).catch(A=>console.error("Error updating title:",A))}return _})},[]),y=h.useCallback(async(x,T)=>{const P=T.trim(),_={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString(),sender:"user",text:P,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,_),u(x),a(!0);try{let w=null,R=null;const A=n.find(Z=>Z.id===x),F=[...A?.messages||[],_].map(Z=>({role:Z.sender==="user"?"user":"assistant",content:Z.text})),H=zh(P)?D_(F):null,se=H?O_(H):P,te=H??P,V=P_(P)?__({userId:t?.uid||"anonymous",prompt:P,history:F}):null,ie=Z=>{if(!V)return;const O=vt(Z).trim();O&&C_(V,O)},re=Dh(P,{history:F});if(re){const Z={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:re,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,Z);return}if(V){const Z=E_(V);if(Z){const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:Z,timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,O);return}}try{const Z=await ou();w=Z.apiService,R=Z.ApiTimeoutError}catch(Z){console.error("Failed to load API service for chat:",Z);const O={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:Xs(te),timestamp:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};g(x,O);return}const ue=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});let D="",he=null;const st=$_(P),X=F_(P),U=L_(P),G=X||!!U,J={sessionId:x,...U?{expectedEndMarker:U,completionMode:"marker"}:{}},we=Z=>Di(P,Z,U,X),ae=Z=>{Z.trim()&&s(O=>O.map(ee=>{if(ee.id!==x)return ee;if(!he){he=`stream-${typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Date.now().toString()}-${Math.random().toString(36).slice(2,8)}`;const ge={id:he,sender:"ai",text:Z,timestamp:ue},K=[...ee.messages,ge];return{...ee,messages:K,messageCount:K.length,updatedAt:new Date}}return{...ee,messages:ee.messages.map(ge=>ge.id===he?{...ge,text:Z}:ge),updatedAt:new Date}}))},le=()=>{if(!he)return;const Z=he;s(O=>O.map(ee=>{if(ee.id!==x)return ee;const ge=ee.messages.filter(K=>K.id!==Z);return{...ee,messages:ge,messageCount:ge.length,updatedAt:new Date}}))};try{const{response:Z}=await w.chat(se,F,K=>{D+=K,st&&ae(JP(D))},J);let O=vt(Z||D).trim();if(G&&O&&we(O)){try{const K=await w.chatSafe(iu(P,O,U),F,J),Ye=vt(K.data.response).trim();O=Qs(O,Ye)}catch(K){console.warn("Streaming completion repair failed:",K)}if(G&&O&&we(O))try{const K=await w.chatSafe(au(P,O,U),F,J),Ye=vt(K.data.response).trim();O=Qs(O,Ye)}catch(K){console.warn("Streaming plain continuation repair failed:",K)}if(G&&O&&we(O))try{const K=await w.chatSafe(cu(P,U),F,J),Ye=vt(K.data.response).trim();Ye&&(O=lu(P,O,Ye,U,X))}catch(K){console.warn("Streaming full completion repair failed:",K)}}const ee=we(O);(!O||ee&&!G)&&(O=Xs(te,F)),ie(O),he&&le();const ge={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ue};g(x,ge)}catch(Z){R&&Z instanceof R?console.warn(`Streaming timed out after ${Z.timeoutMs}ms, falling back to non-streaming chat.`,Z):console.warn("Streaming failed, falling back to non-streaming chat:",Z),he&&le();let O="";try{const K=w??(await ou()).apiService,{data:Ye}=await K.chatSafe(se,F,J);if(O=vt(Ye.response).trim(),G&&O&&we(O))try{const Le=await K.chatSafe(iu(P,O,U),F,J),Je=vt(Le.data.response).trim();O=Qs(O,Je)}catch(Le){console.warn("Non-stream completion repair failed:",Le)}if(G&&O&&we(O))try{const Le=await K.chatSafe(au(P,O,U),F,J),Je=vt(Le.data.response).trim();O=Qs(O,Je)}catch(Le){console.warn("Non-stream plain continuation repair failed:",Le)}if(G&&O&&we(O))try{const Le=await K.chatSafe(cu(P,U),F,J),Je=vt(Le.data.response).trim();Je&&(O=lu(P,O,Je,U,X))}catch(Le){console.warn("Non-stream full completion repair failed:",Le)}}catch(K){console.warn("Chat request failed, using local fallback response:",K),O=Xs(te,F)}const ee=we(O);(!O||ee&&!G)&&(O=Xs(te,F)),ie(O);const ge={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Date.now()+1).toString(),sender:"ai",text:O,timestamp:ue};g(x,ge)}if(A&&A.messages.length===1){const Z=n.find(O=>O.id===x);if(Z&&Z.messages.length>1){const O=p(Z.messages),ee=f.current.get(x);(ee||Promise.resolve(x)).then(async K=>{await(await un()).updateSessionTitle(K,O)}).catch(K=>console.error("Error updating title:",K))}}}finally{a(!1),u(null)}},[n,g,t]),v=h.useCallback((x,T)=>{s(w=>w.map(R=>R.id===x?{...R,title:T}:R));const P=f.current.get(x);(P||Promise.resolve(x)).then(async w=>{await(await un()).updateSessionTitle(w,T)}).catch(w=>console.error("Error updating session title:",w))},[]),k=h.useCallback(x=>{s(_=>_.filter(w=>w.id!==x)),r===x&&o(null);const T=f.current.get(x);(T||Promise.resolve(x)).then(async _=>{await(await un()).deleteSession(_)}).catch(_=>console.error("Error deleting session:",_)),f.current.delete(x)},[r]),S=h.useCallback(()=>n.find(x=>x.id===r)||null,[n,r]);return b.jsx(Lh.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})},B_=[{id:"first_lesson",title:"First Steps",description:"Complete your first lesson",icon:Mo,iconColor:"text-yellow-500",xpReward:50,condition:"lesson_complete",threshold:1,category:"learning"},{id:"lesson_10",title:"Dedicated Learner",description:"Complete 10 lessons",icon:Mo,iconColor:"text-blue-500",xpReward:200,condition:"lesson_complete",threshold:10,category:"learning"},{id:"lesson_50",title:"Knowledge Seeker",description:"Complete 50 lessons",icon:Rl,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:Ol,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:Il,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:Pi,iconColor:"text-orange-500",xpReward:100,condition:"speed_quiz",category:"learning"},{id:"quiz_10",title:"Quiz Enthusiast",description:"Complete 10 quizzes",icon:bx,iconColor:"text-cyan-500",xpReward:200,condition:"quiz_complete",threshold:10,category:"learning"},{id:"quiz_50",title:"Quiz Champion",description:"Complete 50 quizzes",icon:Mo,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:Vx,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:mr,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:Gs,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:Gs,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:Gs,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:Ml,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:Pi,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:Nx,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:pr,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:Ml,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:Ux,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:Gs,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:mr,iconColor:"text-orange-500",xpReward:500,condition:"mastery_10",threshold:10,category:"mastery"},{id:"mastery_level",title:"Rising Star",description:"Reach level 5",icon:pr,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:Dl,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:Rl,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:Ex,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:Il,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:pr,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:Cl,iconColor:"text-amber-400",xpReward:1e3,condition:"social_xp",category:"mastery"},{id:"explore_profile",title:"Identity Set",description:"Complete your user profile",icon:Xx,iconColor:"text-blue-400",xpReward:50,condition:"explore_profile_complete",category:"exploration"},{id:"explore_first_friend",title:"Socialite",description:"Add your first friend",icon:Ll,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:Al,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:Jx,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:kx,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:Rx,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:Dl,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:Ll,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:Cl,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:Ol,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:mr,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:Al,iconColor:"text-violet-400",xpReward:200,condition:"social_daily_return",threshold:7,category:"social"}];new Map(B_.map(e=>[e.id,e]));const Lo=async(e,t,n,s)=>{try{const r=q(N,"users",e),o=await ve(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 x=0;for(let T=1;T<=m;T++)x+=Math.floor(100*Math.pow(1.5,T-1));if(f>=x)m++,y=!0;else break}const v={currentXP:l,totalXP:f,level:m,updatedAt:ce()};u!==1&&(v.xpMultiplier=1),await dt(r,v);const k=q(Xe(N,"xpActivities"));return await $e(k,{activityId:k.id,userId:e,type:n,xpEarned:t,description:s,timestamp:ce()}),{newLevel:m,leveledUp:y,xp:l,addedXp:t}}catch(r){throw console.error("Error awarding XP:",r),r}},IR=async(e,t=!1,n="all",s=10)=>{try{const r=Ot(Xe(N,"leaderboard"),vn("totalXP","desc"),ks(s)),o=await zn(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),[]}},DR=(e,t,n=!1,s="all",r=10)=>{const o=Ot(Xe(N,"leaderboard"),vn("totalXP","desc"),ks(r));return Yt(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([])})},OR=async e=>{try{const t=await ve(q(N,"achievements",e));return t.exists()?t.data().achievements||[]:[]}catch(t){return console.error("Error getting user achievements:",t),[]}},LR=async(e,t,n)=>{try{const s=q(N,"users",e),r=await ve(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=q(N,"users",e),s=await ve(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:Lu(t),updatedAt:ce()}),{success:!0,message:"Avatar item unlocked!"})}catch(n){return console.error("Error unlocking avatar item:",n),{success:!1,message:"Failed to unlock item"}}},Xr=3e4,jh=3,Nh=1e3;class Dt 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 bn 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 zr extends Error{endpoint;originalError;constructor(t,n){super(`Network error on ${t}: ${n.message}`),this.name="ApiNetworkError",this.endpoint=t,this.originalError=n}}class je extends Error{endpoint;details;constructor(t,n){super(`Validation error before calling ${t}: ${n}`),this.name="ApiValidationError",this.endpoint=t,this.details=n}}const U_=new Set([408,429,500,502,503,504]);function q_(e){return U_.has(e)}function ja(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 Rt(e,t,n,s){ja({timestamp:new Date().toISOString(),level:"info",endpoint:e,method:t,message:n,details:s})}function Oi(e,t,n,s){ja({timestamp:new Date().toISOString(),level:"warn",endpoint:e,method:t,message:n,details:s})}function Ne(e,t,n,s){ja({timestamp:new Date().toISOString(),level:"error",endpoint:e,method:t,message:n,details:s})}function G_(e,t,n=Xr){const s=new AbortController,r=setTimeout(()=>s.abort(),n);return{promise:fetch(e,{...t,signal:s.signal}).finally(()=>clearTimeout(r)),abort:()=>s.abort()}}let W_=e=>new Promise(t=>setTimeout(t,e));function uu(e){return W_(e)}function H_(e,t=Nh){const n=t*Math.pow(2,e),s=Math.random()*t;return Math.min(n+s,3e4)}async function du(e,t={},n={}){const{maxRetries:s=jh,timeoutMs:r=Xr,baseBackoffMs:o=Nh}=n,i=(t.method??"GET").toUpperCase();let a;for(let c=0;c<=s;c++){const u=Date.now();try{c>0&&Rt(e,i,`Retry attempt ${c}/${s}`);const{promise:d}=G_(e,t,r),l=await d,f=Date.now()-u;if(l.ok)return Rt(e,i,`${l.status} in ${f}ms`,{attempt:c}),await l.json();const p=await l.text().catch(()=>"Unable to read response body"),m=q_(l.status),g=new Dt({status:l.status,statusText:l.statusText,endpoint:e,responseBody:p,retryable:m,requestId:l.headers.get("x-request-id")??void 0});if(Ne(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){Oi(e,i,`Rate limited. Waiting ${v}s (Retry-After header)`),await uu(v*1e3),a=g;continue}}}a=g}catch(d){const l=Date.now()-u;if(d instanceof Dt&&!d.retryable)throw d;if(d instanceof DOMException&&d.name==="AbortError"){const f=new bn(e,r);Ne(e,i,`Timeout after ${l}ms`,{attempt:c,timeoutMs:r}),a=f}else if(d instanceof TypeError&&d.message.includes("fetch")){const f=new zr(e,d);Ne(e,i,`Network error after ${l}ms: ${d.message}`,{attempt:c}),a=f}else d instanceof Dt?a=d:(a=d instanceof Error?d:new Error(String(d)),Ne(e,i,`Unexpected error: ${a.message}`,{attempt:c}))}if(cs==null||s==="").map(([s])=>s);if(n.length>0)throw new je(e,`Missing required fields: ${n.join(", ")}`)}function Re(e,t,n,s,r){if(typeof n!="number"||isNaN(n)||nr)throw new je(e,`${t} must be a number between ${s} and ${r}, got ${n}`)}function Z_(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 K_=e=>{switch(e){case"success":return Y_;case"info":return eE;case"warning":return J_;case"error":return tE;default:return null}},Q_=Array(12).fill(0),X_=({visible:e,className:t})=>I.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},I.createElement("div",{className:"sonner-spinner"},Q_.map((n,s)=>I.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),Y_=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"})),J_=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"})),eE=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"})),tE=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"})),nE=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"})),sE=()=>{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 Li=1;class rE{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:Li++,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(iE(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||Li++;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 nt=new rE,oE=(e,t)=>{const n=t?.id||Li++;return nt.addToast({title:e,...t,id:n}),n},iE=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",aE=oE,cE=()=>nt.toasts,lE=()=>nt.getActiveToasts(),ct=Object.assign(aE,{success:nt.success,info:nt.info,warning:nt.warning,error:nt.error,custom:nt.custom,message:nt.message,promise:nt.promise,dismiss:nt.dismiss,loading:nt.loading},{getHistory:cE,getToasts:lE});Z_("[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 Ys(e){return e.label!==void 0}const uE=3,dE="24px",fE="16px",fu=4e3,hE=356,pE=14,mE=45,gE=200;function _t(...e){return e.filter(Boolean).join(" ")}function yE(e){const[t,n]=e.split("-"),s=[];return t&&s.push(t),n&&s.push(n),s}const bE=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:x,defaultRichColors:T,closeButton:P,style:_,cancelButtonStyle:w,actionButtonStyle:R,className:A="",descriptionClassName:B="",duration:F,position:H,gap:se,expandByDefault:te,classNames:V,icons:ie,closeButtonAriaLabel:re="Close toast"}=e,[ue,D]=I.useState(null),[he,st]=I.useState(null),[X,U]=I.useState(!1),[G,J]=I.useState(!1),[we,ae]=I.useState(!1),[le,Z]=I.useState(!1),[O,ee]=I.useState(!1),[ge,K]=I.useState(0),[Ye,Le]=I.useState(0),Je=I.useRef(l.duration||F||fu),on=I.useRef(null),pt=I.useRef(null),Ds=v===0,Os=v+1<=g,Ge=l.type,it=l.dismissible!==!1,$t=l.className||"",eo=l.descriptionClassName||"",Ft=I.useMemo(()=>y.findIndex(Y=>Y.toastId===l.id)||0,[y,l.id]),an=I.useMemo(()=>{var Y;return(Y=l.closeButton)!=null?Y:P},[l.closeButton,P]),Wn=I.useMemo(()=>l.duration||F||fu,[l.duration,F]),Tn=I.useRef(0),rt=I.useRef(0),Wt=I.useRef(0),mt=I.useRef(null),[to,Hn]=H.split("-"),Ls=I.useMemo(()=>y.reduce((Y,Ee,ze)=>ze>=Ft?Y:Y+Ee.height,0),[y,Ft]),Zn=sE(),no=l.invert||d,Kn=Ge==="loading";rt.current=I.useMemo(()=>Ft*se+Ls,[Ft,Ls]),I.useEffect(()=>{Je.current=Wn},[Wn]),I.useEffect(()=>{U(!0)},[]),I.useEffect(()=>{const Y=pt.current;if(Y){const Ee=Y.getBoundingClientRect().height;return Le(Ee),m(ze=>[{toastId:l.id,height:Ee,position:l.position},...ze]),()=>m(ze=>ze.filter(Te=>Te.toastId!==l.id))}},[m,l.id]),I.useLayoutEffect(()=>{if(!X)return;const Y=pt.current,Ee=Y.style.height;Y.style.height="auto";const ze=Y.getBoundingClientRect().height;Y.style.height=Ee,Le(ze),m(Te=>Te.find(_e=>_e.toastId===l.id)?Te.map(_e=>_e.toastId===l.id?{..._e,height:ze}:_e):[{toastId:l.id,height:ze,position:l.position},...Te])},[X,l.title,l.description,m,l.id,l.jsx,l.action,l.cancel]);const at=I.useCallback(()=>{J(!0),K(rt.current),m(Y=>Y.filter(Ee=>Ee.toastId!==l.id)),setTimeout(()=>{x(l)},gE)},[l,x,m,rt]);I.useEffect(()=>{if(l.promise&&Ge==="loading"||l.duration===1/0||l.type==="loading")return;let Y;return S||p||Zn?(()=>{if(Wt.current{Je.current!==1/0&&(Tn.current=new Date().getTime(),Y=setTimeout(()=>{l.onAutoClose==null||l.onAutoClose.call(l,l),at()},Je.current))})(),()=>clearTimeout(Y)},[S,p,l,Ge,Zn,at]),I.useEffect(()=>{l.delete&&(at(),l.onDismiss==null||l.onDismiss.call(l,l))},[at,l.delete]);function Qn(){var Y;if(ie?.loading){var Ee;return I.createElement("div",{className:_t(V?.loader,l==null||(Ee=l.classNames)==null?void 0:Ee.loader,"sonner-loader"),"data-visible":Ge==="loading"},ie.loading)}return I.createElement(X_,{className:_t(V?.loader,l==null||(Y=l.classNames)==null?void 0:Y.loader),visible:Ge==="loading"})}const so=l.icon||ie?.[Ge]||K_(Ge);var Xn,cn;return I.createElement("li",{tabIndex:0,ref:pt,className:_t(A,$t,V?.toast,l==null||(t=l.classNames)==null?void 0:t.toast,V?.default,V?.[Ge],l==null||(n=l.classNames)==null?void 0:n[Ge]),"data-sonner-toast":"","data-rich-colors":(Xn=l.richColors)!=null?Xn:T,"data-styled":!(l.jsx||l.unstyled||f),"data-mounted":X,"data-promise":!!l.promise,"data-swiped":O,"data-removed":G,"data-visible":Os,"data-y-position":to,"data-x-position":Hn,"data-index":v,"data-front":Ds,"data-swiping":we,"data-dismissible":it,"data-type":Ge,"data-invert":no,"data-swipe-out":le,"data-swipe-direction":he,"data-expanded":!!(S||te&&X),"data-testid":l.testId,style:{"--index":v,"--toasts-before":v,"--z-index":k.length-v,"--offset":`${G?ge:rt.current}px`,"--initial-height":te?"auto":`${Ye}px`,..._,...l.style},onDragEnd:()=>{ae(!1),D(null),mt.current=null},onPointerDown:Y=>{Y.button!==2&&(Kn||!it||(on.current=new Date,K(rt.current),Y.target.setPointerCapture(Y.pointerId),Y.target.tagName!=="BUTTON"&&(ae(!0),mt.current={x:Y.clientX,y:Y.clientY})))},onPointerUp:()=>{var Y,Ee,ze;if(le||!it)return;mt.current=null;const Te=Number(((Y=pt.current)==null?void 0:Y.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Pt=Number(((Ee=pt.current)==null?void 0:Ee.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),_e=new Date().getTime()-((ze=on.current)==null?void 0:ze.getTime()),Fe=ue==="x"?Te:Pt,Pn=Math.abs(Fe)/_e;if(Math.abs(Fe)>=mE||Pn>.11){K(rt.current),l.onDismiss==null||l.onDismiss.call(l,l),st(ue==="x"?Te>0?"right":"left":Pt>0?"down":"up"),at(),Z(!0);return}else{var et,Ve;(et=pt.current)==null||et.style.setProperty("--swipe-amount-x","0px"),(Ve=pt.current)==null||Ve.style.setProperty("--swipe-amount-y","0px")}ee(!1),ae(!1),D(null)},onPointerMove:Y=>{var Ee,ze,Te;if(!mt.current||!it||((Ee=window.getSelection())==null?void 0:Ee.toString().length)>0)return;const _e=Y.clientY-mt.current.y,Fe=Y.clientX-mt.current.x;var Pn;const et=(Pn=e.swipeDirections)!=null?Pn:yE(H);!ue&&(Math.abs(Fe)>1||Math.abs(_e)>1)&&D(Math.abs(Fe)>Math.abs(_e)?"x":"y");let Ve={x:0,y:0};const Yn=gt=>1/(1.5+Math.abs(gt)/20);if(ue==="y"){if(et.includes("top")||et.includes("bottom"))if(et.includes("top")&&_e<0||et.includes("bottom")&&_e>0)Ve.y=_e;else{const gt=_e*Yn(_e);Ve.y=Math.abs(gt)0)Ve.x=Fe;else{const gt=Fe*Yn(Fe);Ve.x=Math.abs(gt)0||Math.abs(Ve.y)>0)&&ee(!0),(ze=pt.current)==null||ze.style.setProperty("--swipe-amount-x",`${Ve.x}px`),(Te=pt.current)==null||Te.style.setProperty("--swipe-amount-y",`${Ve.y}px`)}},an&&!l.jsx&&Ge!=="loading"?I.createElement("button",{"aria-label":re,"data-disabled":Kn,"data-close-button":!0,onClick:Kn||!it?()=>{}:()=>{at(),l.onDismiss==null||l.onDismiss.call(l,l)},className:_t(V?.closeButton,l==null||(s=l.classNames)==null?void 0:s.closeButton)},(cn=ie?.close)!=null?cn:nE):null,(Ge||l.icon||l.promise)&&l.icon!==null&&(ie?.[Ge]!==null||l.icon)?I.createElement("div",{"data-icon":"",className:_t(V?.icon,l==null||(r=l.classNames)==null?void 0:r.icon)},l.promise||l.type==="loading"&&!l.icon?l.icon||Qn():null,l.type!=="loading"?so:null):null,I.createElement("div",{"data-content":"",className:_t(V?.content,l==null||(o=l.classNames)==null?void 0:o.content)},I.createElement("div",{"data-title":"",className:_t(V?.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(B,eo,V?.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&&Ys(l.cancel)?I.createElement("button",{"data-button":!0,"data-cancel":!0,style:l.cancelButtonStyle||w,onClick:Y=>{Ys(l.cancel)&&it&&(l.cancel.onClick==null||l.cancel.onClick.call(l.cancel,Y),at())},className:_t(V?.cancelButton,l==null||(c=l.classNames)==null?void 0:c.cancelButton)},l.cancel.label):null,I.isValidElement(l.action)?l.action:l.action&&Ys(l.action)?I.createElement("button",{"data-button":!0,"data-action":!0,style:l.actionButtonStyle||R,onClick:Y=>{Ys(l.action)&&(l.action.onClick==null||l.action.onClick.call(l.action,Y),!Y.defaultPrevented&&at())},className:_t(V?.actionButton,l==null||(u=l.classNames)==null?void 0:u.actionButton)},l.action.label):null)};function hu(){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 vE(e,t){const n={};return[e,t].forEach((s,r)=>{const o=r===1,i=o?"--mobile-offset":"--offset",a=o?fE:dE;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 zo=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=uE,toastOptions:v,dir:k=hu(),gap:S=pE,icons:x,containerAriaLabel:T="Notifications"}=t,[P,_]=I.useState([]),w=I.useMemo(()=>s?P.filter(X=>X.toasterId===s):P.filter(X=>!X.toasterId),[P,s]),R=I.useMemo(()=>Array.from(new Set([o].concat(w.filter(X=>X.position).map(X=>X.position)))),[w,o]),[A,B]=I.useState([]),[F,H]=I.useState(!1),[se,te]=I.useState(!1),[V,ie]=I.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),re=I.useRef(null),ue=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),D=I.useRef(null),he=I.useRef(!1),st=I.useCallback(X=>{_(U=>{var G;return(G=U.find(J=>J.id===X.id))!=null&&G.delete||nt.dismiss(X.id),U.filter(({id:J})=>J!==X.id)})},[]);return I.useEffect(()=>nt.subscribe(X=>{if(X.dismiss){requestAnimationFrame(()=>{_(U=>U.map(G=>G.id===X.id?{...G,delete:!0}:G))});return}setTimeout(()=>{Tp.flushSync(()=>{_(U=>{const G=U.findIndex(J=>J.id===X.id);return G!==-1?[...U.slice(0,G),{...U[G],...X},...U.slice(G+1)]:[X,...U]})})})}),[P]),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:U})=>{ie(U?"dark":"light")})}catch{X.addListener(({matches:G})=>{try{ie(G?"dark":"light")}catch(J){console.error(J)}})}},[f]),I.useEffect(()=>{P.length<=1&&H(!1)},[P]),I.useEffect(()=>{const X=U=>{var G;if(i.every(ae=>U[ae]||U.code===ae)){var we;H(!0),(we=re.current)==null||we.focus()}U.code==="Escape"&&(document.activeElement===re.current||(G=re.current)!=null&&G.contains(document.activeElement))&&H(!1)};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[i]),I.useEffect(()=>{if(re.current)return()=>{D.current&&(D.current.focus({preventScroll:!0}),D.current=null,he.current=!1)}},[re.current]),I.createElement("section",{ref:n,"aria-label":`${T} ${ue}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},R.map((X,U)=>{var G;const[J,we]=X.split("-");return w.length?I.createElement("ol",{key:X,dir:k==="auto"?hu():k,tabIndex:-1,ref:re,className:u,"data-sonner-toaster":!0,"data-sonner-theme":V,"data-y-position":J,"data-x-position":we,style:{"--front-toast-height":`${((G=A[0])==null?void 0:G.height)||0}px`,"--width":`${hE}px`,"--gap":`${S}px`,...g,...vE(d,l)},onBlur:ae=>{he.current&&!ae.currentTarget.contains(ae.relatedTarget)&&(he.current=!1,D.current&&(D.current.focus({preventScroll:!0}),D.current=null))},onFocus:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||he.current||(he.current=!0,D.current=ae.relatedTarget)},onMouseEnter:()=>H(!0),onMouseMove:()=>H(!0),onMouseLeave:()=>{se||H(!1)},onDragEnd:()=>H(!1),onPointerDown:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||te(!0)},onPointerUp:()=>te(!1)},w.filter(ae=>!ae.position&&U===0||ae.position===X).map((ae,le)=>{var Z,O;return I.createElement(bE,{key:ae.id,icons:x,index:le,toast:ae,defaultRichColors:p,duration:(Z=v?.duration)!=null?Z:m,className:v?.className,descriptionClassName:v?.descriptionClassName,invert:r,visibleToasts:y,closeButton:(O=v?.closeButton)!=null?O:c,interacting:se,position:X,style:v?.style,unstyled:v?.unstyled,classNames:v?.classNames,cancelButtonStyle:v?.cancelButtonStyle,actionButtonStyle:v?.actionButtonStyle,closeButtonAriaLabel:v?.closeButtonAriaLabel,removeToast:st,toasts:w.filter(ee=>ee.position==ae.position),heights:A.filter(ee=>ee.position==ae.position),setHeights:B,expandByDefault:a,gap:S,expanded:F,swipeDirections:t.swipeDirections})})):null}))});function wE(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 xE(e,t){const n=ye.currentUser;if(n)try{const s=q(N,"_analytics/rateLimitHits",n.uid);await $e(s,{uid:n.uid,endpoint:e,retryAfter:t,timestamp:ce()},{merge:!0})}catch(s){console.warn("Failed to log rate limit hit:",s)}}const jo=new Map;function SE(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=jo.get(e);r&&clearInterval(r.timerId);const o=window.setInterval(()=>{Math.ceil((s-Date.now())/1e3)<=0&&(clearInterval(o),jo.delete(e),ct.dismiss(n))},1e3);jo.set(e,{endpoint:e,endsAt:s,timerId:o})}async function kE(e,t){if(e.status!==429)return!1;const n=wE(e);return await xE(t,n),SE(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",Yr=(e,t)=>t,$h=(e,t)=>t,No=Yr(void 0,!0),pu=Yr(void 0,!0),mu=Yr(void 0,!0),gu=Yr(void 0,!0),yu=$h(void 0,9e4),$o=$h(void 0,9e5);let Fo=!0,bu=0;const TE=6e4;async function PE(){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 _E(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 EE(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 CE(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 Ct={maxRetries:jh,timeoutMs:Xr,baseBackoffMs:1e3},Qt={...Ct,timeoutMs:6e4},AE={...Qt,maxRetries:1,timeoutMs:45e3,baseBackoffMs:750},RE={...Ct,maxRetries:1,timeoutMs:2e4,baseBackoffMs:500},rs={maxRetries:2,timeoutMs:12e4,baseBackoffMs:2e3},ME={maxRetries:0,timeoutMs:8e3,baseBackoffMs:500};let Js=null;async function IE(){return Js||(Js=(async()=>{try{Rt("/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?(Rt("/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}})(),Js)}async function z(e,t,n=Ct){const s=`${Ss}${e}`,r=t?.method??"GET";Rt(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){Ne(e,r,"Failed to acquire Firebase ID token",d)}return{...t,headers:c}};let i=await o(!1);try{const a=await du(s,i,n);return Rt(e,r,"Request succeeded"),a}catch(a){if(a instanceof Dt&&a.status===401&&ye.currentUser)try{Rt(e,r,"401 received, refreshing Firebase token and retrying once"),i=await o(!0);const c=await du(s,i,n);return Rt(e,r,"Request succeeded after token refresh"),c}catch(c){throw c instanceof Dt?Ne(e,r,`HTTP ${c.status}: ${c.responseBody.slice(0,300)}`):c instanceof bn?Ne(e,r,`Timeout after ${c.timeoutMs}ms`):c instanceof zr?Ne(e,r,`Network error: ${c.originalError.message}`):Ne(e,r,`Unexpected: ${c instanceof Error?c.message:String(c)}`),c}throw a instanceof Dt?(Ne(e,r,`HTTP ${a.status}: ${a.responseBody.slice(0,300)}`),a.status===429&&await kE(new Response(a.responseBody,{status:429,headers:{"retry-after":"60"}}),e)):a instanceof bn?Ne(e,r,`Timeout after ${a.timeoutMs}ms`):a instanceof zr?Ne(e,r,`Network error: ${a.originalError.message}`):Ne(e,r,`Unexpected: ${a instanceof Error?a.message:String(a)}`),a}}async function vu(e,t,n=Xr){const s=`${Ss}${e}`,r=t?.method??"GET";Rt(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){Ne(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 Dt({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 Dt&&i.status===401&&ye.currentUser)return Rt(e,r,"401 received for blob request, refreshing Firebase token and retrying once"),o(!0);throw i}}const DE={response:"Sorry, the AI tutor is temporarily unavailable. Please try again in a moment."},OE={riskLevel:"Medium",confidence:0,analysis:{labels:[],scores:[]},risk_level:"medium",risk_score:0,top_factors:["Fallback risk response due to temporary service unavailability"]},LE={learningPath:"Unable to generate a learning path right now. Please try again later."},zE={insight:"Daily insight is temporarily unavailable. Please refresh later."},jE={expression:"",result:"Error: calculation service unavailable",steps:[],simplified:null,latex:null};function NE(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.riskLevel=="string"&&typeof t.confidence=="number"}function wu(e){if(typeof e!="object"||e===null)return!1;const t=e;return Array.isArray(t.questions)&&typeof t.totalPoints=="number"}const $E=e=>new Promise(t=>setTimeout(t,e));function FE(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 wt={getImportGroundedRolloutFlags(){return{quizEnabled:No,lessonEnabled:pu,feedbackEnabled:mu}},async reportImportGroundedFeedback(e){return mu?z("/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 z("/health",void 0,{...Ct,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"),yu)};u=setTimeout(()=>d("total"),$o);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){Ne("/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 P=await y.text().catch(()=>"Unable to read response body");throw new Error(`Streaming request failed (${y.status}): ${P.slice(0,300)}`)}g=y.body.getReader();const v=new TextDecoder;let k="",S="",x=!1;const T=P=>{const _=P.indexOf(` `),w=P.indexOf(`\r \r `);return _===-1&&w===-1?null:_===-1?{index:w,length:4}:w===-1?{index:_,length:2}:_wt.chat(e,t,void 0,n),DE,"chat")},async predictRisk(e){Se("/api/predict-risk",{engagementScore:e.engagementScore,avgQuizScore:e.avgQuizScore,attendance:e.attendance,assignmentCompletion:e.assignmentCompletion}),Re("/api/predict-risk","engagementScore",e.engagementScore,0,100),Re("/api/predict-risk","avgQuizScore",e.avgQuizScore,0,100),Re("/api/predict-risk","attendance",e.attendance,0,100),Re("/api/predict-risk","assignmentCompletion",e.assignmentCompletion,0,100);const t=await z("/api/predict-risk",{method:"POST",body:JSON.stringify(e)});if(!NE(t))throw Ne("/api/predict-risk","POST","Invalid response shape",t),new Error("Invalid risk prediction response from server");return t},async predictRiskSafe(e){return ss(()=>wt.predictRisk(e),OE,"predictRisk")},async predictRiskBatch(e){if(!Array.isArray(e)||e.length===0)throw new je("/api/predict-risk/batch","students array must not be empty");return z("/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 je("/api/learning-path","weaknesses must be a non-empty array");return z("/api/learning-path",{method:"POST",body:JSON.stringify(e)},Qt)},async getLearningPathSafe(e){return ss(()=>wt.getLearningPath(e),LE,"getLearningPath")},async getDailyInsight(e,t){if(!Array.isArray(e.students)||e.students.length===0)throw new je("/api/analytics/daily-insight","students array must not be empty");return z("/api/analytics/daily-insight",{method:"POST",body:JSON.stringify(e),signal:t?.signal},Qt)},async getDailyInsightSafe(e){return ss(()=>wt.getDailyInsight(e),zE,"getDailyInsight")},async getImportedClassOverview(e){if(!e?.forceRefresh&&!Fo&&Date.now()!r||r.size===0))throw new je("/api/upload/class-records","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new je("/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"),z("/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 vu(`/api/templates/class-records${n?`?${n}`:""}`,{method:"GET"},3e4)},async uploadClassRecordTemplate(e,t){if(!e||e.size===0)throw new je("/api/class-records/upload","File must be non-empty");if(e.size>10*1024*1024)throw new je("/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),z("/api/class-records/upload",{method:"POST",body:n},rs)},async previewStudentAccountImport(e,t){if(!e||e.size===0)throw new je("/api/import/student-accounts/preview","A non-empty file is required");if(e.size>10*1024*1024)throw new je("/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),z("/api/import/student-accounts/preview",{method:"POST",body:n},rs)},async commitStudentAccountImport(e){return Se("/api/import/student-accounts/commit",{previewToken:e.previewToken}),z("/api/import/student-accounts/commit",{method:"POST",body:JSON.stringify(e)},Ct)},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 z("/api/teacher/create-student-account",{method:"POST",body:JSON.stringify(t)},Ct)},async getAdminUsers(e){const t=e?.page??1,n=e?.pageSize??25;Re("/api/admin/users","page",t,1,1e4),Re("/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()),z(`/api/admin/users?${s.toString()}`,{method:"GET"},RE)},async updateAdminUser(e,t){const n=e.trim();Se("/api/admin/users",{uid:n});const s=new URLSearchParams;return s.set("uid",n),z(`/api/admin/users?${s.toString()}`,{method:"PATCH",body:JSON.stringify(t)},Ct)},async bulkAdminUsers(e){return Se("/api/admin/users/bulk-action",{action:e.action}),z("/api/admin/users/bulk-action",{method:"POST",body:JSON.stringify(e)},Ct)},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 je("/api/admin/users","lrn is required for student accounts");return z("/api/admin/users",{method:"POST",body:JSON.stringify(e)},Ct)},async deleteAdminUser(e){const t=e.trim();Se("/api/admin/users",{uid:t});const n=new URLSearchParams;return n.set("uid",t),z(`/api/admin/users?${n.toString()}`,{method:"DELETE"},Ct)},async getRiskRefreshMonitor(e){const t=e?.limit??10;Re("/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),z(`/api/upload/class-records/risk-refresh/recent?${n.toString()}`)},async getImportGroundedTelemetrySummary(e){const t=e?.days??7,n=e?.limit??5e3;Re("/api/feedback/import-grounded/summary","days",t,1,30),Re("/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),z(`/api/feedback/import-grounded/summary?${s.toString()}`)},async getImportGroundedAccessAudit(e){const t=e?.days??7,n=e?.limit??200;Re("/api/import-grounded/access-audit","days",t,1,30),Re("/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),z(`/api/import-grounded/access-audit?${s.toString()}`)},async exportImportGroundedAccessAuditCsv(e){const t=e?.days??7,n=e?.limit??200;Re("/api/import-grounded/access-audit","days",t,1,30),Re("/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),vu(`/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 je("/api/upload/course-materials","At least one file is required");if(n.some(r=>!r||r.size===0))throw new je("/api/upload/course-materials","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new je("/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),z("/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),z("/api/teacher-materials/upload",{method:"POST",body:n},rs)},async getRecentCourseMaterials(e){const t=e?.limit??10;Re("/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),z(`/api/upload/course-materials/recent?${n.toString()}`)},async getCourseMaterialTopics(e){const t=e?.limit??20;Re("/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),z(`/api/course-materials/topics?${n.toString()}`)},async generateLessonPlan(e){Se("/api/lesson/generate",{gradeLevel:e.gradeLevel});const t={...e,preferImportedTopics:pu&&(e.preferImportedTopics??!0)};if(gu){const n=await wt.submitLessonPlanAsync(t),r=(await wt.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 z("/api/lesson/generate",{method:"POST",body:JSON.stringify(t)},Qt)},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 je("/api/quiz/generate","topics must be a non-empty array");const n={...e,preferImportedTopics:No&&(e.preferImportedTopics??!0)};if(gu){const r=await wt.submitQuizAsync(n);t?.onTaskCreated?.(r.taskId);const i=(await wt.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(!wu(i))throw new Error("Invalid quiz generation response from async task payload.");return i}const s=await z("/api/quiz/generate",{method:"POST",body:JSON.stringify(n)},Qt);if(!wu(s))throw Ne("/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:No&&(e.preferImportedTopics??!0)};return z("/api/quiz/preview",{method:"POST",body:JSON.stringify(t)},Qt)},async submitLessonPlanAsync(e){return z("/api/lesson/generate-async",{method:"POST",body:JSON.stringify(e)},Qt)},async submitQuizAsync(e){return z("/api/quiz/generate-async",{method:"POST",body:JSON.stringify(e)},Qt)},async getTaskStatus(e){return Se("/api/tasks/{taskId}",{taskId:e}),z(`/api/tasks/${encodeURIComponent(e)}`)},async listTasks(e){const t=new URLSearchParams;e?.limit!=null&&(Re("/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 z(`/api/tasks${n?`?${n}`:""}`)},async cancelTask(e){return Se("/api/tasks/{taskId}/cancel",{taskId:e}),z(`/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 wt.getTaskStatus(e);if(t?.onProgress?.(o),o.status==="completed")return o;if(o.status==="failed"||o.status==="cancelled")throw new Error(FE(o.error));await $E(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 z(`/api/quiz/topics${t}`)},async getStudentCompetency(e,t){return Se("/api/quiz/student-competency",{studentId:e}),z("/api/quiz/student-competency",{method:"POST",body:JSON.stringify({studentId:e,quizHistory:t})})},async evaluateExpression(e){return Se("/api/calculator/evaluate",{expression:e}),z("/api/calculator/evaluate",{method:"POST",body:JSON.stringify({expression:e})})},async evaluateExpressionSafe(e){return ss(()=>wt.evaluateExpression(e),{...jE,expression:e},"evaluateExpression")},async automationDiagnosticCompleted(e){return Se("/api/automation/diagnostic-completed",{lrn:e.lrn,results:e.results}),z("/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}),z("/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}),z("/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}),z("/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}),z("/api/automation/content-updated",{method:"POST",body:JSON.stringify(e)})},getInferenceMetrics:async()=>z("/api/ops/inference-metrics",{method:"GET"}),getModelConfig:async()=>z("/api/admin/model-config",{method:"GET"}),setModelProfile:async e=>z("/api/admin/model-config/profile",{method:"POST",body:JSON.stringify({profile:e})}),setModelOverride:async(e,t)=>z("/api/admin/model-config/override",{method:"POST",body:JSON.stringify({key:e,value:t})}),resetModelConfig:async()=>z("/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 z("/api/admin/reingest-pdf",{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({subjectId:e,storagePath:t})})},getRagHealth:async()=>z("/api/rag/health",{method:"GET"}),adminDeleteFile:async(e,t)=>z("/api/admin/delete-file",{method:"POST",body:JSON.stringify({fileId:e,collection:t})}),async generateInterventionPlan(e){return z("/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 z(`/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 z(`/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 z(`/api/class-records/${e}/students${s?`?${s}`:""}`,{method:"GET"})},async generateClassReport(e){return z(`/api/class-records/${e}/ai-report`,{method:"POST"})},async generateQuizFromModule(e){return z(`/api/teacher-materials/${e}/generate-quiz`,{method:"POST"})},async getStudentRecommendations(e){return z(`/api/student/${e}/recommendations`,{method:"GET"})}};async function VE(e,t,n,s){Se("/api/rag/lesson",{topic:e,subject:t,quarter:n}),Re("/api/rag/lesson","quarter",n,1,4);const r=await z("/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 BE(e,t,n,s){Se("/api/rag/generate-problem",{topic:e,subject:t,quarter:n,difficulty:s}),Re("/api/rag/generate-problem","quarter",n,1,4);const r=await z("/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 UE(e,t){return!Array.isArray(e)||e.length===0?"":(await z("/api/rag/analysis-context",{method:"POST",body:JSON.stringify({weakTopics:e,subject:t})})).curriculumContext||""}async function qE(e){const t=e?`?grade_level=${encodeURIComponent(e)}`:"";return z(`/api/curriculum/subjects${t}`)}async function GE(e){try{return await z(`/api/curriculum/subjects/${e}`)}catch{return null}}async function WE(e){try{return await z(`/api/curriculum/subjects/${e}/topics`)}catch{return[]}}async function HE(e,t){try{return await z(`/api/curriculum/subjects/${e}/topics/${t}`)}catch{return null}}const ZE=Object.freeze(Object.defineProperty({__proto__:null,ApiError:Dt,ApiNetworkError:zr,ApiTimeoutError:bn,ApiValidationError:je,apiFetch:z,apiService:wt,fetchAnalysisCurriculumContext:UE,generateGroundedProblem:BE,generateRagLesson:_E,generateRagProblem:EE,getCurriculumGroundedLesson:VE,getCurriculumSubject:GE,getCurriculumSubjects:qE,getCurriculumTopic:HE,getCurriculumTopics:WE,getRagAnalysisContext:CE,getRagHealth:PE,warmupBackend:IE},Symbol.toStringTag,{value:"Module"})),Fh="competencyProfiles",jR=async e=>{const t=q(N,Fh,e),n=await ve(t);return n.exists()?n.data():null},KE=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:ce(),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:ce()}])),primaryWeakness:i,primaryStrength:o,suggestedModule:a,updatedAt:ce()};await $e(q(N,Fh,e),c,{merge:!0})},Jr=async e=>{const t={userId:e,subjects:{},lessons:{},quizAttempts:[],totalLessonsCompleted:0,totalQuizzesCompleted:0,averageScore:0,updatedAt:new Date};return await $e(q(N,"progress",e),t),t},QE=async e=>{try{const t=q(N,"progress",e),n=await ve(t);if(n.exists()){const s=n.data();return{...s,updatedAt:s.updatedAt?.toDate()||new Date}}return await Jr(e)}catch(t){return console.error("Error getting user progress:",t),null}},NR=(e,t)=>{const n=q(N,"progress",e);return Yt(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)})},$R=async(e,t,n)=>{const s=Math.max(0,Math.min(100,n)),r=q(N,"progress",e);await $e(r,{[`lessons.${t}.lessonId`]:t,[`lessons.${t}.progressPercent`]:s,updatedAt:ce()},{merge:!0})},FR=async(e,t,n,s,r)=>{const o=q(N,"progress",e),i=await ve(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 $e(o,{[`subjects.${t}.modulesProgress.${n}.progress`]:f,[`subjects.${t}.modulesProgress.${n}.lastAccessedAt`]:ce(),updatedAt:ce()},{merge:!0}),f},VR=async(e,t,n,s,r,o=50,i,a)=>{try{const c=q(N,"progress",e);let u=await ve(c);u.exists()||(await Jr(e),u=await ve(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 $e(c,{[`lessons.${s}`]:l,[`subjects.${t}.modulesProgress.${n}`]:p,...m&&{totalLessonsCompleted:fs(1)},updatedAt:ce()},{merge:!0}),await Vh(e,o,"lesson_complete",`Completed lesson: ${s}`)}catch(c){throw console.error("Error completing lesson:",c),c}},BR=async(e,t,n,s,r,o)=>{try{const i=q(N,"progress",e);let a=await ve(i);a.exists()||(await Jr(e),a=await ve(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:ce()})}catch(i){throw console.error("Error recording practice quiz:",i),i}},UR=async(e,t,n,s,r,o,i,a)=>{try{const c=q(N,"progress",e);let u=await ve(c);u.exists()||(await Jr(e),u=await ve(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:ce()}),await Vh(e,f,"quiz_complete",`Completed quiz: ${s} (Score: ${r}%)`)}catch(c){throw console.error("Error completing quiz:",c),c}},Vh=async(e,t,n,s)=>{try{const r=q(N,"users",e);let o=1;try{const u=(await ve(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:ce()});const a=q(Xe(N,"xpActivities"));await $e(a,{activityId:a.id,userId:e,type:n,xpEarned:i,description:s,timestamp:ce()})}catch(r){console.error("Error awarding XP:",r)}},gr={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"}},XE=300*1e3,YE=1800*1e3,zi=new Rm({defaultOptions:{queries:{staleTime:XE,gcTime:YE,retry:1,refetchOnWindowFocus:!1}}}),JE=async()=>{await zi.cancelQueries(),zi.clear()},xu={quizDefaults:{timeLimitMinutes:30,passingScore:75,maxAttempts:3},classPreferences:{autoEnroll:!1,classVisibility:"public"},studentAnalyticsVisibility:!0,notifyOnSubmission:!0,notifyOnStudentActivity:!1},Su={maintenanceMode:!1,defaultGradeLevel:"Grade 11",defaultCurriculum:"STEM",maxClassSize:50,auditLogVisible:!0,aiConfig:{modelName:"deepseek-chat",temperature:.7,endpoint:"https://api.deepseek.com"}},eC="preferences",Na=()=>JSON.parse(JSON.stringify(gr)),Bh=e=>{const t=Na();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},$a=e=>q(N,"users",e,"settings",eC),Uh=async e=>{const t=$a(e),n=await ve(t);if(!n.exists()){const s=Na();return await $e(t,{...s,createdAt:ce(),updatedAt:ce()}),s}return Bh(n.data())},tC=async(e,t)=>{const n=await Uh(e),s=Bh({...n,...t});return await $e($a(e),{...s,updatedAt:ce()},{merge:!0}),s},qh="mathpulse_appearance",nC=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(qh,JSON.stringify(e.appearance))}catch{}},sC=()=>{try{const e=localStorage.getItem(qh);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{}},rC=async()=>{try{if(await JE(),A_(),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.")}},oC=async e=>{const t=q(N,"users",e),n=await ve(t),s=await ve($a(e)),r=["progress","xpActivities","achievements","notifications","tasks","chatSessions","chatMessages"],o=await Promise.all(r.map(async i=>{const a=Ot(Xe(N,i),Mt("userId","==",e)),c=await zn(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():Na(),collections:o.reduce((i,a)=>(i[a.collectionName]=a.items,i),{})}},Fa=async e=>{const t=ye.currentUser;if(!t||!t.email)throw new Error("No user logged in");const n=Zp.credential(t.email,e);await Kp(t,n)},qR=async(e,t)=>{if(await Fa(e),!ye.currentUser)throw new Error("Re-auth failed");await Wp(ye.currentUser,t)},GR=async(e,t)=>{if(await Fa(e),!ye.currentUser)throw new Error("Re-auth failed");await Gp(ye.currentUser,t)},WR=async(e,t)=>{if(await Fa(e),!ye.currentUser)throw new Error("Re-auth failed");await Hp(ye.currentUser);try{const{deleteDoc:n}=await oe(async()=>{const{deleteDoc:s}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{deleteDoc:s}},__vite__mapDeps([1,2]));await n(q(N,"users",t))}catch{}},Gh=e=>q(N,"users",e,"settings","teacherPreferences"),iC=async e=>{const t=await ve(Gh(e));return t.exists()?{...xu,...t.data()}:{...xu}},HR=async(e,t)=>{const n=await iC(e),s={...n,...t,quizDefaults:{...n.quizDefaults,...t.quizDefaults},classPreferences:{...n.classPreferences,...t.classPreferences}};return await $e(Gh(e),{...s,updatedAt:ce()},{merge:!0}),s},Wh=()=>q(N,"system","config"),aC=async()=>{const e=await ve(Wh());return e.exists()?{...Su,...e.data()}:{...Su}},ZR=async e=>{const t=await aC(),n={...t,...e,aiConfig:{...t.aiConfig,...e.aiConfig}};return await $e(Wh(),{...n,updatedAt:ce()},{merge:!0}),n};function Hh(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 Zh(e){const t=Hh(e);return t.setHours(0,0,0,0),t}function cC(e){const t=Hh(e);return t.setHours(23,59,59,999),t}function Gn(){const e=ye.currentUser?.uid??null;return e||console.warn("[notificationFirestoreService] Skipping Firestore call — user not authenticated"),e}const lC=e=>{const t=e.data(),n=t.createdAt,s=n instanceof Dn?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}},uC=async e=>{if(!Gn())throw new Error("Cannot create notification — not authenticated");try{const n=q(Xe(N,"notifications",e.userId,"items")),s={userId:e.userId,type:e.type,title:e.title,message:e.message,isRead:!1,createdAt:ce(),...e.metadata?{metadata:e.metadata}:{},...e.actionUrl?{actionUrl:e.actionUrl}:{}};return await $e(n,s),n.id}catch(n){throw console.error("[notificationFirestoreService] Error creating notification:",n),n}},dC=async(e,t)=>{if(Gn())try{const n=q(N,"notifications",e,"items",t),s=dt(n,{isRead:!0}).catch(i=>console.warn("[firestore] markAsRead subcollection skipped:",i)),r=q(N,"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}},fC=async e=>{if(Gn())try{const t=Ot(Xe(N,"notifications",e,"items"),Mt("isRead","==",!1)),s=(await zn(t)).docs.map(r=>dt(r.ref,{isRead:!0}));try{const r=Ot(Xe(N,"notifications"),Mt("userId","==",e),Mt("read","==",!1)),o=await zn(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}},hC=async(e,t)=>{try{const n=q(N,"notifications",e,"items",t),s=yr(n).catch(i=>console.warn("[firestore] deleteNotification subcollection skipped:",i)),r=q(N,"notifications",t),o=yr(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}},pC=(e,t)=>{const n=Gn();if(!n||n!==e)return console.warn("[notificationFirestoreService] subscribeToNotifications skipped — auth UID mismatch or not signed in"),t([]),()=>{};const s=Ot(Xe(N,"notifications",e,"items"),vn("createdAt","desc")),r=Ot(Xe(N,"notifications"),Mt("userId","==",e),vn("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=Yt(s,f=>{o=f.docs.map(p=>lC(p)),a=!0,c&&u()},()=>{a=!0,c&&u()}),l=Yt(r,f=>{i=f.docs.map(p=>{const m=p.data(),g=m.createdAt,y=g instanceof Dn?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()}},mC=async e=>{if(!Gn())return!1;try{const t=new Date,n=Zh(t),s=cC(t),r=Ot(Xe(N,"notifications",e,"items"),Mt("type","==","daily_checkin"),Mt("createdAt",">=",n),Mt("createdAt","<=",s),vn("createdAt","asc"),ks(1));return!(await zn(r)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking daily check-in:",t),!1}},gC=async e=>{if(!Gn())return!1;try{const n=Zh(new Date),s=Ot(Xe(N,"notifications",e,"items"),Mt("type","==","streak_reminder"),Mt("createdAt",">=",n),vn("createdAt","asc"),ks(1));return!(await zn(s)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking reminder:",t),!1}};async function Kh(e){try{await uC(e)}catch(t){console.error("[NotificationService] Failed to create notification:",t)}}function yC(e){const t=h.useRef(!1);h.useEffect(()=>{if(!e||t.current)return;t.current=!0,(async()=>{try{if(await mC(e)||await gC(e))return;await Kh({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 Qh=h.createContext(null),Vo=({children:e})=>{const{currentUser:t,userProfile:n}=Ms(),[s,r]=h.useState([]),[o,i]=h.useState(!0),a=t?.uid??null,c=h.useRef([]);yC(n?.role==="student"?a:null),h.useEffect(()=>{if(!a)return r([]),i(!1),()=>{};i(!0);const m=pC(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 dC(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 fC(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 hC(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(Qh.Provider,{value:p,children:e})},KR=()=>{const e=h.useContext(Qh);if(!e)throw new Error("useNotifications must be used within a NotificationProvider");return e},ku="/firebase-messaging-sw.js";let Bo=null,Tu=!1,Uo=!1;async function Va(){if(!Tu){try{Uo=await zp()}catch{Uo=!1}Tu=!0}return Uo?(Bo||(Bo=jp(qt)),Bo):null}async function bC(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.getRegistration(ku);return e||await navigator.serviceWorker.register(ku,{scope:"/"})}catch(e){return console.warn("[pushNotificationService] SW registration failed:",e),null}}async function Xh(e){if(!e||typeof window>"u"||typeof Notification>"u")return null;const t=await Va();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 bC();if(!r)return null;let o=null;try{o=await Lp(t,{vapidKey:s,serviceWorkerRegistration:r})}catch(i){return console.warn("[pushNotificationService] getToken failed:",i),null}if(!o)return null;try{const i=q(N,"users",e,"fcmTokens",o),a={token:o,userId:e,platform:"web",userAgent:typeof navigator<"u"?navigator.userAgent:"",createdAt:ce(),updatedAt:ce(),active:!0};await $e(i,a,{merge:!0})}catch(i){console.warn("[pushNotificationService] persisting token failed:",i)}return o}function Yh(e){let t,n=!1;return Va().then(s=>{n||!s||(t=Op(s,e))}),()=>{n=!0,t?.()}}async function Jh(e,t){if(!(!e||!t)){try{const n=q(N,"users",e,"fcmTokens",t);await dt(n,{active:!1,updatedAt:ce()})}catch(n){console.warn("[pushNotificationService] marking token inactive failed:",n)}try{const n=await Va();n&&await Dp(n)}catch(n){console.warn("[pushNotificationService] deleteToken failed:",n)}}}const QR=Object.freeze(Object.defineProperty({__proto__:null,deregisterPushToken:Jh,onForegroundMessage:Yh,requestPushPermissionAndRegister:Xh},Symbol.toStringTag,{value:"Module"})),vC={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 wC(e){return e?vC[e]??"system_alert":"system_alert"}function xC(){const{currentUser:e}=Ms(),t=Bi(),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 Xh(o);a||(n.current=c,c&&(i=Yh(u=>{const d=u.notification??{},l=u.data??{},f=d.title||l.title||"MathPulse AI",p=d.body||l.body||"",m=l.notificationType;Kh({userId:o,type:wC(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 Jh(o,i),n.current=null)}}}const qo=()=>(xC(),null),SC=(e,t)=>{const n=new Array(e.length+t.length);for(let s=0;s({classGroupId:e,validator:t}),ep=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),jr="-",Pu=[],TC="arbitrary..",PC=e=>{const t=EC(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return _C(i);const a=i.split(jr),c=a[0]===""&&a.length>1?1:0;return tp(a,c,t)},getConflictingClassGroupIds:(i,a)=>{if(a){const c=s[i],u=n[i];return c?u?SC(u,c):c:u||Pu}return n[i]||Pu}}},tp=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const u=tp(e,t+1,o);if(u)return u}const i=n.validators;if(i===null)return;const a=t===0?e.join(jr):e.slice(t).join(jr),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?TC+s:void 0})(),EC=e=>{const{theme:t,classGroups:n}=e;return CC(n,t)},CC=(e,t)=>{const n=ep();for(const s in e){const r=e[s];Ba(r,n,s,t)}return n},Ba=(e,t,n,s)=>{const r=e.length;for(let o=0;o{if(typeof e=="string"){RC(e,t,n);return}if(typeof e=="function"){MC(e,t,n,s);return}IC(e,t,n,s)},RC=(e,t,n)=>{const s=e===""?t:np(t,e);s.classGroupId=n},MC=(e,t,n,s)=>{if(DC(e)){Ba(e(s),t,n,s);return}t.validators===null&&(t.validators=[]),t.validators.push(kC(n,e))},IC=(e,t,n,s)=>{const r=Object.entries(e),o=r.length;for(let i=0;i{let n=e;const s=t.split(jr),r=s.length;for(let o=0;o"isThemeGetter"in e&&e.isThemeGetter===!0,OC=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)}}},ji="!",_u=":",LC=[],Eu=(e,t,n,s,r)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:s,isExternal:r}),zC=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 Eu(o,p,f,m)};if(t){const r=t+_u,o=s;s=i=>i.startsWith(r)?o(i.slice(r.length)):Eu(LC,!1,i,void 0,!0)}if(n){const r=s;s=o=>n({className:o,parseClassName:r})}return s},jC=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}},NC=e=>({cache:OC(e.cacheSize),parseClassName:zC(e),sortModifiers:jC(e),...PC(e)}),$C=/\s+/,FC=(e,t)=>{const{parseClassName:n,getClassGroupId:s,getConflictingClassGroupIds:r,sortModifiers:o}=t,i=[],a=e.trim().split($C);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+ji:k,x=S+v;if(i.indexOf(x)>-1)continue;i.push(x);const T=r(v,y);for(let P=0;P0?" "+c:c)}return c},VC=(...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=NC(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=FC(c,n);return r(c,d),d};return o=i,(...c)=>o(VC(...c))},UC=[],Ae=e=>{const t=n=>n[e]||UC;return t.isThemeGetter=!0,t},rp=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,op=/^\((?:(\w[\w-]*):)?(.+)\)$/i,qC=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,GC=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,WC=/\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$/,HC=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ZC=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,KC=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ht=e=>qC.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),Zt=e=>!!e&&Number.isInteger(Number(e)),Go=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Vt=e=>GC.test(e),ip=()=>!0,QC=e=>WC.test(e)&&!HC.test(e),Ua=()=>!1,XC=e=>ZC.test(e),YC=e=>KC.test(e),JC=e=>!L(e)&&!$(e),eA=e=>rn(e,lp,Ua),L=e=>rp.test(e),dn=e=>rn(e,up,QC),Cu=e=>rn(e,cA,ne),tA=e=>rn(e,fp,ip),nA=e=>rn(e,dp,Ua),Au=e=>rn(e,ap,Ua),sA=e=>rn(e,cp,YC),er=e=>rn(e,hp,XC),$=e=>op.test(e),os=e=>kn(e,up),rA=e=>kn(e,dp),Ru=e=>kn(e,ap),oA=e=>kn(e,lp),iA=e=>kn(e,cp),tr=e=>kn(e,hp,!0),aA=e=>kn(e,fp,!0),rn=(e,t,n)=>{const s=rp.exec(e);return s?s[1]?t(s[1]):n(s[2]):!1},kn=(e,t,n=!1)=>{const s=op.exec(e);return s?s[1]?t(s[1]):n:!1},ap=e=>e==="position"||e==="percentage",cp=e=>e==="image"||e==="url",lp=e=>e==="length"||e==="size"||e==="bg-size",up=e=>e==="length",cA=e=>e==="number",dp=e=>e==="family-name",fp=e=>e==="number"||e==="weight",hp=e=>e==="shadow",lA=()=>{const e=Ae("color"),t=Ae("font"),n=Ae("text"),s=Ae("font-weight"),r=Ae("tracking"),o=Ae("leading"),i=Ae("breakpoint"),a=Ae("container"),c=Ae("spacing"),u=Ae("radius"),d=Ae("shadow"),l=Ae("inset-shadow"),f=Ae("text-shadow"),p=Ae("drop-shadow"),m=Ae("blur"),g=Ae("perspective"),y=Ae("aspect"),v=Ae("ease"),k=Ae("animate"),S=()=>["auto","avoid","all","avoid-page","page","left","right","column"],x=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...x(),$,L],P=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto","contain","none"],w=()=>[$,L,c],R=()=>[Ht,"full","auto",...w()],A=()=>[Zt,"none","subgrid",$,L],B=()=>["auto",{span:["full",Zt,$,L]},Zt,$,L],F=()=>[Zt,"auto",$,L],H=()=>["auto","min","max","fr",$,L],se=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],te=()=>["start","end","center","stretch","center-safe","end-safe"],V=()=>["auto",...w()],ie=()=>[Ht,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],re=()=>[Ht,"screen","full","dvw","lvw","svw","min","max","fit",...w()],ue=()=>[Ht,"screen","full","lh","dvh","lvh","svh","min","max","fit",...w()],D=()=>[e,$,L],he=()=>[...x(),Ru,Au,{position:[$,L]}],st=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",oA,eA,{size:[$,L]}],U=()=>[Go,os,dn],G=()=>["","none","full",u,$,L],J=()=>["",ne,os,dn],we=()=>["solid","dashed","dotted","double"],ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],le=()=>[ne,Go,Ru,Au],Z=()=>["","none",m,$,L],O=()=>["none",ne,$,L],ee=()=>["none",ne,$,L],ge=()=>[ne,$,L],K=()=>[Ht,"full",...w()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Vt],breakpoint:[Vt],color:[ip],container:[Vt],"drop-shadow":[Vt],ease:["in","out","in-out"],font:[JC],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Vt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Vt],shadow:[Vt],spacing:["px",ne],text:[Vt],"text-shadow":[Vt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ht,L,$,y]}],container:["container"],columns:[{columns:[ne,L,$,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:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:R()}],"inset-x":[{"inset-x":R()}],"inset-y":[{"inset-y":R()}],start:[{"inset-s":R(),start:R()}],end:[{"inset-e":R(),end:R()}],"inset-bs":[{"inset-bs":R()}],"inset-be":[{"inset-be":R()}],top:[{top:R()}],right:[{right:R()}],bottom:[{bottom:R()}],left:[{left:R()}],visibility:["visible","invisible","collapse"],z:[{z:[Zt,"auto",$,L]}],basis:[{basis:[Ht,"full","auto",a,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,Ht,"auto","initial","none",L]}],grow:[{grow:["",ne,$,L]}],shrink:[{shrink:["",ne,$,L]}],order:[{order:[Zt,"first","last","none",$,L]}],"grid-cols":[{"grid-cols":A()}],"col-start-end":[{col:B()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":A()}],"row-start-end":[{row:B()}],"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:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...se(),"normal"]}],"justify-items":[{"justify-items":[...te(),"normal"]}],"justify-self":[{"justify-self":["auto",...te()]}],"align-content":[{content:["normal",...se()]}],"align-items":[{items:[...te(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...te(),{baseline:["","last"]}]}],"place-content":[{"place-content":se()}],"place-items":[{"place-items":[...te(),"baseline"]}],"place-self":[{"place-self":["auto",...te()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:V()}],mx:[{mx:V()}],my:[{my:V()}],ms:[{ms:V()}],me:[{me:V()}],mbs:[{mbs:V()}],mbe:[{mbe:V()}],mt:[{mt:V()}],mr:[{mr:V()}],mb:[{mb:V()}],ml:[{ml:V()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:ie()}],"inline-size":[{inline:["auto",...re()]}],"min-inline-size":[{"min-inline":["auto",...re()]}],"max-inline-size":[{"max-inline":["none",...re()]}],"block-size":[{block:["auto",...ue()]}],"min-block-size":[{"min-block":["auto",...ue()]}],"max-block-size":[{"max-block":["none",...ue()]}],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,dn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,aA,tA]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Go,L]}],"font-family":[{font:[rA,nA,t]}],"font-features":[{"font-features":[L]}],"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,$,L]}],"line-clamp":[{"line-clamp":[ne,"none",$,Cu]}],leading:[{leading:[o,...w()]}],"list-image":[{"list-image":["none",$,L]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,L]}],"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:[...we(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",$,dn]}],"text-decoration-color":[{decoration:D()}],"underline-offset":[{"underline-offset":[ne,"auto",$,L]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,L]}],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",$,L]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:he()}],"bg-repeat":[{bg:st()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Zt,$,L],radial:["",$,L],conic:[Zt,$,L]},iA,sA]}],"bg-color":[{bg:D()}],"gradient-from-pos":[{from:U()}],"gradient-via-pos":[{via:U()}],"gradient-to-pos":[{to:U()}],"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:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-bs":[{"border-bs":J()}],"border-w-be":[{"border-be":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...we(),"hidden","none"]}],"divide-style":[{divide:[...we(),"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:[...we(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,$,L]}],"outline-w":[{outline:["",ne,os,dn]}],"outline-color":[{outline:D()}],shadow:[{shadow:["","none",d,tr,er]}],"shadow-color":[{shadow:D()}],"inset-shadow":[{"inset-shadow":["none",l,tr,er]}],"inset-shadow-color":[{"inset-shadow":D()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:D()}],"ring-offset-w":[{"ring-offset":[ne,dn]}],"ring-offset-color":[{"ring-offset":D()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":D()}],"text-shadow":[{"text-shadow":["none",f,tr,er]}],"text-shadow-color":[{"text-shadow":D()}],opacity:[{opacity:[ne,$,L]}],"mix-blend":[{"mix-blend":[...ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ae()}],"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":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":le()}],"mask-image-linear-to-pos":[{"mask-linear-to":le()}],"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":le()}],"mask-image-t-to-pos":[{"mask-t-to":le()}],"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":le()}],"mask-image-r-to-pos":[{"mask-r-to":le()}],"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":le()}],"mask-image-b-to-pos":[{"mask-b-to":le()}],"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":le()}],"mask-image-l-to-pos":[{"mask-l-to":le()}],"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":le()}],"mask-image-x-to-pos":[{"mask-x-to":le()}],"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":le()}],"mask-image-y-to-pos":[{"mask-y-to":le()}],"mask-image-y-from-color":[{"mask-y-from":D()}],"mask-image-y-to-color":[{"mask-y-to":D()}],"mask-image-radial":[{"mask-radial":[$,L]}],"mask-image-radial-from-pos":[{"mask-radial-from":le()}],"mask-image-radial-to-pos":[{"mask-radial-to":le()}],"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":x()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":le()}],"mask-image-conic-to-pos":[{"mask-conic-to":le()}],"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:he()}],"mask-repeat":[{mask:st()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,L]}],filter:[{filter:["","none",$,L]}],blur:[{blur:Z()}],brightness:[{brightness:[ne,$,L]}],contrast:[{contrast:[ne,$,L]}],"drop-shadow":[{"drop-shadow":["","none",p,tr,er]}],"drop-shadow-color":[{"drop-shadow":D()}],grayscale:[{grayscale:["",ne,$,L]}],"hue-rotate":[{"hue-rotate":[ne,$,L]}],invert:[{invert:["",ne,$,L]}],saturate:[{saturate:[ne,$,L]}],sepia:[{sepia:["",ne,$,L]}],"backdrop-filter":[{"backdrop-filter":["","none",$,L]}],"backdrop-blur":[{"backdrop-blur":Z()}],"backdrop-brightness":[{"backdrop-brightness":[ne,$,L]}],"backdrop-contrast":[{"backdrop-contrast":[ne,$,L]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,$,L]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,$,L]}],"backdrop-invert":[{"backdrop-invert":["",ne,$,L]}],"backdrop-opacity":[{"backdrop-opacity":[ne,$,L]}],"backdrop-saturate":[{"backdrop-saturate":[ne,$,L]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,$,L]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,L]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",$,L]}],ease:[{ease:["linear","initial",v,$,L]}],delay:[{delay:[ne,$,L]}],animate:[{animate:["none",k,$,L]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,L]}],"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:ee()}],"scale-x":[{"scale-x":ee()}],"scale-y":[{"scale-y":ee()}],"scale-z":[{"scale-z":ee()}],"scale-3d":["scale-3d"],skew:[{skew:ge()}],"skew-x":[{"skew-x":ge()}],"skew-y":[{"skew-y":ge()}],transform:[{transform:[$,L,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:K()}],"translate-x":[{"translate-x":K()}],"translate-y":[{"translate-y":K()}],"translate-z":[{"translate-z":K()}],"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",$,L]}],"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":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"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",$,L]}],fill:[{fill:["none",...D()]}],"stroke-w":[{stroke:[ne,os,dn,Cu]}],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"]}},uA=BC(lA);function mn(...e){return uA(tm(e))}function dA({className:e,...t}){return b.jsx(Yp,{"data-slot":"avatar",className:mn("relative flex size-10 shrink-0 overflow-hidden rounded-full",e),...t})}function Mu({className:e,...t}){return b.jsx(Jp,{"data-slot":"avatar-image",className:mn("aspect-square size-full",e),...t})}function fA({className:e,...t}){return b.jsx(em,{"data-slot":"avatar-fallback",className:mn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}function hA(e){return e==="male"?"/icons/male-student.png":e==="female"?"/icons/female-student.png":"/icons/neutral-student.png"}const pA=e=>{const t=(e||"").trim();return t?t.split(/\s+/).slice(0,2).map(n=>n[0]?.toUpperCase()).join(""):"U"},mA=({src:e,name:t,gender:n,className:s,fallbackClassName:r,imageClassName:o})=>{const i=pA(t),a=hA(n);return b.jsxs(dA,{className:mn("shrink-0",s),children:[e?b.jsx(Mu,{src:e,alt:t||"User",className:mn("object-cover",o)}):b.jsx(Mu,{src:a,alt:t||"User",className:mn("object-cover",o)}),b.jsx(fA,{className:mn("bg-gradient-to-br from-violet-500 to-indigo-600 text-white font-display font-bold text-xs select-none",r),children:i})]})},gA={Functions:"Functions and Graphs",BusinessMath:"Business and Financial Mathematics",Logic:"Logic and Reasoning"},XR={Functions:"gm-q2-functions-graphs",BusinessMath:"gm-q1-business-finance",Logic:"gm-q4-propositions-syllogisms-fallacies"},yA=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},bA=[{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"}],vA=Object.fromEntries(bA.map(e=>[e.competencyCode,{lessonId:e.lessonId,storagePath:e.storagePath,sourceFile:e.sourceFile}])),Iu=[{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/"}],qa={"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"}},wA={"Grade 11":["gen-math"]},xA="Foundational competency flow with guided examples, step-by-step vocabulary support, and scaffolded checkpoints.",tt=(e,t,n,s,r,o,i,a,c,u,d,l)=>({id:e,subjectId:t,subject:qa[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:[Iu[0],Iu[1]]}),SA=[tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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 kA(e,t){return`${e.moduleDescription} ${xA}`}function TA(e,t){const n=t==="Grade 11"?"22 min":"18 min";return e.competencies.map((s,r)=>{const o=vA[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 PA(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 _A(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 EA(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 CA(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 AA(e){return EA(e)}function RA(e,t){const n=CA(t),s=wA[e];return n?s.filter(r=>n.includes(r)):s}function MA(e,t){const n=RA(e,t);return SA.filter(s=>s.grade_level_availability.includes(e)).filter(s=>n.includes(s.subjectId)).map(s=>{const r=PA(s),o=TA(s,e),i=_A(s,r),a=qa[s.subjectId],c=o.some(d=>d.storagePath&&d.storagePath.length>0),u=s.isAvailable??c??!0;return{id:s.id,title:s.moduleTitle,description:kA(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}})}const YR=qa,IA=()=>{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`},DA=async e=>{const{uid:t,score:n,subject:s,title:r}=e,o=s||r||"General";let i="";return await Cp(N,async a=>{const c=q(N,"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:Dn.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},x=S.count+1,T=S.totalScore+n,P=T/x;d={overallGpa:v/100*4,averageScore:v,quizzesCompleted:g,subjectPerformance:{...k,[o]:{totalScore:T,count:x,avgScore:P}},lastUpdated:Dn.now()}}a.set(c,d,{merge:!0});const l=Xe(N,"users",t,"assessments"),f=q(l);i=f.id;const p={title:e.title,subject:o,type:e.type,score:e.score,totalQuestions:e.totalQuestions,completedAt:Dn.now(),risk:e.risk,intervention:e.intervention,xpEarned:e.xpEarned,badgeUnlocked:e.badgeUnlocked,semester:IA(),createdAt:ce()};a.set(f,p)}),i},JR=(e,t)=>{const n=q(N,"users",e,"gradeSummary","current");return Yt(n,s=>{s.exists()?t(s.data()):t(null)},s=>{console.error("[gradesService] subscribeToGradeSummary error:",s),t(null)})},eM=(e,t)=>{const n=Ot(Xe(N,"users",e,"assessments"),vn("completedAt","desc"),ks(20));return Yt(n,s=>{const r=[];s.forEach(o=>{r.push({id:o.id,...o.data()})}),t(r)},s=>{console.error("[gradesService] subscribeToAssessments error:",s),t([])})};function OA(e){const{assessmentId:t,overallScorePercent:n,overallRisk:s,intervention:r,proficiencyProfile:o}=e,i=zA(n),a=jA(n,s,o),c=NA(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:pp(s),updatedAt:new Date}}async function LA(e,t){const n=q(N,"users",e,"dashboardSummary","heroBannerModal");await $e(n,{...t,updatedAt:ce()})}async function tM(e){const t=q(N,"users",e,"dashboardSummary","heroBannerModal"),n=await ve(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:mp(s.updatedAt)}}function nM(e,t){const n=q(N,"users",e,"dashboardSummary","heroBannerModal");return Yt(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:mp(r.updatedAt)})},s=>{console.warn("[heroBannerSummaryService] Subscription error:",s),t(null)})}function zA(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 jA(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 NA(e,t,n){return t&&t.trim().length>0?t:(pp(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 pp(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 mp(e){return e?e instanceof Date?e:e instanceof Dn?e.toDate():typeof e=="string"||typeof e=="number"?new Date(e):new Date:new Date}const $A=h.lazy(()=>oe(()=>import("./LoginPage-DKWs9ixZ.js"),__vite__mapDeps([13,3,14,7,8,15,16,17,18,19,1,2,4,5,6,9,10]))),FA=h.lazy(()=>oe(()=>import("./TeacherDashboard-Uxc_axO7.js"),__vite__mapDeps([20,3,14,7,8,15,21,22,23,24,1,2,4,5,6,9,10,25,26,27,28,29,30,31,32,16,33,34,35,36,18,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55]))),VA=h.lazy(()=>oe(()=>import("./AdminDashboard-BGOkExie.js"),__vite__mapDeps([56,3,57,33,24,35,7,22,44,43,40,58,21,14,8,23,1,2,4,5,6,9,10,59,38,26,15,48,46,28,29,30,31,32,16,53,42,19,25,52,18,17,27,45,47,60,61,62,36]))),Du=h.lazy(()=>oe(()=>import("./Sidebar-DAee_vGE.js").then(e=>e.a),__vite__mapDeps([57,3,33,24,35,7,22,44,43,40,58]))),BA=h.lazy(()=>oe(()=>import("./HeroBanner--aQVgKP1.js"),__vite__mapDeps([63,3,53,7,22,8,1,2,32,31,16,4,5,6,9,10]))),UA=h.lazy(()=>oe(()=>import("./RightSidebar-BF7n5nEK.js"),__vite__mapDeps([64,3,65,50,35,7,44,1,2,4,5,6,8,9,10]))),qA=h.lazy(()=>oe(()=>import("./XPNotification-B3gCYXcz.js"),__vite__mapDeps([66,3,16,1,2,4,5,6,7,8,9,10]))),GA=h.lazy(()=>oe(()=>import("./index-BVqK5_Xi.js"),__vite__mapDeps([67,3,32,68,30,50,55,29,23,22,1,2,4,5,6,7,8,9,10])).then(e=>({default:e.NotificationBell})));h.lazy(()=>oe(()=>import("./SupplementalBanner-DptF9mye.js"),__vite__mapDeps([69,3,22,16,44,1,2,4,5,6,7,8,9,10])));const WA=h.lazy(()=>oe(()=>import("./SupplementalPillCarousel-BucFK7HK.js"),__vite__mapDeps([70,3,44,1,2,4,5,6,7,8,9,10]))),HA=h.lazy(()=>oe(()=>import("./LearningPath-6C1pnB-M.js"),__vite__mapDeps([71,3,72,62,1,2,52,4,5,6,7,8,9,10]))),ZA=h.lazy(()=>oe(()=>import("./CompetencyRadarChart-wJLEa8V5.js"),__vite__mapDeps([73,3,1,2,48,40,16,8,4,5,6,7,9,10])).then(e=>({default:e.CompetencyRadarChart}))),KA=h.lazy(()=>oe(()=>import("./ModulesPage-Dw5f2_tQ.js"),__vite__mapDeps([74,3,47,1,2,72,62,52,14,7,8,75,38,22,4,5,6,9,10,26,76,43,44,36,34,50,77,12,55,48,40,31,60,0,78,49,25,79,16]))),QA=h.lazy(()=>oe(()=>import("./AIChatPage-6rPaXTro.js"),__vite__mapDeps([80,3,14,7,8,15,51,9,10,1,2,4,5,6,27,25,23,43,37]))),XA=h.lazy(()=>oe(()=>import("./GradesPage-DFzgWMGj.js"),__vite__mapDeps([81,3,14,7,8,48,40,49,1,2,42,31,32,79,4,5,6,9,10]))),YA=h.lazy(()=>oe(()=>import("./LeaderboardPage-BhhK2vnv.js"),__vite__mapDeps([82,3,22,52,83,1,2,4,5,6,7,8,9,10]))),JA=h.lazy(()=>oe(()=>import("./QuizBattlePage-B59IiVNM.js"),__vite__mapDeps([84,3,65,48,40,1,2,14,7,8,59,38,26,15,61,41,76,85,86,16,44,4,5,6,9,10]))),eR=h.lazy(()=>oe(()=>import("./AvatarShop-CiwigxhN.js"),__vite__mapDeps([87,3,7,83,1,2,35,85,86,45,16,58,4,5,6,8,9,10]))),tR=h.lazy(()=>oe(()=>import("./FloatingAITutor-C6E9qFVh.js"),__vite__mapDeps([88,3,89,39,22,37,1,2,4,5,6,7,8,9,10]))),nR=h.lazy(()=>oe(()=>import("./RewardsModal-vFV0nluD.js"),__vite__mapDeps([90,3,1,2,22,4,5,6,7,8,9,10]))),Wo=h.lazy(()=>oe(()=>import("./ProfileModal-BujeMrz5.js"),__vite__mapDeps([91,3,14,7,8,15,59,38,26,92,4,2,5,22,39,27,46,17,36,45,1,6,9,10]))),sR=h.lazy(()=>oe(()=>import("./ConfirmModal-BDSADafu.js"),__vite__mapDeps([21,3,14,7,8,22,23,24,1,2,4,5,6,9,10]))),Ho=h.lazy(()=>oe(()=>import("./SettingsModal-BlqFNEeQ.js"),__vite__mapDeps([93,3,59,7,38,26,14,8,15,61,21,22,23,24,1,2,4,5,6,9,10,92,39,27,46,30,42,36,40,68,52,18]))),rR=h.lazy(()=>oe(()=>import("./ScientificCalculator-Ba2j64OY.js"),__vite__mapDeps([75,3,38,22,1,2,4,5,6,7,8,9,10]))),oR=h.lazy(()=>oe(()=>import("./InitialAssessmentModal-BXrHaNxu.js"),__vite__mapDeps([94,3,14,7,8,95,1,2,22,50,4,5,6,9,10]))),iR=h.lazy(()=>oe(()=>import("./AssessmentPage-BRsvq8VI.js"),__vite__mapDeps([96,3,14,7,8,95,89,22,52,50,44,1,2,4,5,6,9,10]))),aR=h.lazy(()=>oe(()=>import("./DiagnosticBreakdown-DMdwTTKX.js"),__vite__mapDeps([97,3,1,2,22,52,77,31,40,38,4,5,6,7,8,9,10]))),cR=()=>{const{isLoggedIn:e,userProfile:t,userRole:n,loading:s,refreshProfile:r}=Ms();Bi();const o=jt(),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(null),m=h.useRef(null),[g,y]=h.useState(!1),[v,k]=h.useState(!1),[S,x]=h.useState(!1),[T,P]=h.useState(!1);h.useEffect(()=>{(async()=>{try{const M=await ve(q(N,"settings","general"));M.exists()&&M.data()?.maintenanceMode===!0?(x(!0),e&&n!=="admin"&&await eu()):x(!1)}catch{}P(!0)})()},[e,n]);const _=t,[w,R]=h.useState(_?.level||1),[A,B]=h.useState(_?.currentXP||0),[F,H]=h.useState(_?.totalXP||0),se=Math.floor(100*Math.pow(1.5,w-1));let te=0;for(let C=1;C{const C=_?.learnerCurriculumAssignments?.subjects??_?.assignedSubjects??_?.curriculumAssignedSubjects??[];return Array.isArray(C)?C:[]},[_]),ue=h.useMemo(()=>MA(ie,re),[ie,re]),[D,he]=h.useState({collapsed:!1}),st={Dashboard:"/",Modules:"/modules","AI Chat":"/chat",Assessment:"/assessment","Quiz Battle":"/battle",Leaderboard:"/leaderboard",Grades:"/grades","Avatar Studio":"/avatar"},X={"/":"Dashboard","/modules":"Modules","/chat":"AI Chat","/assessment":"Assessment","/battle":"Quiz Battle","/leaderboard":"Leaderboard","/grades":"Grades","/avatar":"Avatar Studio"};h.useEffect(()=>{const C=X[o.pathname]||"Dashboard";f(C)},[o.pathname]),h.useEffect(()=>{const C=()=>{const M=X[window.location.pathname]||"Dashboard";f(M)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[]);const U=(C,M)=>{M?Ds(M):C==="Modules"&&l!=="Modules"&&Ds(null),C==="Quiz Battle"&&l!=="Quiz Battle"?(he({collapsed:g}),y(!0)):l==="Quiz Battle"&&C!=="Quiz Battle"&&y(D.collapsed),f(C);const W=st[C];W&&window.location.pathname!==W&&window.history.pushState({},"",W),k(!1)},[G,J]=h.useState(!1),[we,ae]=h.useState({show:!1,xp:0,message:""}),[le,Z]=h.useState(!1),[O,ee]=h.useState(!1),[ge,K]=h.useState(!1),[Ye,Le]=h.useState(!1),[Je,on]=h.useState({}),[pt,Ds]=h.useState(null),[Os,Ge]=h.useState(!1),[it,$t]=h.useState(gr),[eo,Ft]=h.useState(""),[an,Wn]=h.useState(!1),[Tn,rt]=h.useState(!1),[Wt,mt]=h.useState(null),[to,Hn]=h.useState(!1),[Ls,Zn]=h.useState(!1),[no,Kn]=h.useState(0),[at,Qn]=h.useState(!1),[so,Xn]=h.useState(!1),[cn,Y]=h.useState(""),[Ee,ze]=h.useState([]),[Te,Pt]=h.useState(_?.atRiskSubjects||[]),[_e,Fe]=h.useState(_?.priorityTopics||[]),[Pn,et]=h.useState(_?.gpa||"0.00");h.useEffect(()=>{e&&n==="student"&&t&&QE(t.uid).then(C=>{if(C&&C.averageScore>0){const M=Math.min(C.averageScore/25,4).toFixed(2);et(M)}}).catch(C=>console.error("Error loading progress for GPA:",C))},[e,n,t]);const[Ve,Yn]=h.useState(!1);h.useEffect(()=>{_&&n==="student"?(R(_.level||1),B(_.currentXP||0),H(_.totalXP||0),Pt(_.atRiskSubjects||[]),Fe(_.priorityTopics||[]),Yn(!0)):n!=="student"&&Yn(!0)},[t,n]),h.useEffect(()=>{if(!e||n!=="student"){Wn(!1);return}let C=!1;const M=()=>{C||Wn(!0)},W=window.requestIdleCallback,pe=window.cancelIdleCallback,lo=window.setTimeout(M,800),uo=window.requestAnimationFrame(()=>{W||M()}),yt=W?.(()=>{M()},{timeout:500});return()=>{C=!0,window.clearTimeout(lo),window.cancelAnimationFrame(uo),yt!==void 0&&pe&&pe(yt)}},[e,n]),h.useEffect(()=>{on({})},[t?.uid]);const gt=h.useMemo(()=>{const C=new Set;return Te.map(W=>yA(W)).filter(W=>W!==null).filter(W=>C.has(W)?!1:(C.add(W),!0))},[Te]),zs=h.useMemo(()=>{const C=_e.length>0?_e:gt,M=new Set;return C.filter(W=>M.has(W)?!1:(M.add(W),!0))},[_e,gt]),yp=()=>{rt(!0)};h.useEffect(()=>{const C=()=>rt(!0);return window.addEventListener("mathpulse:open-assessment",C),()=>window.removeEventListener("mathpulse:open-assessment",C)},[]),h.useEffect(()=>{if(!e||n!=="student"||!Ve||!t?.uid)return;let C=!1;return(async()=>{try{Hn(!!_?.assessmentDismissed),Zn(!!_?.initialAssessmentCompleted);const W=await Zo(q(N,"diagnosticResults",t.uid)).catch(()=>ve(q(N,"diagnosticResults",t.uid))),pe=await Zo(q(N,"competencyProfiles",t.uid)).catch(()=>ve(q(N,"competencyProfiles",t.uid)));if(C)return;const lo=W.exists()&&W.data()?.status==="completed",uo=pe.exists()&&pe.data()?.overallScore>0;if(!lo&&!uo){mt(!1);const yt=setTimeout(()=>{!C&&!to&&!Ls&&(sessionStorage.getItem("mathpulse_iar_session_dismissed")==="true"||rt(!0))},1e3);return()=>clearTimeout(yt)}else{if(mt(!0),W.exists()){const yt=W.data();yt?.riskProfile&&(Pt(yt.riskProfile.weak_domains||[]),Fe(yt.riskProfile.critical_gaps||[]))}if(pe.exists()){const yt=pe.data();yt?.primaryWeakness&&Pt(Wa=>[...new Set([...Wa,yt.primaryWeakness])])}}}catch(W){console.error("[diagnostic] Firestore check failed:",W)}})(),()=>{C=!0}},[e,n,Ve,t?.uid,no]);const bp=[...Te].sort().join("|"),Jn=t?.uid?`mathpulse_supplemental_dismissed_${t.uid}`:null;h.useEffect(()=>{if(!Jn){Ft("");return}try{const C=localStorage.getItem(Jn)||"";Ft(C)}catch{Ft("")}},[Jn]);const vp=()=>{if(Ft(""),!!Jn)try{localStorage.removeItem(Jn)}catch{}};Te.length>0,h.useEffect(()=>{(async()=>{if(!t?.uid){$t(gr);return}try{const M=await Uh(t.uid);$t(M)}catch(M){console.error("Error loading user settings:",M),$t(gr)}})()},[t?.uid]),h.useEffect(()=>{nC(it)},[it]);const wp=(C,M)=>{rt(!1),Y(C),ze(M),Qn(!0)},Ga=async C=>{if(Qn(!1),mt(!0),Xn(!0),C.xpEarned>0&&t?.uid)try{await Lo(t.uid,C.xpEarned,"manual","Diagnostic assessment completed"),ct.success(`Assessment complete! +${C.xpEarned} XP earned. ${C.badgeUnlocked.replace("_"," ")} badge unlocked!`)}catch{ct.success("Assessment complete!")}else ct.success("Assessment complete!");if(t?.uid&&C.competencyScores&&C.proficiencyProfile)try{await KE(t.uid,{uid:t.uid,assessmentId:`assessment-${Date.now()}`,completedAt:new Date,rawScore:C.overallScorePercent,totalQuestions:Object.values(C.competencyScores).reduce((M,W)=>M+W.attempted,0),correctAnswers:Object.values(C.competencyScores).reduce((M,W)=>M+W.correct,0),timeSpentSeconds:0,competencyScores:C.competencyScores,recommendations:C.proficiencyProfile.weaknesses.map(M=>`Focus on ${M}`),proficiencyProfile:C.proficiencyProfile,assessmentType:"initial"})}catch(M){console.error("[WARN] Failed to save competency profile:",M)}if(t?.uid)try{const M=OA({assessmentId:cn?`assessment-${cn}`:`assessment-${Date.now()}`,overallScorePercent:C.overallScorePercent,overallRisk:C.overallRisk,intervention:C.intervention,proficiencyProfile:C.proficiencyProfile});await LA(t.uid,M)}catch(M){console.error("[App] Failed to save hero banner summary:",M)}if(t?.uid){try{const M=await ve(q(N,"diagnosticResults",t.uid));if(M.exists()){const W=M.data();W?.riskProfile&&(Pt(W.riskProfile.weak_domains||[]),Fe(W.riskProfile.critical_gaps||[]))}vp()}catch(M){console.error("[diagnostic] Failed to refresh risk data:",M)}try{await dt(q(N,"users",t.uid),{initialAssessmentCompleted:!0,assessmentDismissed:!1,assessmentCompletedAt:ce()}),await Lo(t.uid,50,"initial_assessment","Initial assessment completed")}catch(M){console.error("[App] Failed to persist assessment completion:",M)}try{await DA({uid:t.uid,testId:cn||"diagnostic",title:"Diagnostic Assessment",subject:"General Mathematics",type:"diagnostic",score:C.overallScorePercent,totalQuestions:Object.values(C.competencyScores||{}).reduce((M,W)=>M+W.attempted,0),risk:C.overallRisk,intervention:C.intervention,xpEarned:C.xpEarned,badgeUnlocked:C.badgeUnlocked})}catch(M){console.error("[App] Failed to persist grade result:",M)}}},xp=()=>{f("AI Chat")},Sp=async(C,M)=>{if(t)try{const W=await Lo(t.uid,C,"manual",M);B(W.xp),W.leveledUp&&R(W.newLevel),H(pe=>pe+C),await r(),ae({show:!0,xp:C,message:M})}catch(W){console.error("Error awarding XP:",W)}},ro=async()=>{try{await eu(),on({}),f("Dashboard"),Z(!1)}catch(C){console.error("Error logging out:",C)}},_n=async C=>{if(!t){K(!1),ee(!1);return}const M={};["name","email","phone","photo","avatarLayers","gender","lrn","grade","section","school","enrollmentDate","major","gpa","department","subject","yearsOfExperience","qualification","position"].forEach(pe=>{C[pe]!==void 0&&(M[pe]=C[pe])});try{await zP(t.uid,M),on(pe=>({...pe,...M})),K(!1),ee(!1),ct.success("Profile updated successfully")}catch(pe){console.error("Error saving profile:",pe),ct.error("Failed to update profile")}},oo=async C=>{if(t?.uid)try{const M=await tC(t.uid,C);$t(M),ct.success("Settings saved successfully")}catch(M){throw console.error("Error saving settings:",M),ct.error("Failed to save settings"),M}},io=async()=>{if(!t?.uid)return;const C=await oC(t.uid),M=new Blob([JSON.stringify(C,null,2)],{type:"application/json"}),W=URL.createObjectURL(M),pe=document.createElement("a");pe.href=W,pe.download=`mathpulse-data-export-${t.uid}-${Date.now()}.json`,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe),URL.revokeObjectURL(W),ct.success("Data export downloaded")},ao=async()=>{await rC(),ct.success("Local cache cleared")},co=async()=>{if(!t)throw new Error("No active profile found.");const C=n==="student"?_?.lrn||t.uid:void 0;n==="student"&&(await yr(q(N,"diagnosticResults",t.uid)).catch(()=>{}),await yr(q(N,"competencyProfiles",t.uid)).catch(()=>{}));const{resetTestingDataForRole:M}=await oe(async()=>{const{resetTestingDataForRole:pe}=await import("./testResetService-3LGLpyer.js");return{resetTestingDataForRole:pe}},__vite__mapDeps([98,1,2,3,4,5,6,7,8,9,10])),W=await M({uid:t.uid,role:n,lrn:C});n==="student"&&(R(1),B(0),H(0),Pt([]),Fe([]),mt(null),Hn(!1),Zn(!1),et("0.00"),f("Dashboard"),r(),Kn(pe=>pe+1)),ct.success(W.summary)},We=t?{uid:t.uid,name:t.name,email:t.email,phone:t.phone||"",photo:t.photo||"",avatarLayers:t.avatarLayers,role:t.role,...n==="student"&&_?{lrn:_.lrn,grade:_.grade,section:_.section,school:_.school,enrollmentDate:_.enrollmentDate,major:_.major,gpa:Pn}:{},...Je}:{uid:void 0,name:"User",email:"",phone:"",photo:"",avatarLayers:void 0,role:n},js=We.name.trim().split(/\s+/).find(C=>/\p{L}/u.test(C))||We.name.trim()||"User";if(h.useEffect(()=>{const C=M=>{if(!(M.target instanceof HTMLInputElement||M.target instanceof HTMLTextAreaElement)&&M.altKey)switch(M.key.toLowerCase()){case"d":M.preventDefault(),U("Dashboard");break;case"m":M.preventDefault(),U("Modules");break;case"c":M.preventDefault(),U("AI Chat");break;case"g":M.preventDefault(),U("Grades");break;case"b":M.preventDefault(),U("Quiz Battle");break;case"s":M.preventDefault(),ee(!0);break;case"p":M.preventDefault(),K(!0);break;case"k":M.preventDefault(),Le(W=>!W);break}};if(e&&n==="student")return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e,n]),h.useEffect(()=>{const C=M=>{const W=M.detail;W?.tab&&e&&U(W.tab)};return window.addEventListener("mathpulse:navigate",C),()=>window.removeEventListener("mathpulse:navigate",C)},[e]),s)return b.jsx(ns,{});if(S&&(!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(Ti,{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($A,{})});if(!(n!=="student"||Ve))return b.jsx(ns,{message:"Preparing your dashboard..."});if(n==="teacher")return b.jsx(Vo,{children:b.jsxs(b.Fragment,{children:[b.jsx(qo,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading teacher dashboard..."}),children:b.jsx(FA,{onLogout:ro,onOpenProfile:()=>K(!0),onOpenSettings:()=>ee(!0)})}),ge&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Wo,{isOpen:ge,onClose:()=>K(!1),profileData:We,onSave:_n})}),O&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ho,{isOpen:O,onClose:()=>ee(!1),profileData:We,onSave:_n,settingsData:it,onSaveSettings:oo,onApplySettingsPreview:$t,onExportData:io,onClearCache:ao,onResetData:co})}),b.jsx(zo,{position:"top-right",richColors:!0,closeButton:!0})]})});if(n==="admin")return b.jsx(Vo,{children:b.jsxs(b.Fragment,{children:[b.jsx(qo,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading admin dashboard..."}),children:b.jsx(VA,{onLogout:ro,onOpenProfile:()=>K(!0),onOpenSettings:()=>ee(!0)})}),ge&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Wo,{isOpen:ge,onClose:()=>K(!1),profileData:We,onSave:_n})}),O&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ho,{isOpen:O,onClose:()=>ee(!1),profileData:We,onSave:_n,settingsData:it,onSaveSettings:oo,onApplySettingsPreview:$t,onExportData:io,onClearCache:ao,onResetData:co})}),b.jsx(zo,{position:"top-right",richColors:!0,closeButton:!0})]})});const kp=b.jsx(Vo,{children:b.jsxs(b.Fragment,{children:[b.jsx(qo,{}),b.jsx(V_,{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(Du,{activeTab:l,setActiveTab:U,userRole:n,onOpenSettings:()=>ee(!0),onLogout:()=>Z(!0),sidebarCollapsed:g,setSidebarCollapsed:y,forceCollapsed:l==="Quiz Battle"})})}),v&&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:()=>k(!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(Du,{mode:"mobile",onRequestClose:()=>k(!1),activeTab:l,setActiveTab:U,userRole:n,onOpenSettings:()=>{ee(!0),k(!1)},onLogout:()=>{Z(!0),k(!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:()=>k(!0),"aria-label":"Open navigation",children:b.jsx(zx,{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, ",We.name.split(" ")[0],"!"]})]}),b.jsxs("div",{className:"hidden md:flex items-center gap-2 ml-2",children:[b.jsxs("button",{onClick:()=>J(!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(pr,{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 ",w]})]}),b.jsxs("button",{onClick:()=>J(!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:`${V}/${se} XP to next level`,children:[b.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b.jsx(Pi,{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:[A," 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,V/se*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(mr,{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:()=>Le(C=>!C),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(wx,{size:20,className:"group-hover:scale-110 transition-transform"})}),b.jsx(h.Suspense,{fallback:c,children:b.jsx(GA,{})}),b.jsxs("button",{onClick:()=>K(!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: ${We.name}`,children:[b.jsx(mA,{src:We.photo,name:We.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:js})})]})]})]}),b.jsx("main",{ref:m,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(Nf,{mode:"wait",children:b.jsx(On.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(BA,{userName:js,userLevel:w,avatarLayers:We.avatarLayers,onContinueLearning:()=>U("Modules"),showAssessmentTooltip:!Wt&&Wt!==null,onOpenAssessment:yp,studentId:t?.uid,assessmentCompleted:Wt===!0})}),an&&Wt&>.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(Ti,{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:()=>U("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(fx,{className:"h-3.5 w-3.5"})]})]}),b.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:zs.map((C,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,". ",gA[C]]},C))})]}),an&&Te.length>0&&b.jsx(h.Suspense,{fallback:a,children:b.jsx(WA,{atRiskSubjects:Te,onTopicClick:C=>{U("Modules")}})}),Ve&&an&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(HA,{modules:ue,onNavigateToModules:C=>U("Modules",C),atRiskSubjects:Te,priorityTopics:zs})})}),Ve&&an&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(ZA,{})})})]}),b.jsx("div",{className:"col-span-12 xl:col-span-3 pt-2",children:an?b.jsx(h.Suspense,{fallback:d,children:b.jsx(UA,{currentUserId:t?.uid||"",onOpenRewards:()=>J(!0),onOpenLeaderboard:()=>f("Leaderboard"),onNavigateToModules:()=>f("Modules"),onNavigateToQuizBattle:()=>U("Quiz Battle"),userLevel:w,userPhoto:We.photo,currentXP:V,xpToNextLevel:se,overallXP:A,userName:js})}):d})]})}):l==="Modules"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(KA,{onEarnXP:Sp,atRiskSubjects:Te,priorityTopics:zs,initialModuleId:pt,isInQuizMode:Os,setIsInQuizMode:Ge,hasCompletedDiagnostic:Wt??!1})}):l==="Leaderboard"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(YA,{currentUserPhoto:We.photo})}):l==="Quiz Battle"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(JA,{})}):l==="AI Chat"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(QA,{})}):l==="Grades"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(XA,{})}):l==="Avatar Studio"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(eR,{onSaveProfile:C=>{on(M=>({...M,avatarLayers:C}))},onNavigateToModules:()=>U("Modules")})}):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(tR,{constraintsRef:p,onFullScreen:xp})})}),b.jsx(h.Suspense,{fallback:null,children:b.jsx(qA,{xp:we.xp,message:we.message,show:we.show,onComplete:()=>ae(C=>({...C,show:!1}))})}),G&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(nR,{isOpen:G,onClose:()=>J(!1),userLevel:w,currentXP:V,xpToNextLevel:se,totalXP:F,userId:t?.uid||""})}),ge&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Wo,{isOpen:ge,onClose:()=>K(!1),profileData:We,onSave:_n})}),le&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(sR,{isOpen:le,onClose:()=>Z(!1),onConfirm:ro,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"})}),O&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ho,{isOpen:O,onClose:()=>ee(!1),profileData:We,onSave:_n,settingsData:it,onSaveSettings:oo,onApplySettingsPreview:$t,onExportData:io,onClearCache:ao,onResetData:co})}),Ye&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(rR,{isOpen:Ye,onClose:()=>Le(!1)})}),Tn&&!at&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(oR,{isOpen:Tn&&!at,onClose:()=>rt(!1),onDismiss:()=>{rt(!1),Hn(!0)},userId:t?.uid||"",strand:_?.major||"STEM",gradeLevel:_?.grade||"Grade 11",onAssessmentStart:wp,onAssessmentComplete:Ga})}),at&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(iR,{testId:cn,questions:Ee,userName:js,onComplete:Ga,onCancel:()=>{Qn(!1),f("Dashboard")}})}),so&&t?.uid&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(aR,{userId:t.uid,mode:"fullscreen",onClose:()=>{Xn(!1),f("Dashboard")}})})]})]})}),b.jsx(zo,{position:"top-right",richColors:!0,closeButton:!0})]})});return b.jsx(NP,{children:kp})},nr="mathpulse_chunk_reload_attempted",lR=[/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 Ou(e){return e?.message?lR.some(t=>t.test(e.message)):!1}class uR 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),Ou(t))try{sessionStorage.getItem(nr)||(sessionStorage.setItem(nr,String(Date.now())),console.warn("[ErrorBoundary] Stale chunk detected — reloading to recover."),window.location.reload())}catch{}}handleReset=()=>{try{sessionStorage.removeItem(nr)}catch{}this.setState({hasError:!1,error:null})};render(){if(this.state.hasError){if(Ou(this.state.error)){let t=!1;try{t=!!sessionStorage.getItem(nr)}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}}sC();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 gp=document.getElementById("root");if(!gp)throw new Error("Root element not found");Pp.createRoot(gp).render(b.jsx(uR,{children:b.jsx(Xg,{children:b.jsx(Mm,{client:zi,children:b.jsx(jP,{children:b.jsx(cR,{})})})})}));export{Ex as $,Cl as A,bx as B,wx as C,KR as D,Ol as E,Al as F,Rl as G,ns as H,gx as I,mA as J,UE as K,Ox as L,zx as M,ye as N,bn as O,zr as P,dA as Q,Nx as R,Ml as S,Dl as T,Jx as U,Mu as V,fA as W,mr as X,kR as Y,Pi as Z,oe as _,fx as a,qR as a$,Gs as a0,nM as a1,tM as a2,DR as a3,pr as a4,Vx as a5,Vo as a6,Kh as a7,cC as a8,yA as a9,Pm as aA,hm as aB,Ze as aC,SR as aD,MR as aE,JR as aF,eM as aG,qE as aH,OR as aI,IR as aJ,iS as aK,Yf as aL,LR as aM,zP as aN,B_ as aO,Rx as aP,kx as aQ,Ux as aR,_R as aS,xu as aT,Su as aU,HR as aV,ZR as aW,iC as aX,aC as aY,gr as aZ,GR as a_,XR as aa,NR as ab,VR as ac,FR as ad,$R as ae,UR as af,BR as ag,Lo as ah,zR as ai,AA as aj,MA as ak,jR as al,YR as am,CE as an,gA as ao,Nr as ap,ym as aq,um as ar,xR as as,Qo as at,St as au,$u as av,cm as aw,lm as ax,Ko as ay,zu as az,Mo as b,WR as b0,rS as b1,qt as b2,Jr as b3,s_ as b4,PR as b5,ZE as b6,QR as b7,CR as c,AR as d,fe as e,Zh as f,N as g,Nf as h,Ll as i,ct as j,VE as k,wt as l,On as m,mn as n,Dt as o,Ix as p,Il as q,hA as r,ER as s,Hh as t,Ms as u,z as v,RR as w,Ti as x,QE as y,Xx as z}; +`);if(!F){w=T(k);continue}if(A==="chunk"){let H=F;try{const se=JSON.parse(F);typeof se?.chunk=="string"&&(H=se.chunk)}catch{}H&&(S+=H,n(H),f())}else if(A==="error"){let H="Streaming failed on server.";try{const se=JSON.parse(F);typeof se?.detail=="string"&&se.detail.trim()&&(H=se.detail)}catch{F.trim()&&(H=F.trim())}throw new Error(H)}w=T(k)}}if(x)return{response:S};throw new Error("Stream closed before end event.")}catch(y){throw a==="idle"?new bn("/api/chat/stream",yu):a==="total"?new bn("/api/chat/stream",$o):y instanceof DOMException&&y.name==="AbortError"?new bn("/api/chat/stream",$o):y}finally{if(l(),g)try{await g.cancel()}catch{}}}return await z("/api/chat",{method:"POST",body:JSON.stringify(r)},AE)},async chatSafe(e,t,n){return ss(()=>wt.chat(e,t,void 0,n),DE,"chat")},async predictRisk(e){Se("/api/predict-risk",{engagementScore:e.engagementScore,avgQuizScore:e.avgQuizScore,attendance:e.attendance,assignmentCompletion:e.assignmentCompletion}),Re("/api/predict-risk","engagementScore",e.engagementScore,0,100),Re("/api/predict-risk","avgQuizScore",e.avgQuizScore,0,100),Re("/api/predict-risk","attendance",e.attendance,0,100),Re("/api/predict-risk","assignmentCompletion",e.assignmentCompletion,0,100);const t=await z("/api/predict-risk",{method:"POST",body:JSON.stringify(e)});if(!NE(t))throw Ne("/api/predict-risk","POST","Invalid response shape",t),new Error("Invalid risk prediction response from server");return t},async predictRiskSafe(e){return ss(()=>wt.predictRisk(e),OE,"predictRisk")},async predictRiskBatch(e){if(!Array.isArray(e)||e.length===0)throw new je("/api/predict-risk/batch","students array must not be empty");return z("/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 je("/api/learning-path","weaknesses must be a non-empty array");return z("/api/learning-path",{method:"POST",body:JSON.stringify(e)},Qt)},async getLearningPathSafe(e){return ss(()=>wt.getLearningPath(e),LE,"getLearningPath")},async getDailyInsight(e,t){if(!Array.isArray(e.students)||e.students.length===0)throw new je("/api/analytics/daily-insight","students array must not be empty");return z("/api/analytics/daily-insight",{method:"POST",body:JSON.stringify(e),signal:t?.signal},Qt)},async getDailyInsightSafe(e){return ss(()=>wt.getDailyInsight(e),zE,"getDailyInsight")},async getImportedClassOverview(e){if(!e?.forceRefresh&&!Fo&&Date.now()!r||r.size===0))throw new je("/api/upload/class-records","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new je("/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"),z("/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 vu(`/api/templates/class-records${n?`?${n}`:""}`,{method:"GET"},3e4)},async uploadClassRecordTemplate(e,t){if(!e||e.size===0)throw new je("/api/class-records/upload","File must be non-empty");if(e.size>10*1024*1024)throw new je("/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),z("/api/class-records/upload",{method:"POST",body:n},rs)},async previewStudentAccountImport(e,t){if(!e||e.size===0)throw new je("/api/import/student-accounts/preview","A non-empty file is required");if(e.size>10*1024*1024)throw new je("/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),z("/api/import/student-accounts/preview",{method:"POST",body:n},rs)},async commitStudentAccountImport(e){return Se("/api/import/student-accounts/commit",{previewToken:e.previewToken}),z("/api/import/student-accounts/commit",{method:"POST",body:JSON.stringify(e)},Ct)},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 z("/api/teacher/create-student-account",{method:"POST",body:JSON.stringify(t)},Ct)},async getAdminUsers(e){const t=e?.page??1,n=e?.pageSize??25;Re("/api/admin/users","page",t,1,1e4),Re("/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()),z(`/api/admin/users?${s.toString()}`,{method:"GET"},RE)},async updateAdminUser(e,t){const n=e.trim();Se("/api/admin/users",{uid:n});const s=new URLSearchParams;return s.set("uid",n),z(`/api/admin/users?${s.toString()}`,{method:"PATCH",body:JSON.stringify(t)},Ct)},async bulkAdminUsers(e){return Se("/api/admin/users/bulk-action",{action:e.action}),z("/api/admin/users/bulk-action",{method:"POST",body:JSON.stringify(e)},Ct)},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 je("/api/admin/users","lrn is required for student accounts");return z("/api/admin/users",{method:"POST",body:JSON.stringify(e)},Ct)},async deleteAdminUser(e){const t=e.trim();Se("/api/admin/users",{uid:t});const n=new URLSearchParams;return n.set("uid",t),z(`/api/admin/users?${n.toString()}`,{method:"DELETE"},Ct)},async getRiskRefreshMonitor(e){const t=e?.limit??10;Re("/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),z(`/api/upload/class-records/risk-refresh/recent?${n.toString()}`)},async getImportGroundedTelemetrySummary(e){const t=e?.days??7,n=e?.limit??5e3;Re("/api/feedback/import-grounded/summary","days",t,1,30),Re("/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),z(`/api/feedback/import-grounded/summary?${s.toString()}`)},async getImportGroundedAccessAudit(e){const t=e?.days??7,n=e?.limit??200;Re("/api/import-grounded/access-audit","days",t,1,30),Re("/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),z(`/api/import-grounded/access-audit?${s.toString()}`)},async exportImportGroundedAccessAuditCsv(e){const t=e?.days??7,n=e?.limit??200;Re("/api/import-grounded/access-audit","days",t,1,30),Re("/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),vu(`/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 je("/api/upload/course-materials","At least one file is required");if(n.some(r=>!r||r.size===0))throw new je("/api/upload/course-materials","All files must be non-empty");if(n.some(r=>r.size>10*1024*1024))throw new je("/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),z("/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),z("/api/teacher-materials/upload",{method:"POST",body:n},rs)},async getRecentCourseMaterials(e){const t=e?.limit??10;Re("/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),z(`/api/upload/course-materials/recent?${n.toString()}`)},async getCourseMaterialTopics(e){const t=e?.limit??20;Re("/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),z(`/api/course-materials/topics?${n.toString()}`)},async generateLessonPlan(e){Se("/api/lesson/generate",{gradeLevel:e.gradeLevel});const t={...e,preferImportedTopics:pu&&(e.preferImportedTopics??!0)};if(gu){const n=await wt.submitLessonPlanAsync(t),r=(await wt.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 z("/api/lesson/generate",{method:"POST",body:JSON.stringify(t)},Qt)},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 je("/api/quiz/generate","topics must be a non-empty array");const n={...e,preferImportedTopics:No&&(e.preferImportedTopics??!0)};if(gu){const r=await wt.submitQuizAsync(n);t?.onTaskCreated?.(r.taskId);const i=(await wt.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(!wu(i))throw new Error("Invalid quiz generation response from async task payload.");return i}const s=await z("/api/quiz/generate",{method:"POST",body:JSON.stringify(n)},Qt);if(!wu(s))throw Ne("/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:No&&(e.preferImportedTopics??!0)};return z("/api/quiz/preview",{method:"POST",body:JSON.stringify(t)},Qt)},async submitLessonPlanAsync(e){return z("/api/lesson/generate-async",{method:"POST",body:JSON.stringify(e)},Qt)},async submitQuizAsync(e){return z("/api/quiz/generate-async",{method:"POST",body:JSON.stringify(e)},Qt)},async getTaskStatus(e){return Se("/api/tasks/{taskId}",{taskId:e}),z(`/api/tasks/${encodeURIComponent(e)}`)},async listTasks(e){const t=new URLSearchParams;e?.limit!=null&&(Re("/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 z(`/api/tasks${n?`?${n}`:""}`)},async cancelTask(e){return Se("/api/tasks/{taskId}/cancel",{taskId:e}),z(`/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 wt.getTaskStatus(e);if(t?.onProgress?.(o),o.status==="completed")return o;if(o.status==="failed"||o.status==="cancelled")throw new Error(FE(o.error));await $E(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 z(`/api/quiz/topics${t}`)},async getStudentCompetency(e,t){return Se("/api/quiz/student-competency",{studentId:e}),z("/api/quiz/student-competency",{method:"POST",body:JSON.stringify({studentId:e,quizHistory:t})})},async evaluateExpression(e){return Se("/api/calculator/evaluate",{expression:e}),z("/api/calculator/evaluate",{method:"POST",body:JSON.stringify({expression:e})})},async evaluateExpressionSafe(e){return ss(()=>wt.evaluateExpression(e),{...jE,expression:e},"evaluateExpression")},async automationDiagnosticCompleted(e){return Se("/api/automation/diagnostic-completed",{lrn:e.lrn,results:e.results}),z("/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}),z("/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}),z("/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}),z("/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}),z("/api/automation/content-updated",{method:"POST",body:JSON.stringify(e)})},getInferenceMetrics:async()=>z("/api/ops/inference-metrics",{method:"GET"}),getModelConfig:async()=>z("/api/admin/model-config",{method:"GET"}),setModelProfile:async e=>z("/api/admin/model-config/profile",{method:"POST",body:JSON.stringify({profile:e})}),setModelOverride:async(e,t)=>z("/api/admin/model-config/override",{method:"POST",body:JSON.stringify({key:e,value:t})}),resetModelConfig:async()=>z("/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 z("/api/admin/reingest-pdf",{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({subjectId:e,storagePath:t})})},getRagHealth:async()=>z("/api/rag/health",{method:"GET"}),adminDeleteFile:async(e,t)=>z("/api/admin/delete-file",{method:"POST",body:JSON.stringify({fileId:e,collection:t})}),async generateInterventionPlan(e){return z("/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 z(`/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 z(`/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 z(`/api/class-records/${e}/students${s?`?${s}`:""}`,{method:"GET"})},async generateClassReport(e){return z(`/api/class-records/${e}/ai-report`,{method:"POST"})},async generateQuizFromModule(e){return z(`/api/teacher-materials/${e}/generate-quiz`,{method:"POST"})},async getStudentRecommendations(e){return z(`/api/student/${e}/recommendations`,{method:"GET"})}};async function VE(e,t,n,s){Se("/api/rag/lesson",{topic:e,subject:t,quarter:n}),Re("/api/rag/lesson","quarter",n,1,4);const r=await z("/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 BE(e,t,n,s){Se("/api/rag/generate-problem",{topic:e,subject:t,quarter:n,difficulty:s}),Re("/api/rag/generate-problem","quarter",n,1,4);const r=await z("/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 UE(e,t){return!Array.isArray(e)||e.length===0?"":(await z("/api/rag/analysis-context",{method:"POST",body:JSON.stringify({weakTopics:e,subject:t})})).curriculumContext||""}async function qE(e){const t=e?`?grade_level=${encodeURIComponent(e)}`:"";return z(`/api/curriculum/subjects${t}`)}async function GE(e){try{return await z(`/api/curriculum/subjects/${e}`)}catch{return null}}async function WE(e){try{return await z(`/api/curriculum/subjects/${e}/topics`)}catch{return[]}}async function HE(e,t){try{return await z(`/api/curriculum/subjects/${e}/topics/${t}`)}catch{return null}}const ZE=Object.freeze(Object.defineProperty({__proto__:null,ApiError:Dt,ApiNetworkError:zr,ApiTimeoutError:bn,ApiValidationError:je,apiFetch:z,apiService:wt,fetchAnalysisCurriculumContext:UE,generateGroundedProblem:BE,generateRagLesson:_E,generateRagProblem:EE,getCurriculumGroundedLesson:VE,getCurriculumSubject:GE,getCurriculumSubjects:qE,getCurriculumTopic:HE,getCurriculumTopics:WE,getRagAnalysisContext:CE,getRagHealth:PE,warmupBackend:IE},Symbol.toStringTag,{value:"Module"})),Fh="competencyProfiles",jR=async e=>{const t=q(N,Fh,e),n=await ve(t);return n.exists()?n.data():null},KE=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:ce(),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:ce()}])),primaryWeakness:i,primaryStrength:o,suggestedModule:a,updatedAt:ce()};await $e(q(N,Fh,e),c,{merge:!0})},Jr=async e=>{const t={userId:e,subjects:{},lessons:{},quizAttempts:[],totalLessonsCompleted:0,totalQuizzesCompleted:0,averageScore:0,updatedAt:new Date};return await $e(q(N,"progress",e),t),t},QE=async e=>{try{const t=q(N,"progress",e),n=await ve(t);if(n.exists()){const s=n.data();return{...s,updatedAt:s.updatedAt?.toDate()||new Date}}return await Jr(e)}catch(t){return console.error("Error getting user progress:",t),null}},NR=(e,t)=>{const n=q(N,"progress",e);return Yt(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)})},$R=async(e,t,n)=>{const s=Math.max(0,Math.min(100,n)),r=q(N,"progress",e);await $e(r,{[`lessons.${t}.lessonId`]:t,[`lessons.${t}.progressPercent`]:s,updatedAt:ce()},{merge:!0})},FR=async(e,t,n,s,r)=>{const o=q(N,"progress",e),i=await ve(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 $e(o,{[`subjects.${t}.modulesProgress.${n}.progress`]:f,[`subjects.${t}.modulesProgress.${n}.lastAccessedAt`]:ce(),updatedAt:ce()},{merge:!0}),f},VR=async(e,t,n,s,r,o=50,i,a)=>{try{const c=q(N,"progress",e);let u=await ve(c);u.exists()||(await Jr(e),u=await ve(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 $e(c,{[`lessons.${s}`]:l,[`subjects.${t}.modulesProgress.${n}`]:p,...m&&{totalLessonsCompleted:fs(1)},updatedAt:ce()},{merge:!0}),await Vh(e,o,"lesson_complete",`Completed lesson: ${s}`)}catch(c){throw console.error("Error completing lesson:",c),c}},BR=async(e,t,n,s,r,o)=>{try{const i=q(N,"progress",e);let a=await ve(i);a.exists()||(await Jr(e),a=await ve(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:ce()})}catch(i){throw console.error("Error recording practice quiz:",i),i}},UR=async(e,t,n,s,r,o,i,a)=>{try{const c=q(N,"progress",e);let u=await ve(c);u.exists()||(await Jr(e),u=await ve(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:ce()}),await Vh(e,f,"quiz_complete",`Completed quiz: ${s} (Score: ${r}%)`)}catch(c){throw console.error("Error completing quiz:",c),c}},Vh=async(e,t,n,s)=>{try{const r=q(N,"users",e);let o=1;try{const u=(await ve(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:ce()});const a=q(Xe(N,"xpActivities"));await $e(a,{activityId:a.id,userId:e,type:n,xpEarned:i,description:s,timestamp:ce()})}catch(r){console.error("Error awarding XP:",r)}},gr={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"}},XE=300*1e3,YE=1800*1e3,zi=new Rm({defaultOptions:{queries:{staleTime:XE,gcTime:YE,retry:1,refetchOnWindowFocus:!1}}}),JE=async()=>{await zi.cancelQueries(),zi.clear()},xu={quizDefaults:{timeLimitMinutes:30,passingScore:75,maxAttempts:3},classPreferences:{autoEnroll:!1,classVisibility:"public"},studentAnalyticsVisibility:!0,notifyOnSubmission:!0,notifyOnStudentActivity:!1},Su={maintenanceMode:!1,defaultGradeLevel:"Grade 11",defaultCurriculum:"STEM",maxClassSize:50,auditLogVisible:!0,aiConfig:{modelName:"deepseek-chat",temperature:.7,endpoint:"https://api.deepseek.com"}},eC="preferences",Na=()=>JSON.parse(JSON.stringify(gr)),Bh=e=>{const t=Na();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},$a=e=>q(N,"users",e,"settings",eC),Uh=async e=>{const t=$a(e),n=await ve(t);if(!n.exists()){const s=Na();return await $e(t,{...s,createdAt:ce(),updatedAt:ce()}),s}return Bh(n.data())},tC=async(e,t)=>{const n=await Uh(e),s=Bh({...n,...t});return await $e($a(e),{...s,updatedAt:ce()},{merge:!0}),s},qh="mathpulse_appearance",nC=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(qh,JSON.stringify(e.appearance))}catch{}},sC=()=>{try{const e=localStorage.getItem(qh);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{}},rC=async()=>{try{if(await JE(),A_(),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.")}},oC=async e=>{const t=q(N,"users",e),n=await ve(t),s=await ve($a(e)),r=["progress","xpActivities","achievements","notifications","tasks","chatSessions","chatMessages"],o=await Promise.all(r.map(async i=>{const a=Ot(Xe(N,i),Mt("userId","==",e)),c=await zn(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():Na(),collections:o.reduce((i,a)=>(i[a.collectionName]=a.items,i),{})}},Fa=async e=>{const t=ye.currentUser;if(!t||!t.email)throw new Error("No user logged in");const n=Zp.credential(t.email,e);await Kp(t,n)},qR=async(e,t)=>{if(await Fa(e),!ye.currentUser)throw new Error("Re-auth failed");await Wp(ye.currentUser,t)},GR=async(e,t)=>{if(await Fa(e),!ye.currentUser)throw new Error("Re-auth failed");await Gp(ye.currentUser,t)},WR=async(e,t)=>{if(await Fa(e),!ye.currentUser)throw new Error("Re-auth failed");await Hp(ye.currentUser);try{const{deleteDoc:n}=await oe(async()=>{const{deleteDoc:s}=await import("./vendor-firebase-firestore-CNv3xXal.js");return{deleteDoc:s}},__vite__mapDeps([1,2]));await n(q(N,"users",t))}catch{}},Gh=e=>q(N,"users",e,"settings","teacherPreferences"),iC=async e=>{const t=await ve(Gh(e));return t.exists()?{...xu,...t.data()}:{...xu}},HR=async(e,t)=>{const n=await iC(e),s={...n,...t,quizDefaults:{...n.quizDefaults,...t.quizDefaults},classPreferences:{...n.classPreferences,...t.classPreferences}};return await $e(Gh(e),{...s,updatedAt:ce()},{merge:!0}),s},Wh=()=>q(N,"system","config"),aC=async()=>{const e=await ve(Wh());return e.exists()?{...Su,...e.data()}:{...Su}},ZR=async e=>{const t=await aC(),n={...t,...e,aiConfig:{...t.aiConfig,...e.aiConfig}};return await $e(Wh(),{...n,updatedAt:ce()},{merge:!0}),n};function Hh(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 Zh(e){const t=Hh(e);return t.setHours(0,0,0,0),t}function cC(e){const t=Hh(e);return t.setHours(23,59,59,999),t}function Gn(){const e=ye.currentUser?.uid??null;return e||console.warn("[notificationFirestoreService] Skipping Firestore call — user not authenticated"),e}const lC=e=>{const t=e.data(),n=t.createdAt,s=n instanceof Dn?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}},uC=async e=>{if(!Gn())throw new Error("Cannot create notification — not authenticated");try{const n=q(Xe(N,"notifications",e.userId,"items")),s={userId:e.userId,type:e.type,title:e.title,message:e.message,isRead:!1,createdAt:ce(),...e.metadata?{metadata:e.metadata}:{},...e.actionUrl?{actionUrl:e.actionUrl}:{}};return await $e(n,s),n.id}catch(n){throw console.error("[notificationFirestoreService] Error creating notification:",n),n}},dC=async(e,t)=>{if(Gn())try{const n=q(N,"notifications",e,"items",t),s=dt(n,{isRead:!0}).catch(i=>console.warn("[firestore] markAsRead subcollection skipped:",i)),r=q(N,"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}},fC=async e=>{if(Gn())try{const t=Ot(Xe(N,"notifications",e,"items"),Mt("isRead","==",!1)),s=(await zn(t)).docs.map(r=>dt(r.ref,{isRead:!0}));try{const r=Ot(Xe(N,"notifications"),Mt("userId","==",e),Mt("read","==",!1)),o=await zn(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}},hC=async(e,t)=>{try{const n=q(N,"notifications",e,"items",t),s=yr(n).catch(i=>console.warn("[firestore] deleteNotification subcollection skipped:",i)),r=q(N,"notifications",t),o=yr(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}},pC=(e,t)=>{const n=Gn();if(!n||n!==e)return console.warn("[notificationFirestoreService] subscribeToNotifications skipped — auth UID mismatch or not signed in"),t([]),()=>{};const s=Ot(Xe(N,"notifications",e,"items"),vn("createdAt","desc")),r=Ot(Xe(N,"notifications"),Mt("userId","==",e),vn("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=Yt(s,f=>{o=f.docs.map(p=>lC(p)),a=!0,c&&u()},()=>{a=!0,c&&u()}),l=Yt(r,f=>{i=f.docs.map(p=>{const m=p.data(),g=m.createdAt,y=g instanceof Dn?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()}},mC=async e=>{if(!Gn())return!1;try{const t=new Date,n=Zh(t),s=cC(t),r=Ot(Xe(N,"notifications",e,"items"),Mt("type","==","daily_checkin"),Mt("createdAt",">=",n),Mt("createdAt","<=",s),vn("createdAt","asc"),ks(1));return!(await zn(r)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking daily check-in:",t),!1}},gC=async e=>{if(!Gn())return!1;try{const n=Zh(new Date),s=Ot(Xe(N,"notifications",e,"items"),Mt("type","==","streak_reminder"),Mt("createdAt",">=",n),vn("createdAt","asc"),ks(1));return!(await zn(s)).empty}catch(t){return console.error("[notificationFirestoreService] Error checking reminder:",t),!1}};async function Kh(e){try{await uC(e)}catch(t){console.error("[NotificationService] Failed to create notification:",t)}}function yC(e){const t=h.useRef(!1);h.useEffect(()=>{if(!e||t.current)return;t.current=!0,(async()=>{try{if(await mC(e)||await gC(e))return;await Kh({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 Qh=h.createContext(null),Vo=({children:e})=>{const{currentUser:t,userProfile:n}=Ms(),[s,r]=h.useState([]),[o,i]=h.useState(!0),a=t?.uid??null,c=h.useRef([]);yC(n?.role==="student"?a:null),h.useEffect(()=>{if(!a)return r([]),i(!1),()=>{};i(!0);const m=pC(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 dC(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 fC(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 hC(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(Qh.Provider,{value:p,children:e})},KR=()=>{const e=h.useContext(Qh);if(!e)throw new Error("useNotifications must be used within a NotificationProvider");return e},ku="/firebase-messaging-sw.js";let Bo=null,Tu=!1,Uo=!1;async function Va(){if(!Tu){try{Uo=await zp()}catch{Uo=!1}Tu=!0}return Uo?(Bo||(Bo=jp(qt)),Bo):null}async function bC(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.getRegistration(ku);return e||await navigator.serviceWorker.register(ku,{scope:"/"})}catch(e){return console.warn("[pushNotificationService] SW registration failed:",e),null}}async function Xh(e){if(!e||typeof window>"u"||typeof Notification>"u")return null;const t=await Va();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 bC();if(!r)return null;let o=null;try{o=await Lp(t,{vapidKey:s,serviceWorkerRegistration:r})}catch(i){return console.warn("[pushNotificationService] getToken failed:",i),null}if(!o)return null;try{const i=q(N,"users",e,"fcmTokens",o),a={token:o,userId:e,platform:"web",userAgent:typeof navigator<"u"?navigator.userAgent:"",createdAt:ce(),updatedAt:ce(),active:!0};await $e(i,a,{merge:!0})}catch(i){console.warn("[pushNotificationService] persisting token failed:",i)}return o}function Yh(e){let t,n=!1;return Va().then(s=>{n||!s||(t=Op(s,e))}),()=>{n=!0,t?.()}}async function Jh(e,t){if(!(!e||!t)){try{const n=q(N,"users",e,"fcmTokens",t);await dt(n,{active:!1,updatedAt:ce()})}catch(n){console.warn("[pushNotificationService] marking token inactive failed:",n)}try{const n=await Va();n&&await Dp(n)}catch(n){console.warn("[pushNotificationService] deleteToken failed:",n)}}}const QR=Object.freeze(Object.defineProperty({__proto__:null,deregisterPushToken:Jh,onForegroundMessage:Yh,requestPushPermissionAndRegister:Xh},Symbol.toStringTag,{value:"Module"})),vC={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 wC(e){return e?vC[e]??"system_alert":"system_alert"}function xC(){const{currentUser:e}=Ms(),t=Bi(),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 Xh(o);a||(n.current=c,c&&(i=Yh(u=>{const d=u.notification??{},l=u.data??{},f=d.title||l.title||"MathPulse AI",p=d.body||l.body||"",m=l.notificationType;Kh({userId:o,type:wC(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 Jh(o,i),n.current=null)}}}const qo=()=>(xC(),null),SC=(e,t)=>{const n=new Array(e.length+t.length);for(let s=0;s({classGroupId:e,validator:t}),ep=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),jr="-",Pu=[],TC="arbitrary..",PC=e=>{const t=EC(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return _C(i);const a=i.split(jr),c=a[0]===""&&a.length>1?1:0;return tp(a,c,t)},getConflictingClassGroupIds:(i,a)=>{if(a){const c=s[i],u=n[i];return c?u?SC(u,c):c:u||Pu}return n[i]||Pu}}},tp=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const u=tp(e,t+1,o);if(u)return u}const i=n.validators;if(i===null)return;const a=t===0?e.join(jr):e.slice(t).join(jr),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?TC+s:void 0})(),EC=e=>{const{theme:t,classGroups:n}=e;return CC(n,t)},CC=(e,t)=>{const n=ep();for(const s in e){const r=e[s];Ba(r,n,s,t)}return n},Ba=(e,t,n,s)=>{const r=e.length;for(let o=0;o{if(typeof e=="string"){RC(e,t,n);return}if(typeof e=="function"){MC(e,t,n,s);return}IC(e,t,n,s)},RC=(e,t,n)=>{const s=e===""?t:np(t,e);s.classGroupId=n},MC=(e,t,n,s)=>{if(DC(e)){Ba(e(s),t,n,s);return}t.validators===null&&(t.validators=[]),t.validators.push(kC(n,e))},IC=(e,t,n,s)=>{const r=Object.entries(e),o=r.length;for(let i=0;i{let n=e;const s=t.split(jr),r=s.length;for(let o=0;o"isThemeGetter"in e&&e.isThemeGetter===!0,OC=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)}}},ji="!",_u=":",LC=[],Eu=(e,t,n,s,r)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:s,isExternal:r}),zC=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 Eu(o,p,f,m)};if(t){const r=t+_u,o=s;s=i=>i.startsWith(r)?o(i.slice(r.length)):Eu(LC,!1,i,void 0,!0)}if(n){const r=s;s=o=>n({className:o,parseClassName:r})}return s},jC=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}},NC=e=>({cache:OC(e.cacheSize),parseClassName:zC(e),sortModifiers:jC(e),...PC(e)}),$C=/\s+/,FC=(e,t)=>{const{parseClassName:n,getClassGroupId:s,getConflictingClassGroupIds:r,sortModifiers:o}=t,i=[],a=e.trim().split($C);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+ji:k,x=S+v;if(i.indexOf(x)>-1)continue;i.push(x);const T=r(v,y);for(let P=0;P0?" "+c:c)}return c},VC=(...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=NC(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=FC(c,n);return r(c,d),d};return o=i,(...c)=>o(VC(...c))},UC=[],Ae=e=>{const t=n=>n[e]||UC;return t.isThemeGetter=!0,t},rp=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,op=/^\((?:(\w[\w-]*):)?(.+)\)$/i,qC=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,GC=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,WC=/\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$/,HC=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ZC=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,KC=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ht=e=>qC.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),Zt=e=>!!e&&Number.isInteger(Number(e)),Go=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Vt=e=>GC.test(e),ip=()=>!0,QC=e=>WC.test(e)&&!HC.test(e),Ua=()=>!1,XC=e=>ZC.test(e),YC=e=>KC.test(e),JC=e=>!L(e)&&!$(e),eA=e=>rn(e,lp,Ua),L=e=>rp.test(e),dn=e=>rn(e,up,QC),Cu=e=>rn(e,cA,ne),tA=e=>rn(e,fp,ip),nA=e=>rn(e,dp,Ua),Au=e=>rn(e,ap,Ua),sA=e=>rn(e,cp,YC),er=e=>rn(e,hp,XC),$=e=>op.test(e),os=e=>kn(e,up),rA=e=>kn(e,dp),Ru=e=>kn(e,ap),oA=e=>kn(e,lp),iA=e=>kn(e,cp),tr=e=>kn(e,hp,!0),aA=e=>kn(e,fp,!0),rn=(e,t,n)=>{const s=rp.exec(e);return s?s[1]?t(s[1]):n(s[2]):!1},kn=(e,t,n=!1)=>{const s=op.exec(e);return s?s[1]?t(s[1]):n:!1},ap=e=>e==="position"||e==="percentage",cp=e=>e==="image"||e==="url",lp=e=>e==="length"||e==="size"||e==="bg-size",up=e=>e==="length",cA=e=>e==="number",dp=e=>e==="family-name",fp=e=>e==="number"||e==="weight",hp=e=>e==="shadow",lA=()=>{const e=Ae("color"),t=Ae("font"),n=Ae("text"),s=Ae("font-weight"),r=Ae("tracking"),o=Ae("leading"),i=Ae("breakpoint"),a=Ae("container"),c=Ae("spacing"),u=Ae("radius"),d=Ae("shadow"),l=Ae("inset-shadow"),f=Ae("text-shadow"),p=Ae("drop-shadow"),m=Ae("blur"),g=Ae("perspective"),y=Ae("aspect"),v=Ae("ease"),k=Ae("animate"),S=()=>["auto","avoid","all","avoid-page","page","left","right","column"],x=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...x(),$,L],P=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto","contain","none"],w=()=>[$,L,c],R=()=>[Ht,"full","auto",...w()],A=()=>[Zt,"none","subgrid",$,L],B=()=>["auto",{span:["full",Zt,$,L]},Zt,$,L],F=()=>[Zt,"auto",$,L],H=()=>["auto","min","max","fr",$,L],se=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],te=()=>["start","end","center","stretch","center-safe","end-safe"],V=()=>["auto",...w()],ie=()=>[Ht,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],re=()=>[Ht,"screen","full","dvw","lvw","svw","min","max","fit",...w()],ue=()=>[Ht,"screen","full","lh","dvh","lvh","svh","min","max","fit",...w()],D=()=>[e,$,L],he=()=>[...x(),Ru,Au,{position:[$,L]}],st=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",oA,eA,{size:[$,L]}],U=()=>[Go,os,dn],G=()=>["","none","full",u,$,L],J=()=>["",ne,os,dn],we=()=>["solid","dashed","dotted","double"],ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],le=()=>[ne,Go,Ru,Au],Z=()=>["","none",m,$,L],O=()=>["none",ne,$,L],ee=()=>["none",ne,$,L],ge=()=>[ne,$,L],K=()=>[Ht,"full",...w()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Vt],breakpoint:[Vt],color:[ip],container:[Vt],"drop-shadow":[Vt],ease:["in","out","in-out"],font:[JC],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Vt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Vt],shadow:[Vt],spacing:["px",ne],text:[Vt],"text-shadow":[Vt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ht,L,$,y]}],container:["container"],columns:[{columns:[ne,L,$,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:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:R()}],"inset-x":[{"inset-x":R()}],"inset-y":[{"inset-y":R()}],start:[{"inset-s":R(),start:R()}],end:[{"inset-e":R(),end:R()}],"inset-bs":[{"inset-bs":R()}],"inset-be":[{"inset-be":R()}],top:[{top:R()}],right:[{right:R()}],bottom:[{bottom:R()}],left:[{left:R()}],visibility:["visible","invisible","collapse"],z:[{z:[Zt,"auto",$,L]}],basis:[{basis:[Ht,"full","auto",a,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,Ht,"auto","initial","none",L]}],grow:[{grow:["",ne,$,L]}],shrink:[{shrink:["",ne,$,L]}],order:[{order:[Zt,"first","last","none",$,L]}],"grid-cols":[{"grid-cols":A()}],"col-start-end":[{col:B()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":A()}],"row-start-end":[{row:B()}],"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:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...se(),"normal"]}],"justify-items":[{"justify-items":[...te(),"normal"]}],"justify-self":[{"justify-self":["auto",...te()]}],"align-content":[{content:["normal",...se()]}],"align-items":[{items:[...te(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...te(),{baseline:["","last"]}]}],"place-content":[{"place-content":se()}],"place-items":[{"place-items":[...te(),"baseline"]}],"place-self":[{"place-self":["auto",...te()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:V()}],mx:[{mx:V()}],my:[{my:V()}],ms:[{ms:V()}],me:[{me:V()}],mbs:[{mbs:V()}],mbe:[{mbe:V()}],mt:[{mt:V()}],mr:[{mr:V()}],mb:[{mb:V()}],ml:[{ml:V()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:ie()}],"inline-size":[{inline:["auto",...re()]}],"min-inline-size":[{"min-inline":["auto",...re()]}],"max-inline-size":[{"max-inline":["none",...re()]}],"block-size":[{block:["auto",...ue()]}],"min-block-size":[{"min-block":["auto",...ue()]}],"max-block-size":[{"max-block":["none",...ue()]}],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,dn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,aA,tA]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Go,L]}],"font-family":[{font:[rA,nA,t]}],"font-features":[{"font-features":[L]}],"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,$,L]}],"line-clamp":[{"line-clamp":[ne,"none",$,Cu]}],leading:[{leading:[o,...w()]}],"list-image":[{"list-image":["none",$,L]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,L]}],"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:[...we(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",$,dn]}],"text-decoration-color":[{decoration:D()}],"underline-offset":[{"underline-offset":[ne,"auto",$,L]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,L]}],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",$,L]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:he()}],"bg-repeat":[{bg:st()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Zt,$,L],radial:["",$,L],conic:[Zt,$,L]},iA,sA]}],"bg-color":[{bg:D()}],"gradient-from-pos":[{from:U()}],"gradient-via-pos":[{via:U()}],"gradient-to-pos":[{to:U()}],"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:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-bs":[{"border-bs":J()}],"border-w-be":[{"border-be":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...we(),"hidden","none"]}],"divide-style":[{divide:[...we(),"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:[...we(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,$,L]}],"outline-w":[{outline:["",ne,os,dn]}],"outline-color":[{outline:D()}],shadow:[{shadow:["","none",d,tr,er]}],"shadow-color":[{shadow:D()}],"inset-shadow":[{"inset-shadow":["none",l,tr,er]}],"inset-shadow-color":[{"inset-shadow":D()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:D()}],"ring-offset-w":[{"ring-offset":[ne,dn]}],"ring-offset-color":[{"ring-offset":D()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":D()}],"text-shadow":[{"text-shadow":["none",f,tr,er]}],"text-shadow-color":[{"text-shadow":D()}],opacity:[{opacity:[ne,$,L]}],"mix-blend":[{"mix-blend":[...ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ae()}],"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":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":le()}],"mask-image-linear-to-pos":[{"mask-linear-to":le()}],"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":le()}],"mask-image-t-to-pos":[{"mask-t-to":le()}],"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":le()}],"mask-image-r-to-pos":[{"mask-r-to":le()}],"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":le()}],"mask-image-b-to-pos":[{"mask-b-to":le()}],"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":le()}],"mask-image-l-to-pos":[{"mask-l-to":le()}],"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":le()}],"mask-image-x-to-pos":[{"mask-x-to":le()}],"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":le()}],"mask-image-y-to-pos":[{"mask-y-to":le()}],"mask-image-y-from-color":[{"mask-y-from":D()}],"mask-image-y-to-color":[{"mask-y-to":D()}],"mask-image-radial":[{"mask-radial":[$,L]}],"mask-image-radial-from-pos":[{"mask-radial-from":le()}],"mask-image-radial-to-pos":[{"mask-radial-to":le()}],"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":x()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":le()}],"mask-image-conic-to-pos":[{"mask-conic-to":le()}],"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:he()}],"mask-repeat":[{mask:st()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,L]}],filter:[{filter:["","none",$,L]}],blur:[{blur:Z()}],brightness:[{brightness:[ne,$,L]}],contrast:[{contrast:[ne,$,L]}],"drop-shadow":[{"drop-shadow":["","none",p,tr,er]}],"drop-shadow-color":[{"drop-shadow":D()}],grayscale:[{grayscale:["",ne,$,L]}],"hue-rotate":[{"hue-rotate":[ne,$,L]}],invert:[{invert:["",ne,$,L]}],saturate:[{saturate:[ne,$,L]}],sepia:[{sepia:["",ne,$,L]}],"backdrop-filter":[{"backdrop-filter":["","none",$,L]}],"backdrop-blur":[{"backdrop-blur":Z()}],"backdrop-brightness":[{"backdrop-brightness":[ne,$,L]}],"backdrop-contrast":[{"backdrop-contrast":[ne,$,L]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,$,L]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,$,L]}],"backdrop-invert":[{"backdrop-invert":["",ne,$,L]}],"backdrop-opacity":[{"backdrop-opacity":[ne,$,L]}],"backdrop-saturate":[{"backdrop-saturate":[ne,$,L]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,$,L]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,L]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",$,L]}],ease:[{ease:["linear","initial",v,$,L]}],delay:[{delay:[ne,$,L]}],animate:[{animate:["none",k,$,L]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,L]}],"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:ee()}],"scale-x":[{"scale-x":ee()}],"scale-y":[{"scale-y":ee()}],"scale-z":[{"scale-z":ee()}],"scale-3d":["scale-3d"],skew:[{skew:ge()}],"skew-x":[{"skew-x":ge()}],"skew-y":[{"skew-y":ge()}],transform:[{transform:[$,L,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:K()}],"translate-x":[{"translate-x":K()}],"translate-y":[{"translate-y":K()}],"translate-z":[{"translate-z":K()}],"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",$,L]}],"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":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"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",$,L]}],fill:[{fill:["none",...D()]}],"stroke-w":[{stroke:[ne,os,dn,Cu]}],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"]}},uA=BC(lA);function mn(...e){return uA(tm(e))}function dA({className:e,...t}){return b.jsx(Yp,{"data-slot":"avatar",className:mn("relative flex size-10 shrink-0 overflow-hidden rounded-full",e),...t})}function Mu({className:e,...t}){return b.jsx(Jp,{"data-slot":"avatar-image",className:mn("aspect-square size-full",e),...t})}function fA({className:e,...t}){return b.jsx(em,{"data-slot":"avatar-fallback",className:mn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}function hA(e){return e==="male"?"/icons/male-student.png":e==="female"?"/icons/female-student.png":"/icons/neutral-student.png"}const pA=e=>{const t=(e||"").trim();return t?t.split(/\s+/).slice(0,2).map(n=>n[0]?.toUpperCase()).join(""):"U"},mA=({src:e,name:t,gender:n,className:s,fallbackClassName:r,imageClassName:o})=>{const i=pA(t),a=hA(n);return b.jsxs(dA,{className:mn("shrink-0",s),children:[e?b.jsx(Mu,{src:e,alt:t||"User",className:mn("object-cover",o)}):b.jsx(Mu,{src:a,alt:t||"User",className:mn("object-cover",o)}),b.jsx(fA,{className:mn("bg-gradient-to-br from-violet-500 to-indigo-600 text-white font-display font-bold text-xs select-none",r),children:i})]})},gA={Functions:"Functions and Graphs",BusinessMath:"Business and Financial Mathematics",Logic:"Logic and Reasoning"},XR={Functions:"gm-q2-functions-graphs",BusinessMath:"gm-q1-business-finance",Logic:"gm-q4-propositions-syllogisms-fallacies"},yA=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},bA=[{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"}],vA=Object.fromEntries(bA.map(e=>[e.competencyCode,{lessonId:e.lessonId,storagePath:e.storagePath,sourceFile:e.sourceFile}])),Iu=[{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/"}],qa={"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"}},wA={"Grade 11":["gen-math"]},xA="Foundational competency flow with guided examples, step-by-step vocabulary support, and scaffolded checkpoints.",tt=(e,t,n,s,r,o,i,a,c,u,d,l)=>({id:e,subjectId:t,subject:qa[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:[Iu[0],Iu[1]]}),SA=[tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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"),tt("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 kA(e,t){return`${e.moduleDescription} ${xA}`}function TA(e,t){const n=t==="Grade 11"?"22 min":"18 min";return e.competencies.map((s,r)=>{const o=vA[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 PA(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 _A(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 EA(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 CA(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 AA(e){return EA(e)}function RA(e,t){const n=CA(t),s=wA[e];return n?s.filter(r=>n.includes(r)):s}function MA(e,t){const n=RA(e,t);return SA.filter(s=>s.grade_level_availability.includes(e)).filter(s=>n.includes(s.subjectId)).map(s=>{const r=PA(s),o=TA(s,e),i=_A(s,r),a=qa[s.subjectId],c=o.some(d=>d.storagePath&&d.storagePath.length>0),u=s.isAvailable??c??!0;return{id:s.id,title:s.moduleTitle,description:kA(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}})}const YR=qa,IA=()=>{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`},DA=async e=>{const{uid:t,score:n,subject:s,title:r}=e,o=s||r||"General";let i="";return await Cp(N,async a=>{const c=q(N,"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:Dn.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},x=S.count+1,T=S.totalScore+n,P=T/x;d={overallGpa:v/100*4,averageScore:v,quizzesCompleted:g,subjectPerformance:{...k,[o]:{totalScore:T,count:x,avgScore:P}},lastUpdated:Dn.now()}}a.set(c,d,{merge:!0});const l=Xe(N,"users",t,"assessments"),f=q(l);i=f.id;const p={title:e.title,subject:o,type:e.type,score:e.score,totalQuestions:e.totalQuestions,completedAt:Dn.now(),risk:e.risk,intervention:e.intervention,xpEarned:e.xpEarned,badgeUnlocked:e.badgeUnlocked,semester:IA(),createdAt:ce()};a.set(f,p)}),i},JR=(e,t)=>{const n=q(N,"users",e,"gradeSummary","current");return Yt(n,s=>{s.exists()?t(s.data()):t(null)},s=>{console.error("[gradesService] subscribeToGradeSummary error:",s),t(null)})},eM=(e,t)=>{const n=Ot(Xe(N,"users",e,"assessments"),vn("completedAt","desc"),ks(20));return Yt(n,s=>{const r=[];s.forEach(o=>{r.push({id:o.id,...o.data()})}),t(r)},s=>{console.error("[gradesService] subscribeToAssessments error:",s),t([])})};function OA(e){const{assessmentId:t,overallScorePercent:n,overallRisk:s,intervention:r,proficiencyProfile:o}=e,i=zA(n),a=jA(n,s,o),c=NA(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:pp(s),updatedAt:new Date}}async function LA(e,t){const n=q(N,"users",e,"dashboardSummary","heroBannerModal");await $e(n,{...t,updatedAt:ce()})}async function tM(e){const t=q(N,"users",e,"dashboardSummary","heroBannerModal"),n=await ve(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:mp(s.updatedAt)}}function nM(e,t){const n=q(N,"users",e,"dashboardSummary","heroBannerModal");return Yt(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:mp(r.updatedAt)})},s=>{console.warn("[heroBannerSummaryService] Subscription error:",s),t(null)})}function zA(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 jA(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 NA(e,t,n){return t&&t.trim().length>0?t:(pp(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 pp(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 mp(e){return e?e instanceof Date?e:e instanceof Dn?e.toDate():typeof e=="string"||typeof e=="number"?new Date(e):new Date:new Date}const $A=h.lazy(()=>oe(()=>import("./LoginPage-BLe3Cr5c.js"),__vite__mapDeps([13,3,14,7,8,15,16,17,18,19,1,2,4,5,6,9,10]))),FA=h.lazy(()=>oe(()=>import("./TeacherDashboard-D7do0AjP.js"),__vite__mapDeps([20,3,14,7,8,15,21,22,23,24,1,2,4,5,6,9,10,25,26,27,28,29,30,31,32,16,33,34,35,36,18,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55]))),VA=h.lazy(()=>oe(()=>import("./AdminDashboard-DY4v_Yug.js"),__vite__mapDeps([56,3,57,33,24,35,7,22,44,43,40,58,21,14,8,23,1,2,4,5,6,9,10,59,38,26,15,48,46,28,29,30,31,32,16,53,42,19,25,52,18,17,27,45,47,60,61,62,36]))),Du=h.lazy(()=>oe(()=>import("./Sidebar-DPdujCJv.js").then(e=>e.a),__vite__mapDeps([57,3,33,24,35,7,22,44,43,40,58]))),BA=h.lazy(()=>oe(()=>import("./HeroBanner-DGWA0f42.js"),__vite__mapDeps([63,3,53,7,22,8,1,2,32,31,16,4,5,6,9,10]))),UA=h.lazy(()=>oe(()=>import("./RightSidebar-DY3YTL-R.js"),__vite__mapDeps([64,3,65,50,35,7,44,1,2,4,5,6,8,9,10]))),qA=h.lazy(()=>oe(()=>import("./XPNotification-BWSMGDCy.js"),__vite__mapDeps([66,3,16,1,2,4,5,6,7,8,9,10]))),GA=h.lazy(()=>oe(()=>import("./index-CvXxFcEI.js"),__vite__mapDeps([67,3,32,68,30,50,55,29,23,22,1,2,4,5,6,7,8,9,10])).then(e=>({default:e.NotificationBell})));h.lazy(()=>oe(()=>import("./SupplementalBanner-BLQPu9lu.js"),__vite__mapDeps([69,3,22,16,44,1,2,4,5,6,7,8,9,10])));const WA=h.lazy(()=>oe(()=>import("./SupplementalPillCarousel-BmES_4dd.js"),__vite__mapDeps([70,3,44,1,2,4,5,6,7,8,9,10]))),HA=h.lazy(()=>oe(()=>import("./LearningPath-BkBmgh8H.js"),__vite__mapDeps([71,3,72,62,1,2,52,4,5,6,7,8,9,10]))),ZA=h.lazy(()=>oe(()=>import("./CompetencyRadarChart-DMNMZ6Ga.js"),__vite__mapDeps([73,3,1,2,48,40,16,8,4,5,6,7,9,10])).then(e=>({default:e.CompetencyRadarChart}))),KA=h.lazy(()=>oe(()=>import("./ModulesPage-BVHCL2m4.js"),__vite__mapDeps([74,3,47,1,2,72,62,52,14,7,8,75,38,22,4,5,6,9,10,26,76,43,44,36,34,50,77,12,55,48,40,31,60,0,78,49,25,79,16]))),QA=h.lazy(()=>oe(()=>import("./AIChatPage-BP31m_mb.js"),__vite__mapDeps([80,3,14,7,8,15,51,9,10,1,2,4,5,6,27,25,23,43,37]))),XA=h.lazy(()=>oe(()=>import("./GradesPage-D7AMuxL8.js"),__vite__mapDeps([81,3,14,7,8,48,40,49,1,2,42,31,32,79,4,5,6,9,10]))),YA=h.lazy(()=>oe(()=>import("./LeaderboardPage-DIBnra9H.js"),__vite__mapDeps([82,3,22,52,83,1,2,4,5,6,7,8,9,10]))),JA=h.lazy(()=>oe(()=>import("./QuizBattlePage-Cm-cnqCP.js"),__vite__mapDeps([84,3,65,48,40,1,2,14,7,8,59,38,26,15,61,41,76,85,86,16,44,4,5,6,9,10]))),eR=h.lazy(()=>oe(()=>import("./AvatarShop-1g2VJnfQ.js"),__vite__mapDeps([87,3,7,83,1,2,35,85,86,45,16,58,4,5,6,8,9,10]))),tR=h.lazy(()=>oe(()=>import("./FloatingAITutor-DpWLWA30.js"),__vite__mapDeps([88,3,89,39,22,37,1,2,4,5,6,7,8,9,10]))),nR=h.lazy(()=>oe(()=>import("./RewardsModal-e7BnIl6w.js"),__vite__mapDeps([90,3,1,2,22,4,5,6,7,8,9,10]))),Wo=h.lazy(()=>oe(()=>import("./ProfileModal-BpvupEPF.js"),__vite__mapDeps([91,3,14,7,8,15,59,38,26,92,4,2,5,22,39,27,46,17,36,45,1,6,9,10]))),sR=h.lazy(()=>oe(()=>import("./ConfirmModal-BVHZuXaM.js"),__vite__mapDeps([21,3,14,7,8,22,23,24,1,2,4,5,6,9,10]))),Ho=h.lazy(()=>oe(()=>import("./SettingsModal-Bj9L7UBt.js"),__vite__mapDeps([93,3,59,7,38,26,14,8,15,61,21,22,23,24,1,2,4,5,6,9,10,92,39,27,46,30,42,36,40,68,52,18]))),rR=h.lazy(()=>oe(()=>import("./ScientificCalculator-CLa3avU-.js"),__vite__mapDeps([75,3,38,22,1,2,4,5,6,7,8,9,10]))),oR=h.lazy(()=>oe(()=>import("./InitialAssessmentModal-BXyrazRg.js"),__vite__mapDeps([94,3,14,7,8,95,1,2,22,50,4,5,6,9,10]))),iR=h.lazy(()=>oe(()=>import("./AssessmentPage-DhcG3TWJ.js"),__vite__mapDeps([96,3,14,7,8,95,89,22,52,50,44,1,2,4,5,6,9,10]))),aR=h.lazy(()=>oe(()=>import("./DiagnosticBreakdown-lTfPVQ3_.js"),__vite__mapDeps([97,3,1,2,22,52,77,31,40,38,4,5,6,7,8,9,10]))),cR=()=>{const{isLoggedIn:e,userProfile:t,userRole:n,loading:s,refreshProfile:r}=Ms();Bi();const o=jt(),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(null),m=h.useRef(null),[g,y]=h.useState(!1),[v,k]=h.useState(!1),[S,x]=h.useState(!1),[T,P]=h.useState(!1);h.useEffect(()=>{(async()=>{try{const M=await ve(q(N,"settings","general"));M.exists()&&M.data()?.maintenanceMode===!0?(x(!0),e&&n!=="admin"&&await eu()):x(!1)}catch{}P(!0)})()},[e,n]);const _=t,[w,R]=h.useState(_?.level||1),[A,B]=h.useState(_?.currentXP||0),[F,H]=h.useState(_?.totalXP||0),se=Math.floor(100*Math.pow(1.5,w-1));let te=0;for(let C=1;C{const C=_?.learnerCurriculumAssignments?.subjects??_?.assignedSubjects??_?.curriculumAssignedSubjects??[];return Array.isArray(C)?C:[]},[_]),ue=h.useMemo(()=>MA(ie,re),[ie,re]),[D,he]=h.useState({collapsed:!1}),st={Dashboard:"/",Modules:"/modules","AI Chat":"/chat",Assessment:"/assessment","Quiz Battle":"/battle",Leaderboard:"/leaderboard",Grades:"/grades","Avatar Studio":"/avatar"},X={"/":"Dashboard","/modules":"Modules","/chat":"AI Chat","/assessment":"Assessment","/battle":"Quiz Battle","/leaderboard":"Leaderboard","/grades":"Grades","/avatar":"Avatar Studio"};h.useEffect(()=>{const C=X[o.pathname]||"Dashboard";f(C)},[o.pathname]),h.useEffect(()=>{const C=()=>{const M=X[window.location.pathname]||"Dashboard";f(M)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[]);const U=(C,M)=>{M?Ds(M):C==="Modules"&&l!=="Modules"&&Ds(null),C==="Quiz Battle"&&l!=="Quiz Battle"?(he({collapsed:g}),y(!0)):l==="Quiz Battle"&&C!=="Quiz Battle"&&y(D.collapsed),f(C);const W=st[C];W&&window.location.pathname!==W&&window.history.pushState({},"",W),k(!1)},[G,J]=h.useState(!1),[we,ae]=h.useState({show:!1,xp:0,message:""}),[le,Z]=h.useState(!1),[O,ee]=h.useState(!1),[ge,K]=h.useState(!1),[Ye,Le]=h.useState(!1),[Je,on]=h.useState({}),[pt,Ds]=h.useState(null),[Os,Ge]=h.useState(!1),[it,$t]=h.useState(gr),[eo,Ft]=h.useState(""),[an,Wn]=h.useState(!1),[Tn,rt]=h.useState(!1),[Wt,mt]=h.useState(null),[to,Hn]=h.useState(!1),[Ls,Zn]=h.useState(!1),[no,Kn]=h.useState(0),[at,Qn]=h.useState(!1),[so,Xn]=h.useState(!1),[cn,Y]=h.useState(""),[Ee,ze]=h.useState([]),[Te,Pt]=h.useState(_?.atRiskSubjects||[]),[_e,Fe]=h.useState(_?.priorityTopics||[]),[Pn,et]=h.useState(_?.gpa||"0.00");h.useEffect(()=>{e&&n==="student"&&t&&QE(t.uid).then(C=>{if(C&&C.averageScore>0){const M=Math.min(C.averageScore/25,4).toFixed(2);et(M)}}).catch(C=>console.error("Error loading progress for GPA:",C))},[e,n,t]);const[Ve,Yn]=h.useState(!1);h.useEffect(()=>{_&&n==="student"?(R(_.level||1),B(_.currentXP||0),H(_.totalXP||0),Pt(_.atRiskSubjects||[]),Fe(_.priorityTopics||[]),Yn(!0)):n!=="student"&&Yn(!0)},[t,n]),h.useEffect(()=>{if(!e||n!=="student"){Wn(!1);return}let C=!1;const M=()=>{C||Wn(!0)},W=window.requestIdleCallback,pe=window.cancelIdleCallback,lo=window.setTimeout(M,800),uo=window.requestAnimationFrame(()=>{W||M()}),yt=W?.(()=>{M()},{timeout:500});return()=>{C=!0,window.clearTimeout(lo),window.cancelAnimationFrame(uo),yt!==void 0&&pe&&pe(yt)}},[e,n]),h.useEffect(()=>{on({})},[t?.uid]);const gt=h.useMemo(()=>{const C=new Set;return Te.map(W=>yA(W)).filter(W=>W!==null).filter(W=>C.has(W)?!1:(C.add(W),!0))},[Te]),zs=h.useMemo(()=>{const C=_e.length>0?_e:gt,M=new Set;return C.filter(W=>M.has(W)?!1:(M.add(W),!0))},[_e,gt]),yp=()=>{rt(!0)};h.useEffect(()=>{const C=()=>rt(!0);return window.addEventListener("mathpulse:open-assessment",C),()=>window.removeEventListener("mathpulse:open-assessment",C)},[]),h.useEffect(()=>{if(!e||n!=="student"||!Ve||!t?.uid)return;let C=!1;return(async()=>{try{Hn(!!_?.assessmentDismissed),Zn(!!_?.initialAssessmentCompleted);const W=await Zo(q(N,"diagnosticResults",t.uid)).catch(()=>ve(q(N,"diagnosticResults",t.uid))),pe=await Zo(q(N,"competencyProfiles",t.uid)).catch(()=>ve(q(N,"competencyProfiles",t.uid)));if(C)return;const lo=W.exists()&&W.data()?.status==="completed",uo=pe.exists()&&pe.data()?.overallScore>0;if(!lo&&!uo){mt(!1);const yt=setTimeout(()=>{!C&&!to&&!Ls&&(sessionStorage.getItem("mathpulse_iar_session_dismissed")==="true"||rt(!0))},1e3);return()=>clearTimeout(yt)}else{if(mt(!0),W.exists()){const yt=W.data();yt?.riskProfile&&(Pt(yt.riskProfile.weak_domains||[]),Fe(yt.riskProfile.critical_gaps||[]))}if(pe.exists()){const yt=pe.data();yt?.primaryWeakness&&Pt(Wa=>[...new Set([...Wa,yt.primaryWeakness])])}}}catch(W){console.error("[diagnostic] Firestore check failed:",W)}})(),()=>{C=!0}},[e,n,Ve,t?.uid,no]);const bp=[...Te].sort().join("|"),Jn=t?.uid?`mathpulse_supplemental_dismissed_${t.uid}`:null;h.useEffect(()=>{if(!Jn){Ft("");return}try{const C=localStorage.getItem(Jn)||"";Ft(C)}catch{Ft("")}},[Jn]);const vp=()=>{if(Ft(""),!!Jn)try{localStorage.removeItem(Jn)}catch{}};Te.length>0,h.useEffect(()=>{(async()=>{if(!t?.uid){$t(gr);return}try{const M=await Uh(t.uid);$t(M)}catch(M){console.error("Error loading user settings:",M),$t(gr)}})()},[t?.uid]),h.useEffect(()=>{nC(it)},[it]);const wp=(C,M)=>{rt(!1),Y(C),ze(M),Qn(!0)},Ga=async C=>{if(Qn(!1),mt(!0),Xn(!0),C.xpEarned>0&&t?.uid)try{await Lo(t.uid,C.xpEarned,"manual","Diagnostic assessment completed"),ct.success(`Assessment complete! +${C.xpEarned} XP earned. ${C.badgeUnlocked.replace("_"," ")} badge unlocked!`)}catch{ct.success("Assessment complete!")}else ct.success("Assessment complete!");if(t?.uid&&C.competencyScores&&C.proficiencyProfile)try{await KE(t.uid,{uid:t.uid,assessmentId:`assessment-${Date.now()}`,completedAt:new Date,rawScore:C.overallScorePercent,totalQuestions:Object.values(C.competencyScores).reduce((M,W)=>M+W.attempted,0),correctAnswers:Object.values(C.competencyScores).reduce((M,W)=>M+W.correct,0),timeSpentSeconds:0,competencyScores:C.competencyScores,recommendations:C.proficiencyProfile.weaknesses.map(M=>`Focus on ${M}`),proficiencyProfile:C.proficiencyProfile,assessmentType:"initial"})}catch(M){console.error("[WARN] Failed to save competency profile:",M)}if(t?.uid)try{const M=OA({assessmentId:cn?`assessment-${cn}`:`assessment-${Date.now()}`,overallScorePercent:C.overallScorePercent,overallRisk:C.overallRisk,intervention:C.intervention,proficiencyProfile:C.proficiencyProfile});await LA(t.uid,M)}catch(M){console.error("[App] Failed to save hero banner summary:",M)}if(t?.uid){try{const M=await ve(q(N,"diagnosticResults",t.uid));if(M.exists()){const W=M.data();W?.riskProfile&&(Pt(W.riskProfile.weak_domains||[]),Fe(W.riskProfile.critical_gaps||[]))}vp()}catch(M){console.error("[diagnostic] Failed to refresh risk data:",M)}try{await dt(q(N,"users",t.uid),{initialAssessmentCompleted:!0,assessmentDismissed:!1,assessmentCompletedAt:ce()}),await Lo(t.uid,50,"initial_assessment","Initial assessment completed")}catch(M){console.error("[App] Failed to persist assessment completion:",M)}try{await DA({uid:t.uid,testId:cn||"diagnostic",title:"Diagnostic Assessment",subject:"General Mathematics",type:"diagnostic",score:C.overallScorePercent,totalQuestions:Object.values(C.competencyScores||{}).reduce((M,W)=>M+W.attempted,0),risk:C.overallRisk,intervention:C.intervention,xpEarned:C.xpEarned,badgeUnlocked:C.badgeUnlocked})}catch(M){console.error("[App] Failed to persist grade result:",M)}}},xp=()=>{f("AI Chat")},Sp=async(C,M)=>{if(t)try{const W=await Lo(t.uid,C,"manual",M);B(W.xp),W.leveledUp&&R(W.newLevel),H(pe=>pe+C),await r(),ae({show:!0,xp:C,message:M})}catch(W){console.error("Error awarding XP:",W)}},ro=async()=>{try{await eu(),on({}),f("Dashboard"),Z(!1)}catch(C){console.error("Error logging out:",C)}},_n=async C=>{if(!t){K(!1),ee(!1);return}const M={};["name","email","phone","photo","avatarLayers","gender","lrn","grade","section","school","enrollmentDate","major","gpa","department","subject","yearsOfExperience","qualification","position"].forEach(pe=>{C[pe]!==void 0&&(M[pe]=C[pe])});try{await zP(t.uid,M),on(pe=>({...pe,...M})),K(!1),ee(!1),ct.success("Profile updated successfully")}catch(pe){console.error("Error saving profile:",pe),ct.error("Failed to update profile")}},oo=async C=>{if(t?.uid)try{const M=await tC(t.uid,C);$t(M),ct.success("Settings saved successfully")}catch(M){throw console.error("Error saving settings:",M),ct.error("Failed to save settings"),M}},io=async()=>{if(!t?.uid)return;const C=await oC(t.uid),M=new Blob([JSON.stringify(C,null,2)],{type:"application/json"}),W=URL.createObjectURL(M),pe=document.createElement("a");pe.href=W,pe.download=`mathpulse-data-export-${t.uid}-${Date.now()}.json`,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe),URL.revokeObjectURL(W),ct.success("Data export downloaded")},ao=async()=>{await rC(),ct.success("Local cache cleared")},co=async()=>{if(!t)throw new Error("No active profile found.");const C=n==="student"?_?.lrn||t.uid:void 0;n==="student"&&(await yr(q(N,"diagnosticResults",t.uid)).catch(()=>{}),await yr(q(N,"competencyProfiles",t.uid)).catch(()=>{}));const{resetTestingDataForRole:M}=await oe(async()=>{const{resetTestingDataForRole:pe}=await import("./testResetService-BuCuwryb.js");return{resetTestingDataForRole:pe}},__vite__mapDeps([98,1,2,3,4,5,6,7,8,9,10])),W=await M({uid:t.uid,role:n,lrn:C});n==="student"&&(R(1),B(0),H(0),Pt([]),Fe([]),mt(null),Hn(!1),Zn(!1),et("0.00"),f("Dashboard"),r(),Kn(pe=>pe+1)),ct.success(W.summary)},We=t?{uid:t.uid,name:t.name,email:t.email,phone:t.phone||"",photo:t.photo||"",avatarLayers:t.avatarLayers,role:t.role,...n==="student"&&_?{lrn:_.lrn,grade:_.grade,section:_.section,school:_.school,enrollmentDate:_.enrollmentDate,major:_.major,gpa:Pn}:{},...Je}:{uid:void 0,name:"User",email:"",phone:"",photo:"",avatarLayers:void 0,role:n},js=We.name.trim().split(/\s+/).find(C=>/\p{L}/u.test(C))||We.name.trim()||"User";if(h.useEffect(()=>{const C=M=>{if(!(M.target instanceof HTMLInputElement||M.target instanceof HTMLTextAreaElement)&&M.altKey)switch(M.key.toLowerCase()){case"d":M.preventDefault(),U("Dashboard");break;case"m":M.preventDefault(),U("Modules");break;case"c":M.preventDefault(),U("AI Chat");break;case"g":M.preventDefault(),U("Grades");break;case"b":M.preventDefault(),U("Quiz Battle");break;case"s":M.preventDefault(),ee(!0);break;case"p":M.preventDefault(),K(!0);break;case"k":M.preventDefault(),Le(W=>!W);break}};if(e&&n==="student")return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e,n]),h.useEffect(()=>{const C=M=>{const W=M.detail;W?.tab&&e&&U(W.tab)};return window.addEventListener("mathpulse:navigate",C),()=>window.removeEventListener("mathpulse:navigate",C)},[e]),s)return b.jsx(ns,{});if(S&&(!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(Ti,{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($A,{})});if(!(n!=="student"||Ve))return b.jsx(ns,{message:"Preparing your dashboard..."});if(n==="teacher")return b.jsx(Vo,{children:b.jsxs(b.Fragment,{children:[b.jsx(qo,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading teacher dashboard..."}),children:b.jsx(FA,{onLogout:ro,onOpenProfile:()=>K(!0),onOpenSettings:()=>ee(!0)})}),ge&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Wo,{isOpen:ge,onClose:()=>K(!1),profileData:We,onSave:_n})}),O&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ho,{isOpen:O,onClose:()=>ee(!1),profileData:We,onSave:_n,settingsData:it,onSaveSettings:oo,onApplySettingsPreview:$t,onExportData:io,onClearCache:ao,onResetData:co})}),b.jsx(zo,{position:"top-right",richColors:!0,closeButton:!0})]})});if(n==="admin")return b.jsx(Vo,{children:b.jsxs(b.Fragment,{children:[b.jsx(qo,{}),b.jsx(h.Suspense,{fallback:b.jsx(ns,{message:"Loading admin dashboard..."}),children:b.jsx(VA,{onLogout:ro,onOpenProfile:()=>K(!0),onOpenSettings:()=>ee(!0)})}),ge&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Wo,{isOpen:ge,onClose:()=>K(!1),profileData:We,onSave:_n})}),O&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ho,{isOpen:O,onClose:()=>ee(!1),profileData:We,onSave:_n,settingsData:it,onSaveSettings:oo,onApplySettingsPreview:$t,onExportData:io,onClearCache:ao,onResetData:co})}),b.jsx(zo,{position:"top-right",richColors:!0,closeButton:!0})]})});const kp=b.jsx(Vo,{children:b.jsxs(b.Fragment,{children:[b.jsx(qo,{}),b.jsx(V_,{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(Du,{activeTab:l,setActiveTab:U,userRole:n,onOpenSettings:()=>ee(!0),onLogout:()=>Z(!0),sidebarCollapsed:g,setSidebarCollapsed:y,forceCollapsed:l==="Quiz Battle"})})}),v&&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:()=>k(!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(Du,{mode:"mobile",onRequestClose:()=>k(!1),activeTab:l,setActiveTab:U,userRole:n,onOpenSettings:()=>{ee(!0),k(!1)},onLogout:()=>{Z(!0),k(!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:()=>k(!0),"aria-label":"Open navigation",children:b.jsx(zx,{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, ",We.name.split(" ")[0],"!"]})]}),b.jsxs("div",{className:"hidden md:flex items-center gap-2 ml-2",children:[b.jsxs("button",{onClick:()=>J(!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(pr,{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 ",w]})]}),b.jsxs("button",{onClick:()=>J(!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:`${V}/${se} XP to next level`,children:[b.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b.jsx(Pi,{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:[A," 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,V/se*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(mr,{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:()=>Le(C=>!C),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(wx,{size:20,className:"group-hover:scale-110 transition-transform"})}),b.jsx(h.Suspense,{fallback:c,children:b.jsx(GA,{})}),b.jsxs("button",{onClick:()=>K(!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: ${We.name}`,children:[b.jsx(mA,{src:We.photo,name:We.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:js})})]})]})]}),b.jsx("main",{ref:m,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(Nf,{mode:"wait",children:b.jsx(On.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(BA,{userName:js,userLevel:w,avatarLayers:We.avatarLayers,onContinueLearning:()=>U("Modules"),showAssessmentTooltip:!Wt&&Wt!==null,onOpenAssessment:yp,studentId:t?.uid,assessmentCompleted:Wt===!0})}),an&&Wt&>.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(Ti,{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:()=>U("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(fx,{className:"h-3.5 w-3.5"})]})]}),b.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:zs.map((C,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,". ",gA[C]]},C))})]}),an&&Te.length>0&&b.jsx(h.Suspense,{fallback:a,children:b.jsx(WA,{atRiskSubjects:Te,onTopicClick:C=>{U("Modules")}})}),Ve&&an&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(HA,{modules:ue,onNavigateToModules:C=>U("Modules",C),atRiskSubjects:Te,priorityTopics:zs})})}),Ve&&an&&b.jsx(h.Suspense,{fallback:a,children:b.jsx("div",{className:"pb-4",children:b.jsx(ZA,{})})})]}),b.jsx("div",{className:"col-span-12 xl:col-span-3 pt-2",children:an?b.jsx(h.Suspense,{fallback:d,children:b.jsx(UA,{currentUserId:t?.uid||"",onOpenRewards:()=>J(!0),onOpenLeaderboard:()=>f("Leaderboard"),onNavigateToModules:()=>f("Modules"),onNavigateToQuizBattle:()=>U("Quiz Battle"),userLevel:w,userPhoto:We.photo,currentXP:V,xpToNextLevel:se,overallXP:A,userName:js})}):d})]})}):l==="Modules"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(KA,{onEarnXP:Sp,atRiskSubjects:Te,priorityTopics:zs,initialModuleId:pt,isInQuizMode:Os,setIsInQuizMode:Ge,hasCompletedDiagnostic:Wt??!1})}):l==="Leaderboard"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(YA,{currentUserPhoto:We.photo})}):l==="Quiz Battle"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(JA,{})}):l==="AI Chat"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(QA,{})}):l==="Grades"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(XA,{})}):l==="Avatar Studio"?b.jsx(h.Suspense,{fallback:i,children:b.jsx(eR,{onSaveProfile:C=>{on(M=>({...M,avatarLayers:C}))},onNavigateToModules:()=>U("Modules")})}):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(tR,{constraintsRef:p,onFullScreen:xp})})}),b.jsx(h.Suspense,{fallback:null,children:b.jsx(qA,{xp:we.xp,message:we.message,show:we.show,onComplete:()=>ae(C=>({...C,show:!1}))})}),G&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(nR,{isOpen:G,onClose:()=>J(!1),userLevel:w,currentXP:V,xpToNextLevel:se,totalXP:F,userId:t?.uid||""})}),ge&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Wo,{isOpen:ge,onClose:()=>K(!1),profileData:We,onSave:_n})}),le&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(sR,{isOpen:le,onClose:()=>Z(!1),onConfirm:ro,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"})}),O&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(Ho,{isOpen:O,onClose:()=>ee(!1),profileData:We,onSave:_n,settingsData:it,onSaveSettings:oo,onApplySettingsPreview:$t,onExportData:io,onClearCache:ao,onResetData:co})}),Ye&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(rR,{isOpen:Ye,onClose:()=>Le(!1)})}),Tn&&!at&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(oR,{isOpen:Tn&&!at,onClose:()=>rt(!1),onDismiss:()=>{rt(!1),Hn(!0)},userId:t?.uid||"",strand:_?.major||"STEM",gradeLevel:_?.grade||"Grade 11",onAssessmentStart:wp,onAssessmentComplete:Ga})}),at&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(iR,{testId:cn,questions:Ee,userName:js,onComplete:Ga,onCancel:()=>{Qn(!1),f("Dashboard")}})}),so&&t?.uid&&b.jsx(h.Suspense,{fallback:null,children:b.jsx(aR,{userId:t.uid,mode:"fullscreen",onClose:()=>{Xn(!1),f("Dashboard")}})})]})]})}),b.jsx(zo,{position:"top-right",richColors:!0,closeButton:!0})]})});return b.jsx(NP,{children:kp})},nr="mathpulse_chunk_reload_attempted",lR=[/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 Ou(e){return e?.message?lR.some(t=>t.test(e.message)):!1}class uR 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),Ou(t))try{sessionStorage.getItem(nr)||(sessionStorage.setItem(nr,String(Date.now())),console.warn("[ErrorBoundary] Stale chunk detected — reloading to recover."),window.location.reload())}catch{}}handleReset=()=>{try{sessionStorage.removeItem(nr)}catch{}this.setState({hasError:!1,error:null})};render(){if(this.state.hasError){if(Ou(this.state.error)){let t=!1;try{t=!!sessionStorage.getItem(nr)}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}}sC();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 gp=document.getElementById("root");if(!gp)throw new Error("Root element not found");Pp.createRoot(gp).render(b.jsx(uR,{children:b.jsx(Xg,{children:b.jsx(Mm,{client:zi,children:b.jsx(jP,{children:b.jsx(cR,{})})})})}));export{Ex as $,Cl as A,bx as B,wx as C,KR as D,Ol as E,Al as F,Rl as G,ns as H,gx as I,mA as J,UE as K,Ox as L,zx as M,ye as N,bn as O,zr as P,dA as Q,Nx as R,Ml as S,Dl as T,Jx as U,Mu as V,fA as W,mr as X,kR as Y,Pi as Z,oe as _,fx as a,qR as a$,Gs as a0,nM as a1,tM as a2,DR as a3,pr as a4,Vx as a5,Vo as a6,Kh as a7,cC as a8,yA as a9,Pm as aA,hm as aB,Ze as aC,SR as aD,MR as aE,JR as aF,eM as aG,qE as aH,OR as aI,IR as aJ,iS as aK,Yf as aL,LR as aM,zP as aN,B_ as aO,Rx as aP,kx as aQ,Ux as aR,_R as aS,xu as aT,Su as aU,HR as aV,ZR as aW,iC as aX,aC as aY,gr as aZ,GR as a_,XR as aa,NR as ab,VR as ac,FR as ad,$R as ae,UR as af,BR as ag,Lo as ah,zR as ai,AA as aj,MA as ak,jR as al,YR as am,CE as an,gA as ao,Nr as ap,ym as aq,um as ar,xR as as,Qo as at,St as au,$u as av,cm as aw,lm as ax,Ko as ay,zu as az,Mo as b,WR as b0,rS as b1,qt as b2,Jr as b3,s_ as b4,PR as b5,ZE as b6,QR as b7,CR as c,AR as d,fe as e,Zh as f,N as g,Nf as h,Ll as i,ct as j,VE as k,wt as l,On as m,mn as n,Dt as o,Ix as p,Il as q,hA as r,ER as s,Hh as t,Ms as u,z as v,RR as w,Ti as x,QE as y,Xx as z}; diff --git a/assets/index-BVqK5_Xi.js b/assets/index-CvXxFcEI.js similarity index 91% rename from assets/index-BVqK5_Xi.js rename to assets/index-CvXxFcEI.js index 043c9a0b375c75557f31e459ba9d988949619c07..6d537327af23283e98af51047aa042abbfd62878 100644 --- a/assets/index-BVqK5_Xi.js +++ b/assets/index-CvXxFcEI.js @@ -1 +1 @@ -import{D as m,Z as u,b as p,X as h,T as f,E as b}from"./index-BYG24j30.js";import{a6 as V,a7 as W}from"./index-BYG24j30.js";import{j as e,r as c,b as g}from"./vendor-react-B4AQeu28.js";import{C as v}from"./circle-alert-D1BZWAsh.js";import{M as y}from"./megaphone-DX0jSVq2.js";import{B as d}from"./bell-CJfHcVLS.js";import{C as j}from"./circle-check-big-uJgj_456.js";import{C as k}from"./clipboard-check-CC5IRbh7.js";import{f as N,C as w}from"./formatDistanceToNow-C9WeR9GV.js";import{T as C}from"./trash-2-Bz07bxtW.js";import{X as _}from"./x-DU8WEZ6X.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const E={achievement_unlocked:b,level_up:f,quiz_result:k,daily_checkin:j,streak_milestone:h,streak_reminder:d,teacher_announcement:y,new_assignment:p,xp_earned:u,system_alert:v},R=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";default:return"bg-[#edf1f7] text-[#5a6578]"}},z=({notification:t})=>{const{markAsRead:r,deleteNotification:a}=m(),o=E[t.type]||d,i=R(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=N(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})})]})})},T=({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(w,{size:14}),"Mark all read"]}),e.jsx("button",{onClick:t,className:"text-sky-200 hover:text-white transition-colors",title:"Close",children:e.jsx(_,{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(z,{notification:s},s.id))})]});return g.createPortal(l,document.body)},H=()=>{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(T,{onClose:()=>a(!1)})]})};export{H as NotificationBell,V as NotificationProvider,W as notify,m as useNotifications}; +import{D as m,Z as u,b as p,X as h,T as f,E as b}from"./index-CR5aYAL9.js";import{a6 as V,a7 as W}from"./index-CR5aYAL9.js";import{j as e,r as c,b as g}from"./vendor-react-B4AQeu28.js";import{C as v}from"./circle-alert-CSWToxPb.js";import{M as y}from"./megaphone-D_BUBJZ4.js";import{B as d}from"./bell-DVzATilo.js";import{C as j}from"./circle-check-big-CWD8eO1a.js";import{C as k}from"./clipboard-check-B4PuSMw1.js";import{f as N,C as w}from"./formatDistanceToNow-B4dD00jc.js";import{T as C}from"./trash-2-BtGasoad.js";import{X as _}from"./x-DiyyYv8Q.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const E={achievement_unlocked:b,level_up:f,quiz_result:k,daily_checkin:j,streak_milestone:h,streak_reminder:d,teacher_announcement:y,new_assignment:p,xp_earned:u,system_alert:v},R=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";default:return"bg-[#edf1f7] text-[#5a6578]"}},z=({notification:t})=>{const{markAsRead:r,deleteNotification:a}=m(),o=E[t.type]||d,i=R(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=N(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})})]})})},T=({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(w,{size:14}),"Mark all read"]}),e.jsx("button",{onClick:t,className:"text-sky-200 hover:text-white transition-colors",title:"Close",children:e.jsx(_,{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(z,{notification:s},s.id))})]});return g.createPortal(l,document.body)},H=()=>{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(T,{onClose:()=>a(!1)})]})};export{H as NotificationBell,V as NotificationProvider,W as notify,m as useNotifications}; diff --git a/assets/input-CtjqQUbX.js b/assets/input-DgZjxAsx.js similarity index 92% rename from assets/input-CtjqQUbX.js rename to assets/input-DgZjxAsx.js index 4ced8d0039454f053525b886b00e3cc4544e18db..62c75fff2510d5c016349c9b56e513476ffbf334 100644 --- a/assets/input-CtjqQUbX.js +++ b/assets/input-DgZjxAsx.js @@ -1 +1 @@ -import{j as t}from"./vendor-react-B4AQeu28.js";import{n}from"./index-BYG24j30.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{n}from"./index-CR5aYAL9.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/lightbulb-C6VPAE81.js b/assets/lightbulb-CRrzx6iX.js similarity index 94% rename from assets/lightbulb-C6VPAE81.js rename to assets/lightbulb-CRrzx6iX.js index ee0c05dccb596ec1aaee882d9387f29ddd16fa70..3c605a3b14ea292b2125e6c27cfc99911804b32a 100644 --- a/assets/lightbulb-C6VPAE81.js +++ b/assets/lightbulb-CRrzx6iX.js @@ -1,4 +1,4 @@ -import{e as c}from"./index-BYG24j30.js";/** +import{e as c}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/log-out-7LnFvNg-.js b/assets/log-out-BT_ShBSM.js similarity index 89% rename from assets/log-out-7LnFvNg-.js rename to assets/log-out-BT_ShBSM.js index 23c27964b7d71df4a0b50e565400ca575af35e1a..4561513c88508559676dd1be2145dc145347c69e 100644 --- a/assets/log-out-7LnFvNg-.js +++ b/assets/log-out-BT_ShBSM.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BYG24j30.js";/** +import{e as o}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/mail-B8qfL-UK.js b/assets/mail-sfPSTvMi.js similarity index 89% rename from assets/mail-B8qfL-UK.js rename to assets/mail-sfPSTvMi.js index 79b99be942710f1bd2693c376e9186aea0f53509..8d63197b20c365610581d6632f62e03795bbd841 100644 --- a/assets/mail-B8qfL-UK.js +++ b/assets/mail-sfPSTvMi.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/maximize-2-7OlWKBmu.js b/assets/maximize-2-DtyTSFtD.js similarity index 91% rename from assets/maximize-2-7OlWKBmu.js rename to assets/maximize-2-DtyTSFtD.js index d15c4755b7a5901ca18d828113e2cb6546e5b7d7..4af8b6f0df9ad9b788108c24201d1100c93551d7 100644 --- a/assets/maximize-2-7OlWKBmu.js +++ b/assets/maximize-2-DtyTSFtD.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/megaphone-DX0jSVq2.js b/assets/megaphone-D_BUBJZ4.js similarity index 89% rename from assets/megaphone-DX0jSVq2.js rename to assets/megaphone-D_BUBJZ4.js index c569423a7908ee4f8a7bdb327422cf8c2076c833..86493661b19085314f32b61255796881890cf52b 100644 --- a/assets/megaphone-DX0jSVq2.js +++ b/assets/megaphone-D_BUBJZ4.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/minus-sZ1MmK-H.js b/assets/minus-D8MfEHLl.js similarity index 84% rename from assets/minus-sZ1MmK-H.js rename to assets/minus-D8MfEHLl.js index f9ce503de7e0f02b32eabf17bed12e25dac207d6..22293a33364ed16bce83fd9ef10abde1122fd157 100644 --- a/assets/minus-sZ1MmK-H.js +++ b/assets/minus-D8MfEHLl.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BYG24j30.js";/** +import{e as o}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/plus-C5IM0tm0.js b/assets/plus-Cp5Q-YTc.js similarity index 87% rename from assets/plus-C5IM0tm0.js rename to assets/plus-Cp5Q-YTc.js index e902ef88df5748c8d2cdf5135f4b4dd2b4ca6c01..36bf4b3d6dca459129794fbc180a7599b0e393e0 100644 --- a/assets/plus-C5IM0tm0.js +++ b/assets/plus-Cp5Q-YTc.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/quizService-Dg-FcCkj.js b/assets/quizService-83ZGYTl6.js similarity index 98% rename from assets/quizService-Dg-FcCkj.js rename to assets/quizService-83ZGYTl6.js index d92f6cb41f130e77ce8808914f76a47210f38ecc..f4e12eaa50f7e0f3b767d56e0431aedf8d4a17f1 100644 --- a/assets/quizService-Dg-FcCkj.js +++ b/assets/quizService-83ZGYTl6.js @@ -1,4 +1,4 @@ -import{e as g,g as n}from"./index-BYG24j30.js";import{query as h,collection as d,where as m,orderBy as L,getDocs as w,doc as o,setDoc as l,updateDoc as y,serverTimestamp as r,deleteDoc as _}from"./vendor-firebase-firestore-CNv3xXal.js";/** +import{e as g,g as n}from"./index-CR5aYAL9.js";import{query as h,collection as d,where as m,orderBy as L,getDocs as w,doc as o,setDoc as l,updateDoc as y,serverTimestamp as r,deleteDoc as _}from"./vendor-firebase-firestore-CNv3xXal.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/save-DidAD_jg.js b/assets/save-BpEMiY1d.js similarity index 91% rename from assets/save-DidAD_jg.js rename to assets/save-BpEMiY1d.js index 686d4089cbd127196dee81540121507cdc99fdab..87409a4fcafd6e6964316c129178eaf2a236aa81 100644 --- a/assets/save-DidAD_jg.js +++ b/assets/save-BpEMiY1d.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BYG24j30.js";/** +import{e as a}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/search-qXpo6Bz-.js b/assets/search-1a4wCp_r.js similarity index 88% rename from assets/search-qXpo6Bz-.js rename to assets/search-1a4wCp_r.js index 513441b4f9de426e2478368e543f430628bde79a..6af95c6db70263e1c850830c17cf52dc021589b8 100644 --- a/assets/search-qXpo6Bz-.js +++ b/assets/search-1a4wCp_r.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/select-DM5m46Pk.js b/assets/select-DMAe8pN9.js similarity index 94% rename from assets/select-DM5m46Pk.js rename to assets/select-DMAe8pN9.js index 4f4dad5db7a5f8e1bb91d475dffe270c94aa25dc..0b6f554fc41a475a3117a40fb64dc79bd6ef28f0 100644 --- a/assets/select-DM5m46Pk.js +++ b/assets/select-DMAe8pN9.js @@ -1 +1 @@ -import{j as e}from"./vendor-react-B4AQeu28.js";import{t as l,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}from"./vendor-radix-BPuEd8FG.js";import{n as r}from"./index-BYG24j30.js";import{C as n,a as h}from"./chevron-up-vEHTl-in.js";import{C as b}from"./check-C-Jb6xS0.js";function _({...t}){return e.jsx(l,{"data-slot":"select",...t})}function k({...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]: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(n,{className:"size-4"})})]})}function I({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(j,{}),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(w,{})]})})}function V({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(b,{className:"size-4"})})}),a]})}function j({className:t,...a}){return e.jsx(g,{"data-slot":"select-scroll-up-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(h,{className:"size-4"})})}function w({className:t,...a}){return e.jsx(v,{"data-slot":"select-scroll-down-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(n,{className:"size-4"})})}export{_ as S,B as a,k as b,I as c,V as d}; +import{j as e}from"./vendor-react-B4AQeu28.js";import{t as l,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}from"./vendor-radix-BPuEd8FG.js";import{n as r}from"./index-CR5aYAL9.js";import{C as n,a as h}from"./chevron-up-BrrK8Cng.js";import{C as b}from"./check-MAu_C8ty.js";function _({...t}){return e.jsx(l,{"data-slot":"select",...t})}function k({...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]: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(n,{className:"size-4"})})]})}function I({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(j,{}),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(w,{})]})})}function V({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(b,{className:"size-4"})})}),a]})}function j({className:t,...a}){return e.jsx(g,{"data-slot":"select-scroll-up-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(h,{className:"size-4"})})}function w({className:t,...a}){return e.jsx(v,{"data-slot":"select-scroll-down-button",className:r("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(n,{className:"size-4"})})}export{_ as S,B as a,k as b,I as c,V as d}; diff --git a/assets/send-Cs_bBaZx.js b/assets/send-B1wbvsc_.js similarity index 90% rename from assets/send-Cs_bBaZx.js rename to assets/send-B1wbvsc_.js index 907629fc058a04460f975b67553c29e5f00aa301..4f74a49e206b7eb2d3a3655d6a009576cab14610 100644 --- a/assets/send-Cs_bBaZx.js +++ b/assets/send-B1wbvsc_.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BYG24j30.js";/** +import{e as a}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/shield-check-CoyMgFec.js b/assets/shield-check-CuuwgPnV.js similarity index 92% rename from assets/shield-check-CoyMgFec.js rename to assets/shield-check-CuuwgPnV.js index 3850e3d18f1f8af8176337d7dde352b6f42af1a3..ba3b13bb0074d7de97b48cccccae6f414270dd60 100644 --- a/assets/shield-check-CoyMgFec.js +++ b/assets/shield-check-CuuwgPnV.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/shirt-DhJu64M2.js b/assets/shirt-DT9OZcT1.js similarity index 90% rename from assets/shirt-DhJu64M2.js rename to assets/shirt-DT9OZcT1.js index e263a1faf2d698fba720938ea82291224e4138d6..4b0e2b84a4426105bc163972bc0758b436503a54 100644 --- a/assets/shirt-DhJu64M2.js +++ b/assets/shirt-DT9OZcT1.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BYG24j30.js";/** +import{e as a}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/skeleton-9NZnc9sp.js b/assets/skeleton-nK8OdpwJ.js similarity index 93% rename from assets/skeleton-9NZnc9sp.js rename to assets/skeleton-nK8OdpwJ.js index d683398444bfdb57f59237c1bdfbb7c12ff89970..2511a279276e8af0acf1440d0dc896e1a495e14a 100644 --- a/assets/skeleton-9NZnc9sp.js +++ b/assets/skeleton-nK8OdpwJ.js @@ -1,4 +1,4 @@ -import{e,n as a}from"./index-BYG24j30.js";import{j as s}from"./vendor-react-B4AQeu28.js";/** +import{e,n as a}from"./index-CR5aYAL9.js";import{j as s}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-DiaNugT9.js b/assets/sparkles-Df420Y_c.js similarity index 93% rename from assets/sparkles-DiaNugT9.js rename to assets/sparkles-Df420Y_c.js index 6dd9d71bd7be616cbe708ec77363c426a0ab5aca..6683f2231831aa3073fbacb95dc4c39d28f39227 100644 --- a/assets/sparkles-DiaNugT9.js +++ b/assets/sparkles-Df420Y_c.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BYG24j30.js";/** +import{e as a}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/subjects-CnMsFeDX.js b/assets/subjects-CruSaBwq.js similarity index 98% rename from assets/subjects-CnMsFeDX.js rename to assets/subjects-CruSaBwq.js index e4e872de9ad6bd758203f8ad2ad225431e9ebf35..d1d057d9d0ce768703122e63e077a0d077546410 100644 --- a/assets/subjects-CnMsFeDX.js +++ b/assets/subjects-CruSaBwq.js @@ -1 +1 @@ -import{C as a}from"./index-BYG24j30.js";import{C as o}from"./chart-column-BOgIfbES.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-CR5aYAL9.js";import{C as o}from"./chart-column-nZ0JrvMi.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-CqM6p44O.js b/assets/switch-DI6PCkYC.js similarity index 93% rename from assets/switch-CqM6p44O.js rename to assets/switch-DI6PCkYC.js index 78884f6ad04b650ffd452cc3ba8ebfb014f9005e..ef5d16955b770daba7aa252cf7e0813187e743aa 100644 --- a/assets/switch-CqM6p44O.js +++ b/assets/switch-DI6PCkYC.js @@ -1 +1 @@ -import{j as e}from"./vendor-react-B4AQeu28.js";import{m as n,n as s}from"./vendor-radix-BPuEd8FG.js";import{n as t}from"./index-BYG24j30.js";function c({className:a,...r}){return e.jsx(n,{"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(s,{"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 n,n as s}from"./vendor-radix-BPuEd8FG.js";import{n as t}from"./index-CR5aYAL9.js";function c({className:a,...r}){return e.jsx(n,{"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(s,{"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-3LGLpyer.js b/assets/testResetService-BuCuwryb.js similarity index 99% rename from assets/testResetService-3LGLpyer.js rename to assets/testResetService-BuCuwryb.js index 45b527dfb54b8d2dabf30da14c43101e2cff164d..a14794832e2ce1e397901cdff3d4f69d7c7c8d75 100644 --- a/assets/testResetService-3LGLpyer.js +++ b/assets/testResetService-BuCuwryb.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{b3 as k,g as i,N as $}from"./index-BYG24j30.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-BPuEd8FG.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 H(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{H 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{b3 as k,g as i,N as $}from"./index-CR5aYAL9.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-BPuEd8FG.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 H(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{H as resetTestingDataForRole}; diff --git a/assets/tooltip-B8dZx5CM.js b/assets/tooltip-COrnGY4E.js similarity index 94% rename from assets/tooltip-B8dZx5CM.js rename to assets/tooltip-COrnGY4E.js index 9171f47d3f46a7b841d9b852becc92c3326bbb77..a1cbdb1b450526294a7cb11f555d6c5df388ed31 100644 --- a/assets/tooltip-B8dZx5CM.js +++ b/assets/tooltip-COrnGY4E.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-BPuEd8FG.js";import{n as p}from"./index-BYG24j30.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-BPuEd8FG.js";import{n as p}from"./index-CR5aYAL9.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-MJBRfiN7.js b/assets/trackingService-BGfVSr6K.js similarity index 93% rename from assets/trackingService-MJBRfiN7.js rename to assets/trackingService-BGfVSr6K.js index b4190fdd4a0b1d2ffca5e37c92d229b3d2bd7094..2fa16bdec607ddb3b2896c04e2508b25443aff56 100644 --- a/assets/trackingService-MJBRfiN7.js +++ b/assets/trackingService-BGfVSr6K.js @@ -1 +1 @@ -import{collection as e,addDoc as s,serverTimestamp as a}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as c}from"./index-BYG24j30.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const m="moduleActivities",E=async(o,r,i)=>{try{const t=e(c,m);await s(t,{userId:o,activityType:"chat_session",metadata:{sessionId:r,messageCount:i},timestamp:a()})}catch(t){throw console.error("Error logging chat session:",t),t}},T=async(o,r,i)=>{try{const t=e(c,m);await s(t,{userId:o,activityType:"lesson_view",moduleId:r,topicId:i,timestamp:a()})}catch(t){throw console.error("Error logging lesson view:",t),t}};export{E as logChatSession,T as logLessonView}; +import{collection as e,addDoc as s,serverTimestamp as a}from"./vendor-firebase-firestore-CNv3xXal.js";import{g as c}from"./index-CR5aYAL9.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-BPuEd8FG.js";import"./vendor-charts-CAmziV1y.js";import"./vendor-markdown-yqZQ_iQm.js";const m="moduleActivities",E=async(o,r,i)=>{try{const t=e(c,m);await s(t,{userId:o,activityType:"chat_session",metadata:{sessionId:r,messageCount:i},timestamp:a()})}catch(t){throw console.error("Error logging chat session:",t),t}},T=async(o,r,i)=>{try{const t=e(c,m);await s(t,{userId:o,activityType:"lesson_view",moduleId:r,topicId:i,timestamp:a()})}catch(t){throw console.error("Error logging lesson view:",t),t}};export{E as logChatSession,T as logLessonView}; diff --git a/assets/trash-2-Bz07bxtW.js b/assets/trash-2-BtGasoad.js similarity index 92% rename from assets/trash-2-Bz07bxtW.js rename to assets/trash-2-BtGasoad.js index bf102e90ef618bea02aee21e540f1906044e9513..c0856e9e219ef887e66a00149d052f9e00584bad 100644 --- a/assets/trash-2-Bz07bxtW.js +++ b/assets/trash-2-BtGasoad.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/upload-z5a73neo.js b/assets/upload-Dv-dcZHV.js similarity index 89% rename from assets/upload-z5a73neo.js rename to assets/upload-Dv-dcZHV.js index c7e0bf141f6c428151cd291e7c8aa06be41f1c40..f539f8cd20f8148dfab3ee6e3244695ff90f3fe8 100644 --- a/assets/upload-z5a73neo.js +++ b/assets/upload-Dv-dcZHV.js @@ -1,4 +1,4 @@ -import{e as o}from"./index-BYG24j30.js";/** +import{e as o}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/useCurriculum-BCsJVZ1p.js b/assets/useCurriculum-BQeS3LyA.js similarity index 93% rename from assets/useCurriculum-BCsJVZ1p.js rename to assets/useCurriculum-BQeS3LyA.js index 74bb084d2ea4b25d114ce5b986304f68c560c2d8..086e8a9e3d2928465a2d45888c68944f97573e2a 100644 --- a/assets/useCurriculum-BCsJVZ1p.js +++ b/assets/useCurriculum-BQeS3LyA.js @@ -1 +1 @@ -import{r}from"./vendor-react-B4AQeu28.js";import{aH as g}from"./index-BYG24j30.js";import{S as f}from"./subjects-CnMsFeDX.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{aH as g}from"./index-CR5aYAL9.js";import{S as f}from"./subjects-CruSaBwq.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-BqmsqlKE.js b/assets/useFeatureAccess-DCme1VYw.js similarity index 91% rename from assets/useFeatureAccess-BqmsqlKE.js rename to assets/useFeatureAccess-DCme1VYw.js index d2ab3b0b74de8d570d3eeb311b0b941fe083d6be..cd96ce1f8b4ccf078f446684c3a84123fa66e0fb 100644 --- a/assets/useFeatureAccess-BqmsqlKE.js +++ b/assets/useFeatureAccess-DCme1VYw.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-BYG24j30.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-CR5aYAL9.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-C5wg1Gx-.js b/assets/useQuery-CFyiy_x4.js similarity index 99% rename from assets/useQuery-C5wg1Gx-.js rename to assets/useQuery-CFyiy_x4.js index 9fa15131f606e4a3e2f9524e81b4468c46e1ab92..faa4db6aff61b6bbfe74048eaf299a32f216ce36 100644 --- a/assets/useQuery-C5wg1Gx-.js +++ b/assets/useQuery-CFyiy_x4.js @@ -1 +1 @@ -import{ap as Y,aq as N,ar as u,as as Q,at as g,au as M,av as x,aw as B,ax as G,ay as C,az as J,aA as X,aB as A,aC as W,aD as V,Y as Z}from"./index-BYG24j30.js";import{r as d}from"./vendor-react-B4AQeu28.js";var $=class extends Y{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=G(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||J.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,...X(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(n.fetchStatus="idle")}let{error:y,errorUpdatedAt:D,status:v}=n;o=n.data;let F=!1;if(e.placeholderData!==void 0&&o===void 0&&v==="pending"){let c;r?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(c=r.data,F=!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&&!F)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,D=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:D,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{ap as Y,aq as N,ar as u,as as Q,at as g,au as M,av as x,aw as B,ax as G,ay as C,az as J,aA as X,aB as A,aC as W,aD as V,Y as Z}from"./index-CR5aYAL9.js";import{r as d}from"./vendor-react-B4AQeu28.js";var $=class extends Y{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=G(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||J.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,...X(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(n.fetchStatus="idle")}let{error:y,errorUpdatedAt:D,status:v}=n;o=n.data;let F=!1;if(e.placeholderData!==void 0&&o===void 0&&v==="pending"){let c;r?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(c=r.data,F=!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&&!F)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,D=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:D,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-CNwO6mr3.js b/assets/useSubjectAvailability-SVKjmUD3.js similarity index 97% rename from assets/useSubjectAvailability-CNwO6mr3.js rename to assets/useSubjectAvailability-SVKjmUD3.js index 7d1be2031e4b4fc1fdc80ac7c41570a548447780..b4537312c1a07852dd079a6dc8916485ef92d6ba 100644 --- a/assets/useSubjectAvailability-CNwO6mr3.js +++ b/assets/useSubjectAvailability-SVKjmUD3.js @@ -1 +1 @@ -import{r as u}from"./vendor-react-B4AQeu28.js";import{g as j}from"./index-BYG24j30.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-CR5aYAL9.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-WJgblgWN.js b/assets/volume-x-FcYe0Ron.js similarity index 97% rename from assets/volume-x-WJgblgWN.js rename to assets/volume-x-FcYe0Ron.js index 926ec3475e6893f107b127d9e4b8b87f3819d74e..16a44a4f95a60b86bd152334b106eab388378c8b 100644 --- a/assets/volume-x-WJgblgWN.js +++ b/assets/volume-x-FcYe0Ron.js @@ -1,4 +1,4 @@ -import{e as a}from"./index-BYG24j30.js";/** +import{e as a}from"./index-CR5aYAL9.js";/** * @license lucide-react v0.487.0 - ISC * * This source code is licensed under the ISC license. diff --git a/assets/x-DU8WEZ6X.js b/assets/x-DiyyYv8Q.js similarity index 87% rename from assets/x-DU8WEZ6X.js rename to assets/x-DiyyYv8Q.js index 4b647ba6d93112582b1d8e8eb1b518f25030cac3..70756845cd37c08f3258b165f1c55800d328ce92 100644 --- a/assets/x-DU8WEZ6X.js +++ b/assets/x-DiyyYv8Q.js @@ -1,4 +1,4 @@ -import{e}from"./index-BYG24j30.js";/** +import{e}from"./index-CR5aYAL9.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 9cf90b1bb70e9cacb5719529ca5b51589b209c64..322c8c638e386a72f1670d9d59847364baf4575f 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} - +