PageSourceSearch

https://mindcrafter.lovable.app/assets/ClassroomRoom-BkstycNw.js

js mindcrafter.lovable.app collected 2026-10-03 03:34:15 UTC 326,562 bytes, 184 lines download raw bytes

1import{j as e,d0 as cs,d1 as Qs,a2 as Ys,Z as es,c7 as ds,X as Pt,b1 as ke,U as Je,aH as We,aQ as $t,aI as ts,aP as Ks,aT as ka,aS as Ta,aU as Ea,a5 as ft,a7 as us,a8 as it,bG as He,bh as ut,ce as ms,d2 as hs,b2 as Js,aY as gs,ab as nt,cr as Mt,a9 as Qe,d3 as Aa,ao as Ws,ak as zt,cX as ss,d4 as Pa,bl as as,b6 as gt,ci as Ia,d5 as Fa,d6 as Da,c$ as La,b4 as $a,$ as Ps,d7 as Ma,aG as yt,b7 as Rt,aW as Gt,cR as Zs,G as za,M as Xs,bn as Ra,Q as Ga,a0 as qa,d8 as Oa,a3 as tt,bF as Ua,J as rs,a4 as ot,b5 as It,d9 as Ba,cE as Yt,bm as Va,cS as Ha,K as ea,bO as Qa,bj as Ya,bJ as Ka,b8 as Et,cG as ns,bP as pt,da as Is,db as Fs,bi as Ja,dc as Wa,cF as Ds,dd as Za,cB as Xa,de as Ct,cd as Ls,aR as er}from"./ui-vendor-CphGW0d_.js";import{r as t,R as lt}from"./react-vendor-BOawO_dD.js";import{E as Ge,aA as tr,z as E,aB as ps,j as De,k as Le,l as $e,m as Me,n as Z,B as _,a2 as ta,a3 as sa,a5 as aa,L as Te,g as Ft,aC as Dt,aD as sr,aE as at,C as te,S as ar,f as me,o as we,aF as jt,u as Xe,I as _e,ac as bt,ad as et,$ as wt,e as ie,aG as rr,aH as nr,t as rt,aI as or,D as qe,p as Oe,q as Be,r as Ve,Z as ra,v as qt,w as Ot,x as Ye,y as Ke,a6 as ir,a7 as lr,a8 as cr,a9 as dr,a0 as Ze,aw as na,ax as oa,ay as ia,az as os,aJ as $s,aK as ur,am as is,c as Ee,d as Ae,aL as mr,P as At,aM as xs,aN as hr,al as Kt,a1 as gr,ai as pr,aO as Jt,J as ne,aP as la,aQ as xr,s as fr,au as vr,aR as yr,av as jr,ah as br}from"./index-Cn92Z84x.js";import{u as wr,a as ca,b as Nr,c as Cr,C as Wt}from"./CollapsibleSection-DO4lrEN3.js";import{S as vt}from"./slider-Dxp9bXDg.js";import{L as da,d as fs,a as Sr}from"./react-ecosystem-BT3vmxzF.js";import{M as st}from"./MessageFormatter-FQbaEpH3.js";import{u as _r}from"./useHomeworkFileUpload-BzUSy_MC.js";import{u as ct,g as Lt,a as vs,M as mt,b as kr,c as ys,C as Nt,d as Tr,e as Er,A as Ar,v as Ut,I as js,f as Pr,G as Ir,S as Fr,P as Dr,h as Lr,i as $r,F as Mr,L as zr}from"./LearningToolModal-D8SBZC2J.js";import{L as Rr,F as Gr,g as qr}from"./learningTools-C-L-GPs2.js";import{E as Or}from"./jspdf.es.min-BL67v0Dp.js";import{a as Ur}from"./jspdf.plugin.autotable-CKrDCDFb.js";import{u as Br,V as Vr,M as Hr,a as Qr}from"./VoiceRecordingIndicator-CkWntlLO.js";import{f as Ms}from"./formatDistanceToNow-CJEa0op3.js";import{u as Yr}from"./useUserPersonalization-D2YNCYto.js";import{u as bs}from"./useToolAssistantSettings-DSD9yL5W.js";import{B as Kr}from"./ButtonJournal-C7UNW-wJ.js";import{u as Jr}from"./useBadgeProgressEngine-6X17zjJb.js";import{u as Wr}from"./useClassroomLearningTools-DtoHcu-z.js";import{a as ua,u as Zr}from"./useTutors-Cx8cNXJI.js";import{u as Xr}from"./useLearningToolLauncher-D6QPAaYc.js";import{D as en,a as tn,b as sn,c as an,d as rn}from"./drawer-DEQ5RWGO.js";import{R as nn,a as zs,b as on}from"./resizable-dCTlQpQe.js";import"./data-vendor-CMH9r-4t.js";import"./index-B3BTLcT-.js";import"./index-CuVSClOr.js";import"./generateCategoricalChart-BpMdOWyi.js";import"./tiny-invariant-BaFNuDhB.js";import"./value-CTJVzmQ8.js";import"./BarChart-C3SpPras.js";import"./YAxis-DHwiHI8x.js";import"./PieChart-C3rvhyfA.js";import"./alert-dialog-BrrpgaWQ.js";import"./table-DiB-099h.js";import"./typeof-QjJsDpFa.js";import"./unsupportedIterableToArray-BlAcjINT.js";import"./endOfMonth-fQjdYjMI.js";import"./calendar-i7uK9d12.js";import"./addDays-Cgc1_uCx.js";import"./subDays-BsWWOQUG.js";import"./isAfter-CebtaFui.js";import"./index.min-CLJaQHSX.js";import"./UniversalAudioPlayer-DhBwFaNT.js";const Bt=()=>{const[s,a]=t.useState([]),[m,x]=t.useState(!1),{user:p}=Ge(),{handleAppAction:l}=tr(),h=wr(),u=t.useCallback(async()=>{try{const{data:y,error:N}=await E.from("hidden_communication_triggers").select("*").eq("is_active",!0).order("trigger_name");if(N)throw N;a(y||[])}catch(y){console.error("Error loading hidden triggers:",y)}},[]),d=t.useCallback(async(y,N)=>{if(!p?.id)return!1;try{const{data:A,error:w}=await E.rpc("track_student_tutor_interaction",{p_student_id:p.id,p_tutor_name:y,p_classroom_id:N});if(w)throw w;return!A}catch(A){return console.error("Error checking first time interaction:",A),!1}},[p?.id]),n=t.useCallback(async()=>
1{if(!p?.id)return null;try{const{data:y,error:N}=await E.rpc("get_student_profile_for_assistant",{p_student_id:p.id});if(N)throw N;return y}catch(y){return console.error("Error getting student profile:",y),null}},[p?.id]),r=t.useCallback(async(y,N,A,w,P,k)=>{if(p?.id)try{const{error:I}=await E.from("hidden_assistant_messages").insert({classroom_id:y,student_id:p.id,tutor_name:N,trigger_code:A,direction:w,hidden_content:P,user_message_id:k});if(I)throw I}catch(I){console.error("Error saving hidden message:",I)}},[p?.id]),v=t.useCallback(y=>{const N=["frustrated","confused","don't understand","difficult","hard","can't figure out","stuck","doesn't make sense","help me","i give up","this is stupid","hate this","annoying"],A=y.toLowerCase();return N.some(w=>A.includes(w))},[]),j=t.useCallback(y=>{const N=["interesting","fascinating","tell me more","love this","amazing","cool","awesome","want to learn","excited","more examples","what else","how about","can we explore"],A=y.toLowerCase(),w=(y.match(/\?/g)||[]).length>1,P=N.some(k=>A.includes(k));return w||P||y.length>150},[]),b=t.useCallback(y=>{const N=["explain again","clarify","show me","example","step by step","break it down","simpler","easier way","not sure","unclear"],A=y.toLowerCase();return N.some(w=>A.includes(w))},[]),g=t.useCallback(y=>{const N=["ok","sure","fine","whatever","i guess","maybe","don't care","boring","tired","later"],A=y.toLowerCase(),w=y.length<20,P=N.some(k=>A.includes(k));return w&&P},[]),c=t.useCallback(async(y,N,A,w)=>{const P=[];w&&P.push("FIRST_TIME_CHAT"),v(y)&&P.push("USER_FRUSTRATED"),j(y)&&P.push("HIGH_ENGAGEMENT"),b(y)&&P.push("NEEDS_HELP"),g(y)&&P.push("LOW_ENGAGEMENT");for(const k of P){const I=s.find(T=>T.trigger_code===k);if(I)try{const T=JSON.parse(I.app_action),M={trigger:k};if(T.action==="send_learning_profile"||T.action==="send_student_profile"){const G=await n();M.studentProfile=G}T.action==="suggest_classroom"&&(M.suggestedClassroom={classroomId:T.classroom_id,reason:T.reason,assignmentRelated:T.assignment_related||!1}),await r(N,A,k,"app_to_assistant",M),console.log("🔄 Hidden trigger activated:",k,M)}catch(T){console.error("Error processing trigger:",k,T)}}return P},[s,v,j,b,g,n,r]),o=t.useCallback(async(y,N,A,w,P,k)=>{if(!y)return{cleanResponse:y,generatedButtons:[],autoAwards:[]};console.log("🔄 Parsing assistant response for secret codes:",y);const I=/\[PROFILE_EVOLUTION:([^:]+):(\{[^}]*\})\]/g;let T;for(;(T=I.exec(y))!==null;)try{const K=parseFloat(T[1])||.7,O=JSON.parse(T[2]);if(console.log("🧠 Profile evolution detected:",{confidenceScore:K,updates:O}),p?.id){const{error:W}=await E.rpc("record_profile_evolution",{p_student_id:A,p_tutor_name:w,p_personality_id:null,p_updates:O,p_observation:{source:"chat_interaction",confidence:K,context:N},p_confidence:K});W?console.error("Error recording profile evolution:",W):console.log("✅ Profile evolution recorded successfully")}}catch(K){console.error("Error processing PROFILE_EVOLUTION:",K)}const M=/\[APP_ACTION:REQUEST_RESOURCES:(\{[^}]+\})\]/g;let G,D=null;for(;(G=M.exec(y))!==null;)try{const K=JSON.parse(G[1]);K.resource==="learner_profile"&&(console.log("🔄 Processing REQUEST_RESOURCES for learner_profile"),D=await n(),await r(N,w,"REQUEST_RESOURCES","assistant_to_app",{request:K,response:D},P))}catch(K){console.error("Error processing REQUEST_RESOURCES:",K)}try{const K=/\[APP_ACTION:([A-Z_]+):(\{[^}]*\})\]/g;let O;for(;(O=K.exec(y))!==null;)try{const W=O[1],B=JSON.parse(O[2]);W==="CHALLENGE_GENERATED"&&(console.log("🎯 Challenge generation detected, setting support mode context"),await r(N,w,"CHALLENGE_GENERATED","app_to_assistant",{mode:B.mode||"support",source:B.source||"unknown",timestamp:new Date().toISOString()},P)),await r(N,w,W,"assistant_to_app",B,P),l({actionCode:W,messageData:B,handlerType:"custom",handlerConfig:{source:"assistant_hidden_code"}})}catch(W){console.warn("Failed to process APP_ACTION payload",W)}}catch(K){console.warn("APP_ACTION parsing error",K)}const Y=y.replace(/\[PROFILE_EVOLUTION:[^\]]+\]/g,"").replace(/\[APP_ACTION:[^\]]+\]/g,""),{displayText:de,buttonCodes:pe}=h.parseOpenAIResponse(Y),xe=de.replace(/\[[A-Za-z0-9_@#$%^&*!]+#[A-Z_]+#?[^\]]*\]/g,""),ce=[];for(const K of pe)if(K.buttonType==="TOKEN_AUTO_AWARD"||K.buttonType==="TOKEN_REWARD"&&K.customData?.includes('"requiresClick":false'))try{const O=JSON.parse(K.customData||"{}");ce.push({amount:O.amount||5,reason:O.reason||"for your work",event:O.event||"auto_reward"}),console.log("✨ Auto-award detected:",ce[ce.length-1])}catch(O){console.warn("Failed to parse auto-award payload:",O)}const oe=pe.filter(K=>!(K.buttonType==="TOKEN_AUTO_AWARD"||K.buttonType==="TOKEN_REWARD"&&K.customData?.includes('"requiresClick":false')));let ae=[];oe.length>0&&(console.log("🔄 Found clickable button codes, generating dynamic buttons:",oe),ae=await h.generateDynamicButtons(oe));try{const{data:K,error:O}=await E.functions.invoke("parse-assistant-response",{body:{assistantResponse:y,classroomId:N,studentId:A,tutorName:w,userMessageId:P,assistantMessageId:k,profileData:D}});return!O&&K?.success&&K.messages?.length>0&&(console.log("🔄 Processing assistant actions:",K.messages),K.messages.forEac
1h(W=>{l(W)})),{cleanResponse:xe,generatedButtons:ae,autoAwards:ce,messages:K?.messages||[],profileData:D}}catch(K){return console.error("Edge function not available, using local parsing only:",K),{cleanResponse:xe,generatedButtons:ae,autoAwards:ce,messages:[],profileData:D}}},[l,h,n,r,p]),i=t.useCallback(async y=>{try{const{data:N,error:A}=await E.from("assistant_app_messages").select("*").eq("student_id",y).eq("is_processed",!1).order("created_at",{ascending:!0});if(A)throw A;return N||[]}catch(N){return console.error("Error fetching assistant messages:",N),[]}},[]),f=t.useCallback(async y=>{try{const{error:N}=await E.from("assistant_app_messages").update({is_processed:!0,processed_at:new Date().toISOString()}).eq("id",y);if(N)throw N}catch(N){console.error("Error marking message as processed:",N)}},[]);return{triggers:s,isLoading:m,loadTriggers:u,checkFirstTimeInteraction:d,getStudentProfileForAssistant:n,processMessageForTriggers:c,saveHiddenMessage:r,parseAssistantResponse:o,getUnprocessedAssistantMessages:i,markMessageProcessed:f,dynamicButtons:{activeButtons:h.activeButtons,currentSequence:h.currentSequence,currentStep:h.currentStep,handleButtonClick:h.handleButtonClick,clearActiveButtons:h.clearActiveButtons,parseOpenAIResponse:h.parseOpenAIResponse,generateDynamicButtons:h.generateDynamicButtons}}},ln=s=>{const[a,m]=t.useState({chillMode:!1,learnerProfile:null,chatPreferences:null,profileRequestPending:!1,profileTimeout:null});t.useEffect(()=>{const n=r=>{console.log("🔄 Chat preferences updated:",r.detail),m(v=>({...v,chatPreferences:r.detail.preferences}))};return window.addEventListener("chat-preferences-updated",n),()=>{window.removeEventListener("chat-preferences-updated",n)}},[]);const x=t.useCallback(n=>{const r=n.toLowerCase();return r.includes("chill mode")?(m(v=>({...v,chillMode:!0})),console.log("🔄 Chill mode activated"),!0):r.includes("back to normal")||r.includes("normal mode")?(m(v=>({...v,chillMode:!1})),console.log("🔄 Chill mode deactivated"),!0):!1},[]),p=t.useCallback(n=>{m(r=>(r.profileTimeout&&clearTimeout(r.profileTimeout),{...r,learnerProfile:n,profileRequestPending:!1,profileTimeout:null}))},[]),l=t.useCallback(n=>{m(r=>({...r,chatPreferences:n}))},[]),h=t.useCallback(()=>{m(n=>{n.profileTimeout&&clearTimeout(n.profileTimeout);const r=setTimeout(()=>{console.log("🔄 Profile request timeout - proceeding with defaults"),m(v=>({...v,profileRequestPending:!1,profileTimeout:null}))},5e3);return{...n,profileRequestPending:!0,profileTimeout:r}})},[]),u=t.useCallback(()=>({chillMode:a.chillMode,learnerProfile:a.learnerProfile,chatPreferences:a.chatPreferences,hasProfile:!!a.learnerProfile,profilePending:a.profileRequestPending}),[a]),d=t.useCallback(()=>{m(n=>(n.profileTimeout&&clearTimeout(n.profileTimeout),{chillMode:!1,learnerProfile:null,chatPreferences:null,profileRequestPending:!1,profileTimeout:null}))},[]);return{conversationState:a,processUserMessage:x,setLearnerProfile:p,setChatPreferences:l,startProfileRequest:h,getAssistantContext:u,clearState:d,chillMode:a.chillMode,hasLearnerProfile:!!a.learnerProfile}},ma=()=>{const{studentProfile:s}=ps(),[a,m]=t.useState(null),[x,p]=t.useState(!0);t.useEffect(()=>{s?.id&&l()},[s?.id]);const l=async()=>{if(s?.id)try{const{data:u,error:d}=await E.from("chat_preferences").select("*").eq("student_id",s.id).maybeSingle();if(d&&d.code!=="PGRST116"){console.error("Error loading chat preferences:",d);return}u&&m({tone:u.tone,formality:u.formality_level,verbosity:u.verbosity_level,useEmojis:u.use_emojis,detailedExplanations:u.detailed_explanations})}finally{p(!1)}};return{preferences:a,loading:x,savePreferences:async u=>{if(!s?.id)return console.error("No student profile found"),{success:!1,error:"No student profile"};try{const{error:d}=await E.from("chat_preferences").upsert({student_id:s.id,tone:u.tone,formality_level:u.formality,verbosity_level:u.verbosity,use_emojis:u.useEmojis,detailed_explanations:u.detailedExplanations,updated_at:new Date().toISOString()},{onConflict:"student_id"});return d?(console.error("Error saving chat preferences:",d),{success:!1,error:d.message}):(m(u),window.dispatchEvent(new CustomEvent("chat-preferences-updated",{detail:{preferences:u,studentId:s.id}})),{success:!0})}catch(d){return console.error("Error in savePreferences:",d),{success:!1,error:"Failed to save preferences"}}},refreshPreferences:l}},cn=s=>{const a=Bt(),m=ln(),{preferences:x}=ma();return t.useEffect(()=>{x&&m.setChatPreferences(x)},[x]),t.useEffect(()=>{const u=d=>{try{const n=d.detail?.codes;Array.isArray(n)&&n.length&&a.dynamicButtons.generateDynamicButtons(n)}catch(n){console.error("Error handling dynamic-buttons:generate in helper hook",n)}};return window.addEventListener("dynamic-buttons:generate",u),()=>window.removeEventListener("dynamic-buttons:generate",u)},[a]),{processAIResponse:async(u,d,n)=>{const r=await a.parseAssistantResponse(u,s,n||"",d);return r.profileData&&m.setLearnerProfile(r.profileData),{cleanResponse:r.cleanResponse||u,generatedButtons:r.generatedButtons||[],shouldShowButtons:r.generatedButtons?.length>0,conversationContext:m.getAssistantContext()}},processUserMessage:u=>({modeChanged:m.processUserMessage(u),chillMode:m.chillMode,conversationContext:m.getAssistantContext()}),handleButtonClick:async(u,d)=>await a.dynamicButtons.handleButtonClick(u,s,d),activeButtons:a.dynamicButtons.activeButtons,clearButtons:a.dynamicButtons.clearActiveButtons,conversationState:m.getAssistantContext(),chillMode:m.chillMode,hasLearnerProfile:m.hasLearnerProfile}},dn=({selectedVoice:s,onVoiceChange:a,className:m})=>{const[x,p]=t.useState([]);t.useEffect(()=>{const u=()=>{const d=speechSynthesis.getVoices();p(d)};return u(),speechSynthesis.onvoiceschanged=u,()=>{speechSynthesis.onvoiceschanged=null}},[]);const l=x.reduce((u,d)=>{const n=d.lang.split("-")[0];return u[n]||(u[n]=[]),u[n].push(d),u},{}),h=u=>{const d=x.find(n=>n.name===u);if(d){const n=new SpeechSynthesisUtterance("Hello, this is how I sound!");n.voice=d,n.rate=1,n.volume=.7,speechSynthesis.speak(n)}};return e.jsx("div",{className:m,children:e.jsxs(De,{value:s,onValueChange:a,children:[e.jsx(Le,{children:e.jsx($e,{placeholder:"Select a voice"})}),e.jsx(Me,{children:Object.entries(l).map(([u,d])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground uppercase",children:new Intl.DisplayNames(["en"],{type:"language"}).of(u)||u}),d.map(n=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Z,{value:n.name,className:"flex-1",children:[n.name," ",n.localService?"(Local)":"(Remote)"]}),e.jsx(_,{variant:"ghost",size:"sm",onClick:r=>{r.stopPropagation(),h(n.name)},className:"ml-2 p-1 h-auto",children:e.jsx(cs,{className:"w-3 h-3"})})]},n.name))]},u))})]})})},Zt=({onSettingsChange:s,className:a})=>{const[m,x]=t.useState(()=>{const l=localStorage.getItem("classroom-tts-settings");return l?JSON.parse(l):{voice:"",rate:1,volume:.8,autoRead:!1,enabled:!0}});t.useEffect(()=>{if(!m.voice){const l=speechSynthesis.getVoices();if(l.length>0){const u=(()=>{const n=window.location.pathname.match(/\/classrooms\/([^\/]+)/);if(n){const r=n[1];try{const v=Dt(r);if(v&&v.name){const j=v.name.toLowerCase(),b=["diana","trudi","farah","connie","isabel","tara","paula","priyanka","shiela","betty","misha","leah","ciara"],g=["simon","rowland","peter","barry","stanley","yuri","matthew","eugene","billy","brian","uriel","gabriel","corey","haskell","sean"],c=b.some(i=>j.includes(i)),o=g.some(i=>j.includes(i));if(c){const i=l.find(f=>f.lang.includes("en-GB")&&(f.name.toLowerCase().includes("female")||f.name.toLowerCase().includes("kate")||f.name.toLowerCase().includes("susan")))||l.find(f=>f.lang.includes("en-")&&f.name.toLowerCase().includes("female"));if(i)return i.name}if(o){const i=l.find(f=>f.lang.includes("en-GB")&&(f.name.toLowerCase().includes("male")||f.name.toLowerCase().includes("daniel")||f.name.toLowerCase().includes("oliver")))||l.find(f=>f.lang.includes("en-")&&f.name.toLowerCase().includes("male"));if(i)return i.name}}}catch(v){console.warn("Could not determine tutor gender for voice selection:",v)}}return(l.find(r=>r.default)||l[0]).name})();x(d=>({...d,voice:u}))}}},[m.voice]),t.useEffect(()=>{localStorage.setItem("classroom-tts-settings",JSON.stringify(m)),s(m)},[m,s]);const p=l=>{x(h=>({...h,...l}))};return e.jsx("div",{className:a,children:e.jsxs(ta,{children:[e.jsx(sa,{asChild:!0,children:e.jsxs(_,{size:"sm",className:"gap-2 bg-gradient-to-r from-blue-500 to-cyan-400 text-white hover:from-blue-600 hover:to-cyan-500 border-0 shadow-md hover:shadow-lg transition-all duration-200 hover:scale-105",children:[m.enabled?e.jsx(cs,{className:"w-4 h-4"}):e.jsx(Qs,{className:"w-4 h-4"}),e.jsx(Ys,{className:"w-4 h-4"}),"TTS"]})}),e.jsx(aa,{className:"w-80 space-y-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Te,{htmlFor:"tts-enabled",children:"Enable Text-to-Speech"}),e.jsx(Ft,{id:"tts-enabled",checked:m.enabled,onCheckedChange:l=>p({enabled:l})})]}),m.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Te,{children:"Voice"}),e.jsx(dn,{selectedVoice:m.voice,onVoiceChange:l=>p({voice:l})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Te,{children:["Speed: ",m.rate.toFixed(1),"x"]}),e.jsx(vt,{value:[m.rate],onValueChange:([l])=>p({rate:l}),min:.5,max:2,step:.1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Te,{children:["Volume: ",Math.round(m.volume*100),"%"]}),e.jsx(vt,{value:[m.volume],onValueChange:([l])=>p({volume:l}),min:0,max:1,step:.1})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Te,{htmlFor:"auto-read",children:"Auto-read new messages"}),e.jsx(Ft,{id:"auto-read",checked:m.autoRead,onCheckedChange:l=>p({autoRead:l})})]})]})]})})]})})},un=()=>{const{isPlaying:s,currentMessage:a,stopVoice:m}=sr();return s?e.jsx("div",{className:"fixed top-20 right-6 z-50 animate-in slide-in-from-right-2 duration-300",children:e.jsxs("div",{className:"bg-background/95 backdrop-blur-sm border border-border rounded-lg shadow-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cs,{className:"w-4 h-4"}),e.jsx("span",{children:"Reading message..."})]}),e.jsxs(_,{variant:"outline",size:"sm",onClick:m,className:"gap-2 h-8",children:[e.jsx(Qs,{className:"w-4 h-4"}),"Stop"]})]}),a&&e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground max-w-xs truncate",children:['"',a,'"']})]})}):null},mn=({classroomSubject:s})=>{const{currentStudent:a,isLoading:m}=at();return m?e.jsx(te,{className:"p-4 mb-4 bg-card/50 border-border/50",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Tokens"})]}),e.jsx(ar,{className:"h-6 w-12"})]})}):e.jsxs("div",{className:"flex items-center gap-4 p-4 mb-4 bg-card/50 border border-border/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[e.jsx(es,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Your Tokens"}),e.jsx(me,{variant:"secondary",className:"ml-2 bg-primary/10 text-primary border-primary/20 px-3 py-1 token-count",children:(a?.total_tokens||0).toLocaleStr
1ing()})]})]}),e.jsx(_,{variant:"outline",size:"sm",className:"gap-2",asChild:!0,children:e.jsxs(da,{to:"/rewards",children:[e.jsx(ds,{className:"h-4 w-4"}),e.jsx("span",{children:"Rewards Hub"})]})})]})},hn=({open:s,onOpenChange:a,offers:m,onCollect:x})=>{if(!s)return null;const p=m.filter(l=>l.buttonType==="TOKEN_REWARD");return e.jsxs("div",{className:"fixed inset-0 z-[60]",children:[e.jsx("div",{className:"absolute inset-0 bg-background/60 backdrop-blur-sm",onClick:()=>a(!1)}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4",children:e.jsxs(te,{className:"bg-card border-border shadow-2xl w-[360px] max-w-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Rewards"})]}),e.jsx(_,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",onClick:()=>a(!1),children:e.jsx(Pt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"p-4 space-y-3",children:p.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No rewards available right now."}):p.map(l=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border/60 p-3 bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:l.buttonText}),l.customData?.eventType&&e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:String(l.customData.eventType).split("_").join(" ")})]}),e.jsx(_,{size:"sm",onClick:async()=>{await x(l),a(!1)},children:"Collect"})]},l.id))})]})})]})},gn={"interactive-quiz":30,flashcards:30,"study-guide":20,"generate-challenge":20,roleplay:20,"homework-help":15,"learning-profile":15,"generate-image":10,"generate-table":10,"principle-injection":10,"scrape-youtube":5,"suggestion-box":5},pn=()=>{const[s,a]=t.useState(!1),{toast:m}=we(),{currentStudent:x}=at();return{awardTokensForTool:t.useCallback(async(l,h,u)=>{if(!x?.id)return console.warn("No student session found for token award"),null;const d=gn[l]||10;a(!0);try{const n=`${x.id}-${l}-${h}-${Date.now()}`,{data:r,error:v}=await E.functions.invoke("award-tool-tokens",{body:{studentId:x.id,toolId:l,classroomId:h,tokenAmount:d,completionKey:n,completionData:u}});if(v)throw v;return r.newTotal!==void 0&&window.dispatchEvent(new CustomEvent("student:tokens-update",{detail:{newTotal:r.newTotal}})),m({title:`🎉 +${d} tokens earned!`,description:`${r.toolName||"Tool"} completed successfully. 💰 Redeem your tokens for rewards you actually like on the Rewards page!`,duration:8e3}),{success:!0,tokensAwarded:d,newTotal:r.newTotal}}catch(n){return console.error("Error awarding tokens:",n),null}finally{a(!1)}},[x,m]),isAwarding:s}},xn=({classroomId:s,initialTopic:a="",context:m,persistence:x,onComplete:p,onClearTool:l})=>{const[h,u]=t.useState(x?.toolState?.topic||a),[d,n]=t.useState(x?.toolState?.guide||""),[r,v]=t.useState(!1),[j,b]=t.useState(!1),{toast:g}=we(),{age:c}=jt(),{isStudent:o}=Xe(),{saveAid:i,refetch:f}=ct(),{user:y}=Ge();t.useEffect(()=>{d&&h&&console.log("💾 Study guide state updated")},[d,h]);const N=o()?Lt(c):"College",A=o()?vs(c):"advanced",w=async()=>{if(!h.trim()){g({title:"Topic Required",description:"Please enter a topic for the study guide.",variant:"destructive"});return}v(!0);const k=new AbortController,I=setTimeout(()=>k.abort(),45e3);try{const{data:T,error:M}=await E.functions.invoke("generate-study-guide-stewart",{body:{topic:h,studyLevel:A,gradeLevel:N,includeImages:!1,context:m||"",step:"full_guide"},signal:k.signal});if(M)throw console.error("Study guide generation error:",M),M;let G="";if(T?.sections&&Array.isArray(T.sections)?G=T.sections.map(D=>`## ${D.title}
2
3${D.content}`).join(`
4
5`):T?.content&&typeof T.content=="string"?G=T.content:typeof T=="string"&&(G=T),!G)throw new Error("No content generated");n(G),g({title:"Study Guide Generated!",description:"Your personalized study guide is ready."}),console.log("Study guide generated successfully, calling onComplete"),p?.({to
5pic:h,guide:G,timestamp:new Date().toISOString()}),console.log("onComplete called, study guide should remain visible")}catch(T){console.error("Error generating study guide:",T);let M="Could not generate study guide.";T.name==="AbortError"?M="Study guide generation timed out after 45 seconds. Please try again.":T.message&&(M=T.message),g({title:"Generation Failed",description:M,variant:"destructive"})}finally{clearTimeout(I),v(!1)}},P=async()=>{if(!y){g({title:"Authentication Required",description:"Please log in to save to Learning Aids.",variant:"destructive"});return}if(!d){g({title:"No Content",description:"There is no study guide to save.",variant:"destructive"});return}b(!0);try{await i({user_id:y.id,title:`Study Guide: ${h}`,content_type:"study_guide",content:{guide:d,generatedAt:new Date().toISOString()},metadata:{classroomId:s,gradeLevel:N,studyLevel:A,topic:h},tags:[h,"study_guide",s],is_favorite:!1}),await f(),g({title:"Saved!",description:"Study guide saved to My Learning Aids"})}catch(k){console.error("Error saving to learning aids:",k)}finally{b(!1)}};return e.jsx("div",{className:"p-4 space-y-3",children:d?e.jsxs("div",{className:"space-y-3 max-h-96 overflow-y-auto",children:[e.jsx("div",{className:"text-sm bg-muted/50 rounded-lg p-3",children:e.jsx(st,{content:d})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(mt,{text:d,className:"w-full"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_,{variant:"outline",size:"sm",onClick:P,disabled:j,className:"flex-1",children:j?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),"Save to My Learning Aids"]})}),e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>{n(""),u(""),l?.()},className:"flex-1",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Start New"]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Study Guide Topic"}),e.jsx(_e,{value:h,onChange:k=>u(k.target.value),placeholder:"Enter topic to study...",disabled:r})]}),e.jsx(_,{onClick:w,disabled:r||!h.trim(),className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"mr-2 h-4 w-4"}),"Generate Study Guide"]})})]})})},fn=({classroomId:s,initialTopic:a="",context:m,chatMessages:x,persistence:p,onComplete:l,onContentChange:h,onClearTool:u,onTopicChange:d})=>{const[n,r]=t.useState(p?.toolState?.topic||a),[v,j]=t.useState(p?.toolState?.questions||[]),[b,g]=t.useState(p?.toolState?.currentQuestionIndex||0),[c,o]=t.useState(null),[i,f]=t.useState(!1),[y,N]=t.useState(p?.toolState?.score||0),[A,w]=t.useState(!1),[P,k]=t.useState(!1),[I,T]=t.useState(!1),{toast:M}=we(),{saveAid:G,refetch:D}=ct(),{user:Y}=Ge();t.useEffect(()=>{v.length>0&&p?.updateToolState&&(p.updateToolState(p.tool.id,{toolState:{questions:v,currentQuestionIndex:b,score:y,topic:n}}),console.log("💾 Quiz state persisted"))},[v,b,y,n]);const de=async()=>{if(!n.trim()){M({title:"Topic Required",description:"Please enter a topic for the quiz.",variant:"destructive"});return}w(!0);try{const O=async B=>{const{data:F,error:Q}=await E.functions.invoke("openai-assistant-quiz",{body:{classroomId:s,questionCount:5,difficulty:"Mixed",topics:B&&n?[n]:void 0,chatMessages:x||[]}});if(Q)throw Q;return F};let W=await O(!0);(!W?.questions||W.questions.length===0)&&(W=await O(!1)),W?.questions&&W.questions.length>0?(j(W.questions),g(0),N(0),d?.(n),M({title:"Quiz Generated!",description:`${W.questions.length} questions ready.`})):(console.log("Quiz generation returned no questions:",W),M({title:"No questions generated",description:"Try a more specific topic.",variant:"destructive"}))}catch(O){console.error("Error generating quiz:",O);const W=O.message||O.toString()||"Could not generate quiz. Please try again.";M({title:"Quiz Generation Failed",description:W,variant:"destructive"})}finally{w(!1)}},pe=()=>{if(c===null)return;c===v[b].correctAnswer&&N(y+1),f(!0)},xe=()=>{if(b<v.length-1)g(b+1),o(null),f(!1);else{const O=y+(c===v[b].correctAnswer?1:0);
5T(!0),l?.({topic:n||a,totalQuestions:v.length,score:O,timestamp:new Date().toISOString()})}},ce=async()=>{if(!Y){M({title:"Authentication Required",description:"Please log in to save to Learning Aids.",variant:"destructive"});return}if(!v||v.length===0){M({title:"No Content",description:"There is no quiz to save.",variant:"destructive"});return}k(!0);try{const O=y+(c===v[b]?.correctAnswer?1:0);await G({user_id:Y.id,title:`Quiz: ${n}`,content_type:"interactive_quiz",content:{questions:v,score:O,totalQuestions:v.length,generatedAt:new Date().toISOString()},metadata:{classroomId:s,topic:n},tags:[n,"quiz",s],is_favorite:!1}),await D(),M({title:"Saved!",description:"Quiz saved to My Learning Aids"})}catch(O){console.error("Error saving to learning aids:",O),M({title:"Save Failed",description:"Could not save quiz",variant:"destructive"})}finally{k(!1)}},oe=v[b],ae=b===v.length-1,K=y+(i&&c===oe?.correctAnswer?1:0);return v.length===0?e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quiz Topic"}),e.jsx(_e,{value:n,onChange:O=>r(O.target.value),placeholder:"Enter topic for quiz...",disabled:A})]}),e.jsx(_,{onClick:de,disabled:A||!n.trim(),className:"w-full",children:A?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"mr-2 h-4 w-4"}),"Generate Quiz"]})})]}):I?e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Quiz Completed!"}),e.jsxs("div",{className:"text-2xl font-bold text-primary",children:["Score: ",K,"/",v.length]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:K===v.length?"Perfect score! 🎉":K>=v.length*.7?"Great job! 👏":"Keep practicing! 💪"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(_,{variant:"outline",size:"sm",onClick:ce,disabled:P,className:"w-full",children:P?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),"Save to My Learning Aids"]})}),e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>{j([]),r(""),g(0),N(0),o(null),f(!1),T(!1),u?.()},className:"w-full",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Start New Quiz"]})]})]}):e.jsxs("div",{className:"p-4 space-y-4 max-h-96 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"font-medium",children:["Question ",b+1," of ",v.length]}),e.jsxs("span",{className:"text-muted-foreground",children:["Score: ",K,"/",v.length]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:oe.question}),e.jsx(bt,{value:c?.toString()??"",onValueChange:O=>!i&&o(parseInt(O)),disabled:i,children:oe.options.map((O,W)=>e.jsxs("div",{className:`flex items-center space-x-2 p-2 rounded ${i?W===oe.correctAnswer?"bg-green-500/10 border border-green-500/30":W===c?"bg-red-500/10 border border-red-500/30":"":""}`,children:[e.jsx(et,{value:W.toString(),id:`option-${W}`}),e.jsx(Te,{htmlFor:`option-${W}`,className:"flex-1 cursor-pointer",children:O}),i&&W===oe.correctAnswer&&e.jsx(ts,{className:"h-4 w-4 text-green-600"}),i&&W===c&&W!==oe.correctAnswer&&e.jsx(Ks,{className:"h-4 w-4 text-red-600"})]},W))},`question-${b}`),i&&oe.explanation&&e.jsxs("div",{className:"bg-muted/50 p-3 rounded text-sm",children:[e.jsx("span",{className:"font-medium",children:"Explanation: "}),oe.explanation]})]}),e.jsx("div",{className:"flex gap-2",children:i?e.jsx(_,{onClick:xe,className:"flex-1",children:ae?"Finish Quiz":"Next Question"}):e.jsx(_,{onClick:pe,disabled:c===null,className:"flex-1",children:"Check Answer"})})]})},vn=({classroomId:s,initialTopic:a="",context:m,persistence:x,onComplete:p,onClearTool:l,completedData:h})=>{const{saveAid:u,refetch:d}=ct(),[n,r]=t.useState(()=>x?.toolState?.topic?x.toolState.topic:localStorage.getItem(`flashcards_${s}_topic`)||a),[v,j]=t.useState(()=>{if(x?.toolState?.flashcards)return x.toolState.flashcards;const G=localStorage.getItem(`flashcards_${s}_cards`);return G?JSON.parse(G):[]}),[b,g]=t.useState(x?.toolState?.currentIndex??0),[c,o]=t.useState(x?.toolState?.isFlipped??!1),[i,f]=t.useState(!1),[y,N]=t.useState(x?.toolState?.hasCompleted??!1),{toast:A}=we();t.useEffect(()=>{v.length>0&&(localStorage.setItem(`flashcards_${s}_cards`,JSON.stringify(v)),localStorage.setItem(`flashcards_${s}_topic`,n))},[v,n,s]),t.useEffect(()=>{h?.flashcards&&(j(h.flashcards),r(h.topic),g(0),o(!1),N(!0))},[h]);const w=async()=>
5{if(!n.trim()){A({title:"Topic Required",description:"Please enter a topic for flashcards.",variant:"destructive"});return}f(!0);try{const{data:G,error:D}=await E.functions.invoke("openai-assistant-flashcards",{body:{classroomId:s,cardCount:8,topics:[n],difficulty:"Mixed"}});if(D)throw D;G?.flashcards&&G.flashcards.length>0&&(j(G.flashcards),g(0),o(!1),A({title:"Flashcards Generated!",description:`${G.flashcards.length} cards ready to study.`}))}catch(G){console.error("Error generating flashcards:",G),A({title:"Generation Failed",description:G.message||"Could not generate flashcards.",variant:"destructive"})}finally{f(!1)}},P=()=>{b<v.length-1?(g(b+1),o(!1)):y||(N(!0),p?.({topic:n,totalCards:v.length,cardsStudied:v.length,flashcards:v,timestamp:new Date().toISOString()}))},k=async()=>{try{const G=v.map((D,Y)=>`**Card ${Y+1}**
6
7**Question:** ${D.front}
8
9**Answer:** ${D.back}
10`).join(`
11---
12
13`);await u({title:`Flashcards: ${n}`,content_type:"study_guide",content:{type:"flashcards",topic:n,subject:s,cardCount:v.length,cards:v,guide:G},tags:["flashcards",n.toLowerCase(),s],metadata:{generated_by:"AI",card_type:"standard"},user_id:"",is_favorite:!1}),await d(),A({title:"Saved!",description:"Flashcards saved to My Learning Aids"})}catch(G){console.error("Error saving flashcards:",G),A({title:"Save Failed",description:"Could not save flashcards",variant:"destructive"})}},I=()=>{b>0&&(g(b-1),o(!1))},T=()=>{j([]),r(""),g(0),o(!1),N(!1),localStorage.removeItem(`flashcards_${s}_cards`),localStorage.removeItem(`flashcards_${s}_topic`),l?.(),A({title:"Reset Complete",description:"Ready to generate new flashcards."})};if(v.length===0)return e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Flashcard Topic"}),e.jsx(_e,{value:n,onChange:G=>r(G.target.value),placeholder:"Enter topic for flashcards...",disabled:i})]}),e.jsx(_,{onClick:w,disabled:i||!n.trim(),className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"mr-2 h-4 w-4"}),"Generate Flashcards"]})})]});const M=v[b];return e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between text-sm",children:e.jsxs("span",{className:"font-medium",children:["Card ",b+1," of ",v.length]})}),e.jsx(te,{className:`min-h-[200px] p-6 flex items-center justify-center cursor-pointer transition-all duration-300 hover:scale-[1.02] border-2 ${c?"bg-white dark:bg-white":"bg-black dark:bg-black"}`,onClick:()=>o(!c),children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm mb-2 font-medium text-muted-foreground",children:c?"Back":"Front"}),e.jsx("p",{className:`text-base ${c?"text-black":"text-foreground"}`,children:c?M.back:M.front})]})}),e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>o(!c),className:"w-full",children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Flip Card"]}),e.jsxs(_,{onClick:k,className:"w-full gap-2 text-foreground",style:{backgroundColor:"hsl(270, 90%, 60%)",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) 3"},children:[e.jsx(We,{className:"h-4 w-4"}),"Save to My Learning Aids"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_,{variant:"outline",onClick:I,disabled:b===0,className:"flex-1",children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsxs(_,{onClick:P,className:"flex-1",children:[b===v.length-1?"Finish":"Next",e.jsx(Ea,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(_,{onClick:T,className:"w-full mt-2 text-foreground",style:{backgroundColor:"hsl(175, 100%, 37%)"},children:"Start New"})]})},yn=({classroomId:s,initialTopic:a,context:m,onComplete:x})=>e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Roleplay scenarios are best experienced in the full modal. Click below to launch the roleplay tool."}),e.jsxs(_,{onClick:()=>{x?.({action:"launch_full_modal",topic:a})},className:"w-full",children:[e.jsx(ft,{className:"mr-2 h-4 w-4"}),"Launch Roleplay"]})]}),jn=({classroomId:s,onComplete:a,onContentChange:m,chatMessages:x=[],initialTopic:p,persistence:l})=>{const h=l?.toolState||{},[u,d]=t.useState(h.challengeInput||p||""),[n,r]=t.useState(h.selectedType||""),[v,j]=t.useState(h.selectedTemplate||""),[b,g]=t.useState(!1),[c,o]=t.useState(!1),[i,f]=t.useState(h.locked||!1),[y,N]=t.useState(h.suggestion||null),{toast:A}=we(),{suggestions:w,getSuggestionsByType:P,getChallengeTypes:k}=kr(s),{spendAICredit:I,canUseAI:T}=wt(),{age:M}=jt(),G=ys(s),D=()=>`chad_inchat_analysis_${s}_${x.length}`,Y=["Reverse Engineering Project","Innovation Sprint","Prototype & Test","Tutorial Creation","Evidence Investigation","Expert Interview Series","Documentary Creation","Data Detective","System Mapping","Optimization Project","Experiment Design","Challenge Accepted","Product Review Analysis","Perspective Collection","Comparative Analysis"].map(B=>({id:`default:${B}`,title:B,estimated_time_minutes:60,difficulty_level:"medium"})),de=[{value:"creative-innovation",label:"Creative Innovation 🎨"},{value:"deep-dive-investigation",label:"Deep Dive Investigation 🔍"},{value:"problem-solving-quest",label:"Problem Solving Quest ⚡"},{value:"critical-analysis-mission",label:"Critical Analysis Mission 🧠"},{value:"skill-mastery-challenge",label:"Skill Mastery Challenge 🏆"},{value:"real-world-impact-project",label:"Real-World Impact Project 🌍"}],pe=(()=>{const B=k();return B.length?B:de})(),xe=w.length?w:Y,ce=n&&P(n).length?P(n):xe;t.useEffect(()=>{l&&l.tool.id&&l.updateToolState(l.tool.id,{toolState:{locked:i,suggestion:y,selectedType:n,selectedTemplate:v,challengeInput:u,analyzedAt:Date.now()}})},[i,y,n,v,u]);const oe=()=>{const B=x.slice(-10).map(C=>C.content.toLowerCase()).join(" "),F=[...x].reverse().find(C=>C.role==="user")?.content||"",Q=(...C)=>C.some(H=>B.includes(H));let S="problem-solving-quest",z="Challenge Accepted";if(Q("design","build","prototype","create","invent"))S="creative-innovation",z="Prototype & Test";else if(Q("analyze","compare","evaluate","review","critique"))S="critical-analysis-mission",z=Q("product")?"Product Review Analysis":"Comparative Analysis";else if(Q("experiment","hypothesis","test","variable"))S="skill-mastery-challenge",z="Experiment Design";else if(Q("data","survey","chart","graph","measure"))S="deep-dive-investigation",z="Data Detective";else if(Q("interview","expert","talk to"))S="deep-dive-investigation",z="Expert Interview Series";
13else if(Q("optimize","improve","efficiency","streamline"))S="problem-solving-quest",z="Optimization Project";else if(Q("map","system","flow","process"))S="critical-analysis-mission",z="System Mapping";else{const C=(G.subject||"").toLowerCase();C.includes("business")||C.includes("entrepreneur")?(S="real-world-impact-project",z="Innovation Sprint"):C.includes("science")||C.includes("biology")||C.includes("chemistry")||C.includes("physics")?(S="skill-mastery-challenge",z="Experiment Design"):(C.includes("history")||C.includes("social"))&&(S="critical-analysis-mission",z="Perspective Collection")}const V=u||p||F;return{focusTopic:V||`Key concept in ${G.subject}`,suggestedType:S,suggestedTemplate:z,reasoning:"Auto-selected using chat keyword heuristics and classroom subject as fallback.",confidence:"medium"}};t.useEffect(()=>{if(console.log("🎯 ChatGenerateChallenge mounted. Checking locked/cached state...",{messageCount:x.length,isLocked:i,hasChadSuggestion:!!y,hasPersistedSuggestion:!!h.suggestion}),i&&h.suggestion){console.log("🔒 Locked state found, hydrating from persistence"),N(h.suggestion),h.selectedType&&!n&&r(h.selectedType),h.selectedTemplate&&!v&&j(h.selectedTemplate),h.challengeInput&&!u&&d(h.challengeInput);return}const B=D(),F=sessionStorage.getItem(B);if(F)try{const Q=JSON.parse(F);if(console.log("✅ Loaded Chad suggestion from sessionStorage cache:",Q),N(Q),f(!0),Q.suggestedType&&!n){const S=pe.find(z=>z.value===Q.suggestedType);r(S?S.value:pe[0]?.value||"")}if(Q.suggestedTemplate&&!v){const S=P(Q.suggestedType).length?P(Q.suggestedType):xe,V=S.find(q=>q.title.toLowerCase()===Q.suggestedTemplate.toLowerCase())?.id||S[0]?.id;V&&j(V)}Q.focusTopic&&!u&&d(Q.focusTopic);return}catch(Q){console.warn("Failed to parse cached suggestion:",Q)}if(x.length>=3&&!y){console.log("✅ Triggering Chad analysis..."),ae();return}if(x.length<3&&!y){console.log("💡 Chat too short, computing fallback suggestion...");const Q=oe();if(N(Q),f(!0),Q.suggestedType&&!n){const S=pe.find(z=>z.value===Q.suggestedType);r(S?S.value:pe[0]?.value||"")}if(Q.suggestedTemplate&&!v){const S=P(Q.suggestedType).length?P(Q.suggestedType):xe,V=S.find(q=>q.title.toLowerCase()===Q.suggestedTemplate.toLowerCase())?.id||S[0]?.id;V&&j(V)}Q.focusTopic&&!u&&d(Q.focusTopic)}},[]),t.useEffect(()=>{y?.suggestedType&&!n&&r(y.suggestedType)},[y]),t.useEffect(()=>{if(n&&!pe.some(B=>B.value===n)){const B=pe[0]?.value||"";B&&r(B)}},[pe,n]),t.useEffect(()=>{y?.focusTopic&&!u&&d(y.focusTopic)},[y]),t.useEffect(()=>{if(y?.suggestedTemplate&&!v&&ce.length>0){const B=ce.find(F=>F.title.toLowerCase()===y.suggestedTemplate.toLowerCase());j(B?B.id:ce[0].id)}},[y,ce,v,n]),t.useEffect(()=>{!v&&ce.length>0&&j(ce[0].id)},[n,ce,v]);const ae=async()=>{console.log("🤖 Chad analyzing chat context...",{messageCount:x.length,subject:G.subject}),o(!0);try{const{data:B,error:F}=await E.functions.invoke("chad-challenge-analyzer",{body:{chatMessages:x.slice(-15),classroomSubject:G.subject}});if(console.log("📊 Chad API response:",{data:B,error:F}),!F&&B&&B.confidence==="high"&&B.focusTopic){console.log("✅ High confidence suggestion from Chad:",B);const z={focusTopic:B.focusTopic,suggestedType:B.suggestedType,suggestedTemplate:B.suggestedTemplate,reasoning:B.reasoning};N(z),f(!0);const V=D();sessionStorage.setItem(V,JSON.stringify(z)),console.log("💾 Saved suggestion to cache and locked:",V);return}console.log("💡 Low confidence or no data, using fallback...");const Q=oe();console.log("💡 Fallback suggestion:",Q),N(Q),f(!0);const S=D();sessionStorage.setItem(S,JSON.stringify(Q)),console.log("💾 Saved fallback suggestion to cache and locked:",S)}catch(B){console.error("❌ Chad analysis error:",B);const F=oe();console.log("💡 Fallback suggestion after error:",F),N(F),f(!0);const Q=D();sessionStorage.setItem(Q,JSON.stringify(F)),console.log("💾 Saved error fallback suggestion to cache and locked:",Q)}finally{o(!1)}},K=()=>{if(!window.confirm("Re-analyze the chat context? This will replace the current suggestion."))return;f(!1),N(null);const B=D();if(sessionStorage.removeItem(B),console.log("🔓 Unlocked and cleared cache, re-analyzing..."),x.length>=3)ae();else{const F=oe();N(F),f(!0)}},O=async()=>
13{if(!u.trim()||!n||!v){A({title:"Missing Information",description:"Please provide a focus topic, challenge type, and template.",variant:"destructive"});return}if(!T){A({title:"No Credits Available",description:"You need credits to use AI features.",variant:"destructive"});return}g(!0);try{if(!await I("Challenge Generator","Generating challenge with Chad")){g(!1);return}const Q=w.find(C=>C.id===v)?.title||(v.startsWith("default:")?v.replace("default:",""):""),S=M?M<=13?"11-13":M<=16?"14-16":"17-18":"14-16",{data:z,error:V}=await E.functions.invoke("chad-challenge-analyzer",{body:{chatMessages:x.slice(-15),classroomSubject:G.subject,focusTopic:u,challengeType:n,templateName:Q,studentAge:S,generateFullChallenge:!0}});if(V)throw V;const q=z.fullChallenge||z.focusTopic;W(q)}catch(B){console.error("Error generating challenge:",B),A({title:"Error",description:"Failed to generate challenge. Please try again.",variant:"destructive"})}finally{g(!1)}},W=B=>{const Q=`I'm ready to start this challenge! Let's do this:
14
15${B}
16
17[APP_ACTION:CHALLENGE_GENERATED:{"mode":"support","source":"chad_generator"}]`;a?.({success:!0,message:Q}),A({title:"Challenge Sent!",description:"Your challenge is ready! Your tutor will guide you through it."})};return e.jsx(te,{className:"border-border/40",children:e.jsxs(ie,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Generate Challenge with Chad"}),i&&e.jsx(me,{variant:"secondary",className:"text-xs",children:"🔒 Locked"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[M&&e.jsxs(me,{variant:"outline",className:"text-xs",children:["Age ",M]}),i&&!c&&e.jsxs(_,{variant:"ghost",size:"sm",onClick:K,className:"text-xs h-7",children:[e.jsx($t,{className:"h-3 w-3 mr-1"}),"Re-analyze"]})]})]}),e.jsx(Nt,{isVisible:c,title:"Chad analyzing chat context...",description:"Reading recent messages to suggest the perfect challenge",showTimerWarning:!0}),y&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-primary/10 rounded-lg text-sm",children:[e.jsx(it,{className:"h-4 w-4 text-primary mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Chad's suggestion:"}),e.jsx("p",{className:"text-muted-foreground",children:y.focusTopic}),y.suggestedTemplate&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Recommended template: ",e.jsx("span",{className:"font-medium",children:y.suggestedTemplate})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"Challenge Focus"}),e.jsx(_e,{value:u,onChange:B=>d(B.target.value),placeholder:"What should the challenge focus on?",className:"bg-background/50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"Challenge Type"}),e.jsxs(De,{value:n,onValueChange:r,children:[e.jsx(Le,{className:"bg-background/50",children:e.jsx($e,{placeholder:"Select a challenge type..."})}),e.jsx(Me,{children:pe.map(B=>e.jsx(Z,{value:B.value,children:B.label},B.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"Template"}),e.jsxs(De,{value:v,onValueChange:j,children:[e.jsx(Le,{className:"bg-background/50",children:e.jsx($e,{placeholder:"Select a template..."})}),e.jsx(Me,{children:ce.map(B=>e.jsx(Z,{value:B.id,children:B.title},B.id))})]})]}),e.jsx(_,{onClick:O,disabled:b||!u.trim()||!n||!v||!T,className:"w-full",children:b?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Generate & Send Challenge"]})})]})]})})},bn=({classroomId:s,initialTopic:a,context:m,onComplete:x})=>{const[p,l]=t.useState(a||""),[h,u]=t.useState(null),[d,n]=t.useState(!1),{toast:r}=we(),v=async()=>{if(!p.trim()){r({title:"Missing prompt",description:"Please describe the image you want to generate",variant:"destructive"});return}n(!0);try{const{data:b,error:g}=await E.functions.invoke("generate-image",{body:{prompt:p,classroomId:s,context:m}});if(g)throw g;u(b.imageUrl),x?.({action:"image_generated",prompt:p,imageUrl:b.imageUrl}),r({title:"Image generated!",description:"Your visual content is ready"})}catch(b){console.error("Error generating image:",b),r({title:"Generation failed",description:b.message||"Failed to generate image",variant:"destructive"})}finally{n(!1)}},j=()=>
17{if(!h)return;const b=document.createElement("a");b.href=h,b.download=`generated-image-${Date.now()}.png`,b.click()};return e.jsx("div",{className:"p-4 space-y-3",children:h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:h,alt:p,className:"w-full h-auto"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{onClick:j,variant:"outline",className:"flex-1",children:[e.jsx(ms,{className:"mr-2 h-4 w-4"}),"Download"]}),e.jsx(_,{onClick:()=>{u(null),l("")},variant:"outline",className:"flex-1",children:"Generate Another"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{value:p,onChange:b=>l(b.target.value),placeholder:"Describe the image you want (e.g., 'diagram of photosynthesis process')",disabled:d}),e.jsx(_,{onClick:v,disabled:d||!p.trim(),className:"w-full",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ut,{className:"mr-2 h-4 w-4"}),"Generate Image"]})})]})})},wn=({classroomId:s,initialTopic:a,context:m,onComplete:x,onTopicChange:p,persistence:l})=>{const[h,u]=t.useState(l?.toolState?.topic||a||""),[d,n]=t.useState(l?.toolState?.tableData||null),[r,v]=t.useState(!1),[j,b]=t.useState(!1),[g,c]=t.useState(l?.toolState?.tableType||""),{toast:o}=we(),{saveAid:i,refetch:f}=ct(),{user:y}=Ge();lt.useEffect(()=>{d&&l?.updateToolState&&(l.updateToolState(l.tool.id,{toolState:{topic:h,tableData:d,tableType:g}}),console.log("💾 Table state persisted"))},[d,h,g]);const N=k=>({checklist:{headers:["Task","Status","Priority","Due Date","Notes"],promptInstructions:"Create a checklist table for tracking tasks and homework."},schedule:{headers:["Time/Date","Activity","Duration","Notes"],promptInstructions:"Create a schedule/timeline table."},comparison:{headers:["Item","Feature 1","Feature 2","Pros","Cons"],promptInstructions:"Create a comparison table."},summary:{headers:["Topic","Key Points","Details","Impact"],promptInstructions:"Create a summary table."}})[k]||{headers:["Column 1","Column 2","Column 3"],promptInstructions:"Create a structured data table."},A=async()=>{if(!h.trim()){o({title:"Missing topic",description:"Please describe what table you want to create",variant:"destructive"});return}v(!0);try{const k=N(g||"summary"),{data:I,error:T}=await E.functions.invoke("generate-table",{body:{tableType:g||"summary",topic:h,additionalRequirements:m||"",template:k,classroomId:s,context:m}});n(I.table),x?.({action:"table_generated",topic:h,rowCount:I.table.rows.length}),typeof p=="function"&&p(h),o({title:"Table created!",description:"Your structured data is ready"})}catch(k){console.error("Error generating table:",k),o({title:"Generation failed",description:k.message||"Failed to generate table",variant:"destructive"})}finally{v(!1)}},w=()=>{if(d)try{const k=new Or({orientation:"p",unit:"pt"});k.setFontSize(14),k.text(`Table: ${h||"Generated Table"}`,40,40),Ur(k,{startY:60,head:[d.headers],body:d.rows,styles:{fontSize:10}});const I=(h||"table").replace(/[^a-z0-9\-]+/gi,"_").slice(0,50);k.save(`table_${I}.pdf`),o({title:"Downloaded",description:"PDF downloaded successfully"})}catch(k){console.error("PDF download failed:",k),o({title:"PDF failed",description:"Could not generate PDF",variant:"destructive"})}},P=async()=>{if(!y){o({title:"Authentication Required",description:"Please log in to save to Learning Aids.",variant:"destructive"});return}if(!d){o({title:"No Content",description:"There is no table to save.",variant:"destructive"});return}b(!0);try{const k=`| ${d.headers.join(" | ")} |`,I=`| ${d.headers.map(()=>"---").join(" | ")} |`,T=d.rows.map(G=>`| ${G.join(" | ")} |`).join(`
18`),M=`${k}
19${I}
20${T}`;await i({user_id:y.id,title:`Table: ${h}`,content_type:"generate_table",content:{markdown:M,table:d,generatedAt:new Date().toISOString()},metadata:{classroomId:s,topic:h,headers:d.headers,rowCount:d.rows.length},tags:[h,"table",s],is_favorite:!1}),await f(),o({title:"Saved!",description:"Table saved to My Learning Aids"})}catch(k){console.error("Error saving to learning aids:",k),o({title:"Save Failed",description:"Could not save table",variant:"destructive"})}finally{b(!1)}};return e.jsx("div",{className:"p-4 space-y-3",children:d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto border rounded-lg",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted",children:e.jsx("tr",{children:d.headers.map((k,I)=>e.jsx("th",{className:"px-3 py-2 text-left font-medium",children:k},I))})}),e.jsx("tbody",{children:d.rows.map((k,I)=>e.jsx("tr",{className:"border-t",children:k.map((T,M)=>e.jsx("td",{className:"px-3 py-2",children:T},M))},I))})]})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(_,{onClick:P,variant:"outline",disabled:j,className:"w-full",children:j?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),"Save to My Learning Aids"]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{onClick:w,variant:"outline",className:"flex-1",children:[e.jsx(ms,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsx(_,{onClick:()=>{n(null),u("")},variant:"outline",className:"flex-1",children:"Generate Another"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{value:h,onChange:k=>u(k.target.value),placeholder:"What table do you need? (e.g., 'Compare mammals vs reptiles')",disabled:r}),e.jsx(_,{onClick:A,disabled:r||!h.trim(),className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"mr-2 h-4 w-4"}),"Generate Table"]})})]})})},Nn=({classroomId:s,initialTopic:a,context:m,onComplete:x})=>{const[p,l]=t.useState(a||""),[h,u]=t.useState([]),[d,n]=t.useState(null),[r,v]=t.useState(!1),[j,b]=t.useState(!1),[g,c]=t.useState(null),{toast:o}=we(),{age:i}=jt();rr();const f=async()=>
20{if(!p.trim()){o({title:"Missing search query",description:"Please describe what video you're looking for",variant:"destructive"});return}if(g&&Date.now()<g){o({title:"YouTube temporarily unavailable",description:"Quota exceeded. Please try again in a few minutes.",variant:"destructive"});return}v(!0);try{const N=`yt:chat:${p.toLowerCase().trim()}|${s}|${i||"unknown"}`,A=await nr.request(N,async()=>{const{data:w,error:P}=await E.functions.invoke("search-youtube-video",{body:{query:p,classroomId:s,context:m,studentAge:i}});if(P){const k=P.message||"Failed to search YouTube";throw k.includes("quota")||k.includes("403")||P.status===429?(c(Date.now()+10*60*1e3),new Error("YouTube API quota exceeded. Please try again later.")):P}return w},{query:p,classroomId:s,age:i},5*60*1e3,!0);A?.videos&&A.videos.length>0?(u(A.videos),o({title:"Videos found!",description:`Found ${A.videos.length} educational videos`})):o({title:"No videos found",description:"Try a different search query",variant:"destructive"})}catch(N){console.error("Error searching video:",N),o({title:"Search failed",description:N.message||"Failed to find video",variant:"destructive"})}finally{v(!1)}};t.useEffect(()=>{a&&!j&&(b(!0),f())},[a,j]);const y=N=>{const A=N.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&\s]+)/);return A?A[1]:""};return e.jsx("div",{className:"p-4 space-y-3",children:d?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"relative aspect-video rounded-lg overflow-hidden bg-black",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${y(d.url)}?autoplay=1`,title:d.title,allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium line-clamp-2",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.channelTitle})]}),e.jsx(_,{onClick:()=>{n(null),x?.({action:"video_completed",query:p,videoTitle:d.title,videoUrl:d.url})},variant:"outline",className:"w-full",children:"Back to Results"})]}):h.length===0?e.jsxs(e.Fragment,{children:[e.jsx(_e,{value:p,onChange:N=>l(N.target.value),placeholder:"What topic do you want to learn about? (e.g., 'photosynthesis explained')",disabled:r,onKeyDown:N=>N.key==="Enter"&&f()}),e.jsx(_,{onClick:f,disabled:r||!p.trim()||g&&Date.now()<g,className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Searching..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Find Videos"]})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Found ",h.length," educational video",h.length!==1?"s":""]}),e.jsx(_,{onClick:()=>{u([]),l("")},variant:"ghost",size:"sm",children:"New Search"})]}),e.jsx("div",{className:"max-h-[500px] overflow-y-auto space-y-3 pr-2",children:h.map((N,A)=>e.jsx("div",{className:"border rounded-lg p-3 hover:bg-accent/5 transition-colors cursor-pointer",onClick:()=>n(N),children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative w-40 h-24 flex-shrink-0 rounded overflow-hidden group",children:[e.jsx("img",{src:N.thumbnail,alt:N.title,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(gs,{className:"w-12 h-12 text-foreground",fill:"white"})})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm line-clamp-2 mb-1",children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:N.channelTitle}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:N.description})]})]})},A))})]})})},Xt=[{id:"spaced-repetition",name:"Spaced Repetition",description:"Review material at increasing intervals to strengthen long-term memory",tips:["Study today, review in 1 day, 3 days, then 7 days","Use flashcards for optimal spacing","Don't cram - spread it out!"]},{id:"active-recall",name:"Active Recall",description:"Test yourself frequently instead of just re-reading notes",tips:["Close your notes and write what you remember","Explain concepts out loud","Create practice questions"]},{id:"interleaving",name:"Interleaving",description:"Mix different topics or types of problems in one study session",tips:["Don't do 20 of the same problem type","Switch between subjects","Combine related but different c
20oncepts"]},{id:"elaboration",name:"Elaboration",description:"Connect new information to what you already know",tips:['Ask "why" and "how" questions',"Create analogies and examples","Relate concepts to personal experiences"]},{id:"dual-coding",name:"Dual Coding",description:"Combine words and visuals to learn more effectively",tips:["Draw diagrams while studying","Create concept maps","Use images to represent ideas"]}],Cn=({classroomId:s,initialTopic:a,context:m,onComplete:x})=>{const[p,l]=t.useState(null),h=d=>{l(d);const n=Xt.find(r=>r.id===d);x?.({action:"principle_applied",principle:n?.name,context:"User wants to apply this learning strategy to their current topic"})},u=Xt.find(d=>d.id===p);return e.jsx("div",{className:"p-4 space-y-3",children:p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 text-green-600 mb-2",children:[e.jsx(Mt,{className:"h-5 w-5"}),e.jsxs("span",{className:"font-medium",children:["Principle Applied: ",u?.name]})]}),e.jsxs(te,{className:"p-3 bg-muted/50",children:[e.jsx("h4",{className:"font-medium text-sm mb-2",children:"How to use this principle:"}),e.jsx("ul",{className:"space-y-1",children:u?.tips.map((d,n)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex gap-2",children:[e.jsx("span",{children:"•"}),e.jsx("span",{children:d})]},n))})]}),e.jsx(_,{onClick:()=>l(null),variant:"outline",className:"w-full",children:"Choose Different Principle"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Choose a learning principle to apply to your current study session:"}),e.jsx("div",{className:"space-y-2",children:Xt.map(d=>e.jsx(te,{className:"p-3 cursor-pointer hover:bg-accent transition-colors",onClick:()=>h(d.id),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(nt,{className:"h-5 w-5 text-primary mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm",children:d.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:d.description})]})]})},d.id))})]})})},Sn=({classroomId:s,initialTopic:a,context:m,onComplete:x})=>{const[p,l]=t.useState(""),[h,u]=t.useState(null),[d,n]=t.useState(!1),{toast:r}=we(),v=async()=>{if(!p.trim()){r({title:"Missing question",description:"Please describe what you need help with",variant:"destructive"});return}n(!0);try{const{data:j,error:b}=await E.functions.invoke("homework-helper",{body:{question:p,classroomId:s,context:m}});if(b)throw b;u(j.guidance),x?.({action:"homework_help_provided",question:p.substring(0,100)}),r({title:"Help provided!",description:"Remember: understanding the process is more important than the answer"})}catch(j){console.error("Error getting homework help:",j),r({title:"Help failed",description:j.message||"Failed to get homework help",variant:"destructive"})}finally{n(!1)}};return e.jsx("div",{className:"p-4 space-y-3",children:h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx(st,{content:h})}),e.jsx(_,{onClick:()=>{u(null),l("")},variant:"outline",className:"w-full",children:"Ask Another Question"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-blue-500/10 border border-blue-500/20 rounded-lg mb-2",children:[e.jsx(it,{className:"h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"I'll guide you through the problem step-by-step without giving you the direct answer. Learning how to solve it is more valuable than just getting the answer!"})]}),e.jsx(rt,{value:p,onChange:j=>l(j.target.value),placeholder:"Describe your homework problem or what you're stuck on...",rows:4,disabled:d}),e.jsx(_,{onClick:v,disabled:d||!p.trim(),className:"w-full",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Getting Help..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"mr-2 h-4 w-4"}),"Get Guidance"]})})]})})},St=[{id:"learning-style",question:"How do you prefer to learn new things?",options:[{value:"visual",label:"Watching videos or looking at diagrams"},{value:"auditory",label:"Listening to explanations or discussions"},{value:"kinesthetic",label:"Doing hands-on activities and practice"},{value:"reading",label:"Reading text and taking notes"}]},{id:"pace",question:"What learning pace works best for you?",options:[{value:"fast",label:"Quick overviews, I grasp concepts rapidly"},{value:"moderate",label:"Balanced pace with examples"},{value:"detailed",label:"Slow and thorough with lots of detail"}]},{id:"structure",question:"Do you prefer structured or flexible learning?",options:[{value:"structured",label:"Step-by-step, organized progression"},{value:"flexible",label:"Explore topics freely as curiosity leads"},{value:"mixed",label:"Combination of both approaches"}]}],_n=({classroomId:s,initialTopic:a,context:m,onComplete:x})=>{const[p,l]=t.useState(0),[h,u]=t.useState({}),[d,n]=t.useState(!1),r=j=>{const b={...h,[St[p].id]:j};u(b),p<St.length-1?l(p+1):d||(n(!0),x?.({action:"learning_profile_completed",preferences:b}))};if(d)return e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-green-600 mb-2",children:[e.jsx(Mt,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:"Profile Complete!"})]}),e.jsxs(te,{className:"p-3 bg-muted/50",children:[e.jsx("h4",{className:"font-medium text-sm mb-2",children:"Your Learning Preferences:"}),e.jsxs("ul",{className:"space-y-1 text-sm text-muted-foreground",children:[e.jsxs("li",{children:["• Style: ",h["learning-style"]]}),e.jsxs("li",{children:["• Pace: ",h.pace]}),e.jsxs("li",{children:["• Structure: ",h.structure]})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"I'll use these preferences to personalize your learning experience!"})]});const v=St[p];return e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Aa,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:["Question ",p+1," of ",St.length]})]}),e.jsx("h4",{className:"font-medium",children:v.question}),e.jsx(bt,{onValueChange:r,className:"space-y-2",children:v.options.map(j=>e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx(et,{value:j.value,id:j.value}),e.jsx(Te,{htmlFor:j.value,className:"cursor-pointer text-sm leading-relaxed",children:j.label})]},j.value))})]})},kn=({classroomId:s,initialTopic:a,context:m,onComplete:x})=>{const[p,l]=t.useState("feedback"),[h,u]=t.useState(""),[d,n]=t.useState(!1),[r,v]=t.useState(!1),{toast:j}=we(),b=async()=>
20{if(!h.trim()){j({title:"Missing message",description:"Please write your suggestion or feedback",variant:"destructive"});return}n(!0);try{const{error:g}=await E.from("user_feedback").insert({category:p,message:h.trim(),classroom_id:s,context:m});if(g)throw g;v(!0),x?.({action:"suggestion_submitted",category:p}),j({title:"Feedback sent!",description:"Thank you for helping us improve"})}catch(g){console.error("Error submitting feedback:",g),j({title:"Submission failed",description:g.message||"Failed to send feedback",variant:"destructive"})}finally{n(!1)}};return r?e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-green-600",children:[e.jsx(Mt,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:"Feedback Received!"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Your ",p," has been sent to our development team. We appreciate your input!"]})]}):e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs(De,{value:p,onValueChange:l,children:[e.jsx(Le,{children:e.jsx($e,{placeholder:"Select category"})}),e.jsxs(Me,{children:[e.jsx(Z,{value:"bug",children:"🐛 Bug Report"}),e.jsx(Z,{value:"feature",children:"💡 Feature Request"}),e.jsx(Z,{value:"feedback",children:"💬 General Feedback"}),e.jsx(Z,{value:"question",children:"❓ Question"})]})]}),e.jsx(rt,{value:h,onChange:g=>u(g.target.value),placeholder:"Tell us what's on your mind...",rows:4,disabled:d}),e.jsx(_,{onClick:b,disabled:d||!h.trim(),className:"w-full",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Send Feedback"]})})]})},Tn=({suggestion:s,classroomId:a,messages:m,persistence:x,onComplete:p,onContentChange:l})=>{`tool-${s.toolId}-${s.topic}`.replace(/\s+/g,"-");const h=x.persistedTools.find(w=>w.tool.toolId===s.toolId&&w.tool.topic===s.topic),[u,d]=t.useState(h?.isExpanded??!0),[n,r]=t.useState(h?.isCompleted??!1),[v,j]=t.useState(h?.completionData??null),[b,g]=t.useState(h?.overrideToolId??s.toolId),c=t.useRef(null),{awardTokensForTool:o}=pn();t.useEffect(()=>{if(h){const w={isExpanded:u,isCompleted:n,completionData:v,overrideToolId:b};x.updateToolState(h.tool.id,w)}},[u,n,v,b]),t.useEffect(()=>{u&&c.current&&setTimeout(()=>{c.current?.scrollIntoView({behavior:"smooth",block:"center"})},100)},[u]);const f=[...Rr,...Gr].find(w=>w.id===b);if(!f)return console.warn("Unknown tool suggested:",s.toolId),null;const y=async w=>{console.log("Tool completed:",w);const P=await o(s.toolId,a,w);j({...w,tokensAwarded:P?.tokensAwarded||0}),r(!0),P&&document.querySelectorAll(".token-count").forEach(k=>{k.classList.add("token-pulse"),setTimeout(()=>k.classList.remove("token-pulse"),2e4)}),p?.(w),l?.()},N=u,A=()=>{const w={classroomId:a,initialTopic:s.topic,context:s.context,chatMessages:m,persistence:h?{...h,updateToolState:x.updateToolState}:void 0,onComplete:y,onContentChange:l,onClearTool:h?()=>x.clearTool(h.tool.id):void 0,onTopicChange:P=>j(k=>({...k||{},topic:P}))};switch(b){case"study-guide":return e.jsx(xn,{...w});case"interactive-quiz":return e.jsx(fn,{...w});case"flashcards":return e.jsx(vn,{...w,completedData:v});case"roleplay":return e.jsx(yn,{...w});case"generate-challenge":return e.jsx(jn,{...w});case"generate-image":return e.jsx(bn,{...w});case"generate-table":return e.jsx(wn,{...w});case"scrape-youtube":return e.jsx(Nn,{...w});case"principle-injection":return e.jsx(Cn,{...w});case"homework-help":return e.jsx(Sn,{...w});case"learning-profile":return e.jsx(_n,{...w});case"suggestion-box":return e.jsx(kn,{...w});case"mini-game":{const P=s.context||"verified-solo",k=or(P);return k?e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl",children:k.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:k.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:k.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-2",children:[e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-2 py-1 rounded",children:k.difficulty}),e.jsxs("span",{className:"text-xs bg-primary/10 text-primary px-2 py-1 rounded",children:["~",k.estimatedMinutes," min"]}),e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-2 py-1 rounded",children:k.playerCount})]})]})]}),e.jsx(_,{onClick:()=>{const I={gameId:P,toolId:"mini-game",context:{gameId:P}};window.dispatchEvent(new CustomEvent("launch-mini-game",{detail:I})),window.dispatchEvent(new CustomEvent("launch-learning-tool",{detail:I}))},className:"w-full",children:"🎮 Play Now"})]}):e.jsxs("div",{className:"text-sm text-muted-foreground p-4",children:["Game not found: ",P]})}default:return e.jsx("div",{className:"text-sm text-muted-foreground p-4",children:"This tool is not yet available in chat. Please use the Learning Tools panel."})}};return e.jsxs(te,{ref:c,className:"mt-2 border-2 overflow-hidden transition-all",style:{borderColor:f.color},children:[e.jsxs("div",{className:"p-3 flex items-center justify-between cursor-pointer hover:bg-accent/5",style:{backgroundColor:`${f.color}15`},onClick:()=>{d(!u)},children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:"text-2xl",children:f.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-semibold text-sm",style:{color:f.color},children:f.name}),(s.toolId==="interactive-quiz"||s.toolId==="study-guide")&&!n&&e.jsxs("select",{value:b,onChange:w=>{g(w.target.value),d(!0)},onClick:w=>w.stopPropagation(),className:"text-xs px-2 py-0.5 rounded border bg-background/50",children:[e.jsx("option",{value:"study-guide",children:"📚 Study Guide"}),e.jsx("option",{value:"interactive-quiz",children:"❓ Quiz"})]}),n?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs bg-green-500/20 text-green-600 px-2 py-0.5 rounded",children:"Completed ✓"}),v?.tokensAwarded&&e.jsxs("span",{className:"text-xs bg-amber-500/20 text-amber-600 px-2 py-0.5 rounded",children:["+",v.tokensAwarded," tokens"]})]}):null]}
20),s.topic&&e.jsxs("p",{className:"text-xs font-medium mt-1 opacity-70",children:["Topic: ",v?.topic||s.topic]})]})]}),e.jsx(_,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:w=>{w.stopPropagation(),d(!u)},children:u?e.jsx(Ws,{className:"h-4 w-4"}):e.jsx(zt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:`border-t ${N?"":"hidden"}`,style:{borderColor:`${f.color}30`},children:A()})]})},En=({permissionState:s,availableMicrophones:a,selectedMicId:m,onMicrophoneChange:x,onTestMicrophone:p,onRequestPermission:l})=>{const h=()=>{switch(s){case"granted":return e.jsx(Mt,{className:"w-4 h-4 text-green-600"});case"denied":return e.jsx(Ks,{className:"w-4 h-4 text-red-600"});case"prompt":return e.jsx(as,{className:"w-4 h-4 text-yellow-600"});default:return e.jsx(as,{className:"w-4 h-4 text-muted-foreground"})}},u=()=>{switch(s){case"granted":return"Microphone access granted";case"denied":return"Microphone access denied";case"prompt":return"Microphone permission needed";default:return"Checking microphone..."}};return e.jsxs(ta,{children:[e.jsx(sa,{asChild:!0,children:e.jsxs(_,{variant:"ghost",size:"icon",className:"relative",title:"Microphone settings",children:[e.jsx(Ys,{className:"w-4 h-4"}),s==="denied"&&e.jsx("span",{className:"absolute top-1 right-1 w-2 h-2 bg-red-600 rounded-full"})]})}),e.jsx(aa,{className:"w-80",align:"end",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Microphone Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure your microphone for voice input"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted rounded-md",children:[h(),e.jsx("span",{className:"text-sm",children:u()})]}),s==="granted"&&a.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Te,{htmlFor:"microphone-select",children:"Select Microphone"}),e.jsxs(De,{value:m,onValueChange:x,children:[e.jsx(Le,{id:"microphone-select",children:e.jsx($e,{placeholder:"Choose microphone"})}),e.jsx(Me,{children:a.map(d=>e.jsx(Z,{value:d.deviceId,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"w-3 h-3"}),d.label||`Microphone ${d.deviceId.slice(0,8)}`]})},d.deviceId))})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[s==="granted"&&e.jsxs(_,{variant:"outline",size:"sm",onClick:p,className:"w-full",children:[e.jsx(Pa,{className:"w-4 h-4 mr-2"}),"Test Microphone"]}),(s==="prompt"||s==="unknown")&&e.jsxs(_,{size:"sm",onClick:l,className:"w-full",children:[e.jsx(ss,{className:"w-4 h-4 mr-2"}),"Request Permission"]}),s==="denied"&&e.jsx("div",{className:"text-sm text-muted-foreground p-2 bg-muted rounded-md",children:"Please enable microphone access in your browser settings to use this feature."})]})]})})]})},An=({open:s,onOpenChange:a})=>{const[m,x]=t.useState({name:"Unknown",isChrome:!1,isSafari:!1,isFirefox:!1,isIOS:!1,isAndroid:!1,isMobile:!1});return t.useEffect(()=>{const p=navigator.userAgent,l=/iPad|iPhone|iPod/.test(p),h=/Android/.test(p),u=/iPhone|iPad|iPod|Android/i.test(p),d=/Chrome/.test(p)&&!/Edge|Edg/.test(p),n=/Safari/.test(p)&&!d&&!/Edge|Edg/.test(p),r=/Firefox/.test(p);let v="Your Browser";d&&(v="Chrome"),n&&(v="Safari"),r&&(v="Firefox"),x({name:v,isChrome:d,isSafari:n,isFirefox:r,isIOS:l,isAndroid:h,isMobile:u})},[]),e.jsx(qe,{open:s,onOpenChange:a,children:e.jsxs(Oe,{className:"sm:max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Be,{children:[e.jsxs(Ve,{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-5 h-5 text-destructive"}),"How to Enable Microphone Access"]}),e.jsxs(ra,{children:["Follow these steps to enable microphone access in ",m.name]})]}),e.jsxs(qt,{defaultValue:m.isMobile?"mobile":"desktop",className:"mt-4",children:[e.jsxs(Ot,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ye,{value:"desktop",children:[e.jsx(gt,{className:"w-4 h-4 mr-2"}),"Desktop"]}),e.jsxs(Ye,{value:"mobile",children:[e.jsx(Ia,{className:"w-4 h-4 mr-2"}),"Mobile"]})]}
20),e.jsxs(Ke,{value:"desktop",className:"space-y-4 mt-4",children:[(m.isChrome||m.name==="Your Browser")&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"w-5 h-5"}),e.jsx("h4",{className:"font-medium",children:"Chrome / Edge"})]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{children:["Click the ",e.jsx("strong",{children:"lock icon"})," or ",e.jsx("strong",{children:"site settings icon"})," in the address bar"]}),e.jsxs("li",{children:["Look for ",e.jsx("strong",{children:'"Microphone"'})," in the permissions list"]}),e.jsxs("li",{children:['Change the setting from "Block" to ',e.jsx("strong",{children:'"Allow"'})]}),e.jsx("li",{children:"Refresh this page"})]})]}),(m.isSafari||m.name==="Your Browser")&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Safari"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{children:["Go to ",e.jsx("strong",{children:"Safari"})," → ",e.jsx("strong",{children:"Settings"})," → ",e.jsx("strong",{children:"Websites"})]}),e.jsxs("li",{children:["Click ",e.jsx("strong",{children:'"Microphone"'})," in the left sidebar"]}),e.jsx("li",{children:"Find this website in the list"}),e.jsxs("li",{children:["Change the setting to ",e.jsx("strong",{children:'"Allow"'})]}),e.jsx("li",{children:"Refresh this page"})]})]}),(m.isFirefox||m.name==="Your Browser")&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Firefox"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{children:["Click the ",e.jsx("strong",{children:"shield or lock icon"})," in the address bar"]}),e.jsxs("li",{children:["Click the arrow next to ",e.jsx("strong",{children:'"Connection Secure"'})]}),e.jsxs("li",{children:["Click ",e.jsx("strong",{children:'"More Information"'})]}),e.jsxs("li",{children:["Go to the ",e.jsx("strong",{children:'"Permissions"'})," tab"]}),e.jsxs("li",{children:["Find ",e.jsx("strong",{children:'"Use the Microphone"'}),' and uncheck "Use Default"']}),e.jsxs("li",{children:["Select ",e.jsx("strong",{children:'"Allow"'})]}),e.jsx("li",{children:"Refresh this page"})]})]})]}),e.jsxs(Ke,{value:"mobile",className:"space-y-4 mt-4",children:[(m.isIOS||m.name==="Your Browser")&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"iPhone / iPad (Safari)"}),e.jsxs("div",{className:"bg-muted p-3 rounded-md space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"System Settings:"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{children:["Open ",e.jsx("strong",{children:"Settings"})," app on your device"]}),e.jsxs("li",{children:["Scroll down and tap ",e.jsx("strong",{children:"Safari"})]}),e.jsxs("li",{children:["Tap ",e.jsx("strong",{children:"Camera"})," or ",e.jsx("strong",{children:"Microphone"})]}),e.jsxs("li",{children:["Make sure it's set to ",e.jsx("strong",{children:'"Ask"'})," or ",e.jsx("strong",{children:'"Allow"'})]}),e.jsx("li",{children:"Return to Safari and refresh this page"})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground bg-yellow-50 dark:bg-yellow-950 p-3 rounded-md",children:[e.jsx("strong",{children:"Note:"})," On iOS, voice input only works in Safari. Chrome and other browsers on iOS use Safari's engine and have the same requirements."]})]}),(m.isAndroid||m.name==="Your Browser")&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Android (Chrome)"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{children:["Tap the ",e.jsx("strong",{children:"lock icon"})," in the address bar"]}),e.jsxs("li",{children:["Tap ",e.jsx("strong",{children:'"Permissions"'})]}),e.jsxs("li",{children:["Find ",e.jsx("strong",{children:'"Microphone"'})," and tap it"]}),e.jsxs("li",{children:["Select ",e.jsx("strong",{children:'"Allow"'})]}),e.jsx("li",{children:"Refresh this page"})]}),e.jsxs("div",{className:"bg-muted p-3 rounded-md mt-3",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Alternative (System Settings):"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm text-muted-foreground",children:[e.jsxs("li",{children:["Open ",e.jsx("strong",{children:"Settings"})," → ",e.jsx("strong",{children:"Apps"})]}),e.jsxs("li",{children:["Find and tap ",e.jsx("strong",{children:"Chrome"})]}),e.jsxs("li",{children:["Tap ",e.jsx("strong",{children:"Permissions"})]}),e.jsxs("li",{children:["Tap ",e.jsx("strong",{children:"Microphone"})]}),e.jsxs("li",{children:["Select ",e.jsx("strong",{children:'"Allow"'})]})]})]})]})]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsx(_,{onClick:()=>a(!1),children:"Got It"})})]})})},Pn=s=>{const a=`in-chat-tools-${s}`,[m,x]=t.useState([]);t.useEffect(()=>{const r=localStorage.getItem(a);if(r)try{const j=JSON.parse(r).filter(b=>{const g=Date.now()-b.timestamp,c=7*24*60*60*1e3;return g<c});x(j),console.log("📖 Loaded persisted in-chat tools:",j.length)}catch(v){console.error("Error parsing persisted tools:",v),localStorage.removeItem(a)}},[a]);const p=t.useCallback(r=>{try{localStorage.setItem(a,JSON.stringify(r)),x(r),console.log("💾 Saved in-chat tools:",r.length)}catch(v){console.error("Error saving tools:",v)}},[a]),l=t.useCallback((r,v)=>{x(j=>{const b=j.map(g=>g.tool.id===r?{...g,...v,timestamp:Date.now()}:g);return localStorage.setItem(a,JSON.stringify(b)),console.log("🔄 Updated tool state:",r),b})},[a]),h=t.useCallback(r=>{const v={tool:r,isExpanded:!0,isCompleted:!1,completionData:null,timestamp:Date.now()};return x(j=>{const b=[...j,v];return localStorage.setItem(a,JSON.stringify(b)),console.log("➕ Added persisted tool:",r.toolId),b}),v},[a]),u=t.useCallback(r=>{x(v=>{const j=v.filter(b=>b.tool.id!==r);return localStorage.setItem(a,JSON.stringify(j)),console.log("➖ Removed persisted tool:",r),j})},[a]),d=t.useCallback(()=>{localStorage.removeItem(a),x([]),console.log("🗑️ Cleared all in-chat tools")},[a]),n=t.useCallback(r=>{x(v=>{const j=v.map(b=>b.tool.id===r?{...b,isCompleted:!1,completionData:null,toolState:{},timestamp:Date.now()}:b);return localStorage.setItem(a,JSON.stringify(j)),console.log("🔄 Reset tool:",r),j})},[a]);return{persistedTools:m,saveTools:p,updateToolState:l,addPersistedTool:h,removePersistedTool:u,clearAllTools:d,clearTool:n}},In=s=>{const[a,m]=t.useState([]),x=Pn(s);t.useEffect(()=>{if(x.persistedTools.length>0){const d=x.persistedTools.map(n=>n.tool);m(d),console.log("🔄 Restored",d.length,"in-chat tools from persistence")}},[]);const p=t.useCallback(d=>{const n={...d,id:`tool-${Date.now()}-${Math.random().toString(36).substr(2,9)}`};return m(r=>[...r,n]),x.addPersistedTool(n),n.id},[x]),l=t.useCallback(d=>{m(n=>n.filter(r=>r.id!==d)),x.removePersistedTool(d)},[x]),h=t.useCallback(()=>{m([]),x.clearAllTools()},[x]),u=t.useCallback(d=>a.filter(n=>n.messageId===d),[a]);return{activeTools:a,addTool:p,removeTool:l,clearTools:h,getToolsForMessage:u,persistence:x}},Rs={1:{label:"Very Simple",description:"Like I'm 5 years old"},2:{label:"Simple",description:"Lots of examples, easy words"},3:{label:"Clear",description:"Straightforward explanations"},4:{label:"Conversational",description:"Friendly with some detail"},5:{label:"Standard",description:"Grade-level explanations"},6:{label:"Moderate",description:"Slightly more sophisticated"},7:{label:"Advanced",description:"College-prep level"}
20,8:{label:"Academic",description:"Advanced language"},9:{label:"Dense",description:"Detailed explanations"},10:{label:"Maximum",description:"Full complexity and nuance"}},Fn=({studentId:s,currentLevel:a,onLevelChange:m,className:x=""})=>{const[p,l]=t.useState(a),[h,u]=t.useState(!1),[d,n]=t.useState(!0),{toast:r}=we();t.useEffect(()=>{l(a)},[a]),t.useEffect(()=>{if(p===a)return;const b=setTimeout(async()=>{u(!0);try{const{error:g}=await E.from("student_profiles").update({complexity_level:p}).eq("id",s);if(g)throw g;m(p);const c=Rs[p];r({title:"Complexity Updated",description:`Tutor will now use ${c.label.toLowerCase()} language: ${c.description}`})}catch(g){console.error("Error updating complexity:",g),r({title:"Update Failed",description:"Could not save complexity preference. Please try again.",variant:"destructive"}),l(a)}finally{u(!1)}},500);return()=>clearTimeout(b)},[p,a,s,m,r]);const v=b=>{l(b[0])},j=Rs[p];return e.jsx(te,{className:`bg-gradient-to-br from-fuchsia-500/10 via-purple-500/10 to-cyan-500/10 border-purple-300/30 ${x}`,children:e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Language Complexity"}),e.jsx(ir,{children:e.jsxs(lr,{children:[e.jsx(cr,{asChild:!0,children:e.jsx(Da,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(dr,{className:"max-w-xs",children:e.jsx("p",{children:"Adjust how simple or complex the tutor's explanations are. Lower numbers use simpler language, higher numbers use more advanced vocabulary and concepts."})})]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(me,{variant:"secondary",className:"text-xs",children:["Level ",p]}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>n(!d),className:"h-8 w-8 p-0",children:d?e.jsx(Ws,{className:"h-4 w-4"}):e.jsx(zt,{className:"h-4 w-4"})})]})]}),d&&e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsx(vt,{value:[p],onValueChange:v,min:1,max:10,step:1,className:"w-full",disabled:h}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Simpler"}),e.jsx("span",{children:"More Complex"})]}),e.jsxs("div",{className:"text-center pt-2 border-t border-purple-300/20",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:j.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j.description}),h&&e.jsx("p",{className:"text-xs text-primary mt-2 animate-pulse",children:"Saving..."})]})]})]})})},Dn=s=>{const[a,m]=t.useState([]),[x,p]=t.useState(!0),{user:l}=Ge(),{toast:h}=we(),u=t.useCallback(async()=>{if(!(!l||!s)){p(!0);try{const{data:r,error:v}=await E.from("classroom_chat_history").select("*").eq("user_id",l.id).eq("classroom_id",s).order("archived_at",{ascending:!1});if(v)throw v;const j=r.map(b=>({id:b.id,session_name:b.session_name,messages:b.messages||[],message_count:b.message_count,archived_at:new Date(b.archived_at),created_at:new Date(b.created_at)}));m(j)}catch(r){console.error("Error loading chat history:",r)}finally{p(!1)}}},[l,s]),d=t.useCallback(async(r,v)=>{if(!(!l||!s||r.length===0))try{const j=v||`Chat Session ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,{error:b}=await E.from("classroom_chat_history").insert({user_id:l.id,classroom_id:s,session_name:j,messages:r,message_count:r.length});if(b)throw b;await u(),h({title:"Chat Archived",description:"Your chat session has been saved to history."})}catch(j){console.error("Error saving chat session:",j),h({title:"Error",description:"Failed to save chat session. Please try again.",variant:"destructive"})}},[l,s,u,h]),n=t.useCallback(async r=>{if(l)try{const{error:v}=await E.from("classroom_chat_history").delete().eq("id",r).eq("user_id",l.id);if(v)throw v;m(j=>j.filter(b=>b.id!==r)),h({title:"Session Deleted",description:"Chat session has been removed from history."})}catch(v){console.error("Error deleting chat session:",v),h({title:"Error",description:"Failed to delete chat session. Please try again.",variant:"destructive"})}},[l,h]);return t.useEffect(()=>{u()},[u]),{chatHistory:a,isLoading:x,saveChatSession:d,deleteChatSession:n,loadChatHistory:u}},Ln=()=>{const[s,a]=t.useState(!1),{toast:m}=we(),x="asst_Iaa6QuCwQL0ICsGHx3yHmLEn";return{generatePetResponse:async({conversationContext:l,currentTopic:h,messageType:u,studentProfile:d})=>{a(!0);try{const n=l.slice(-5).map(g=>`${g.role==="user"?"Student":"Tutor"}: ${g.content}`).join(`
21`);let r="";switch(u){case"greeting":r=`The student just added you to their chat. Welcome them warmly, mention you've shared their learning profile with the tutor, and ask how they're feeling about ${h||"this topic"}.`;break;case"encouragement":r=`The student seems frustrated or stuck on ${h||"this topic"}. Provide encouraging support and suggest they might approach it differently.`;break;case"joke":r=`Tell a light, educational joke or pun related to ${h||"what they're learning"}.`;break;case"puzzle":r=`Create an emoji puzzle related to ${h||"the current topic"}. Format: "What [category] is this: [2-4 emojis]?"`;break;case"analogy":r=`Create a relatable analogy or metaphor to explain ${h||"this concept"} using everyday experiences or pop culture.`;break;case"celebration":r="The student just succeeded or made progress! Celebrate their achievement genuinely but briefly.";break;case"farewell":r="You're heading back to rest. Give a brief, encouraging farewell that acknowledges their progress.";break}const v=`
22CONVERSATION CONTEXT:
23${n}
24
25CURRENT TOPIC: ${h||"General learning"}
26
27STUDENT PROFILE:
28- Name: ${d?.name||"Student"}
29- Interests: ${d?.interests?.join(", ")||"Not specified"}
30- Learning Style: ${d?.learningStyle||"Not specified"}
31- Grade Level: ${d?.gradeLevel||"Not specified"}
32
33REQUEST: ${r}
34
35Respond in character as the pet companion. Keep it SHORT (2-3 sentences max), use 2-3 relevant emojis, and stay relevant to the conversation.
36      `.trim();console.log("🐾 Calling Pet Assistant...",{messageType:u,topic:h});const{data:j,error:b}=await E.functions.invoke("openai-assistant-chat",{body:{assistantId:x,message:v,classroomSubject:h}});return b?(console.error("Error generating pet response:",b),m({title:"Pet unavailable",description:"Your learning companion is taking a quick nap. Try again!",variant:"destructive"}),null):(console.log("🐾 Pet response received:",j?.content?.substring(0,100)),j?.content||null)}catch(n){return console.error("Pet assistant error:",n),m({title:"Pet unavailable",description:"Your learning companion encountered an error.",variant:"destructive"}),null}finally{a(!1)}},isGenerating:s,petAssistantId:x}},xt=t.forwardRef(({classroomId:s,messages:a,onMessagesChange:m,isLoading:x,onLoadingChange:p,dynamicButtons:l,onDynamicButtonClick:h,customization:u,canUseAI:d=!0,availableCredits:n=0,studentId:r,complexityLevel:v=5,onComplexityChange:j,activeTutorName:b,onSwitchTutor:g},c)=>{const[o,i]=t.useState(""),[f,y]=t.useState(!1),[N,A]=t.useState(0),[w,P]=t.useState(!1),[k,I]=t.useState(!1),[T,M]=t.useState(!1),[G,D]=t.useState(v),[Y,de]=t.useState(!1),[pe,xe]=t.useState(!1),[ce,oe]=t.useState(!1),[ae,K]=t.useState(null),{toast:O}=we(),{files:W,uploading:B,addFiles:F,removeFile:Q,clearFiles:S}=_r(),z=t.useRef(null),{persistence:V}=In(s),{saveChatSession:q}=Dn(s),{generatePetResponse:C}=Ln(),{settings:H}
36=ca(),{getStudentProfileForAssistant:ue,saveHiddenMessage:ve}=Bt(),{isRecording:re,isTranscribing:le,permissionState:Ne,availableMicrophones:ze,selectedMicId:Re,recordingDuration:R,audioLevel:$,startRecording:U,stopRecording:se,cancelRecording:ee,setSelectedMicId:J,testMicrophone:ge}=Br();t.useEffect(()=>{D(v)},[v]);const je=L=>{D(L),j?.(L)},Se=(L,X)=>{if(!L.trim()&&W.length===0)return;let be=L.trim();if(W.length>0){const Ce=W.map(Pe=>`📎 ${Pe.name}`).join(`
37`);be=L.trim()?`${L.trim()}
38
39${Ce}
40
41${W.map(Pe=>Pe.content).join(`
42
43`)}`:`${Ce}
44
45${W.map(Pe=>Pe.content).join(`
46
47`)}`}const Ie=/^\s*\[HIDDEN_INSTRUCTION\]/.test(be),ye={id:Date.now().toString(),content:be,sender:"user",timestamp:new Date,imageUrl:X,isHidden:Ie};m([...a,ye]),i(""),S()};t.useImperativeHandle(c,()=>({sendMessage:Se,isPetAssisting:()=>f,incrementPetAssistanceCount:()=>A(L=>L+1)}));const Ue=L=>{try{const X=L.match(/\[TOOL_SUGGEST:mini-game:([a-z-]+):\s*(\{[\s\S]*?\})\s*\]/i);if(X){const Ce=X[1];let Pe=X[2];try{const Qt=JSON.parse(Pe);return{toolId:"mini-game",reason:Qt.reason||"",topic:Qt.topic||"",context:Ce}}catch{Pe=Pe.replace(/(\w+):/g,'"$1":'),Pe=Pe.replace(/'/g,'"');const As=JSON.parse(Pe);return{toolId:"mini-game",reason:As.reason||"",topic:As.topic||"",context:Ce}}}const be=L.match(/\[TOOL_SUGGEST:([a-z-]+):\s*(\{[\s\S]*?\})\s*\]/i);if(!be)return null;const Ie=be[1];let ye=be[2];try{const Ce=JSON.parse(ye);return{toolId:Ie,reason:Ce.reason||"",topic:Ce.topic||"",context:Ce.context||(Ce.gameId?Ce.gameId:"")}}catch{ye=ye.replace(/(\w+):/g,'"$1":'),ye=ye.replace(/'/g,'"');const Pe=JSON.parse(ye);return{toolId:Ie,reason:Pe.reason||"",topic:Pe.topic||"",context:Pe.context||(Pe.gameId?Pe.gameId:"")}}}catch(X){return console.error("Failed to parse tool suggestion:",X),null}},fe=t.useRef(null);t.useEffect(()=>{fe.current?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a.length,x]);const he=L=>{L.preventDefault(),(o.trim()||W.length>0)&&Se(o)},Fe=L=>{L.key==="Enter"&&!L.shiftKey&&(L.preventDefault(),(o.trim()||W.length>0)&&!x&&d&&Se(o))},ht=async()=>{if(!(!o.trim()||T)){M(!0),console.log("🎨 Starting prompt enhancement...",{inputLength:o.length,classroomId:s});try{const L=a.slice(-5).map(Ie=>({role:Ie.sender==="user"?"user":"assistant",content:Ie.content}));console.log("📡 Calling tutor-prompt-enhancer...",{recentMessagesCount:L.length});const{data:X,error:be}=await E.functions.invoke("tutor-prompt-enhancer",{body:{input:o,classroomId:s,recentMessages:L}});if(console.log("📬 Response received:",{data:X,error:be}),be)throw console.error("❌ Edge function error:",be),be;if(X?.success&&X?.transformedText)console.log("✅ Prompt enhanced successfully"),i(X.transformedText),O({title:"Prompt Enhanced",description:"Your message has been improved!"});else throw console.warn("⚠️ Unexpected response format:",X),new Error("Invalid response format")}catch(L){console.error("💥 Enhancement error:",L);const X=L.message||String(L);X.includes("Failed to fetch")||X.includes("fetch")?O({title:"Connection Error",description:"The enhancement service is not available yet. It may still be deploying. Please try again in a moment.",variant:"destructive"}):X.includes("429")||L.status===429?O({title:"Rate Limit Reached",description:"Too many requests. Please wait a moment and try again.",variant:"destructive"}):X.includes("402")||L.status===402?O({title:"Credits Required",description:"Please add credits to your Lovable AI workspace.",variant:"destructive"}):O({title:"Enhancement Failed",description:"Could not enhance your prompt. Please try again.",variant:"destructive"})}finally{M(!1)}}},Ns=async()=>{if(Ne==="prompt"||Ne==="unknown"){de(!0);return}if(Ne==="denied"){xe(!0);return}try{await U()}catch(L){console.error("Failed to start recording:",L)}},Cs=async()=>{try{const L=await se();L&&L.trim()&&i(X=>X?`${X} ${L}`:L)}catch(L){console.error("Failed to stop recording:",L)}},Ss=()=>{ee()},ha=async()=>{de(!1);try{await U()}catch(L){console.error("Failed to request microphone permission:",L)}},ga=()=>{Ne==="denied"?xe(!0):(Ne==="prompt"||Ne==="unknown")&&de(!0)},pa=L=>{L.preventDefault(),L.dataTransfer.dropEffect="copy",I(!0)},xa=L=>{L.preventDefault(),I(!1)},Vt=L=>{const be=L.filter(Ie=>Ie.sender==="tutor").slice(-3).map(Ie=>Ie.content).join(" ").match(/(math|algebra|geometry|biology|chemistry|physics|history|literature|writing|science|reading|fractions|multiplication|division|equations|grammar|spelling)/i);return be?be[1]:"this topic"},_s=async L=>{try{if(L.action==="provide_full_context"){y(!0),A(1),P(!1),window.dispatchEvent(new CustomEvent("pet:entered-chat"));const X=await ue();X&&b&&(await ve(s,b,"SEND_LEARNING_PROFILE","app_to_assistant",{studentProfile:X}),console.log("🐾 Sent full backend student profile to tutor:",X)
47);const be={id:`pet-instant-${Date.now()}`,content:`🐾 Hi! I'm ${L.petName}! Just shared your learning style with your tutor. Give me one sec... 😊`,sender:"tutor",tutorName:L.petName,timestamp:new Date};m([...a,be]),setTimeout(async()=>{const Ie=Vt(a),ye=await C({conversationContext:a.slice(-5).map(Ce=>({role:Ce.sender==="user"?"user":"tutor",content:Ce.content})),currentTopic:Ie,messageType:"greeting",studentProfile:{name:L.ownerName,interests:X?.interests,learningStyle:X?.learning_style,gradeLevel:X?.grade_level}});if(ye){const Ce={id:`pet-ai-${Date.now()}`,content:ye,sender:"tutor",tutorName:L.petName,timestamp:new Date};m([...a,be,Ce])}},2e3)}}catch(X){console.error("Error activating pet assistance:",X)}},fa=async L=>{L.preventDefault(),I(!1);try{const X=L.dataTransfer.getData("application/pet");if(X){const be=JSON.parse(X);await _s(be)}}catch(X){console.error("Error handling pet drop:",X)}};t.useEffect(()=>{const L=async()=>{try{const X=sessionStorage.getItem("dragging-pet-data");if(X){const be=JSON.parse(X);await _s(be),sessionStorage.removeItem("dragging-pet-data")}}catch(X){console.error("Error handling touch drop:",X)}};return window.addEventListener("pet:dropped-on-chat-touch",L),()=>{window.removeEventListener("pet:dropped-on-chat-touch",L)}},[a]),t.useEffect(()=>{if(!f)return;(w&&N>=4||N>=6)&&(async()=>{const be=Vt(a),Ie=await C({conversationContext:a.slice(-5).map(Ce=>({role:Ce.sender==="user"?"user":"tutor",content:Ce.content})),currentTopic:be,messageType:"farewell",studentProfile:{name:H.petName}}),ye={id:`pet-farewell-${Date.now()}`,content:Ie||"🐾 Heading back to rest! You've got this! 💪",sender:"tutor",tutorName:H.petName,timestamp:new Date};m([...a,ye]),y(!1),A(0),P(!1),window.dispatchEvent(new CustomEvent("pet:left-chat"))})()},[N,f,w,a,m,C,H.petName]);const va=()=>{y(!1),A(0),P(!1),window.dispatchEvent(new CustomEvent("pet:left-chat"))},ks=t.useCallback(async L=>{const X=L.toLowerCase(),be=Vt(a);let Ie="encouragement";X.match(/hard|difficult|confused|stuck|don't understand|help/i)?Ie="encouragement":X.match(/yes|yeah|got it|understand|makes sense|i see|correct|right/i)?(Ie="celebration",P(!0)):N%2===0?(Ie=Math.random()>.5?"joke":"puzzle",P(!0)):Ie="analogy";const ye=await C({conversationContext:a.slice(-6).map(Ce=>({role:Ce.sender==="user"?"user":"tutor",content:Ce.content})),currentTopic:be,messageType:Ie,studentProfile:{name:H.petName}});if(ye){const Ce={id:`pet-reply-${Date.now()}`,content:ye,sender:"tutor",tutorName:H.petName,timestamp:new Date};m([...a,Ce]),A(Pe=>Pe+1)}},[a,N,C,H.petName,m]);t.useEffect(()=>{if(!f)return;const L=a[a.length-1];if(!L||L.sender!=="user")return;const X=setTimeout(()=>{ks(L.content)},2e3);return()=>clearTimeout(X)},[a,f,ks]),a.map(L=>L.sender).lastIndexOf("tutor");const ya=L=>L.replace(/\[TOOL_SUGGEST:[^\]]+\]/g,"").replace(/\[PROFILE_EVOLUTION:[^\]]+\]/g,"").replace(/\[APP_ACTION:[^\]]+\]/g,"").replace(/\[HIDDEN_INSTRUCTION[^\]]*\]/gi,"").replace(/\[([A-Za-z0-9@#$%^&*!]+)#([A-Z_]+)#?([^\[\]]*)\]/g,"").trim().replace(/\n\n+/g,`
48
49`),ja=L=>{const X=ya(L);navigator.clipboard.writeText(X),O({title:"Copied",description:"Message copied to clipboard"})},ba=async()=>{if(a.length===0){O({title:"No messages to clear",description:"The chat is already empty."});return}if(window.confirm(`Archive this conversation and start fresh?
50
51Your current conversation will be saved to Chat History.`))try{await q(a,`Chat - ${new Date().toLocaleDateString()}`),m([]),O({title:"Chat Cleared",description:"Previous conversation saved to History."})}catch(X){console.error("Error clearing chat:",X),O({title:"Error",description:"Failed to clear chat. Please try again.",variant:"destructive"})}},wa=async L=>{const X=a.findIndex(Pe=>Pe.id===L);if(X===-1)return;const be=a[X],ye=a.slice(Math.max(0,X-2),Math.min(a.length,X+2)).map(Pe=>`${Pe.sender==="user"?"Student":"Tutor"}: ${Pe.content}`).join(`
52
53`),Ce=`[HIDDEN_INSTRUCTION] Please explain this message in a way an 8-year-old would understand. Break it down step by step, use simple words, and make sure the student fully grasps the concept.
54
55Message to explain: "${be.content}"
56
57Context from conversation:
58${ye}
59
60Remember: Explain like the student is 8 years old. Be patient, clear, and encouraging.`;Se(Ce),O({title:"Explanation requested",description:"Your tutor will explain this message in simple terms"})},[Ts,Es]=t.useState(null),Ht=t.useRef("");t.useEffect(()=>{const L=(l||[]).map(X=>X.id).join("|");if(!L){Ht.current="",Es(null);return}if(Ht.current!==L){Ht.current=L;const X=a[a.length-1]?.id??null;Es(X)}},[l,a]),t.useEffect(()=>{console.log("Chat dynamicButtons count:",l?.length??0)},[l?.length]);const Na=()=>!u?.background_type||!u?.background_value?"bg-background":u.background_type==="gradient"||u.background_type==="color"||u.background_type==="image"?"":"bg-background",Ca=()=>!u?.background_type||!u?.background_value?{}:u.background_type==="gradient"?{background:u.background_value}:u.background_type==="color"?{backgroundColor:u.background_value}:u.background_type==="image"?{backgroundImage:`url(${u.background_value})`,backgroundSize:"cover",backgroundPosition:"center"}:{},Sa=()=>!u?.header_type||!u?.header_value?"border-gray-300 dark:border-border":u.header_type==="gradient"||u.header_type==="color"||u.header_type==="image"?"":"border-gray-300 dark:border-border",_a=()=>!u?.header_type||!u?.header_value?{}:u.header_type==="gradient"?{background:u.header_value}:u.header_type==="color"?{backgroundColor:u.header_value}:u.header_type==="image"?{backgroundImage:`url(${u.header_value})`,backgroundSize:"cover",backgroundPosition:"center"}:{};return e.jsxs(e.Fragment,{children:[e.jsx(Vr,{isRecording:re,duration:R,audioLevel:$,onCancel:Ss}),e.jsx(Hr,{open:Y,onOpenChange:de,onAllow:ha,permissionState:Ne}),e.jsx(An,{open:pe,onOpenChange:xe}),e.jsxs("div",{className:`relative flex flex-col h-full ${Na()} ${k?"ring-2 ring-primary ring-opacity-50":""}`,style:Ca(),onDragOver:pa,onDragLeave:xa,onDrop:fa,"data-chat-drop-zone":"true",children:[b&&e.jsx("div",{className:"bg-primary/20 border-b border-primary/30 p-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 bg-primary rounded-full animate-pulse"}),e.jsxs("span",{className:"text-sm text-primary font-medium",children:["Now chatting with: ",b]}
60)]}),g&&e.jsx(_,{variant:"ghost",size:"sm",onClick:g,className:"text-primary hover:text-primary/80 text-xs",children:"Switch Tutor"})]})}),f&&e.jsx("div",{className:"bg-primary/20 border-b border-primary/30 p-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 bg-primary rounded-full animate-pulse"}),e.jsx("span",{className:"text-sm text-primary font-medium",children:"Pet is helping with personalization"})]}),e.jsx(_,{variant:"ghost",size:"sm",onClick:va,className:"text-primary hover:text-primary/80 text-xs",children:"Dismiss"})]})}),k&&e.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary z-10 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl mb-2",children:"🐾"}),e.jsx("p",{className:"text-primary font-medium",children:"Drop your pet here for enhanced personalization!"})]})}),e.jsx(Ze,{className:"flex-1 p-4 overflow-y-auto",children:e.jsxs("div",{className:"space-y-4",children:[a.map((L,X)=>{const be=Ue(L.content),Ie=L.sender==="user"&&/^\s*\[HIDDEN_INSTRUCTION\]/i.test(L.content);return L.isHidden||Ie?null:e.jsxs("div",{children:[e.jsxs(te,{variant:"paper",className:`p-3 max-w-[80%] relative group ${L.sender==="user"?"ml-auto bg-primary/10 dark:bg-primary/20":"mr-auto"}`,children:[e.jsx("div",{className:"paper-inset p-2 rounded-md",children:e.jsxs("div",{className:"text-sm pr-8 text-foreground",children:[(()=>{let ye=L.content;return L.sender==="tutor"&&(ye=ye.replace(/\[TOOL_SUGGEST:[^\]]+\]/g,"").replace(/\[PROFILE_EVOLUTION:[^\]]+\]/g,"").replace(/\[APP_ACTION:[^\]]+\]/g,"").replace(/\[HIDDEN_INSTRUCTION[^\]]*\]/gi,"").replace(/\[([A-Za-z0-9@#$%^&*!]+)#([A-Z_]+)#?([^\[\]]*)\]/g,"").trim()),e.jsxs(e.Fragment,{children:[L.sender==="tutor"&&L.tutorName&&e.jsxs("div",{className:"font-semibold text-primary mb-1 flex items-center justify-between pr-6",children:[e.jsx("span",{children:L.tutorName}),e.jsx(mt,{text:ye})]}),e.jsx(st,{content:ye})]})})(),L.imageUrl&&e.jsx("img",{src:L.imageUrl,alt:"Message attachment",className:"mt-2 max-w-full rounded"}),e.jsxs("div",{className:"text-xs opacity-70 mt-1",children:[L.timestamp.toLocaleDateString()," ",L.timestamp.toLocaleTimeString()]})]})}),e.jsxs(na,{children:[e.jsx(oa,{asChild:!0,children:e.jsx(_,{type:"button",variant:"ghost",size:"sm",className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6 p-0 hover:bg-background/20",onClick:ye=>ye.stopPropagation(),children:e.jsx(La,{className:"h-4 w-4"})})}),e.jsxs(ia,{align:"end",children:[e.jsx(os,{onSelect:ye=>{ye.preventDefault(),ja(L.content)},children:"Copy"}),e.jsx(os,{onSelect:ye=>{ye.preventDefault(),wa(L.id)},children:"Explain"})]})]})]}),be&&e.jsx(Tn,{suggestion:be,classroomId:s,messages:a,persistence:V,onComplete:ye=>{console.log("Tool completed with result:",ye),ye?.message&&typeof ye.message=="string"&&(console.log("Tool requested message send:",ye.message),Se(ye.message))}}),(L.id===Ts||!Ts&&X===a.length-1)&&e.jsx($s,{buttons:l,onButtonClick:async ye=>{const Ce=await h(ye,L.tutorName||"Tutor");Ce?.contextMessage&&Se(Ce.contextMessage)},className:"mt-2"})]},L.id)}),a.length===0&&(l?.length??0)>0&&e.jsx($s,{buttons:l,onButtonClick:async L=>{const X=await h(L,"Tutor");X?.contextMessage&&Se(X.contextMessage)},className:"mt-2"}),x&&e.jsx(te,{className:"p-3 mr-auto bg-muted",children:e.jsx("div",{className:"text-sm text-foreground",children:"Tutor is typing..."})}),e.jsx("div",{id:"chat-bottom-anchor",ref:fe})]})}),e.jsxs("div",{className:`p-4 border-t ${Sa()}`,style:_a(),children:[r&&e.jsx("div",{className:"mb-4",children:e.jsx(Fn,{studentId:r,currentLevel:G,onLevelChange:je})}),e.jsxs("div",{className:"flex items-center gap-2 mb-3 px-3 py-2 bg-primary/10 border border-primary/20 rounded-lg",children:[e.jsx(Je,{className:"w-4 h-4 text-primary flex-shrink-0"}),e.jsx("p",{className:"text-xs text-primary",children:"💡 Your AI tutor can suggest interactive tools like quizzes, flashcards, and study guides right here in the chat!"})]}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:d?e.jsxs(me,{variant:n<5?"destructive":"secondary",className:"px-2 py-1",children:[e.jsx(es,{className:"w-3 h-3 mr-1"}),n," credits"]}):e.jsxs(me,{variant:"destructive",className:"px-2 py-1",children:[e.jsx($a,{className:"w-3 h-3 mr-1"}),"No Credits"]})}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"1 credit per message"})]}),W.length>0&&e.jsx("div",{className:"mb-2 p-2 bg-muted/50 rounded-md",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:W.map((L,X)=>e.jsxs("div",{className:"flex items-center gap-2 bg-background px-3 py-1 rounded-md text-sm",children:[e.jsx("span",{className:"truncate max-w-[150px]",children:L.name}),e.jsx(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>Q(X),className:"h-5 w-5 p-0",children:e.jsx(Pt,{className:"h-3 w-3"})})]},X))})}),e.jsxs("form",{onSubmit:he,className:"flex gap-2 items-end",children:[e.jsx("input",{type:"file",ref:z,className:"hidden",multiple:!0,accept:".pdf,.jpg,.jpeg,.png,.doc,.docx",onChange:L=>{L.target.files&&(F(L.target.files),L.target.value="")}}),e.jsx(rt,{value:o,onChange:L=>i(L.target.value),onKeyDown:Fe,placeholder:d?"Type your message... (Shift+Enter for new line)":"No credits available for chat",className:"flex-1 bg-background border-input text-foreground resize-none",rows:3,disabled:!d}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(_,{type:"button",variant:"outline",size:"icon",onClick:()=>oe(!ce),title:"Launch mini-games",className:"relative",children:e.jsx(Ps,{className:"w-4 h-4"})}),e.jsx(_,{type:"button",variant:"outline",size:"icon",onClick:()=>z.current?.click(),disabled:B,title:"Attach files",children:e.jsx(Ma,{className:"w-4 h-4"})})]}),e.jsx(Qr,{isRecording:re,isTranscribing:le,permissionState:Ne,disabled:!d||x,onMouseDown:Ns,onMouseUp:Cs,onMouseLeave:Ss,onTouchStart:Ns,onTouchEnd:Cs,onClick:ga}),e.jsx(En,{permissionState:Ne,availableMicrophones:ze,selectedMicId:Re,onMicrophoneChange:J,onTestMicrophone:ge,onRequestPermission:()=>de(!0)}),e.jsx(_,{type:"button",variant:"outline",onClick:ht,disabled:!o.trim()||T||!d,className:"min-w-[100px]",children:T?e.jsx("div",{className:"w-4 h-4 border-2 border-current border-t-transparent roun
60ded-full animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-1"}),"Enhance"]})}),e.jsx(_,{type:"submit",disabled:!o.trim()||x||!d,className:"min-w-[100px]",children:x?e.jsx(e.Fragment,{children:e.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"})}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-1"}),"Send (1 credit)"]})})]}),ce&&e.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-80 bg-card border rounded-lg shadow-lg p-3 z-50",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Ps,{className:"w-4 h-4"}),"Launch Mini-Game"]}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>oe(!1),className:"h-6 w-6 p-0",children:e.jsx(Pt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:ur().map(L=>e.jsx("button",{onClick:()=>{K(L.id),oe(!1)},className:"w-full text-left p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:L.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:L.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:L.description}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(me,{variant:"outline",className:"text-xs",children:L.difficulty}),e.jsxs(me,{variant:"outline",className:"text-xs",children:[L.estimatedMinutes," min"]})]})]})]})},L.id))})]}),a.length>0&&e.jsx("div",{className:"mt-2 flex justify-center",children:e.jsxs(_,{type:"button",variant:"ghost",size:"sm",onClick:ba,className:"text-muted-foreground hover:text-foreground",children:[e.jsx(yt,{className:"w-4 h-4 mr-2"}),"Clear Chat (",a.length," messages)"]})})]})]}),ae&&e.jsx(Tr,{gameId:ae,open:!!ae,onOpenChange:L=>!L&&K(null)})]})});xt.displayName="ClassroomChat";const $n=()=>{const{user:s}=Ge(),{studentProfile:a}=ps(),[m,x]=t.useState(null),[p,l]=t.useState(!1),h=t.useCallback(async()=>{if(!s?.id||!a)return null;l(!0);try{const[d,n,r,v,j,b,g]=await Promise.allSettled([E.from("student_profiles").select("*").eq("student_auth_id",s.id).maybeSingle(),E.from("student_collection_assignments").select("*").eq("student_id",a.id).order("assigned_at",{ascending:!1}).limit(5),E.from("student_earned_badges").select("*").eq("student_id",a.id).order("earned_at",{ascending:!1}).limit(10),E.from("student_tutor_interactions").select("*").eq("student_id",a.id).order("last_interaction_at",{ascending:!1}).limit(10),E.from("classroom_messages").select("classroom_id, content, created_at, sender_type").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(20),E.from("account_manager_private_notes").select("title, content, tags, metadata, created_at").eq("student_id",a.id).order("created_at",{ascending:!1}),E.from("developer_secret_documents").select("title, content, doc_type, metadata, created_at").eq("owner_user_id",s.id).eq("is_active",!0).order("created_at",{ascending:!1})]),c=d.status==="fulfilled"?d.value.data:null,o=n.status==="fulfilled"?n.value.data:[],i=r.status==="fulfilled"?r.value.data:[],f=v.status==="fulfilled"?v.value.data:[],y=j.status==="fulfilled"?j.value.data:[],N=b.status==="fulfilled"?b.value.data:[],A=g.status==="fulfilled"?g.value.data:[];if(!c){const T={user_id:s.id,student_name:a?.student_name||"Student",age:a?.age||16,grade_level:void 0,learning_style:"mixed",communication_preferences:{},interests:a?.interests||[],favorite_subjects:[],hobbies:[],current_assignments:[],completed_work:[],learning_goals:[],strengths:[],areas_for_improvement:[],recent_activity:[],classroom_history:y?.slice(0,10)||[],badges_earned:[],total_tokens:a?.total_tokens||0,account_manager_notes:[],developer_secret_docs:[],profile_completion_percentage:0,last_updated:new Date().toISOString()};return x(T),T}const w=["age","interests","favorite_subjects","hobbies","learning_style"],P=w.filter(T=>{const M=c[T];return M&&(Array.isArray(M)?M.length>0:!0)}),k=Math.round(P.length/w.length*100),I={user_id:s.id,student_name:c.student_name||"Student",age:c.age||16,grade_level:c.grade_level||void 0,learning_style:c.learning_style||"mixed",communication_preferences:c.communication_preferences||{},interests:c.interests||[],favorite_subjects:c.favorite_subjects||[],hobbies:c.hobbies||[],current_assignments:o?.filter(T=>T.status!=="completed")||[],completed_work:o?.filter(T=>T.status==="completed")||[],learning_goals:c.learning_goals||[],strengths:c.strengths||[],areas_for_improvement:c.areas_for_improvement||[],recent_activity:f||[],classroom_history:y?.slice(0,10)||[],badges_earned:i||[],total_tokens:c.total_tokens||0,account_manager_notes:N||[],developer_secret_docs:A||[],profile_completion_percentage:k,last_updated:c.updated_at||new Date().toISOString()};return x(I),I}catch(d){return console.error("Error building comprehensive profile:",d),null}finally{l(!1)}},[s?.id,a?.id]);t.useEffect(()=>{h()}
60,[h]);const u=t.useCallback(d=>[`Student: ${d.student_name}, Age: ${d.age}`,`Learning Style: ${d.learning_style}`,d.interests.length>0?`Interests: ${d.interests.join(", ")}`:null,d.favorite_subjects.length>0?`Favorite Subjects: ${d.favorite_subjects.join(", ")}`:null,d.hobbies.length>0?`Hobbies: ${d.hobbies.join(", ")}`:null,`Total Tokens Earned: ${d.total_tokens}`,d.badges_earned.length>0?`Recent Badges: ${d.badges_earned.slice(0,3).map(r=>r.badge_template?.title).join(", ")}`:null,d.current_assignments.length>0?`Active Assignments: ${d.current_assignments.length}`:null,`Profile ${d.profile_completion_percentage}% complete`].filter(Boolean).join(" | "),[]);return{comprehensiveProfile:m,isLoading:p,refreshProfile:h,generateProfileSummary:u}},Mn=(s,a=[],m,x)=>{const[p,l]=t.useState([]),[h,u]=t.useState(!1),[d,n]=t.useState(!0),[r,v]=t.useState(null),[j,b]=t.useState(null),[g,c]=t.useState(null),{parseAssistantResponse:o,processMessageForTriggers:i,checkFirstTimeInteraction:f,loadTriggers:y}=Bt(),N=S=>{const z=new Date;return z.setHours(0,0,0,0),S.filter(V=>{const q=new Date(V.timestamp);return q.setHours(0,0,0,0),q.getTime()===z.getTime()})},{toast:A}=we(),{user:w}=Ge(),{currentStudent:P}=at(),{comprehensiveProfile:k,generateProfileSummary:I}=$n(),{spendAICredit:T,canUseAI:M,availableCredits:G}=wt(),D=P?.student_auth_id===w?.id,Y=P?.total_tokens||0,de=D?Y>0:M,pe=D?Y:G,xe=t.useCallback(async(S,z,V=1)=>D?Y<V?(A({title:"Not Enough Tokens",description:`You need ${V} tokens to use this feature. You have ${Y} tokens.`,variant:"destructive"}),!1):!0:await T(S,z,V),[D,Y,T,A]);t.useEffect(()=>{y()},[y]),t.useEffect(()=>{if(!D&&s&&a.length>0){const S=a[0],z=`classroom-thread-${s}-${S.assistant_id}-${w?.id||"anonymous"}`,V=localStorage.getItem(z);V&&(v(V),console.log("Loaded existing thread ID for non-student user:",V))}},[D,s,a,w?.id]);const ce=t.useCallback(S=>{if(!D&&s&&a.length>0&&w?.id){const z=a[0],V=`classroom-thread-${s}-${z.assistant_id}-${w.id}`;localStorage.setItem(V,S),v(S),console.log("Saved thread ID for non-student user:",S)}},[D,s,a,w?.id]),oe=t.useCallback(async()=>{if(!w)return null;try{const{data:S,error:z}=await E.from("classroom_chat_sessions").select("*").eq("classroom_id",s).eq("user_id",w.id).eq("is_archived",!1).order("last_message_at",{ascending:!1}).limit(1);if(z)throw z;if(S&&S.length>0)return b(S[0].id),S[0].id;{const V=`Chat - ${new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}`,{data:q,error:C}=await E.from("classroom_chat_sessions").insert({classroom_id:s,user_id:w.id,session_name:V}).select().single();if(C)throw C;return b(q.id),q.id}}catch(S){return console.error("Error loading/creating session:",S),null}},[s,w]),ae=t.useCallback(async()=>{if(w)try{const S=`Chat - ${new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}`,{data:z,error:V}=await E.from("classroom_chat_sessions").insert({classroom_id:s,user_id:w.id,session_name:S}).select().single();if(V)throw V;b(z.id),l([]),A({title:"New Chat Started",description:"Your previous conversation has been saved."})}catch(S){console.error("Error creating new session:",S),A({title:"Error",description:"Failed to create new chat session.",variant:"destructive"})}},[s,w,A]),K=t.useCallback(async()=>{n(!0);try{const S=j||await oe();if(!S){n(!1);return}const{data:z,error:V}=await E.from("classroom_messages").select("*").eq("classroom_id",s).eq("session_id",S).order("created_at",{ascending:!0});if(V)throw V;const q=z.map(C=>({id:C.id,content:C.content,sender:C.sender_type,tutorName:C.sender_name||void 0,timestamp:new Date(C.created_at),imageUrl:C.image_url||void 0}));l(q)}catch(S){console.error("Error loading chat history:",S)}finally{n(!1)}},[s,j,oe]),O=t.useCallback(async S=>{const V={id:Date.now().toString()+Math.random().toString(36).slice(2),timestamp:new Date,...S};if(l(C=>[...C,V]),!w)return V;const q=j||await oe();if(!q)return V;try{const{data:C,error:H}=await E.from("classroom_messages").insert({classroom_id:s,user_id:w.id,session_id:q,sender_type:S.sender,sender_name:S.tutorName||null,content:S.content,image_url:S.imageUrl||null}).select().maybeSingle();if(H)throw H;if(await E.from("classroom_chat_sessions").update({last_message_at:new Date().toISOString(),message_count:p.length+1}).eq("id",q),!C)return V;const ue={id:C.id,content:C.content,sender:C.sender_type,tutorName:C.sender_name||void 0,timestamp:new Date(C.created_at),imageUrl:C.image_url||void 0};return l(ve=>ve.map(re=>re.id===V.id?ue:re)),ue}catch(C){return console.error("Error saving message:",C),V}},[s,w,j,oe,p.length]),W=t.useCallback(S=>{const z={...S,id:Date.now().toString()+Math.random().toString(36).substr(2,9),timestamp:new Date};return l(V=>[...V,z]),z},[]),B=t.useCallback(async S=>{if(a.length===0||!s)return;const z=j||await oe();if(!z)return;try{const{data:C,error:H}=await E.from("classroom_messages").select("id").eq("classroom_id",s).eq("session_id",z).limit(1);if(H)throw H;if(C&&C.length>0)return}catch(C){console.error("Error checking existing messages:",C);return}const V=a[0],q=`Welcome to the ${S} classroom! I'm ${V.name}, your ${V.role}. I specialize in ${V.specialty} and I'm here to help you learn and grow. What would you like to explore today?`;await O({content:q,sender:"tutor",tutorName:V.name})},[a,s,O,j,oe]),F=t.useCallback(async(S,z,V)=>{if(console.log("sendMessage called with:",{content:S,imageFile:z?.name,hasImage:!!z}),!S.trim()&&!z){console.log("No content or image, returning early");return}if(!de){A({title:D?"No Tokens Available":"No Credits Available",description:D?"You need tokens to chat with AI tutors. Complete assignments and activities to earn more tokens!":"You need credits to chat with AI tutors. Please upgrade your plan or buy credits.",variant:"destructive"});return}let q=S.trim(),C;if(z)try{const re=new FileReader,le=await new Promise((Re,R)=>{re.onload=()=>
60Re(re.result),re.onerror=R,re.readAsDataURL(z)}),{data:Ne,error:ze}=await E.functions.invoke("analyze-image",{body:{imageData:le}});ze&&(console.error("Image analysis error:",ze),A({title:"Image Analysis Failed",description:"We'll send your image without analysis.",variant:"destructive"})),Ne?.analysis&&(q=S.trim()?`${S.trim()}
61
62📷 **Image Content:** ${Ne.analysis}`:`📷 **Image Content:** ${Ne.analysis}`),C=le}catch(re){console.error("Error processing image:",re),A({title:"Image Upload Failed",description:"We couldn't process the image, but your message will still be sent.",variant:"destructive"})}await O({content:q,sender:"user",imageUrl:C});try{if(P?.id){const{data:re}=await E.rpc("increment_student_tokens",{p_student_id:P.id,p_classroom_subject:s,p_tokens:2});typeof re=="number"&&window.dispatchEvent(new CustomEvent("student:tokens-update",{detail:{newTotal:re}}))}}catch(re){console.error("Auto token award failed:",re)}if(a.length===0||!s){a.length===0&&A({title:"No Tutor Available",description:"Your message was sent. A tutor isn't available yet.",variant:"destructive"});return}const H=a[0];let ue=!1;try{H&&w?.id&&(ue=await f(H.name,s),await i(q,s,H.name,ue))}catch(re){console.error("Hidden communication error:",re)}if(await xe("AI Classroom",`Chat message: ${q.substring(0,50)}...`,1)){u(!0);try{console.log("Sending message to classroom chat:",{classroomId:s,tutorCount:a.length,tutorNames:a.map(U=>U.name),assistantIds:a.map(U=>U.assistant_id),message:q,hasImage:!!z});const re={userMessage:q,classroomId:s,activeTutors:a,messages:N(p),userId:w?.id,isFirstTimeInteraction:ue,selectedPersonalityId:V,studentProfile:k?{summary:I(k),name:k.student_name,age:k.age,learning_style:k.learning_style,interests:k.interests,recent_achievements:k.badges_earned?.slice(0,3),total_tokens:k.total_tokens,completion_percentage:k.profile_completion_percentage}:P?{summary:`${P.student_name}, mixed learner.`,name:P.student_name,age:null,learning_style:"mixed",interests:[],recent_achievements:[],total_tokens:P.total_tokens||0,completion_percentage:0}:null};console.log("Sending enhanced context to classroom chat:",{...re,studentProfile:re.studentProfile?"Profile included":"No profile"});const le=g&&a.find(U=>U.id===g)||H,Ne=!le.assistant_id,ze=Ne?"milestone-tutor-chat":"openai-assistant-chat";console.log("[Chat Router] Using edge function:",ze,"for tutor:",le.name);const Re=Ne?{message:q,tutorName:le.name,personalityId:le.id,studentId:P?.id,sessionId:P?.session_id,profileContext:re.studentProfile,complexityLevel:x,classroomId:s}:{message:q,assistantId:le.assistant_id,tutorName:le.name,studentId:P?.id,sessionId:P?.session_id,threadId:D?void 0:r,profileContext:re.studentProfile,complexityLevel:x,includeDeepProfile:m?.current?.isPetAssisting?.()||!1||q.toLowerCase().includes("learn")||q.toLowerCase().includes("style")||q.toLowerCase().includes("prefer"),petContext:m?.current?.isPetAssisting?.()?{isPetAssisting:!0,petName:"companion",fullProfileRequested:!0}:void 0},{data:R,error:$}=await E.functions.invoke(ze,{body:Re});if($)throw console.error("Error from classroom chat function:",$),$;if(R?.content){if(R.routeToTutor){console.log("🔀 Routing to tutor:",R.routeToTutor),c(R.routeToTutor);let J=a.find(ge=>ge.id===R.routeToTutor);if(J||(J=is.find(ge=>ge.id===R.routeToTutor)),J){await O({content:R.content,sender:"tutor",tutorName:H.name}),A({title:`Switching to ${J.name}...`,description:`${J.specialty} specialist ready to help.`}),console.log("🎯 Immediate handoff to:",J.name,J.assistant_id);try{const{data:ge,error:je}=await E.functions.invoke("openai-assistant-chat",{body:{message:q,assistantId:J.assistant_id,tutorName:J.name,studentId:P?.id,sessionId:P?.session_id,threadId:D?void 0:r,profileContext:re.studentProfile,complexityLevel:x,includeDeepProfile:m?.current?.isPetAssisting?.()||!1||q.toLowerCase().includes("learn")||q.toLowerCase().includes("style")||q.toLowerCase().includes("prefer"),petContext:m?.current?.isPetAssisting?.()?{isPetAssisting:!0,petName:"companion",fullProfileRequested:!0}:void 0}});if(je)throw console.error("Error from target tutor:",je),je;if(ge?.content){let Se=ge.content;if(w?.id)try{Se=(await o(ge.content,s,w.id,J.name))?.cleanResponse||ge.content}catch(Ue){console.warn("parseAssistantResponse failed for target tutor, using raw content",Ue)}await O({content:Se,sender:"tutor",tutorName:J.name}),console.log("✅ Handoff complete:",J.name,"responded")}}catch(ge){console.error("Error during immediate handoff:",ge),A({title:"Handoff Failed",description:`Could not connect to ${J.name}. Please try again.`,variant:"destructive"})}u(!1);return}}!D&&R.threadId&&R.threadId!==r&&ce(R.threadId);let U=R.content,se=[];if(w?.id)try{const J=await o(R.content,s,w.id,H.name);U=J?.cleanResponse||R.content,se=J?.autoAwards||[]}catch(J){console.warn("parseAssistantResponse failed, using raw content",J)}const ee=await O({content:U,sender:"tutor",tutorName:H.name});for(const J of se)try{if(w?.id){const{data:ge}=await E.from("student_profiles").select("id").eq("student_auth_id",w.id).maybeSingle();if(ge?.id){const{data:je}=await E.rpc("increment_student_tokens",{p_student_id:ge.id,p_classroom_subject:s,p_tokens:J.amount});typeof je=="number"&&window.dispatchEvent(new CustomEvent("student:tokens-update",{detail:{newTotal:je}}))}else{const{data:je}=await E.rpc("increment_classroom_tokens",{p_user_id:w.id,p_classroom_subject:s,p_tokens:J.amount});typeof je=="number"&&window.dispatchEvent(new CustomEvent("classroom:tokens-update",{detail:{tokens:je,classroomSubject:s}}))}await O({content:`✨ You earned ${J.amount} tokens ${J.reason}!`,sender:"tutor",tutorName:"System"}),console.log("✅ Auto-awarded tokens:",J)}
62}catch(ge){console.error("Failed to auto-award tokens:",ge)}}else throw new Error("No response received from tutor")}catch(re){console.error("Error sending message:",re),await O({content:"I'm sorry, I'm having trouble responding right now. Please try again in a moment.",sender:"tutor",tutorName:a[0]?.name||"AI Tutor"}),A({title:"Connection Issue",description:"There was a problem connecting to your tutor. Please try again.",variant:"destructive"})}finally{u(!1)}}},[O,A,a,p,s,m,xe,de,D,Y]),Q=t.useCallback(async()=>{if(!(!j||!w))try{await E.from("classroom_chat_sessions").update({is_archived:!0,archived_at:new Date().toISOString()}).eq("id",j),await ae(),A({title:"Chat Archived",description:"Your previous conversation has been archived and a new chat started."})}catch(S){console.error("Error archiving session:",S),A({title:"Error",description:"Failed to archive chat session.",variant:"destructive"})}},[j,w,ae,A]);return t.useEffect(()=>{K()},[K]),{messages:p,isLoading:h,isLoadingHistory:d,sendMessage:F,addMessage:W,saveMessage:O,addWelcomeMessage:B,clearMessages:Q,createNewSession:ae,loadChatHistory:K,activeTutors:a,activeTutorId:g,setActiveTutorId:c,activeTutorName:g&&(a.find(S=>S.id===g)?.name||is.find(S=>S.id===g)?.name)||null,canUseAI:de,availableCredits:pe,currentSessionId:j}},zn=({open:s,onOpenChange:a,classroomId:m,onSendToChat:x})=>{const{toast:p}=we(),{age:l}=jt(),{currentStudent:h}=at(),{isStudent:u}=Xe(),[d,n]=t.useState(""),[r,v]=t.useState(""),[j,b]=t.useState(""),[g,c]=t.useState(!1),[o,i]=t.useState(""),[f,y]=t.useState(!1);t.useEffect(()=>{if(!r){const P=u()?vs(l):"advanced";v(P),y(!0)}},[l,r,u]),Er(s,f);const N=async()=>{if(!d.trim()){p({title:"Topic Required",description:"Please enter a topic for your study guide.",variant:"destructive"});return}c(!0);try{const P=u()?Lt(l):"College",{data:k,error:I}=await E.functions.invoke("generate-study-guide-stewart",{body:{topic:d,studyLevel:r||"intermediate",gradeLevel:P,additionalNotes:j,includeImages:!1,studentProfile:h?{age:l,name:h.student_name,interests:h.interests}:void 0,step:"full_guide"}});if(I)throw I;let T="";if(k?.sections&&Array.isArray(k.sections)?T=k.sections.map(M=>`## ${M.title}
63
64${M.content}`).join(`
65
66`):k?.content&&typeof k.content=="string"?T=k.content:typeof k=="string"&&(T=k),!T)throw new Error("No content generated");i(T),p({title:"Study Guide Generated!",description:"Your age-appropriate study guide is ready."})}catch(P){console.error("Study guide generation error:",P),p({title:"Generation Failed",description:"Failed to generate study guide. Please try again.",variant:"destructive"})}finally{c(!1)}},A=()=>{x&&o&&(x(`Study Guide Generated:
67
68${o}`),p({title:"Sent to Chat",description:"Study guide has been sent to the classroom chat."}),a(!1))},w=()=>{n(""),v(""),b(""),i(""),c(!1),a(!1)};return e.jsx(qe,{open:s,onOpenChange:w,children:e.jsxs(Oe,{className:"max-w-2xl bg-muted text-foreground border-border",children:[e.jsx(Be,{children:e.jsxs(Ve,{className:"text-xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Qe,{className:"w-6 h-6 text-indigo-500"}),"Generate Study Guide"]})}),e.jsx("div",{className:"space-y-6",children:o?e.jsxs(e.Fragment,{children:[e.jsx(te,{className:"bg-muted border-border",children:e.jsx(ie,{className:"p-4",children:e.jsx("div",{className:"prose prose-sm max-w-none prose-invert",children:e.jsx(st,{content:o})})})}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(mt,{text:o}),e.jsx(_,{onClick:()=>i(""),variant:"outline",className:"border-border text-muted-foreground hover:bg-muted",children:"Generate New"}),x&&e.jsx(_,{onClick:A,className:"bg-blue-600 hover:bg-blue-700",children:"Send to Chat"}),e.jsx(_,{onClick:w,className:"bg-indigo-600 hover:bg-indigo-700",children:"Close"})]})]}):e.jsxs(e.Fragment,{children:[l&&e.jsx(te,{className:"bg-blue-900/20 border-blue-500/20",children:e.jsx(ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-200",children:[e.jsx(Rt,{className:"w-4 h-4"}),e.jsxs("span",{children:["Study guide adapted for age ",l," (",Lt(l),")"]})]})})}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Study Topic *"}),e.jsx(_e,{value:d,onChange:P=>n(P.target.value),placeholder:"Enter the topic you want to study...",className:"bg-muted border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-muted-foreground mb-2 flex items-center",children:["Study Level",e.jsx(Ar,{show:f&&!!r})]}),e.jsxs(De,{value:r,onValueChange:v,children:[e.jsx(Le,{className:"bg-muted border-border text-foreground",children:e.jsx($e,{placeholder:"Select study level"})}),e.jsxs(Me,{className:"bg-muted border-border",children:[e.jsx(Z,{value:"beginner",children:"Beginner"}),e.jsx(Z,{value:"intermediate",children:"Intermediate"}),e.jsx(Z,{value:"advanced",children:"Advanced"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Additional Notes (Optional)"}),e.jsx(rt,{value:j,onChange:P=>b(P.target.value),placeholder:"Any specific areas you want to focus on...",className:"bg-muted border-border text-foreground",rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(_,{onClick:w,variant:"outline",className:"border-border text-muted-foreground hover:bg-muted",children:"Cancel"}),e.jsx(_,{onClick:N,disabled:g||!d.trim(),className:"bg-indigo-600 hover:bg-indigo-700",children:g?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating..."]}):"Generate Study Guide"})]})]})})]})})},Rn=({open:s,onOpenChange:a,classroomId:m,onSendToChat:x,chatMessages:p=[]})=>{const{toast:l}=we(),{spendAICredit:h,canUseAI:u}=wt(),{isParent:d,isYouthLeader:n,isStudent:r}=Xe(),{saveAid:v,refetch:j}=ct(),{age:b}=jt(),[g,c]=t.useState("input"),[o,i]=t.useState(""),[f,y]=t.useState(""),[N,A]=t.useState(""),[w,P]=t.useState(""),[k,I]=t.useState(!1),[T,M]=t.useState(""),[G,D]=t.useState(!1),[Y,de]=t.useState(null),[pe,xe]=t.useState(!1),[ce,oe]=t.useState(null),[ae,K]=t.useState([]),[O,W]=t.useState(!1),[B,F]=t.useState([]),[Q,S]=t.useState(!1),[z,V]=t.useState(!1),q=t.useMemo(()=>Ut(p||[]),[p]),C=t.useCallback(async()=>
68{if(!q.canAnalyze){console.log("Stewart analysis skipped:",q.userFriendlyReason);return}I(!0);try{const{data:$,error:U}=await E.functions.invoke("stewart-study-guide-analyzer",{body:{chatMessages:p.slice(-20),context:{classroomId:m},studentProfile:{age:b||null,student_name:"Student",interests:[]}}});if(U)throw U;console.log("Stewart analysis:",$),de($),$&&$.confidence>=70?(console.log("Stewart analysis: Auto-populating with high confidence:",$.confidence),i($.suggestedTopic||o),y($.suggestedGradeLevel||f),A($.suggestedStudyLevel||N),P($.suggestedNotes||w),l({title:"Fields Auto-Populated!",description:`Stewart analyzed your chat and filled in the study guide settings with ${$.confidence}% confidence.`})):!f&&!N&&(console.log("Stewart analysis: Using role-aware defaults - isStudent:",r(),"age:",b),y(r()?Lt(b):"College"),A(r()?vs(b):"advanced"))}catch($){console.error("Error analyzing with Stewart:",$),l({title:"Analysis Error",description:"Could not analyze chat context. Please fill fields manually.",variant:"destructive"})}finally{I(!1),xe(!0)}},[p,m,o,f,N,w,l]);t.useEffect(()=>{const $=(p?.length??0)>0||!!m;s&&$&&!pe&&!k&&(console.log("Stewart analysis: Starting analysis..."),C())},[s,p,m,pe,k,C]);const H=()=>{xe(!1),C()},ue=async()=>{if(!o.trim()){l({title:"Topic Required",description:"Please enter a topic for your study guide.",variant:"destructive"});return}if(!u){l({title:"Credits Required",description:"You need credits to generate study guides.",variant:"destructive"});return}if(await h("study_guide_outline","Generate study guide outline")){W(!0);try{const{data:U,error:se}=await E.functions.invoke("generate-study-guide-stewart",{body:{topic:o,gradeLevel:f,studyLevel:N,additionalNotes:w,step:"outline",template:"comprehensive"}});if(se)throw se;const ee={title:U.title||`Study Guide: ${o}`,sections:U.sections||[],studyLevel:`${f} - ${N}`,additionalNotes:w};oe(ee),K(ee.sections),c("outline"),l({title:"Outline Generated!",description:"Review and edit your study guide outline."})}catch(U){console.error("Error generating outline:",U),l({title:"Generation Failed",description:"Failed to generate study guide outline. Please try again.",variant:"destructive"})}finally{W(!1)}}},ve=async()=>{if(!(!ce||ae.length===0||!await h("study_guide_full","Generate full study guide",1))){S(!0),c("generate");try{const{data:U,error:se}=await E.functions.invoke("generate-study-guide-stewart",{body:{topic:o,studyLevel:N,additionalNotes:w,sections:ae,step:"full_guide",template:"comprehensive"}});if(se)throw se;const ee=U.sections.map(J=>({title:J.title,content:J.content}));F(ee),V(!0),l({title:"Study Guide Complete!",description:"Your personalized study guide is ready."})}catch(U){console.error("Error generating full guide:",U),l({title:"Generation Failed",description:"Failed to generate study guide. Please try again.",variant:"destructive"})}finally{S(!1)}}},re=async()=>{if(!(!ce||B.length===0))try{const $=B.map(U=>({title:U.title,content:U.content.substring(0,5e3)}));await v({user_id:"",title:ce.title,content_type:"study_guide",content:{topic:o,studyLevel:N,additionalNotes:w,sections:$},metadata:{generatedAt:new Date().toISOString(),classroomId:m,sectionCount:B.length},tags:[o,N,m].filter(Boolean),is_favorite:!1}),setTimeout(()=>{j()},100),l({title:"Saved Successfully!",description:"Study guide saved to your learning aids collection."})}catch($){console.error("Error saving to learning aids:",$),l({title:"Save Failed",description:"Failed to save study guide. Please try again.",variant:"destructive"})}},le=()=>{if(!B.length||!x)return;const $=B.map(U=>`**${U.title}**
69${U.content}`).join(`
70
71`);x(`Study Guide Generated:
72
73${$}`),l({title:"Sent to Chat",description:"Study guide has been sent to the classroom chat."}),a(!1)},Ne=()=>{c("input"),i(""),y(""),A(""),P(""),oe(null),K([]),F([]),V(!1),de(null),xe(!1),a(!1)},ze=()=>{K([...ae,""])},Re=($,U)=>{const se=[...ae];se[$]=U,K(se)},R=$=>{const U=ae.filter((se,ee)=>ee!==$);K(U)};return e.jsx(qe,{open:s,onOpenChange:Ne,children:e.jsxs(Oe,{className:"max-w-5xl max-h-[90vh] bg-background text-foreground border-border",children:[e.jsx(Be,{children:e.jsxs(Ve,{className:"text-xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Qe,{className:"w-6 h-6 text-indigo-500"}),"Enhanced Study Guide Generator",e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${g==="input"?"bg-indigo-500":"bg-gray-600"}`}),e.jsx("div",{className:`w-3 h-3 rounded-full ${g==="outline"?"bg-indigo-500":"bg-gray-600"}`}),e.jsx("div",{className:`w-3 h-3 rounded-full ${g==="generate"?"bg-indigo-500":"bg-gray-600"}`})]})]})}),e.jsx(Ze,{className:"max-h-[75vh]",children:e.jsxs("div",{className:"space-y-6",children:[g==="input"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(te,{className:"bg-muted border-border",children:[e.jsx(Ee,{children:e.jsx(Ae,{className:"text-foreground",children:"Step 1: Study Guide Setup"})}),e.jsxs(ie,{className:"space-y-4",children:[!q.canAnalyze&&e.jsx(js,{messageCount:q.messageCount,minimumNeeded:q.minimumNeeded,toolName:"Study Guide",canFillManually:!0}),k&&e.jsx(Nt,{isVisible:!0}),Y&&!k&&e.jsxs("div",{className:"bg-primary/10 border border-primary/20 rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-primary"}),e.jsx("h4",{className:"font-semibold text-primary",children:"Stewart's Recommendation"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(me,{variant:"secondary",className:"bg-primary/20 text-primary border-primary/30",children:[Y.confidence,"% confident"]}),Y.confidence>=70&&e.jsx(me,{variant:"outline",className:"bg-green-900/20 text-green-400 border-green-600",children:"Auto-populated"})]})]}),e.jsxs(_,{size:"sm",variant:"outline",onClick:H,className:"border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(Gt,{className:"w-3 h-3 mr-1"}),"Analyze Again"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"Analysis:"})," ",Y.reasoning]}),Y.suggestedSections&&e.jsxs("div",{className:"text-sm",children:[e.jsx("strong",{className:"text-primary",children:"Suggested sections:"}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:Y.suggestedSections.map(($,U)=>e.jsx(me,{variant:"outline",className:"text-xs",children:$},U))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Study Topic *"}),e.jsx(_e,{value:o,onChange:$=>i($.target.value),placeholder:"Enter the topic you want to study...",className:"bg-gray-600 border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Grade Level"}),e.jsxs(De,{value:f,onValueChange:y,children:[e.jsx(Le,{className:"bg-gray-600 border-border text-foreground",children:e.jsx($e,{placeholder:"Select grade level"})}),e.jsxs(Me,{className:"bg-muted border-border",children:[e.jsx(Z,{value:"6th-grade",children:"6th Grade"}),e.jsx(Z,{value:"7th-grade",children:"7th Grade"}),e.jsx(Z,{value:"8th-grade",children:"8th Grade"}),e.jsx(Z,{value:"9th-grade",children:"9th Grade"}),e.jsx(Z,{value:"10th-grade",children:"10th Grade"}),e.jsx(Z,{value:"11th-grade",children:"11th Grade"}),e.jsx(Z,{value:"12th-grade",children:"12th Grade"}),e.jsx(Z,{value:"adult",children:"Adult"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Study Level"}),e.jsxs(De,{value:N,onValueChange:A,children:[e.jsx(Le,{className:"bg-gray-600 border-border text-foreground",children:e.jsx($e,{placeholder:"Select study level"})}),e.jsxs(Me,{className:"bg-muted border-border",children:[e.jsx(Z,{value:"beginner",children:"Beginner"}),e.jsx(Z,{value:"intermediate",children:"Intermediate"}),e.jsx(Z,{value:"advanced",children:"Advanced"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Additional Notes (Optional)"}),e.jsx(rt,{value:w,onChange:$=>P($.target.value),placeholder:"Any specific areas you want to focus on...",className:"bg-gray-600 border-border text-foreground",rows:3})]})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(_,{onClick:ue,disabled:O||!o.trim(),className:"bg-indigo-600 hover:bg-indigo-700",children:O?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating Outline..."]}
73):"Generate Outline"})})]}),g==="outline"&&ce&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(te,{className:"bg-muted border-border",children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"text-foreground flex items-center gap-2",children:[e.jsx(Zs,{className:"w-5 h-5"}),"Step 2: Edit Your Study Guide Outline"]})}),e.jsxs(ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Study Guide Title"}),e.jsx(_e,{value:ce.title,onChange:$=>oe({...ce,title:$.target.value}),className:"bg-gray-600 border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-muted-foreground mb-2",children:"Sections"}),e.jsxs("div",{className:"space-y-2",children:[ae.map(($,U)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{value:$,onChange:se=>Re(U,se.target.value),placeholder:`Section ${U+1} title...`,className:"bg-gray-600 border-border text-foreground flex-1"}),e.jsx(_,{variant:"outline",size:"sm",onClick:()=>R(U),className:"border-border text-muted-foreground hover:bg-muted",children:"Remove"})]},U)),e.jsx(_,{variant:"outline",onClick:ze,className:"border-border text-muted-foreground hover:bg-muted",children:"Add Section"})]})]})]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx(_,{variant:"outline",onClick:()=>c("input"),className:"border-border text-muted-foreground hover:bg-muted",children:"Back to Setup"}),e.jsx(_,{onClick:ve,disabled:ae.length===0,className:"bg-indigo-600 hover:bg-indigo-700",children:"Generate Full Study Guide"})]})]}),g==="generate"&&e.jsxs("div",{className:"space-y-4",children:[Q&&!z&&e.jsx(te,{className:"bg-muted border-border",children:e.jsx(ie,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ke,{className:"w-8 h-8 animate-spin mx-auto mb-4 text-indigo-500"}),e.jsx("p",{className:"text-foreground",children:"Generating your study guide..."}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"This may take a moment"})]})})}),B.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Your Study Guide"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{text:B.map($=>`${$.title}
74
75${$.content}`).join(`
76
77`)}),d()||n()?e.jsxs(_,{onClick:re,variant:"outline",size:"sm",className:"border-border text-muted-foreground hover:bg-muted",children:[e.jsx(We,{className:"w-4 h-4 mr-2"}),"Save to Collections"]}):e.jsxs(_,{onClick:re,variant:"outline",size:"sm",className:"border-border text-muted-foreground hover:bg-muted",children:[e.jsx(We,{className:"w-4 h-4 mr-2"}),"Save to My Learning Aids"]})]})]}),B.map(($,U)=>e.jsxs(te,{className:"bg-muted border-border",children:[e.jsx(Ee,{children:e.jsx(Ae,{className:"text-foreground",children:$.title})}),e.jsx(ie,{className:"space-y-4",children:e.jsx("div",{className:"prose prose-sm max-w-none prose-invert",children:e.jsx(st,{content:$.content})})})]},U)),e.jsxs("div",{className:"flex justify-between items-center pt-4",children:[e.jsx(_,{variant:"outline",onClick:()=>c("outline"),className:"border-border text-muted-foreground hover:bg-muted",children:"Edit Outline"}),e.jsxs("div",{className:"flex gap-2",children:[x&&e.jsxs(_,{onClick:le,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Send to Chat"]}),e.jsxs(_,{onClick:Ne,className:"bg-indigo-600 hover:bg-indigo-700",children:[e.jsx(ms,{className:"w-4 h-4 mr-2"}),"Done"]})]})]})]})]})]})})]})})},Gn=s=>{if(s.content_type==="study_guide"&&s.content?.type==="flashcards")return"🎴";switch(s.content_type){case"study_guide":return"📚";case"interactive_quiz":return"🧠";case"generate_table":return"📊";default:return"📝"}},qn=({open:s,onOpenChange:a,aid:m})=>{const{toast:x}=we(),[p,l]=t.useState([]),[h,u]=t.useState(""),[d,n]=t.useState(!1);t.useEffect(()=>{(async()=>{if(s)try{const{data:j}=await E.auth.getUser();if(!j.user){l([]);return}const{data:b,error:g}=await E.from("content_collections").select("id, title").eq("user_id",j.user.id).eq("is_active",!0).eq("is_global",!1).order("title",{ascending:!0});if(g){console.error("Failed to fetch collections:",g),x({title:"Error",description:"Failed to load your collections",variant:"destructive"}),l([]);return}const c=(b||[]).filter(o=>{const i=o.title||"";return!i.startsWith("Flashcards:")&&!/flashcard/i.test(i)});l(c)}catch(j){console.error("Error fetching collections:",j),l([])}})()},[s,x]);const r=async()=>
77{if(h){n(!0);try{const{data:v}=await E.auth.getUser(),j=v?.user?.id,{data:b}=await E.from("content_collections").select("user_id").eq("id",h).maybeSingle();if(!j||!b||b.user_id!==j){x({title:"Not allowed",description:"You can only add items to your own collections.",variant:"destructive"}),n(!1);return}const g=`learning_aid_${m.id}`,{data:c}=await E.from("collection_items").select("id").eq("collection_id",h).eq("content_type","gadget").eq("content_id",g).maybeSingle();if(c){x({title:"Already Added",description:"This learning aid is already in the selected collection",variant:"default"}),n(!1);return}const{data:o}=await E.from("collection_items").select("order_index").eq("collection_id",h).order("order_index",{ascending:!1}).limit(1).maybeSingle(),i=(o?.order_index||0)+1,{error:f}=await E.from("collection_items").insert({collection_id:h,content_id:g,content_type:"gadget",order_index:i,is_required:!1,estimated_time_minutes:15,gadget_metadata:{gadget_type:"learning_aid",is_learning_aid:!0,learning_aid_id:m.id,title:m.title,content_type:m.content_type,content:m.content,icon:Gn(m),color:"#8b5cf6",tags:m.tags||[]}});if(f)throw console.error("Database error adding learning aid:",f),f;x({title:"Success",description:`${m.title} added to collection successfully`}),a(!1),u("")}catch(v){console.error("Error adding learning aid to collection:",v),x({title:"Error",description:v?.message||"Failed to add learning aid to collection",variant:"destructive"})}finally{n(!1)}}};return e.jsx(qe,{open:s,onOpenChange:a,children:e.jsxs(Oe,{children:[e.jsx(Be,{children:e.jsxs(Ve,{children:['Add "',m.title,'" to Collection']})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(De,{value:h,onValueChange:u,children:[e.jsx(Le,{children:e.jsx($e,{placeholder:"Choose a collection"})}),e.jsx(Me,{children:p.length===0?e.jsx("div",{className:"px-2 py-1.5 text-sm text-muted-foreground",children:"No collections found"}):p.map(v=>e.jsx(Z,{value:v.id,children:v.title||"Untitled Collection"},v.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(_,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(_,{onClick:r,disabled:!h||d,children:d?"Adding...":"Add"})]})]})]})})},Gs=s=>{switch(s){case"study_guide":return Qe;case"interactive_quiz":return nt;case"generate_table":return hs;default:return Qe}},qs=s=>{if(s.content_type==="study_guide"&&s.content?.type==="flashcards")return"Flashcards";switch(s.content_type){case"study_guide":return"Study Guide";case"interactive_quiz":return"Interactive Quiz";case"generate_table":return"Data Table";default:return s.content_type}},Os=s=>{switch(s){case"study_guide":return"bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200";case"interactive_quiz":return"bg-violet-100 text-violet-800 dark:bg-violet-900 dark:text-violet-200";case"generate_table":return"bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200";default:return"bg-gray-100 text-gray-800 dark:bg-background dark:text-foreground"}},On=({open:s,onOpenChange:a})=>{const{aids:m,loading:x,searchTerm:p,setSearchTerm:l,selectedType:h,setSelectedType:u,deleteAid:d,toggleFavorite:n}=ct(),[r,v]=t.useState(null),[j,b]=t.useState(new Set),[g,c]=t.useState({}),[o,i]=t.useState(!1),[f,y]=t.useState(null),{toast:N}=we(),A=T=>{v(T)},w=()=>{v(null),c({}),i(!1)},P=()=>{i(!0)},k=()=>{if(!r||r.content_type!=="interactive_quiz")return 0;const T=r.content.questions||[];let M=0;return T.forEach((G,D)=>{g[D]===G.correctAnswer&&M++}),Math.round(M/T.length*100)},I=async T=>{if(!r||r.content_type!=="study_guide")return;const M=r.content.sections[T];if(M.imagePrompt){b(G=>new Set([...G,T]));try{const{data:G,error:D}=await E.functions.invoke("generate-images-openai",{body:{prompt:M.imagePrompt,topic:r.content.topic||"Educational content"}});if(!D&&G?.image)v(Y=>{if(!Y)return Y;const de=[...Y.content.sections];return de[T]={...de[T],image:G.image},{...Y,content:{...Y.content,sections:de}}}),N({title:"Image Regenerated!",description:"The image has been updated successfully."});else throw new Error("Failed to generate image")}catch(G){console.error("Error regenerating image:",G),N({title:"Image Generation Failed",description:"Failed to regenerate image. Please try again.",variant:"destructive"})}finally{b(G=>{const D=new Set(G);return D.delete(T),D})}}};return r?e.jsx(qe,{open:s,onOpenChange:a,children:e.jsxs(Oe,{className:"max-w-4xl max-h-[90vh]",children:[e.jsx(Be,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ve,{className:"flex items-center gap-2",children:[lt.createElement(Gs(r.content_type),{className:"w-5 h-5"}),r.title]}),e.jsx(_,{variant:"outline",onClick:w,children:"Back to Library"})]})}),e.jsx(Ze,{className:"max-h-[70vh]",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(me,{className:Os(r.content_type),children:qs(r)}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Created ",Ms(new Date(r.created_at))," ago"]})]}),r.content_type==="study_guide"&&e.jsx("div",{className:"space-y-6",children:r.content.type==="flashcards"&&r.content.cards?e.jsxs(e.Fragment,{children:[e.jsx(mr,{cards:r.content.cards}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"All Cards (Printable)"}),e.jsx(te,{className:"bg-card border",children:e.jsx(ie,{className:"pt-6",children:e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert",children:e.jsx(st,{content:r.content.guide||""})})})}),e.jsx(mt,{text:r.content.guide||"",className:"w-full mt-4"})]})]}):r.content.sections?.map((T,M)=>e.jsxs(te,{className:"bg-card border",children:[e.jsx(Ee,{children:e.jsx(Ae,{className:"text-lg",children:T.title})}),e.jsxs(ie,{className:"space-y-4",children:[e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert whitespace-pre-wrap",children:T.content}),(T.image||j.has(M))&&e.jsx("div",{className:"mt-4",children:j.has(M)?e.jsx("div",{className:"flex items-center justify-center p-8 bg-muted rounded-lg",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-6 h-6 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Regenerating image..."})]})}):T.image?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:T.image,alt:T.title,className:"max-w-md rounded-lg border"}),T.imagePrompt&&e.jsxs(_,{onClick:()=>I(M),variant:"outline",size:"sm",className:"absolute top-2 right-2",children:[e.jsx(Gt,{className:"w-3 h-3 mr-1"}),"Regenerate"]})]}):null})]})]},M))||e.jsx("div",{className:"space-y-4",children:r.content.guide?e.jsxs(e.Fragment,{children:[e.jsx(te,{className:"bg-card border",children:e.jsx(ie,{className:"pt-6",children:e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert",children:e.jsx(st,{content:r.content.guide})})})}),e.jsx(mt,{text:r.content.guide,className:"w-full"})]}):r.content.text?e.jsx(te,{className:"bg-card border",children:e.jsx(ie,{className:"pt-6",children:e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert whitespace-pre-wrap",children:r.content.text})})}):e.jsx(te,{className:"bg-card border",children:e.jsx(ie,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground",children:"No content available"})})})})}),r.content_type==="interactive_quiz"&&e.jsxs(qt,{defaultValue:"take-quiz",className:"space-y-4",children:[e.jsxs(Ot,{className:"bg-background/80 border border-border shadow-lg p-2 gap-2",children:[e.jsx(Ye,{value:"take-quiz",className:"px-6 py-3 rounded-t-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm hover:bg-muted/60 transition-all",children:"Take Quiz"}),e.jsx(Ye,{value:"answer-key",className:"px-6 py-3 rounded-t-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm hover:bg-muted/60 transition-all",children:"Answer Key"})]}),e.jsxs(Ke,{value:"take-quiz",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 flex-wrap",children:[r.content.difficulty&&e.jsxs(me,{variant:"secondary",children:[r.content.difficulty," Difficulty"]}),r.content.age&&e.jsxs(me,{variant:"outline",children:["Age: ",r.content.age]}),r.content.gradeLevel&&e.jsxs(me,{variant:"outline",children:["Grade: ",r.content.gradeLevel]})]}),o&&e.jsx(te,{className:"bg-primary/10 border-primary/20",children:e.jsx(ie,{className:"pt-6",children:e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"text-3xl font-bold mb-2",children:[k(),"%"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Score"})]})})}),r.content.questions?.map((T,M)=>e.jsxs(te,{children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"text-base",children:["Question ",M+1]})}),e.jsxs(ie,{children:[e.jsx("p",{className:"mb-3 font-medium",children:T.question}),e.jsx(bt,{value:g[M]?.toString(),onValueChange:G=>c(D=>({...D,[M]:parseInt(G)})),disabled:o,children:e.jsx("div",{className:"space-y-2",children:T.options?.map((G,D)=>e.jsxs("div",{className:`flex items-center space-x-2 p-3 rounded border ${o?D===T.correctAnswer?"bg-green-100 border-green-300 dark:bg-green-900 dark:border-green-700":g[M]===D?"bg-red-100 border-red-300 dark:bg-red-900 dark:border-red-700":"bg-gray-50 border-gray-200 dark:bg-muted dark:border-border":"bg-gray-50 border-gray-200 dark:bg-muted dark:border-border hover:bg-gray-100 dark:hover:bg-gray-750"}`,children:[e.jsx(et,{value:D.toString(),id:`q${M}-opt${D}`}),e.jsxs(Te,{htmlFor:`q${M}-opt${D}`,className:"flex-1 cursor-pointer",children:[G,o&&D===T.correctAnswer&&" ✓"]})]},D))})}),o&&T.explanation&&e.jsxs("div",{className:"mt-4 p-3 bg-blue-50 dark:bg-blue-950 rounded border border-blue-200 dark:border-blue-800",children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Explanation:"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T.explanation})]})]})]},M))||e.jsx("p",{children:"No quiz questions available"}),!o&&r.content.questions?.length>0&&e.jsx(_,{onClick:P,className:"w-full",children:"Submit Quiz"})]}),e.jsxs(Ke,{value:"answer-key",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 flex-wrap",children:[r.content.difficulty&&e.jsxs(me,{variant:"secondary",children:[r.content.difficulty," Difficulty"]}),r.content.age&&e.jsxs(me,{variant:"outline",children:["Age: ",r.content.age]}),r.content.gradeLevel&&e.jsxs(me,{variant:"outline",children:["Grade: ",r.content.gradeLevel]})]}),r.content.questions?.map((T,M)=>e.jsxs(te,{children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"text-base",children:["Question ",M+1]})}),e.jsxs(ie,{children:[e.jsx("p",{className:"mb-3 font-medium",children:T.question}),e.jsx("div",{className:"space-y-2",children:T.options?.map((G,D)=>e.jsxs("div",{className:`p-2 rounded border ${D===T.correctAnswer?"bg-green-100 border-green-300 dark:bg-green-900 dark:border-green-700":"bg-gray-50 border-gray-200 dark:bg-muted dark:border-border"}`,children:[G," ",D===T.correctAnswer&&"✓"]},D))}),T.explanation&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 italic",children:T.explanation})]})]},M))||e.jsx("p",{children:"No quiz questions available"})]})]}),r.content_type==="generate_table"&&e.jsx("div",{className:"overflow-x-auto",children:r.content.table?e.jsxs("table",{className:"w-full border-collapse border border-gray-300 dark:border-border",children:[e.jsx("thead",{children:e.jsx("tr",{className:"bg-gray-100 dark:bg-muted",children:r.content.table.headers?.map((T,M)=>e.jsx("th",{className:"border border-gray-300 dark:border-border p-2 text-left",children:T},M))})}),e.jsx("tbody",{children:r.content.table.rows?.map((T,M)=>e.jsx("tr",{className:"even:bg-gray-50 dark:even:bg-background",children:T.map((G,D)=>e.jsx("td",{className:"border border-gray-300 dark:border-border p-2",children:G},D))},M))})]}):e.jsx("p",{children:"No table data available"})})]})})]})}):e.jsxs(qe,{open:s,onOpenChange:a,children:[e.jsxs(Oe,{className:"max-w-5xl max-h-[90vh]",children:[e.jsx(Be,{children:e.jsxs(Ve,{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-r from-purple-500 to-orange-500 flex items-center justify-center",children:e.jsx(Qe,{className:"w-4 h-4 text-foreground"})}),"My Learning Aids"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4 items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(za,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4"}),e.jsx(_e,{placeholder:"Search learning aids...",value:p,onChange:T=>l(T.target.value),className:"pl-10"})]}),e.jsxs(De,{value:h,onValueChange:u,children:[e.jsx(Le,{className:"w-48",children:e.jsx($e,{placeholder:"Filter by type"})}),e.jsxs(Me,{children:[e.jsx(Z,{value:"all",children:"All Types"}),e.jsx(Z,{value:"study_guide",children:"Study Guides"}),e.jsx(Z,{value:"interactive_quiz",children:"Interactive Quizzes"}),e.jsx(Z,{value:"generate_table",children:"Data Tables"})]})]})]}),e.jsx(Ze,{className:"h-[500px]",children:x?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):m.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Qe,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No learning aids found."}),e.jsx("p",{className:"text-sm",children:"Create study guides, quizzes, and tables to see them here!"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:m.map(T=>{const M=Gs(T.content_type);return e.jsxs(te,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Ee,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{className:"w-4 h-4 text-muted-foreground"}),e.jsx(Ae,{className:"text-sm font-medium line-clamp-1",children:T.title})]}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>n(T.id),className:"h-8 w-8 p-0",children:e.jsx(Xs,{className:`w-4 h-4 ${T.is_favorite?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(me,{variant:"secondary",className:Os(T.content_type),children:qs(T)})})]}),e.jsx(ie,{className:"pt-0",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Created ",Ms(new Date(T.created_at))," ago"]}),T.tags.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[T.tags.slice(0,3).map((G,D)=>e.jsx(me,{variant:"outline",className:"text-xs",children:G},D)),T.tags.length>3&&e.jsxs(me,{variant:"outline",className:"text-xs",children:["+",T.tags.length-3]})]}),e.jsxs("div",{className:"flex justify-between items-center gap-2",children:[e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>A(T),className:"flex items-center gap-1",children:[e.jsx(Ra,{className:"w-3 h-3"}),"View"]}
77),e.jsx(_,{variant:"secondary",size:"sm",onClick:()=>y(T),className:"flex items-center gap-1",children:e.jsx(Ga,{className:"w-3 h-3"})}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>d(T.id),className:"flex items-center gap-1 text-destructive hover:text-destructive",children:e.jsx(yt,{className:"w-3 h-3"})})]})]})})]},T.id)})})})]})]}),f&&e.jsx(qn,{open:!!f,onOpenChange:T=>!T&&y(null),aid:f})]})};class Un{async generateQuizPrompt(a,m){const x=a.difficulty==="Mixed"?"Include a mix of Easy, Medium, and Hard questions":a.difficulty?`Focus on ${a.difficulty} level questions`:"Include questions appropriate for the subject level",p=a.topics&&a.topics.length>0?`Focus on these specific topics: ${a.topics.join(", ")}`:"Cover a broad range of topics within your subject area";return`
78You are Collette, an expert educational assessment specialist with expertise in creating personalized quizzes that adapt to recent learning context.
79
80Please generate ${a.questionCount} multiple-choice quiz questions for students learning ${m.specialty}.
81
82IMPORTANT: If provided with recent chat messages or learning context, base your questions on those specific topics and concepts being discussed. Make the questions directly relevant to what the student has been learning about recently.
83
84Requirements:
85- ${x}
86- ${p}
87- Each question should have exactly 4 answer options (A, B, C, D)
88- Only one correct answer per question
89- Include a detailed explanation for each correct answer
90- Questions should be educational and appropriate for the subject level
91- Avoid ambiguous or trick questions
92- Make questions practical and relevant to real-world applications when possible
93- If chat context is provided, create questions that build on those specific discussions and topics
94- Ensure questions test understanding of recently discussed concepts
95
96Please respond with a JSON array in this exact format:
97[
98  {
99    "question": "Question text here?",
100    "options": ["Option A", "Option B", "Option C", "Option D"],
101    "correctAnswer": 0,
102    "explanation": "Detailed explanation of why this answer is correct and why others are wrong.",
103    "difficulty": "Easy|Medium|Hard",
104    "category": "Specific topic or category within ${m.specialty}"
105  }
106]
107
108Ensure the JSON is valid and properly formatted. Do not include any text before or after the JSON array.
109`}async generateQuiz(a){try{console.log("Generating quiz with Collette AI via edge function for classroom:",a.classroomId);const{data:{session:m}}=await E.auth.getSession(),{data:x,error:p}=await E.functions.invoke("openai-assistant-quiz",{headers:{Authorization:`Bearer ${m?.access_token||""}`},body:{classroomId:a.classroomId,questionCount:a.questionCount,difficulty:a.difficulty,topics:a.topics,chatMessages:a.chatMessages,age:a.age,gradeLevel:a.gradeLevel}});if(p)throw console.error("Edge function error:",p),new Error(`Quiz generation failed: ${p.message}`);if(!x||!x.questions)throw new Error("No questions returned from quiz generation service");return console.log(`Successfully generated ${x.questions.length} quiz questions`),x.questions.slice(0,a.questionCount)}catch(m){throw console.error("Error generating dynamic quiz:",m),m}}async generateQuizForClassroom(a,m=5,x){return this.generateQuiz({classroomId:a,questionCount:m,difficulty:x})}}const Bn=new Un,Vn=(s,a)=>{const[m,x]=t.useState([]),[p,l]=t.useState(!1),[h,u]=t.useState(null),{toast:d}=we(),n=t.useCallback(async(v=5,j="Mixed",b,g,c)=>{l(!0),u(null);try{const o=await Bn.generateQuiz({classroomId:s,questionCount:v,difficulty:j,topics:b,chatMessages:a,age:g,gradeLevel:c});return x(o),o}catch(o){const i=o instanceof Error?o.message:"Failed to generate quiz";throw u(i),d({title:"Quiz Generation Failed",description:i,variant:"destructive"}),o}finally{l(!1)}},[s,a,d]),r=t.useCallback(()=>{x([]),u(null)},[]);return{questions:m,isGenerating:p,error:h,generateQuiz:n,clearQuiz:r}},Hn=({open:s,onOpenChange:a,classroomId:m,onTokensEarned:x,onSendToChat:p,chatMessages:l=[]})=>{const{toast:h}=we(),{spendAICredit:u,canUseAI:d}=wt(),{questions:n,isGenerating:r,generateQuiz:v,clearQuiz:j}=Vn(m,l),{studentProfile:b}=ps(),{isParent:g,isYouthLeader:c,isDeveloper:o}=Xe(),{saveAid:i}=ct(),[f,y]=t.useState(0),[N,A]=t.useState(""),[w,P]=t.useState({}),[k,I]=t.useState(!1),[T,M]=t.useState(!1),[G,D]=t.useState(!1),[Y,de]=t.useState(0),[pe,xe]=t.useState(0),[ce,oe]=t.useState(new Set),[ae,K]=t.useState(!1),[O,W]=t.useState(""),[B,F]=t.useState(""),[Q,S]=t.useState(!1),[z,V]=t.useState(null),[q,C]=t.useState(""),[H,ue]=t.useState(""),[ve,re]=t.useState(!1),le=t.useMemo(()=>Ut(l||[]),[l]),Ne=t.useCallback(()=>g()||c()||o()?"Adult":b?.age?b.age.toString():"",[g,c,o,b?.age]),ze=t.useCallback(()=>
109{if(g()||c()||o())return"N/A";if(b?.age){const fe=b.age;if(fe>=6&&fe<=18){const he=fe-5;if(he<=12)return`${he}${he===1?"st":he===2?"nd":he===3?"rd":"th"} Grade`}}return""},[g,c,o,b?.age]);t.useEffect(()=>{const fe=Ne(),he=ze();fe&&!q&&C(fe),he&&!H&&ue(he)},[Ne,ze,q,H]);const Re=fe=>{const he=fe.toLowerCase();return he.includes("math")||he.includes("science")?Math.floor(Math.random()*6)+15:he.includes("literature")||he.includes("social")?Math.floor(Math.random()*6)+10:Math.floor(Math.random()*7)+12},R=t.useCallback(async()=>{if(!le.canAnalyze){console.log("🎯 Collette analysis skipped:",le.userFriendlyReason);return}if(console.log("🎯 Starting Collette analysis with",l.length,"messages"),!d){h({title:"No Credits Available",description:"You need credits to use AI features.",variant:"destructive"});return}if(await u("Quiz Analyzer","Analyzing context for quiz")){K(!0);try{const{data:he,error:Fe}=await E.functions.invoke("collette-quiz-analyzer",{body:{chatMessages:l.slice(-15),context:{classroomId:m},studentProfile:{age:16}}});if(console.log("🎯 Collette response:",{data:he,error:Fe}),Fe)throw Fe;he?.success&&he?.confidence>=60?(console.log("🎯 Collette analysis successful, confidence:",he.confidence),V({confidence:he.confidence,reasoning:he.reasoning,suggestedTopic:he.suggestedTopic,suggestedDifficulty:he.suggestedDifficulty,questionCount:he.questionCount}),W(he.suggestedTopic),F(he.suggestedDifficulty),S(!0)):console.log("🎯 Collette confidence too low or not successful:",he?.confidence)}catch(he){console.error("🎯 Error analyzing chat context:",he)}finally{K(!1)}}},[l,m]);t.useEffect(()=>{console.log("🎯 Quiz modal useEffect triggered:",{open:s,messageCount:l.length,classroomId:m}),s&&l.length>0&&(console.log("🎯 Calling analyzeChatContext"),R())},[s,l.length,m,R]);const $=()=>{if(!N){h({title:"Answer Required",description:"Please select an answer before continuing",variant:"destructive"});return}const fe=n[f],he=N===fe.correctAnswer.toString();P(Fe=>({...Fe,[fe.id]:N})),M(he),I(!0),he&&(xe(Fe=>Fe+1),de(Fe=>Fe+1),x?.(1),h({title:"Correct! 🎉",description:"You earned 1 token!"}))},U=()=>{oe(fe=>new Set(fe).add(f)),f<n.length-1?(y(fe=>
109fe+1),A(""),I(!1)):D(!0),h({title:"Question Skipped",description:"You can review skipped questions later."})},se=()=>{f<n.length-1?(y(fe=>fe+1),A(""),I(!1)):D(!0)},ee=async(fe="Mixed")=>{if(!d){h({title:"No Credits Available",description:"You need credits to use AI features.",variant:"destructive"});return}if(!await u("Quiz Generator","Generating quiz questions"))return;const Fe=z?.questionCount||Re(m);await v(Fe,fe,O?[O]:void 0,q,H)},J=async()=>{if(n.length!==0){re(!0);try{const{data:{user:fe}}=await E.auth.getUser();if(!fe)throw new Error("Not authenticated");await i({user_id:fe.id,title:`Interactive Quiz - ${O||m}`,content_type:"interactive_quiz",content:{questions:n,topic:O||m,difficulty:B||"Mixed",age:q,gradeLevel:H},metadata:{questionCount:n.length,classroomId:m,generatedAt:new Date().toISOString()},tags:[m,"quiz",B||"mixed"].filter(Boolean),is_favorite:!1}),h({title:"Saved Successfully!",description:"Quiz has been saved to your Learning Aids."})}catch(fe){console.error("Error saving quiz:",fe),h({title:"Error",description:"Failed to save quiz to Learning Aids.",variant:"destructive"})}finally{re(!1)}}},ge=()=>{j(),y(0),A(""),P({}),I(!1),D(!1),de(0),xe(0),oe(new Set),W(""),F(""),S(!1)},je=()=>{j(),y(0),A(""),P({}),I(!1),D(!1),de(0),xe(0),oe(new Set),W(""),F(""),S(!1),a(!1)};if(n.length===0&&!r)return e.jsx(qe,{open:s,onOpenChange:je,children:e.jsxs(Oe,{className:"max-w-2xl bg-background text-foreground border-border",children:[e.jsx(Be,{children:e.jsx(Ve,{className:"text-xl font-bold text-foreground",children:"Interactive Quiz Generator"})}),e.jsxs("div",{className:"space-y-6",children:[!le.canAnalyze&&e.jsx(js,{messageCount:le.messageCount,minimumNeeded:le.minimumNeeded,toolName:"Quiz",canFillManually:!0}),e.jsx(Nt,{isVisible:ae,title:"Collette AI analyzing chat context...",description:"Analyzing recent messages to create personalized quiz questions"}),z&&z.confidence>=60&&e.jsx(te,{className:"bg-primary/5 border-primary/20",children:e.jsx(ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-primary mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h5",{className:"font-medium text-primary",children:"Collette's Recommendation"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:z.reasoning}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(me,{variant:"secondary",className:"text-xs",children:[z.confidence,"% confidence"]}),z.confidence>=70&&e.jsx(me,{variant:"default",className:"text-xs",children:"Auto-populated"})]}),e.jsxs(_,{onClick:()=>{const fe=z.suggestedDifficulty;ee(fe)},className:"w-full mt-3 bg-gradient-to-r from-blue-500 to-blue-600 hover:opacity-90 text-white",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Generate ",z.questionCount," Questions on ",z.suggestedTopic," (",z.suggestedDifficulty,")"]})]})]})})}),e.jsxs("div",{className:"text-center space-y-4",style:{opacity:ae?.5:1},children:[e.jsx("p",{className:"text-muted-foreground",children:"Generate an interactive quiz to test your knowledge and earn tokens!"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-left",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Te,{className:"text-muted-foreground",children:"Age (Optional)"}),e.jsxs(De,{value:q,onValueChange:C,children:[e.jsx(Le,{className:"bg-muted border-border text-foreground",children:e.jsx($e,{placeholder:"Select age"})}),e.jsxs(Me,{className:"bg-card border-border",children:[e.jsx(Z,{value:"5",children:"5 years old"}),e.jsx(Z,{value:"6",children:"6 years old"}),e.jsx(Z,{value:"7",children:"7 years old"}),e.jsx(Z,{value:"8",children:"8 years old"}),e.jsx(Z,{value:"9",children:"9 years old"}),e.jsx(Z,{value:"10",children:"10 years old"}),e.jsx(Z,{value:"11",children:"11 years old"}),e.jsx(Z,{value:"12",children:"12 years old"}),e.jsx(Z,{value:"13",children:"13 years old"}),e.jsx(Z,{value:"14",children:"14 years old"}),e.jsx(Z,{value:"15",children:"15 years old"}),e.jsx(Z,{value:"16",children:"16 years old"}),e.jsx(Z,{value:"17",children:"17 years old"}),e.jsx(Z,{value:"18",children:"18 years old"}),e.jsx(Z,{value:"Adult",children:"Adult"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Te,{className:"text-muted-foreground",children:"Grade Level (Optional)"}),e.jsxs(De,{value:H,onValueChange:ue,children:[e.jsx(Le,{className:"bg-muted border-border text-foreground",children:e.jsx($e,{placeholder:"Select grade"})}),e.jsxs(Me,{className:"bg-card border-border",children:[e.jsx(Z,{value:"Kindergarten",children:"Kindergarten"}),e.jsx(Z,{value:"1st Grade",children:"1st Grade"}),e.jsx(Z,{value:"2nd Grade",children:"2nd Grade"}),e.jsx(Z,{value:"3rd Grade",children:"3rd Grade"}),e.jsx(Z,{value:"4th Grade",children:"4th Grade"}),e.jsx(Z,{value:"5th Grade",children:"5th Grade"}),e.jsx(Z,{value:"6th Grade",children:"6th Grade"}),e.jsx(Z,{value:"7th Grade",children:"7th Grade"}),e.jsx(Z,{value:"8th Grade",children:"8th Grade"}),e.jsx(Z,{value:"9th Grade",children:"9th Grade"}),e.jsx(Z,{value:"10th Grade",children:"10th Grade"}),e.jsx(Z,{value:"11th Grade",children:"11th Grade"}),e.jsx(Z,{value:"12th Grade",children:"12th Grade"}),e.jsx(Z,{value:"College",children:"College"}),e.jsx(Z,{value:"N/A",children:"N/A"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_,{onClick:()=>ee("Easy"),disabled:ae,variant:"outline",className:"border-green-600 text-green-300 hover:bg-green-700",children:"Easy Quiz"}),e.jsx(_,{onClick:()=>ee("Medium"),disabled:ae,variant:"outline",className:"border-yellow-600 text-yellow-300 hover:bg-yellow-700",children:"Medium Quiz"}),e.jsx(_,{onClick:()=>ee("Hard"),disabled:ae,variant:"outline",className:"border-red-600 text-red-300 hover:bg-red-700",children:"Hard Quiz"}),e.jsx(_,{onClick:()=>ee("Mixed"),disabled:ae,variant:"outline",className:"border-blue-600 text-blue-300 hover:bg-blue-700",children:"Mixed Difficulty"})]})]})]})]})});if(r)return e.jsx(qe,{open:s,onOpenChange:je,children:e.jsx(Oe,{className:"max-w-2xl bg-background text-foreground border-border",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(ke,{className:"w-8 h-8 animate-spin text-blue-500 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Generating Your Quiz"}),e.jsx("p",{className:"text-muted-foreground text-center",children:"Creating questions based on your classroom content..."})]})})});if(G){const fe=Math.round(pe/n.length*100),he=ce.size;return e.jsx(qe,{open:s,onOpenChange:je,children:e.jsxs(Oe,{className:"max-w-2xl bg-background text-foreground border-border",children:[e.jsx(Be,{children:e.jsxs(Ve,{className:"text-xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(qa,{className:"w-6 h-6 text-yellow-500"}),"Quiz Complete!"]})}),e.jsxs("div",{className:"space-y-6 text-center",children:[e.jsxs("div",{className:"bg-muted p-6 rounded-lg",children:[e.jsxs("div",{className:"text-3xl font-bold text-foreground mb-2",children:[fe,"%"]}),e.jsx("div",{className:"text-muted-foreground mb-4",children:"Final Score"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-green-400",children:pe}),e.jsx("div",{className:"text-muted-foreground",children:"Correct Answers"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-yellow-400",children:he}),e.jsx("div",{className:"text-muted-foreground",children:"Skipped"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-400",children:Y}),e.jsx("div",{className:"text-muted-foreground",children:"Tokens Earned"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[e.jsxs(_,{onClick:ge,variant:"outline",className:"border-border text-muted-foreground hover:bg-muted",children:[e.jsx(Gt,{className:"w-4 h-4 mr-2"}),"New Quiz"]}),e.jsx(_,{onClick:J,disabled:ve,variant:"outline",className:"border-green-600 text-green-300 hover:bg-green-700",children:ve?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-4 h-4 mr-2"}),"Save to Learning Aids"]})}),p&&e.jsx(_,{onClick:()=>{const Fe=`Quiz Results: ${pe}/${n.length} correct (${fe}%) - ${he} skipped - ${Y} tokens earned`;p(Fe),h({title:"Sent to Chat",description:"Quiz results have been sent to the AI tutor."})},variant:"outline",className:"border-blue-600 text-blue-300 hover:bg-blue-700",children:"Send to Chat"}),e.jsx(_,{onClick:je,className:"bg-blue-600 hover:bg-blue-700",children:"Finish"})]})]})]})})}const Se=n[f];
109if(!Se)return null;const Ue=(f+1)/n.length*100;return e.jsx(qe,{open:s,onOpenChange:je,children:e.jsxs(Oe,{className:"max-w-2xl bg-background text-foreground border-border",children:[e.jsx(Be,{children:e.jsxs(Ve,{className:"text-xl font-bold text-foreground",children:["Interactive Quiz - Question ",f+1," of ",n.length]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(At,{value:Ue,className:"w-full"}),e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-4",children:Se.question}),e.jsx(bt,{value:N,onValueChange:A,disabled:k,children:Se.options.map((fe,he)=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(et,{value:he.toString(),id:`option-${he}`}),e.jsx(Te,{htmlFor:`option-${he}`,className:"text-muted-foreground cursor-pointer",children:fe})]},he))})]}),k&&e.jsxs("div",{className:`p-4 rounded-lg ${T?"bg-green-900/50 border border-green-700":"bg-red-900/50 border border-red-700"}`,children:[e.jsx("div",{className:`font-semibold mb-2 ${T?"text-green-300":"text-red-300"}`,children:T?"✓ Correct!":"✗ Incorrect"}),e.jsx("p",{className:"text-muted-foreground",children:Se.explanation})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Tokens earned: ",Y," | Question ",f+1," of ",n.length]}),e.jsx(_,{onClick:J,disabled:ve,variant:"outline",size:"sm",className:"border-green-600 text-green-300 hover:bg-green-700",children:ve?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-4 h-4 mr-2"}),"Save Quiz"]})})]}),e.jsx("div",{className:"flex justify-end gap-2",children:k?e.jsx(_,{onClick:se,className:"bg-blue-600 hover:bg-blue-700",children:f<n.length-1?"Next Question":"Finish Quiz"}):e.jsxs(e.Fragment,{children:[e.jsxs(_,{onClick:U,variant:"outline",size:"sm",className:"border-yellow-600 text-yellow-300 hover:bg-yellow-700",children:[e.jsx(Oa,{className:"w-4 h-4 mr-2"}),"Skip"]}),e.jsx(_,{onClick:$,disabled:!N,className:"bg-blue-600 hover:bg-blue-700",children:"Submit Answer"})]})})]})]})]})})},Qn=({open:s,onOpenChange:a,classroomId:m,onSendToChat:x,chatMessages:p=[]})=>{const[l,h]=t.useState(""),[u,d]=t.useState(null),[n,r]=t.useState(""),[v,j]=t.useState(""),[b,g]=t.useState(!1),[c,o]=t.useState(!1),[i,f]=t.useState(!1),[y,N]=t.useState(""),[A,w]=t.useState(!1),[P,k]=t.useState(null),[I,T]=t.useState(!1),{toast:M}=we(),{spendAICredit:G,canUseAI:D}=wt(),Y=ys(m),{suggestions:de,isLoading:pe,getSuggestionsByCategory:xe,getCategories:ce}=Pr(m),{profile:oe}=Yr(),ae=lt.useCallback((q,C)=>{h(q.category),d(q),q.category==="user_characters"&&!n.trim()&&r("A character related to our discussion"),C?.silent||M({title:"Scenario selected",description:"Ready to generate."})},[n,M]),K=t.useCallback(async()=>{if(p.length===0)return;if(!D){M({title:"No Credits Available",description:"You need credits to use AI features.",variant:"destructive"});return}if(await G("Roleplay Analyzer","Analyzing context for roleplay")){w(!0);try{const{data:C,error:H}=await E.functions.invoke("chad-challenge-analyzer",{body:{chatMessages:p.slice(-10),classroomSubject:m}});if(H)throw H;if(C.confidence==="high"&&C.focusTopic){const ue=de.find(ve=>ve.title.toLowerCase().includes(C.focusTopic.toLowerCase().split(" ")[0])||ve.description.toLowerCase().includes(C.focusTopic.toLowerCase().split(" ")[0]))||de[0];ue&&(k(ue),T(!0),u||ae(ue))}}catch(C){console.error("Error analyzing chat context:",C)}finally{w(!1)}}},[p,m,de,u,ae]);t.useEffect(()=>{s&&p.length>0&&de.length>0&&K()},[s,p.length,de.length,K]),t.useEffect(()=>{s&&P&&!u&&ae(P,{silent:!0})},[s,P,u,ae]);const O=()=>{const q=p.slice(-15);if(q.length===0)return"";const C=q.map(ve=>ve.content).join(" ").toLowerCase(),H=[];return[/discussing? ([a-zA-Z\s]{3,20})/g,/learning about ([a-zA-Z\s]{3,20})/g,/studying ([a-zA-Z\s]{3,20})/g,/working on ([a-zA-Z\s]{3,20})/g,/topic.{0,10}?([a-zA-Z\s]{3,20})/g].forEach(ve=>
109{[...C.matchAll(ve)].forEach(le=>{le[1]&&le[1].trim().length>2&&H.push(le[1].trim())})}),H.length>0?H.slice(0,3).join(", "):""},W=async()=>{if(!u)return;if(!D){M({title:"No Credits Available",description:"You need credits to use AI features.",variant:"destructive"});return}if(await G("Roleplay Generator","Generating roleplay scenario")){g(!0);try{const C=O();let H=u.scenario_prompt;u.category==="user_characters"&&n.trim()&&(H=`You are roleplaying as: ${n}. ${H}`),H=H.replace("{character_name}",n||"the character").replace("{book_title}","the current reading").replace("{author_name}","the author").replace("{mathematician_name}","a famous mathematician").replace("{profession}","a professional in the field").replace("{job_position}","the position").replace("{math_topic}",C).replace("{scenario}",C).replace("{situation}",C).replace("{complaint}","a service issue").replace("{project}","the current project").replace("{field}",Y.subject);const{data:ue,error:ve}=await E.functions.invoke("generate-with-ai",{body:{prompt:`roleplay scenario: ${H}`,userProfile:oe,chatContext:C,classroomSubject:Y.subject,requestType:"roleplay"}});if(ve)throw ve;j(ue.generatedText),N(ue.generatedText)}catch(C){console.error("Error generating roleplay:",C),M({title:"Error",description:"Failed to generate roleplay scenario. Please try again.",variant:"destructive"})}finally{g(!1)}}},B=()=>{if(y&&x){const q=`🎭 **Roleplay Scenario: ${u?.title||"Interactive Scenario"}**
110
111${y}
112
113---
114*Note: The student will take on the roleplay character. Your role is to facilitate the roleplay by responding as other characters, providing context, and guiding the interaction to help the student learn.*`;x(q),a(!1)}},F=()=>{j(""),N(""),f(!1)},Q=()=>{f(!0)},S=()=>{j(y),f(!1)},z=()=>{N(v),f(!1)},V=l&&l!=="all"?xe(l):de;return c?e.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:e.jsxs(_,{onClick:()=>o(!1),className:"bg-gradient-to-r from-purple-500 to-pink-500 hover:opacity-90 text-white",children:[e.jsx(tt,{className:"w-4 h-4 mr-2"}),"Roleplay"]})}):e.jsx(qe,{open:s,onOpenChange:a,children:e.jsxs(Oe,{className:"max-w-4xl max-h-[90vh] overflow-y-auto bg-background border-border",children:[e.jsx(Be,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ve,{className:"text-xl font-semibold text-foreground flex items-center",children:[e.jsx(tt,{className:"w-5 h-5 mr-2 text-purple-500"}),"Interactive Roleplay"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>o(!0),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Ua,{className:"w-4 h-4"})}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>a(!1),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Pt,{className:"w-4 h-4"})})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(Nt,{isVisible:A,title:"Rosalina analyzing chat context...",description:"Finding the perfect roleplay scenario based on your discussion"}),I&&!A&&P&&e.jsxs("div",{className:"bg-purple-900/20 border border-purple-600/30 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx(it,{className:"w-5 h-5 text-yellow-400 animate-glow"}),e.jsx("h4",{className:"text-purple-300 font-medium",children:"AI Suggested Scenario"})]}),e.jsx(te,{className:"cursor-pointer border-purple-500 bg-purple-900/20 mb-3",onClick:()=>ae(P),children:e.jsxs(ie,{className:"p-4",children:[e.jsx("h4",{className:"font-medium text-foreground mb-1",children:P.title}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:P.description}),e.jsx(me,{variant:"secondary",className:"text-xs",children:"Perfect for your current discussion"})]})})]}),e.jsx("div",{className:"text-center",children:e.jsxs("p",{className:"text-muted-foreground text-sm",children:["Choose a roleplay scenario tailored to ",Y.name,". The AI will adapt based on your recent classroom discussions."]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Roleplay Category"}),e.jsxs(De,{value:l,onValueChange:h,children:[e.jsx(Le,{className:"bg-muted border-border text-foreground",children:e.jsx($e,{placeholder:"Select a category..."})}),e.jsxs(Me,{className:"bg-muted border-border",children:[e.jsx(Z,{value:"all",children:"All Categories"}),ce().map(q=>e.jsx(Z,{value:q.value,children:q.label},q.value))]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Choose Scenario"}),e.jsx("div",{className:"grid gap-3 max-h-60 overflow-y-auto",children:pe?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ke,{className:"w-6 h-6 animate-spin text-purple-400"})}):V.map(q=>
114e.jsx(te,{className:`cursor-pointer transition-all ${u?.id===q.id?"border-purple-500 bg-purple-900/20":"border-border bg-muted/50 hover:border-gray-500"}`,onClick:()=>ae(q),children:e.jsx(ie,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-foreground mb-1",children:q.title}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:q.description}),e.jsx(me,{variant:"secondary",className:"text-xs",children:q.category.split("_").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" ")})]})})})},q.id))})]}),u?.category==="user_characters"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Describe Your Character"}),e.jsx(_e,{value:n,onChange:q=>r(q.target.value),placeholder:"e.g., A brave detective from the 1920s, a friendly alien scientist...",className:"bg-muted border-border text-foreground"})]}),e.jsx(_,{onClick:W,disabled:!u||b||u?.category==="user_characters"&&!n.trim(),className:"w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:opacity-90 text-white",children:b?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Creating Roleplay..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Generate Roleplay Scenario"]})}),v&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Your Roleplay Scenario"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{onClick:Q,size:"sm",variant:"outline",className:"text-muted-foreground border-border hover:bg-muted",children:[e.jsx(Zs,{className:"w-3 h-3 mr-1"}),"Edit"]}),e.jsxs(_,{onClick:F,size:"sm",variant:"outline",className:"text-muted-foreground border-border hover:bg-muted",children:[e.jsx(yt,{className:"w-3 h-3 mr-1"}),"Regenerate"]})]})]}),i?e.jsxs("div",{className:"space-y-3",children:[e.jsx(rt,{value:y,onChange:q=>N(q.target.value),className:"bg-muted border-border text-foreground min-h-[100px]",placeholder:"Edit your roleplay scenario..."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_,{onClick:S,className:"bg-green-600 hover:bg-green-700 text-white",children:"Save Changes"}),e.jsx(_,{onClick:z,variant:"outline",className:"text-muted-foreground border-border hover:bg-muted",children:"Cancel"})]})]}):e.jsx(te,{className:"bg-muted/50 border-border",children:e.jsx(ie,{className:"p-4",children:e.jsx("div",{className:"prose prose-invert prose-sm max-w-none",children:y.split(`
115`).map((q,C)=>e.jsx("p",{className:"text-muted-foreground mb-2",children:q},C))})})}),e.jsxs(_,{onClick:B,disabled:i,className:"w-full bg-gradient-to-r from-green-500 to-green-600 hover:opacity-90 text-white",children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Start Roleplay in Chat"]})]})]})]})})},Yn=s=>{const[a,m]=t.useState([]),x=`paula-chat-${s}`,p=`paula-prompt-${s}`;return t.useEffect(()=>{const h=localStorage.getItem(x);if(h)try{const u=JSON.parse(h).map(d=>({...d,timestamp:new Date(d.timestamp)}));m(u)}catch(u){console.error("Error parsing saved messages:",u)}},[x]),t.useEffect(()=>{a.length>0&&localStorage.setItem(x,JSON.stringify(a))},[a,x]),{messages:a,setMessages:m,clearChat:()=>{localStorage.removeItem(x),localStorage.removeItem(p),m([])}}},Kn=({onSelectPrompt:s,category:a,userAge:m,userRole:x})=>{const[p,l]=t.useState([]),[h,u]=t.useState(!0),[d,n]=t.useState(""),[r,v]=t.useState(!1),{user:j}=Ge();if(t.useEffect(()=>{(async()=>{try{let c=a;console.log("🔍 HelpMeAskBetter Debug:",{userAge:m,userRole:x,category:a,rawAge:m}),x==="parent"||x==="youth_leader"||x==="developer"?(c=a,console.log("👨‍💼 Using adult category for role:",x,"→",c)):m&&typeof m=="number"&&m>=15?(c=a,console.log("🎓 Using high school category for age:",m,"→",c)):(c=`${a}_middle_school`,console.log("🧒 Using middle school category (default safe choice) for age:",m,"→",c)),console.log("📊 Fetching prompts for category:",c);const{data:o,error:i}=await E.from("student_prompt_injections").select("id, prompt_text, description").eq("category",c).eq("is_active",!0).order("order_index");if(i){console.error("❌ Error fetching prompt suggestions:",i);return}console.log("✅ Fetched suggestions:",o?.length||0,"items"),l(o||[])}catch(c){console.error("❌ Error fetching suggestions:",c)}finally{u(!1)}})()},[a,m,x]),h)return e.jsx(_,{variant:"outline",size:"sm",disabled:!0,className:"border-border",children:"Loading..."});const b=g=>{n(g.description),s(g.prompt_text),v(!1)};return e.jsxs(na,{open:r,onOpenChange:v,children:[e.jsx(oa,{asChild:!0,children:e.jsxs(_,{variant:"outline",size:"sm",className:"border-border text-muted-foreground hover:bg-muted bg-card",children:[e.jsx(it,{className:"w-4 h-4 mr-2"}),d||"Example Prompts",e.jsx(zt,{className:"w-4 h-4 ml-2"})]})}),e.jsx(ia,{className:"w-80 bg-card border-border text-foreground z-[9999] p-0",side:"top",style:{zIndex:9999},"data-inside-modal-portal":"true",onMouseDown:g=>g.stopPropagation(),children:e.jsxs(Ze,{className:"h-[300px]",children:[p.map(g=>e.jsxs(os,{onClick:c=>{c.preventDefault(),c.stopPropagation(),b(g)},className:"flex flex-col items-start p-3 hover:bg-muted cursor-pointer",children:[e.jsx("div",{className:"text-sm font-medium text-foreground mb-1",children:g.description}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-2",children:g.prompt_text})]},g.id)),e.jsx(xs,{orientation:"vertical"})]})})]})},Jn=(s,a)=>{const{openModal:m}=hr(),{messages:x,setMessages:p,clearChat:l}=Yn(s),[h,u]=t.useState(!1),[d,n]=t.useState(null),r=t.useCallback(async j=>{const b=Ut(j||[]);if(!b.canAnalyze){console.log("Paula analysis skipped:",b.userFriendlyReason);return}u(!0),u(!0);try{const{data:g,error:c}=await E.functions.invoke("paula-chat-analyzer",{body:{chatMessages:j.slice(-15),classroomSubject:s}});if(c)throw c;g.analysis&&g.analysis.confidence!=="low"&&n(g.analysis)}catch(g){console.error("Error analyzing chat context:",g)}finally{u(!1)}},[s]);return{openPaulaModal:j=>(j&&j.length>0&&r(j),m({title:"Prompt Engineer - Paula",content:e.jsx(Wn,{classroomId:s,onSendToChat:a,chatMessages:j,messages:x,setMessages:p,clearChat:l,isAnalyzing
115Chat:h,chatAnalysis:d,analyzeChatContext:r}),size:{width:550,height:600}})),analyzeChatContext:r}},Wn=({classroomId:s,onSendToChat:a,chatMessages:m,messages:x,setMessages:p,clearChat:l,isAnalyzingChat:h,chatAnalysis:u,analyzeChatContext:d})=>{const[n,r]=t.useState(""),[v,j]=t.useState(!1),[b,g]=t.useState(),[c,o]=t.useState(""),i=t.useRef(null),{toast:f}=we();bs();const{user:y}=Ge(),{role:N}=Xe(),A=t.useMemo(()=>Ut(m||[]),[m]),w=`paula-prompt-${s}`;t.useEffect(()=>{const D=localStorage.getItem(w);D&&o(D)},[w]),t.useEffect(()=>{c?localStorage.setItem(w,c):localStorage.removeItem(w)},[c,w]);const P=()=>{i.current?.scrollIntoView({behavior:"smooth"})};t.useEffect(()=>{P()},[x]),t.useEffect(()=>{(async()=>{if(!y){console.log("🚫 No user found for age lookup");return}console.log("👤 Fetching age for user:",y.id);try{const{data:Y,error:de}=await E.from("student_profiles").select("age").eq("student_auth_id",y.id).maybeSingle();!de&&Y?.age?(console.log("🎂 User age found:",Y.age),g(Y.age)):console.log("📊 No age data found or error:",de)}catch(Y){console.log("❌ Could not fetch user age:",Y)}})()},[y]);const k=()=>{let D="";return u&&(D=`
116
117Chat Analysis Context:
118- Current topics: ${u.topics?.join(", ")||"None identified"}
119- Learning style: ${u.learningStyle||"Unknown"}
120- Context summary: ${u.contextSummary||"No recent activity"}
121- Areas for improvement: ${u.improvementAreas?.join(", ")||"General prompting"}
122
123Use this context to provide more relevant and specific prompting advice.`),`You are Paula, an expert prompt engineering assistant designed to help students create more effective prompts for AI tutors and learning tools.
124
125Your role is to:
1261. Help students refine their questions to be more specific and actionable
1272. Suggest better ways to phrase requests for explanations, examples, or practice problems
1283. Guide students on how to provide context that helps AI tutors give better responses
1294. Teach effective prompting techniques in simple, age-appropriate language
130
131Guidelines:
132- Keep responses concise and practical
133- Focus on improving the student's current prompt rather than answering their subject question
134- Suggest specific improvements with examples
135- Be encouraging and supportive
136- If they share a prompt, analyze it and suggest 2-3 specific improvements
137- Reference the chat context when relevant to make suggestions more helpful
138
139IMPORTANT: When providing an improved prompt, always format it using these delimiters:
140REFINED_PROMPT_START
141[The actual improved prompt here]
142REFINED_PROMPT_END
143
144Student context:
145- Age: ${b||"unknown"}
146- Role: ${N||"student"}
147- Classroom: ${s}${D}
148
149Remember: Your job is to teach better prompting, not to answer subject questions directly.`},I=async()=>{if(!n.trim()||v)return;const D={id:Date.now().toString(),content:n,isUser:!0,timestamp:new Date};p(Y=>[...Y,D]),r(""),j(!0);try{const Y=x.map(F=>`${F.isUser?"Student":"Paula"}: ${F.content}`).join(`
150`),de=`${k()}
151
152Previous conversation:
153${Y}
154
155Student's new message: ${n}
156
157As Paula, help this student create a better prompt for their ${s} tutor based on the context above.`,{data:pe,error:xe}=await E.functions.invoke("paula-prompt-engineer",{body:{chatMessages:m||[],classroomSubject:s,userPrompt:n,userAge:b,userRole:N}});if(xe||!pe?.success)throw new Error(xe?.message||pe?.error||"Failed to communicate with Paula");const ce={content:pe.content};let oe="";const ae="REFINED_PROMPT_START",K="REFINED_PROMPT_END",O=ce.content.indexOf(ae),W=ce.content.indexOf(K);if(O!==-1&&W!==-1&&W>O)oe=ce.content.substring(O+ae.length,W).trim();else if(ce.content.toLowerCase().includes("refined prompt")||ce.content.toLowerCase().includes("here's a better way")||ce.content.toLowerCase().includes("try asking")){const Q=ce.content.split(`
158`).find(S=>S.includes('"')&&S.length>20);Q&&(oe=Q.replace(/"/g,"").trim())}const B={id:(Date.now()+1).toString(),content:ce.content,isUser:!1,timestamp:new Date,refinedPrompt:oe||void 0};p(F=>[...F,B]),oe&&o(oe)}catch(Y){console.error("Error communicating with Paula:",Y),f({title:"Communication Error",description:"I'm having trouble connecting to Paula. Please try again.",variant:"destructive"});const de={id:(Date.now()+1).toString(),content:"Sorry, I'm having trouble connecting right now. Please try again in a moment.",isUser:!1,timestamp:new Date};p(pe=>[...pe,de])}finally{j(!1)}},T=()=>{c&&a&&(a(c),o(""),f({title:"Prompt Sent!",description:"Your refined prompt has been sent to the classroom chat."}))},M=D=>
158{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),I())},G=D=>{r(D)};return e.jsxs("div",{className:"h-full bg-background border-border text-foreground flex flex-col max-h-[600px]",children:[e.jsxs("div",{className:"pb-4 border-b border-border flex items-center justify-between flex-shrink-0",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-xl font-semibold",children:[e.jsx(ft,{className:"w-5 h-5 text-yellow-500"}),"Prompt Engineer - Paula"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Let me help you craft the perfect prompt for your tutor"})]}),e.jsxs(_,{onClick:l,variant:"outline",size:"sm",className:"border-border text-muted-foreground hover:bg-muted",children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),"Clear Chat"]})]}),e.jsxs(Ze,{className:"flex-1 overflow-auto",children:[m&&m.length>0&&!A.canAnalyze&&e.jsx("div",{className:"p-4 border-b border-border",children:e.jsx(js,{messageCount:A.messageCount,minimumNeeded:A.minimumNeeded,toolName:"Prompt Analysis",canFillManually:!1})}),m&&m.length>0&&A.canAnalyze&&!h&&!u&&e.jsx("div",{className:"p-4 border-b border-border",children:e.jsx(te,{className:"border-blue-200 bg-blue-50/50",children:e.jsx(ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nt,{className:"h-5 w-5 text-blue-600"}),e.jsx("div",{className:"flex-1",children:e.jsx("p",{className:"text-sm text-blue-800",children:"Paula can analyze your recent conversation to provide better prompt suggestions."})}),e.jsx(_,{variant:"outline",size:"sm",onClick:()=>d(m),className:"border-blue-200 text-blue-700 hover:bg-blue-100",children:"Analyze with Paula"})]})})})}),e.jsx(Nt,{isVisible:h,title:"Paula analyzing chat context...",description:"Extracting topics and suggesting optimal prompting strategies",showTimerWarning:!0}),u&&e.jsx("div",{className:"p-4 border-b border-border",children:e.jsx(te,{className:"bg-primary/5 border-primary/20",children:e.jsx(ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-primary mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h5",{className:"font-medium text-primary",children:"Paula's Analysis"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:u.contextSummary}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Topics:"}),u.topics?.map((D,Y)=>e.jsx(me,{variant:"secondary",className:"text-xs",children:D},Y))]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(me,{variant:"secondary",className:"text-xs",children:[u.confidence," confidence"]}),e.jsx(me,{variant:"default",className:"text-xs",children:"Auto-populated"}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>m&&d(m),className:"text-xs",children:"Analyze Again"})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:e.jsxs("span",{children:["Learning style: ",u.learningStyle]})})]})]})})})}),e.jsx("div",{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[x.map(D=>e.jsx(te,{className:`max-w-[85%] ${D.isUser?"ml-auto bg-blue-600 border-blue-600":"mr-auto bg-yellow-600/20 border-yellow-600/30"}`,children:e.jsxs(ie,{className:"p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(st,{content:D.content,className:"text-sm text-foreground flex-1"}),!D.isUser&&e.jsx(_,{onClick:()=>{const Y=D.refinedPrompt||D.content;a?.(Y),D.refinedPrompt&&o("")},size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-yellow-400 hover:text-yellow-300 hover:bg-yellow-600/20",title:D.refinedPrompt?"Send refined prompt to chat":"Send this message to chat",children:e.jsx(rs,{className:"w-3 h-3"})})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[D.timestamp.toLocaleDateString()," ",D.timestamp.toLocaleTimeString()]})]})},D.id)),v&&e.jsx(te,{className:"max-w-[85%] mr-auto bg-yellow-600/20 border-yellow-600/30",children:e.jsx(ie,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground",children:[e.jsx(ke,{className:"w-4 h-4 animate-spin"}),"Paula is thinking..."]})})}),e.jsx("div",{ref:i})]})}),e.jsx(xs,{orientation:"vertical"})]}),c&&e.jsxs("div",{className:"p-4 border-t border-border bg-yellow-600/10 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-yellow-400",children:"Refined Prompt Ready:"}),e.jsxs(_,{onClick:T,size:"sm",className:"bg-yellow-600 hover:bg-yellow-700 text-gray-900 font-medium",children:[e.jsx(rs,{className:"w-4 h-4 mr-1"}),"Send to Chat"]})]}),e.jsx("div",{className:"text-sm text-muted-foreground bg-card p-2 rounded border border-border",children:c})]}),e.jsxs("div",{className:"p-4 border-t border-border space-y-3 flex-shrink-0",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx(Kn,{onSelectPrompt:G,category:"prompt_engineering",userAge:b,userRole:N||void 0})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{value:n,onChange:D=>r(D.target.value),onKeyPress:M,placeholder:"Describe what you want to learn or ask about...",className:"flex-1 bg-card border-border text-foreground",disabled:v}),e.jsx(_,{onClick:I,disabled:!n.trim()||v,className:"bg-yellow-600 hover:bg-yellow-700 text-gray-900",children:v?e.jsx(ke,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"})})]})]})]})},Zn=({classroomId:s,onSendToChat:a,classroomMessages:m})=>{const{openPaulaModal:x,analyzeChatContext:p}=Jn(s,a);return{openPaulaModal:()=>x(m),analyzeChatContext:p}},Xn=s=>{const[a,m]=t.useState(0),[x,p]=t.useState(!0),{user:l}=Ge(),h=n=>n.trim(),u=async()=>
158{if(!l||!s){p(!1);return}const n=h(s);try{const{data:r,error:v}=await E.from("user_classroom_tokens").select("tokens").eq("user_id",l.id).eq("classroom_subject",n).maybeSingle();if(v&&v.code!=="PGRST116"){console.error("Error fetching tokens:",v);return}m(r?.tokens||0)}catch(r){console.error("Error fetching classroom tokens:",r)}finally{p(!1)}},d=async(n=1)=>{if(!l||!s)return!1;const r=h(s);try{const v=[{triggerCode:"APP_TOKEN_REWARD",buttonType:"TOKEN_REWARD",customData:JSON.stringify({event:"app_token_award",source:"increment_tokens",classroom_id:r,amount:n,expires_minutes:90,note:"Auto offer created by app action"})}];return window.dispatchEvent(new CustomEvent("dynamic-buttons:generate",{detail:{codes:v}})),!0}catch(v){return console.error("Error broadcasting token offer via incrementTokens:",v),!1}};return t.useEffect(()=>{if(!l||!s)return;u();const n=Date.now(),r=Math.random().toString(36).substring(2),v=`classroom-tokens-${l.id}-${s}-${n}-${r}`;let j=!1,b=!0;const g=E.channel(v).on("postgres_changes",{event:"*",schema:"public",table:"user_classroom_tokens",filter:`user_id=eq.${l.id},classroom_subject=eq.${s}`},c=>{j&&b&&(c.eventType==="UPDATE"||c.eventType==="INSERT")&&m(c.new.tokens)}).subscribe(c=>{c==="SUBSCRIBED"&&b&&(j=!0)});return()=>{b=!1,j=!1,E.removeChannel(g)}},[l,s]),{tokens:a,loading:x,incrementTokens:d,refreshTokens:u}},eo=()=>{const[s,a]=t.useState([]),[m,x]=t.useState(!0),{toast:p}=we(),l=async()=>{try{const{data:u,error:d}=await E.from("user_favorited_tools").select("tool_id").order("created_at",{ascending:!0});if(d)throw d;a(u?.map(n=>n.tool_id)||[])}catch(u){console.error("Error loading favorited tools:",u)}finally{x(!1)}},h=async u=>{const d=s.includes(u);if(!d&&s.length>=7)return p({title:"Favorites Full",description:"You can only favorite up to 7 learning tools. Please unstar one to add another.",variant:"destructive"}),!1;try{if(d){const{error:n}=await E.from("user_favorited_tools").delete().eq("tool_id",u);if(n)throw n;a(r=>r.filter(v=>v!==u)),p({title:"Removed from Favorites",description:"Learning tool removed from your favorites."})}else{const{data:{user:n}}=await E.auth.getUser();if(!n)throw new Error("Not authenticated");const{error:r}=await E.from("user_favorited_tools").insert({tool_id:u,user_id:n.id});if(r)throw r;a(v=>[...v,u]),p({title:"Added to Favorites",description:"Learning tool added to your favorites."})}return!0}catch(n){return console.error("Error toggling favorite:",n),p({title:"Error",description:"Failed to update favorites. Please try again.",variant:"destructive"}),!1}};return t.useEffect(()=>{l()},[]),{favoritedTools:s,isLoading:m,toggleFavorite:h,isFavorited:u=>s.includes(u)}},to=({chatContext:s,onSendToChat:a,defaultTab:m="bible-verses"})=>{const{toast:x}=we(),[p,l]=t.useState(!1),[h,u]=t.useState(null),[d,n]=t.useState(null),[r,v]=t.useState(null),[j,b]=t.useState(""),[g,c]=t.useState(""),[o,i]=t.useState(""),f=[{value:"poem",label:"Poem",description:"Memorable verses to help remember concepts"},{value:"rap",label:"Rap Verse",description:"Rhythmic, catchy verses for memorization"},{value:"flashcards",label:"Flash Cards",description:"Question & answer cards for study"},{value:"acronym",label:"Acronym",description:"Word formations to remember lists"},{value:"story",label:"Memory Story",description:"Short stories to reinforce learning"},{value:"mnemonic",label:"Mnemonic Device",description:"Memory techniques and patterns"}],y=async k=>{l(!0);try{const{data:I,error:T}=await E.functions.invoke("bible-verse-generator",{body:{mode:k,chatContext:k==="context-smart"?s:void 0}});if(T)throw T;u(I),x({title:"Bible verse generated!",description:`${I.reference} - ${I.theme}`})}catch(I){console.error("Error generating Bible verse:",I),x({title:"Error",description:"Failed to generate Bible verse",variant:"destructive"})}finally{l(!1)}},N=async k=>{if(k==="user-topic"&&!j.trim()){x({title:"Topic required",description:"Please enter a topic or prayer need",variant:"destructive"});return}l(!0);try{const{data:I,error:T}=await E.functions.invoke("prayer-generator",{body:{mode:k,chatContext:k==="chat-context"?s:void 0,userTopic:k==="user-topic"?j:void 0}});if(T)throw T;n(I),x({title:"Prayer generated!",description:"Generated by Peggy Assistant"})}catch(I){console.error("Error generating prayer:",I),x({title:"Error",description:"Failed to generate prayer",variant:"destructive"})}finally{l(!1)}},A=async()=>
158{if(!o){x({title:"Memory aid type required",description:"Please select a type of memory aid",variant:"destructive"});return}l(!0);try{const{data:k,error:I}=await E.functions.invoke("memory-aids-generator",{body:{aidType:o,chatContext:s,customTopic:g.trim()||void 0}});if(I)throw I;v(k),x({title:"Memory aid generated!",description:`Created a ${k.type} to help with learning`})}catch(k){console.error("Error generating memory aid:",k),x({title:"Error",description:"Failed to generate memory aid",variant:"destructive"})}finally{l(!1)}},w=k=>{navigator.clipboard.writeText(k),x({title:"Copied!",description:"Content copied to clipboard"})},P=(k,I)=>{a&&(a(k,I),x({title:"Sent to chat!",description:`${I} has been shared with your tutor`}))};return e.jsx("div",{className:"w-full max-w-4xl mx-auto p-4",children:e.jsxs(te,{children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"h-5 w-5 text-primary"}),"Faith Learning Tools"]})}),e.jsx(ie,{children:e.jsxs(qt,{defaultValue:m,className:"w-full",children:[e.jsxs(Ot,{className:"grid w-full grid-cols-3",children:[e.jsxs(Ye,{value:"bible-verses",className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-4 w-4"}),"Bible Verses"]}),e.jsxs(Ye,{value:"prayers",className:"flex items-center gap-2",children:[e.jsx(ot,{className:"h-4 w-4"}),"Prayers"]}),e.jsxs(Ye,{value:"memory-aids",className:"flex items-center gap-2",children:[e.jsx(nt,{className:"h-4 w-4"}),"Memory Aids"]})]}),e.jsxs(Ke,{value:"bible-verses",className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(_,{onClick:()=>y("random"),disabled:p,className:"flex items-center gap-2",children:[p?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsx(Ba,{className:"h-4 w-4"}),"Random Verse"]}),e.jsxs(_,{onClick:()=>y("context-smart"),disabled:p||!s,variant:"outline",className:"flex items-center gap-2",children:[p?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsx(ft,{className:"h-4 w-4"}),"Context Smart"]})]}),h&&e.jsx(te,{children:e.jsxs(ie,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{variant:"secondary",children:h.theme}),e.jsxs("blockquote",{className:"text-lg italic border-l-4 border-primary pl-4",children:['"',h.verse,'"']}),e.jsxs("p",{className:"text-right font-semibold text-primary",children:["- ",h.reference]}),h.explanation&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:[e.jsx("strong",{children:"Why this verse:"})," ",h.explanation]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{onClick:()=>w(`"${h.verse}" - ${h.reference}`),variant:"outline",size:"sm",className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"h-4 w-4"}),"Copy"]}),e.jsxs(_,{onClick:()=>P(`"${h.verse}" - ${h.reference}`,"Bible Verse"),size:"sm",className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4"}),"Send to Chat"]})]})]})})]}),e.jsxs(Ke,{value:"prayers",className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(_,{onClick:()=>N("chat-context"),disabled:p||!s,className:"flex items-center gap-2 w-full sm:w-auto",children:[p?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsx(ft,{className:"h-4 w-4"}),"Generate from Chat Context"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{placeholder:"Enter a topic or prayer need...",value:j,onChange:k=>b(k.target.value),className:"flex-1"}),e.jsxs(_,{onClick:()=>N("user-topic"),disabled:p,variant:"outline",className:"flex items-center gap-2",children:[p?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsx(ot,{className:"h-4 w-4"}),"Generate"]})]})]}),d&&e.jsx(te,{children:e.jsxs(ie,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(me,{variant:"secondary",children:["Prayer by ",d.source]}),e.jsx("div",{className:"text-base leading-relaxed whitespace-pre-wrap",children:d.prayer})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{onClick:()=>w(d.prayer),variant:"outline",size:"sm",className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"h-4 w-4"}),"Copy"]}),e.jsxs(_,{onClick:()=>P(d.prayer,"Prayer"),size:"sm",className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4"}),"Send to Chat"]})]})]})})]}),e.jsxs(Ke,{value:"memory-aids",className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(De,{value:o,onValueChange:i,children:[e.jsx(Le,{children:e.jsx($e,{placeholder:"Select a memory aid type..."})}),e.jsx(Me,{children:f.map(k=>e.jsx(Z,{value:k.value,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:k.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:k.description})]})}
158,k.value))})]}),e.jsx(rt,{placeholder:"Optional: Enter a specific topic (leave blank to use chat context)...",value:g,onChange:k=>c(k.target.value),rows:3}),e.jsxs(_,{onClick:A,disabled:p||!o,className:"flex items-center gap-2",children:[p?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsx(it,{className:"h-4 w-4"}),"Generate Memory Aid"]})]}),r&&e.jsx(te,{children:e.jsxs(ie,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{variant:"secondary",children:f.find(k=>k.value===r.type)?.label}),e.jsx("div",{className:"text-base leading-relaxed whitespace-pre-wrap font-mono bg-muted/50 p-4 rounded-lg",children:r.content}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"Topic:"})," ",r.topic]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{onClick:()=>w(r.content),variant:"outline",size:"sm",className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"h-4 w-4"}),"Copy"]}),e.jsxs(_,{onClick:()=>P(r.content,`Memory Aid (${r.type})`),size:"sm",className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4"}),"Send to Chat"]}),e.jsxs(_,{onClick:A,variant:"outline",size:"sm",className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"h-4 w-4"}),"Regenerate"]})]})]})})]})]})})]})})},so=s=>{const{user:a}=Ge(),m=t.useRef(null),[x,p]=t.useState({studyStreak:0,questionsAsked:0,conceptsMastered:0}),[l,h]=t.useState({title:"Daily Learning Goal",description:"Complete learning activities",currentProgress:0,targetCount:3,isCompleted:!1}),[u,d]=t.useState(!0),n=async()=>{if(a)try{const{data:g,error:c}=await E.from("user_learning_stats").select("*").eq("user_id",a.id).eq("classroom_subject",s).maybeSingle();if(c&&c.code!=="PGRST116"){console.error("Error fetching stats:",c);return}const o=new Date().toISOString().split("T")[0],{data:i,error:f}=await E.from("user_daily_goals").select("*").eq("user_id",a.id).eq("classroom_subject",s).eq("goal_date",o).maybeSingle();if(f&&f.code!=="PGRST116"){console.error("Error fetching daily goal:",f);return}g&&p({studyStreak:g.study_streak_days||0,questionsAsked:g.questions_asked_count||0,conceptsMastered:g.concepts_mastered_count||0}),i&&h({title:i.goal_title,description:i.goal_description||"Complete learning activities",currentProgress:i.current_progress,targetCount:i.target_count,isCompleted:i.is_completed})}catch(g){console.error("Error fetching learning data:",g)}finally{d(!1)}};return t.useEffect(()=>{n()},[a,s]),t.useEffect(()=>a?(m.current&&(m.current.statsChannel&&E.removeChannel(m.current.statsChannel),m.current.goalChannel&&E.removeChannel(m.current.goalChannel),m.current=null),(async()=>{try{const c=Date.now(),o=Math.random().toString(36).substring(7),i=`learning-stats-${a.id}-${s}-${c}-${o}`,f=`daily-goals-${a.id}-${s}-${c}-${o}`;console.log("Setting up subscriptions for",a.id,s);const y=E.channel(i).on("postgres_changes",{event:"*",schema:"public",table:"user_learning_stats",filter:`user_id=eq.${a.id},classroom_subject=eq.${s}`},w=>{if(console.log("Stats update received:",w),w.new){const P=w.new;p(k=>({studyStreak:P.study_streak_days||k.studyStreak,questionsAsked:P.questions_asked_count||k.questionsAsked,conceptsMastered:P.concepts_mastered_count||k.conceptsMastered}))}}).subscribe(),N=new Date().toISOString().split("T")[0],A=E.channel(f).on("postgres_changes",{event:"*",schema:"public",table:"user_daily_goals",filter:`user_id=eq.${a.id},classroom_subject=eq.${s},goal_date=eq.${N}`},w=>{if(console.log("Goal update received:",w),w.new){const P=w.new;h({title:P.goal_title,description:P.goal_description||"Complete learning activities",currentProgress:P.current_progress,targetCount:P.target_count,isCompleted:P.is_completed})}}).subscribe();m.current={statsChannel:y,goalChannel:A}}catch(c){console.error("Error setting up subscriptions:",c)}})(),()=>{console.log("Cleaning up subscriptions for",a.id,s),m.current&&(m.current.statsChannel&&E.removeChannel(m.current.statsChannel),m.current.goalChannel&&E.removeChannel(m.current.goalChannel),m.current=null)}):void 0,[a?.id,s]),{stats:x,dailyGoal:l,loading:u,incrementQuestionsAsked:async()=>
158{if(a)try{const{error:g}=await E.rpc("increment_questions_asked",{p_classroom_subject:s});g&&console.error("Error incrementing questions asked:",g)}catch(g){console.error("Error incrementing questions asked:",g)}},incrementConceptsMastered:async()=>{if(a)try{const{error:g}=await E.rpc("increment_concepts_mastered",{p_classroom_subject:s});g&&console.error("Error incrementing concepts mastered:",g)}catch(g){console.error("Error incrementing concepts mastered:",g)}},updateDailyGoalProgress:async(g=1)=>{if(a)try{const{error:c}=await E.rpc("update_daily_goal_progress",{p_classroom_subject:s,p_increment:g});c&&console.error("Error updating daily goal progress:",c)}catch(c){console.error("Error updating daily goal progress:",c)}},logActivity:async(g,c={})=>{if(a)try{const{error:o}=await E.from("user_activity_log").insert({user_id:a.id,classroom_subject:s,activity_type:g,activity_data:c});o&&console.error("Error logging activity:",o)}catch(o){console.error("Error logging activity:",o)}},refetch:n}},ao=()=>{const[s,a]=t.useState([]),[m,x]=t.useState(!0),{toast:p}=we(),l=async()=>{try{const{data:c,error:o}=await E.from("bible_studies").select("*").eq("is_active",!0).order("created_at",{ascending:!1});if(o)throw o;a(c||[])}catch(c){console.error("Error loading bible studies:",c),p({title:"Error",description:"Failed to load bible studies",variant:"destructive"})}finally{x(!1)}},h=async c=>{try{const{data:o}=await E.auth.getUser(),{data:i,error:f}=await E.from("bible_studies").insert({...c,user_id:o.user?.id}).select().single();if(f)throw f;return a(y=>[i,...y]),p({title:"Success",description:"Bible study created successfully"}),i}catch(o){throw console.error("Error creating bible study:",o),p({title:"Error",description:"Failed to create bible study",variant:"destructive"}),o}},u=async(c,o)=>{try{const{data:i,error:f}=await E.from("bible_studies").update(o).eq("id",c).select().single();if(f)throw f;return a(y=>y.map(N=>N.id===c?i:N)),p({title:"Success",description:"Bible study updated successfully"}),i}catch(i){throw console.error("Error updating bible study:",i),p({title:"Error",description:"Failed to update bible study",variant:"destructive"}),i}},d=async(c,o,i,f)=>{try{const{data:y,error:N}=await E.functions.invoke("bible-study-generator",{body:{passage:c,categories:o,audience:i,assistantId:f}});if(N)throw N;return y}catch(y){throw console.error("Error generating study content:",y),y}},n=async(c,o)=>u(c,{collection_id:o}),r=async c=>{try{const{error:o}=await E.from("bible_studies").update({is_active:!1}).eq("id",c);if(o)throw o;a(i=>i.filter(f=>f.id!==c)),p({title:"Success",description:"Bible study deleted successfully"})}catch(o){throw console.error("Error deleting bible study:",o),p({title:"Error",description:"Failed to delete bible study",variant:"destructive"}),o}},v=c=>s.filter(o=>o.target_audience===c),j=c=>s.filter(o=>o.difficulty_level===c),b=c=>s.filter(o=>o.book_name.toLowerCase()===c.toLowerCase()),g=c=>{const o=c.toLowerCase();return s.filter(i=>i.title.toLowerCase().includes(o)||i.bible_passage.toLowerCase().includes(o)||i.book_name.toLowerCase().includes(o)||i.theme_tags.some(f=>f.toLowerCase().includes(o)))};return t.useEffect(()=>{l()},[]),{bibleStudies:s,isLoading:m,createBibleStudy:h,updateBibleStudy:u,generateStudyContent:d,addToCollection:n,deleteBibleStudy:r,getStudiesByAudience:v,getStudiesByDifficulty:j,getStudiesByBook:b,searchStudies:g,loadBibleStudies:l}},ro=({onSendToChat:s})=>{const{toast:a}=we(),{role:m}=Xe(),[x,p]=t.useState(""),[l,h]=t.useState(""),[u,d]=t.useState(""),[n,r]=t.useState(""),[v,j]=t.useState(""),[b,g]=t.useState(""),[c,o]=t.useState("NIV"),[i,f]=t.useState("student"),[y,N]=t.useState("beginner"),[A,w]=t.useState([]),[P,k]=t.useState(!1),[I,T]=t.useState(null),[M,G]=t.useState(""),{bibleStudies:D,createBibleStudy:Y,generateStudyContent:de}=ao(),{getAssistantForTool:pe}=bs(),xe=[{id:"historical_context",label:"Historical Context",icon:ea,description:"Time period, cultural background, geographical setting"},{id:"character_analysis",label:"Character Analysis",icon:Rt,description:"Motivations, character development, lessons learned"},{id:"theological_themes",label:"Theological Themes",icon:ot,description:"Core spiritual principles and doctrinal insights"},{id:"life_application",label:"Life Application",icon:us,description:"Modern-day relevance and practical applications"},{id:"cross_references",label:"Cross References",icon:rs,description:"Related Bible passages and parallel stories"},{id:"discussion_questions",label:"Discussion Questions",icon:Qa,description:"Thought-provoking questions for group study"},{id:"prayer_points",label:"Prayer Points",icon:ot,description:"Specific prayer focuses derived from the passage"},{id:"action_steps",label:"Action Steps",icon:Ya,description:"Practical ways to implement Biblical lessons"},{id:"symbolic_elements",label:"Symbolic Elements",icon:Je,description:"Metaphors, symbols, and deeper meanings"},{id:"leadership_lessons",label:"Leadership Lessons",icon:tt,description:"Principles for Christian leadership and service"}],ce=["NIV","ESV","NASB","KJV","NLT","MSG"],oe=[{title:"David and Goliath",reference:"1 Samuel 17",theme:"courage"},{title:"The Good Samaritan",reference:"Luke 10:25-37",theme:"love"},{title:"The Prodigal Son",reference:"Luke 15:11-32",theme:"forgiveness"},{title:"Moses and the Red Sea",reference:"Exodus 14",theme:"faith"},{title:"Daniel in the Lions Den",reference:"Daniel 6",theme:"courage"},{title:"Jesus Feeds 5000",reference:"Matthew 14:13-21",theme:"provision"},{title:"The Beatitudes",reference:"Matthew 5:1-12",theme:"blessing"},{title:"Pauls Conversion",reference:"Acts 9:1-19",theme:"transformation"}],K=m==="developer"?xe:m==="youth_leader"?xe.filter(S=>S.id!=="theological_themes"):m==="parent"?xe.filter(S=>
158["life_application","character_analysis","discussion_questions","prayer_points","action_steps"].includes(S.id)):xe.filter(S=>["character_analysis","life_application","discussion_questions","action_steps"].includes(S.id)),O=S=>{w(z=>z.includes(S)?z.filter(V=>V!==S):[...z,S])},W=S=>{h(S.reference),G(`Study of ${S.title}`);const z=S.reference.split(" ");if(z.length>=2){const V=z.slice(0,-1).join(" "),q=z[z.length-1];if(d(V),q.includes(":")){const[C,H]=q.split(":");if(r(parseInt(C)),H.includes("-")){const[ue,ve]=H.split("-");j(parseInt(ue)),g(parseInt(ve))}else j(parseInt(H)),g("")}else r(parseInt(q)),j(""),g("")}},B=async()=>{if(!l.trim()||A.length===0){a({title:"Missing Information",description:"Please select a passage and at least one analysis category",variant:"destructive"});return}k(!0);try{const S=pe("biblical-deep-dive")||void 0,z=await de(l,A,i,S);T(z),a({title:"Study Generated!",description:"Your Biblical deep dive study has been created"})}catch(S){console.error("Error generating study:",S),a({title:"Error",description:"Failed to generate study content",variant:"destructive"})}finally{k(!1)}},F=async()=>{if(!I||!M.trim()){a({title:"Missing Information",description:"Please provide a title for your study",variant:"destructive"});return}try{await Y({title:M,bible_passage:l,book_name:u,chapter_number:n||void 0,verse_start:v||void 0,verse_end:b||void 0,translation_version:c,analysis_categories:A,generated_content:I,target_audience:i,theme_tags:[],difficulty_level:y,is_active:!0}),a({title:"Study Saved!",description:"Your Bible study has been saved to your collection"})}catch(S){console.error("Error saving study:",S)}},Q=()=>{if(I&&s){const S=`[Bible Study: ${M}]
159
160${l} (${c})
161
162Key insights from this study have been generated with focus on: ${A.join(", ")}`;s(S),a({title:"Shared with Tutor",description:"Your Bible study has been shared with your tutor"})}};return e.jsx("div",{className:"w-full max-w-6xl mx-auto p-6 space-y-6",children:e.jsxs(te,{children:[e.jsxs(Ee,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-5 w-5 text-primary"}),"Biblical Deep Dive - Advanced Scripture Analysis Tool"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(me,{variant:"outline",className:"flex items-center gap-1",children:[e.jsx(Va,{className:"h-3 w-3"}),m==="developer"?"Full Access":m==="youth_leader"?"Leader Access":m==="parent"?"Parent Access":"Student Access"]})})]}),e.jsxs(ie,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(te,{children:[e.jsx(Ee,{children:e.jsx(Ae,{className:"text-sm",children:"Popular Bible Stories"})}),e.jsx(ie,{children:e.jsx("div",{className:"grid grid-cols-1 gap-2",children:oe.map(S=>e.jsx(_,{variant:"outline",onClick:()=>W(S),className:"h-auto p-3 justify-start",children:e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:S.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S.reference})]})},S.reference))})})]}),e.jsxs(te,{children:[e.jsx(Ee,{children:e.jsx(Ae,{className:"text-sm",children:"Manual Scripture Entry"})}),e.jsxs(ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Full Reference"}),e.jsx(_e,{placeholder:"e.g., John 3:16 or Matthew 5:1-12",value:l,onChange:S=>h(S.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Book"}),e.jsx(_e,{placeholder:"e.g., John",value:u,onChange:S=>d(S.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Chapter"}),e.jsx(_e,{type:"number",placeholder:"3",value:n,onChange:S=>r(S.target.value?parseInt(S.target.value):"")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Verse Start"}),e.jsx(_e,{type:"number",placeholder:"16",value:v,onChange:S=>j(S.target.value?parseInt(S.target.value):"")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Verse End (optional)"}),e.jsx(_e,{type:"number",placeholder:"17",value:b,onChange:S=>g(S.target.value?parseInt(S.target.value):"")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Translation"}),e.jsxs(De,{value:c,onValueChange:o,children:[e.jsx(Le,{children:e.jsx($e,{})}),e.jsx(Me,{children:ce.map(S=>e.jsx(Z,{value:S,children:S},S))})]})]})]})]})]}),e.jsx(Kt,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Analysis Configuration"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Target Audience"}),e.jsxs(De,{value:i,onValueChange:S=>f(S),children:[e.jsx(Le,{children:e.jsx($e,{})}),e.jsxs(Me,{children:[e.jsx(Z,{value:"student",children:"Student"}),e.jsx(Z,{value:"parent",children:"Parent"}),e.jsx(Z,{value:"youth_leader",children:"Youth Leader"}),e.jsx(Z,{value:"super_admin",children:"Super Admin"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Difficulty Level"}),e.jsxs(De,{value:y,onValueChange:S=>N(S),children:[e.jsx(Le,{children:e.jsx($e,{})}),e.jsxs(Me,{children:[e.jsx(Z,{value:"beginner",children:"Beginner"}),e.jsx(Z,{value:"intermediate",children:"Intermediate"}),e.jsx(Z,{value:"advanced",children:"Advanced"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Study Title"}),e.jsx(_e,{placeholder:"Enter study title...",value:M,onChange:S=>G(S.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Analysis Categories"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select the types of analysis you want to include in your study (available based on your role level)"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:K.map(S=>{const z=S.icon,V=A.includes(S.id);return e.jsxs("div",{className:`flex items-start space-x-3 p-3 border rounded-lg cursor-pointer transition-colors ${V?"border-primary bg-primary/5":"hover:border-gray-400"}`,onClick:()=>O(S.id),children:[e.jsx(gr,{checked:V,onChange:()=>O(S.id),className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:S.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:S.description})]})]},S.id)})}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[e.jsx(_,{variant:"outline",size:"sm",onClick:()=>w(K.map(S=>S.id)),children:"Select All"}),e.jsx(_,{variant:"outline",size:"sm",onClick:()=>w([]),children:"Clear All"})]})]}),e.jsx(Kt,{}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(_,{onClick:B,disabled:!l||A.length===0||P,className:"flex items-center gap-2",children:P?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"h-4 w-4"}),"Generate Deep Dive Study"]})}),I&&e.jsxs(e.Fragment,{children:[e.jsxs(_,{variant:"outline",onClick:F,className:"flex items-center gap-2",disabled:!M.trim(),children:[e.jsx(We,{className:"h-4 w-4"}),"Save Study"]}),s&&e.jsxs(_,{variant:"outline",onClick:Q,className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Share with Tutor"]})]})]}),I&&e.jsxs(te,{children:[e.jsxs(Ee,{children:[e.jsx(Ae,{className:"text-lg",children:"Generated Bible Study"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{variant:"outline",children:l}),e.jsx(me,{variant:"outline",children:c}),e.jsx(me,{variant:"outline",children:i}),e.jsx(me,{variant:"outline",children:y})]})]}),e.jsx(ie,{children:e.jsx(Ze,{className:"h-[400px] w-full border rounded-lg p-4",children:e.jsx("div",{className:"space-y-6",children:A.map(S=>{const z=K.find(q=>q.id===S),V=I[S];return!V||!z?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z.icon,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-semibold",children:z.label})]}),e.jsx("div",{className:"text-sm whitespace-pre-wrap",children:typeof V=="string"?V:JSON.stringify(V,null,2)}),e.jsx(Kt,{})]},S)})})})})]}),D.length>0&&e.jsxs(te,{children:[e.jsx(Ee,{children:e.jsx(Ae,{className:"text-sm",children:"Recent Bible Studies"})}),e.jsx(ie,{children:e.jsx("div",{className:"space-y-3",children:D.slice(0,5).map(S=>e.jsxs("div",{className:"p-3 border rounded-lg space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsx("h4",{className:"font-medium",children:S.title}),e.jsx(me,{variant:"outline",children:S.target_audience})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S.bible_passage," (",S.translation_version,")"]}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[S.analysis_categories.slice(0,3).map(z=>e.jsx(me,{variant:"secondary",className:"text-xs",children:z.replace("_"," ")},z)),S.analysis_categories.length>3&&e.jsxs(me,{variant:"secondary",className:"text-xs",children:["+",S.analysis_categories.length-3," more"]})]})]},S.id))})})]})]})]})})},no=({onSendToChat:s})=>{const[a,m]=t.useState(null),[x,p]=t.useState(!1),{characters:l,createConversation:h}=Nr(),{getAssistantForCharacter:u}=Cr(),{getAssistantForTool:d}=bs(),{generateContent:n}=pr(),{toast:r}=we(),v=t.useMemo(()=>["David","Joseph","Mary","Daniel","Esther","Josiah","Samuel"].map(o=>o.toLowerCase()),[]),j=o=>(o||"").toLowerCase().replace(/\(.*?\)/g,"").trim(),b=t.useMemo(()=>l.filter(o=>{const i=j(o.display_name),f=j(o.name);return v.some(y=>i.includes(y)||f.includes(y))}),[l,v]),g=async o=>{try{await h({character_id:o.id,conversation_title:`Teen ${o.display_name}`,messages:[],learning_objectives:[],session_duration_minutes:0,is_completed:!1});const i=u(o.id)||d("biblical-roleplay"),f=(o.primary_stories||[]).slice(0,2).join(", "),y=(o.character_traits||[]).slice(0,3).join(", "),N=`You are ${o.display_name} portrayed as a teenager. Speak in first person with humility and wisdom.
163Open with a warm 2-3 sentence introduction for a teen audience.
164Reference key stories if relevant: ${f}.
165Personality traits to embody: ${y}.
166Keep it respectful and biblically grounded.`;let A=`Hi! I'm ${o.display_name} as a teenager. ${o.personality_description||""}`;if(i)try{const w=await n(i,N),P=typeof w=="string"?w:w?.content??"";P&&(A=P)}catch(w){console.warn("Assistant generation failed, using fallback.",w)}s?(s(A),r({title:"Added to chat",description:`${o.display_name} joined the conversation.`})):(m(o),p(!0))}
166catch(i){console.error("Error adding teen persona:",i),r({title:"Error",description:"Could not add persona to chat",variant:"destructive"})}},c=o=>{switch(o){case"beginner":return"bg-green-100 text-green-800";case"intermediate":return"bg-yellow-100 text-yellow-800";case"advanced":return"bg-red-100 text-red-800";default:return"bg-gray-100 text-gray-800"}};return e.jsx("div",{className:"w-full max-w-6xl mx-auto p-6 space-y-6",children:e.jsxs(te,{children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5 text-primary"}),"Teens in the Bible - Interactive Character Study"]})}),e.jsx(ie,{children:x?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:["Conversation with ",a?.display_name]}),e.jsx(_,{variant:"outline",onClick:()=>p(!1),children:"End Conversation"})]}),e.jsx(te,{children:e.jsx(ie,{className:"p-4",children:e.jsx(Ze,{className:"h-[400px] w-full",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"p-3 bg-muted rounded-lg",children:e.jsxs("p",{className:"text-sm",children:[e.jsxs("strong",{children:[a?.display_name," (Teen):"]})," Peace be with you! I am ",a?.display_name,". ",a?.personality_description]})}),e.jsx("div",{className:"text-center text-sm text-muted-foreground",children:"Chat integration would be implemented here with the OpenAI Assistant API"})]})})})})]}):e.jsx("div",{className:"space-y-6",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(o=>e.jsx(te,{className:"hover:shadow-lg transition-shadow",children:e.jsxs(ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[o.display_name,e.jsx(me,{variant:"outline",children:"Teen"})]}
166),e.jsx(me,{className:c(o.difficulty_rating),children:o.difficulty_rating})]}),e.jsx("div",{className:"flex gap-1",children:e.jsxs(me,{variant:"outline",children:[o.testament," Testament"]})}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-3",children:o.personality_description}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium",children:"Key Stories:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:(o.primary_stories||[]).slice(0,3).map((i,f)=>e.jsx(me,{variant:"secondary",className:"text-xs",children:i},f))})]}),e.jsxs(_,{onClick:()=>g(o),className:"w-full flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4"}),"Add Teen Persona to Chat"]})]})},o.id))})})})]})})},oo=()=>{const[s,a]=t.useState(!1);return Jr(),{awardTokensForTaskCompletion:async(l,h,u)=>{a(!0);try{const{data:d,error:n}=await E.rpc("award_tokens_for_task_completion",{p_student_id:l,p_assignment_id:h,p_item_id:u});if(n)throw n;const{data:r}=await E.from("student_profiles").select("total_tokens").eq("id",l).maybeSingle();typeof r?.total_tokens=="number"&&window.dispatchEvent(new CustomEvent("student:tokens-update",{detail:{newTotal:r.total_tokens}}));const{data:v,error:j}=await E.rpc("award_completion_bonus_if_completed",{p_student_id:l,p_assignment_id:h});if(!j&&v===!0){const{data:b}=await E.from("student_profiles").select("total_tokens").eq("id",l).maybeSingle();typeof b?.total_tokens=="number"&&window.dispatchEvent(new CustomEvent("student:tokens-update",{detail:{newTotal:b.total_tokens}}))}return Jt("collect"),!!d||!0}catch(d){return console.error("Error auto-awarding tokens for task completion:",d),!1}finally{a(!1)}},awardTokensForToolUsage:async(l,h,u)=>{a(!0);try{const{data:d,error:n}=await E.rpc("award_tokens_for_tool_usage",{p_student_id:l,p_tool_name:h,p_classroom_id:u||null});if(n)throw n;const{data:r}=await E.from("student_profiles").select("total_tokens").eq("id",l).maybeSingle();return typeof r?.total_tokens=="number"&&window.dispatchEvent(new CustomEvent("student:tokens-update",{detail:{newTotal:r.total_tokens}})),Jt("collect"),!!d||!0}catch(d){return console.error("Error auto-awarding tokens for tool usage:",d),!1}finally{a(!1)}},awardTokensByEvent:async(l,h,u)=>{a(!0);try{const{data:d,error:n}=await E.rpc("award_tokens_by_event_current",{p_event_type:l,p_classroom_id:h||null,p_metadata:u||{}});if(n)throw n;const r=Array.isArray(d)?d[0]:null;return r&&typeof r.new_total_tokens=="number"&&window.dispatchEvent(new CustomEvent("student:tokens-update",{detail:{newTotal:r.new_total_tokens}})),r&&r.success?(Jt("collect"),!0):!1}catch(d){return console.error("Error awarding tokens by event:",d),!1}finally{a(!1)}},isAwarding:s}},ws=s=>{const[a,m]=t.useState([]),[x,p]=t.useState(!0),[l,h]=t.useState(!1),u=async()=>{if(s)try{const{data:g,error:c}=await E.from("classroom_tutorial_videos").select("*").eq("classroom_id",s).order("slot_number");if(c)throw c;m(g||[])}catch(g){console.error("Error fetching classroom tutorials:",g),ne.error("Failed to load classroom tutorial videos")}finally{p(!1)}};t.useEffect(()=>{u()},[s]);const d=async(g,c)=>{if(s){h(!0);try{const{data:{user:o}}=await E.auth.getUser();if(!o)throw new Error("User not authenticated");const i=Date.now(),f=`${s}/${g}/${i}_${c.name}`,{data:y,error:N}=await E.storage.from("classroom-tutorial-videos").upload(f,c);if(N)throw N;const{data:{publicUrl:A}}=E.storage.from("classroom-tutorial-videos").getPublicUrl(f),w=await n(c);if(!w)throw new Error("Failed to generate thumbnail");const P=`${s}/${g}/${i}_thumbnail.jpg`,{error:k}=await E.storage.from("classroom-tutorial-videos").upload(P,w);if(k)throw k;const{data:{publicUrl:I}}=E.storage.from("classroom-tutorial-videos").getPublicUrl(P),{error:T}=await E.from("classroom_tutorial_videos").upsert({classroom_id:s,slot_number:g,title:`Tutorial Video ${g}`,video_url:A,auto_thumbnail_url:I,uploaded_by:o.id},{onConflict:"classroom_id,slot_number"});if(T)throw T;ne.success("Video uploaded successfully"),await u()}catch(o){console.error("Error uploading video:",o),ne.error("Failed to upload video")}finally{h(!1)}}},n=async g=>new Promise(c=>{const o=document.createElement("video"),i=document.createElement("canvas"),f=i.getContext("2d");
166o.preload="metadata",o.muted=!0,o.playsInline=!0,o.onloadeddata=()=>{o.currentTime=Math.min(2,o.duration/2)},o.onseeked=()=>{i.width=o.videoWidth,i.height=o.videoHeight,f?.drawImage(o,0,0),i.toBlob(y=>{URL.revokeObjectURL(o.src),c(y)},"image/jpeg",.8)},o.onerror=()=>{URL.revokeObjectURL(o.src),c(null)},o.src=URL.createObjectURL(g)});return{classroomTutorials:a,loading:x,uploading:l,uploadVideo:d,saveVideoUrl:async(g,c,o)=>{if(s)try{const{data:{user:i}}=await E.auth.getUser();if(!i)throw new Error("User not authenticated");const{error:f}=await E.from("classroom_tutorial_videos").upsert({classroom_id:s,slot_number:g,title:o||`Tutorial Video ${g}`,video_url:c,uploaded_by:i.id,auto_thumbnail_url:null,custom_thumbnail_url:null},{onConflict:"classroom_id,slot_number"});if(f)throw f;ne.success("Video URL saved successfully"),await u()}catch(i){console.error("Error saving video URL:",i),ne.error("Failed to save video URL")}},updateTitle:async(g,c)=>{if(s)try{const{error:o}=await E.from("classroom_tutorial_videos").update({title:c}).eq("classroom_id",s).eq("slot_number",g);if(o)throw o;ne.success("Title updated successfully"),await u()}catch(o){console.error("Error updating title:",o),ne.error("Failed to update title")}},deleteVideo:async g=>{if(s)try{const{error:c}=await E.from("classroom_tutorial_videos").delete().eq("classroom_id",s).eq("slot_number",g);if(c)throw c;ne.success("Video deleted successfully"),await u()}catch(c){console.error("Error deleting video:",c),ne.error("Failed to delete video")}},getClassroomTutorialBySlot:g=>a.find(c=>c.slot_number===g),refetch:u}},io=({open:s,onOpenChange:a,classroomId:m})=>{const x=t.useRef(null),[p,l]=t.useState(""),{getClassroomTutorialBySlot:h,uploading:u,uploadVideo:d,saveVideoUrl:n,deleteVideo:r}=ws(m),v=h(3),j=3,b=async o=>{const i=o.target.files?.[0];i&&await d(j,i)},g=async()=>{p.trim()&&(await n(j,p.trim()),l(""))},c=async()=>{await r(j)};return e.jsx(qe,{open:s,onOpenChange:a,children:e.jsxs(Oe,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Be,{children:e.jsx(Ve,{children:"Manage Classroom Instructions"})}),e.jsxs("div",{className:"space-y-6 py-4",children:[v&&e.jsx(te,{className:"bg-card border-border",children:e.jsxs(ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ka,{className:"w-5 h-5 text-primary"}),e.jsx("h4",{className:"font-medium text-foreground",children:"Current Tutorial"})]}),e.jsx(_,{variant:"ghost",size:"sm",onClick:c,className:"text-destructive hover:text-destructive",children:e.jsx(yt,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"aspect-video bg-muted rounded-lg overflow-hidden",children:e.jsx("iframe",{src:v.video_url,className:"w-full h-full",allowFullScreen:!0,title:"Classroom Tutorial"})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground",children:v?"Replace Tutorial":"Add Tutorial"}),e.jsxs("div",{children:[e.jsx("input",{ref:x,type:"file",accept:"video/*",onChange:b,className:"hidden"}),e.jsxs(_,{onClick:()=>x.current?.click(),disabled:u,variant:"outline",className:"w-full",children:[e.jsx(Et,{className:"w-4 h-4 mr-2"}),u?"Uploading...":"Upload Video File"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-center text-muted-foreground text-xs",children:"or"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{placeholder:"Paste video URL (YouTube, Vimeo, etc.)",value:p,onChange:o=>l(o.target.value),className:"bg-background border-input text-foreground"}),e.jsxs(_,{size:"sm",onClick:g,disabled:!p.trim(),children:[e.jsx(ns,{className:"w-4 h-4 mr-1"}),"Save"]})]})]})]}),e.jsx(te,{className:"bg-muted/50 border-border",children:e.jsxs(ie,{className:"p-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"For Students:"})," The tutorial video will appear in their Learning Tools section."]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:[e.jsx("strong",{children:"For Managers:"})," You'll see a management card to edit the tutorial."]})]})})]})]})})},ls=({classroomId:s,onActionComplete:a,onHomeworkSubmit:m,onSendToChat:x,chatMessages:p=[],hideHeader:l=!1})=>{const{toast:h}=we();Xn(ys(s).subject);const{toggleFavorite:u,isFavorited:d}=eo();so(s);const[n,r]=t.useState(null),[v,j]=t.useState("bible-verses"),{openPaulaModal:b}=Zn({classroomId:s,onSendToChat:x}),{user:g}=Ge(),{awardTokensForToolUsage:c}=oo(),{currentStudent:o}=at(),{getStudentProfileForAssistant:i,saveHiddenMessage:f}=Bt(),{isToolEnabled:y,getToolOrder:N}=Wr(s),{getClassroomTutorialBySlot:A}=ws(s),w=t.useRef(null),[P,k]=t.useState(!1),[I,T]=t.useState(!1),M=async(F,Q)=>{x&&x(F),o?.id&&await c(o.id,Q,s)},G=s==="faith",D=()=>p&&p.length>0?p.slice(-5).map(Q=>`${Q.sender}: ${Q.content}`).join(`
167`):"",Y=[{id:"my-learning-aids",title:"My Learning Aids",description:"Access your saved study guides, quizzes, and learning materials",icon:Qe,color:"from-purple-500 to-orange-500",onClick:()=>r("my-learning-aids")},{id:"prompt-engineer",title:"Prompt Engineer",description:"Get help crafting the perfect prompt with Paula",icon:ft,color:"from-yellow-500 to-orange-500",onClick:()=>b()},{id:"generate-challenge",title:"Generate Challenge",description:"Create engaging challenges based on your current topic",icon:us,color:"from-purple-500 to-purple-600",onClick:()=>r("generate-challenge")},{id:"scrape-youtube",title:"Find YouTube Video",description:"Discover the perfect educational video for your topic",icon:Js,color:"from-red-500 to-red-600",onClick:()=>r("scrape-youtube")},{id:"principle-injection",title:"Principle Injection",description:"Apply learning principles to your current discussion",icon:nt,color:"from-blue-500 to-blue-600",onClick:()=>r("principle-injection")},{id:"roleplay",title:"Roleplay",description:"Interactive scenarios tailored to your subject",icon:tt,color:"from-purple-500 to-pink-500",onClick:()=>r("roleplay")},{id:"study-guide",title:"Study Guide",description:"Get a personalized study guide with optional AI images",icon:Qe,color:"from-indigo-500 to-indigo-600",onClick:()=>r("enhanced-study-guide")},{id:"interactive-quiz",title:"Interactive Quiz",description:"Test your knowledge with AI-generated questions",icon:nt,color:"from-violet-500 to-violet-600",onClick:()=>r("interactive-quiz")},{id:"generate-image",title:"Generate Image",description:"Create visual content with AI",icon:ut,color:"from-pink-500 to-pink-600",onClick:()=>r("generate-image")},{id:"generate-table",title:"Generate Table",description:"Create structured data tables",icon:hs,color:"from-teal-500 to-teal-600",onClick:()=>r("generate-table")}
167,{id:"flashcards",title:"AI Flashcards",description:"Generate & play with AI-powered flashcards",icon:pt,color:"from-purple-500 to-purple-600",onClick:()=>r("flashcards")},{id:"button-journal",title:"Button Journal",description:"Spiritual Growth Tracker with mood & prayer",icon:Qe,color:"from-indigo-500 to-purple-600",onClick:()=>r("button-journal")},{id:"biblical-deep-dive",title:"Biblical Deep Dive",description:"Advanced Scripture Analysis Tool",icon:It,color:"from-amber-500 to-orange-600",onClick:()=>r("biblical-deep-dive")},{id:"biblical-roleplay",title:"Teens in the Bible",description:"Interactive Character Study conversations",icon:tt,color:"from-emerald-500 to-teal-600",onClick:()=>r("biblical-roleplay")}],de=[{id:"suggestion-box",title:"Suggestion Box",description:"Send suggestions, bugs, and ideas to the developer",icon:it,color:"from-orange-500 to-orange-600",onClick:()=>r("suggestion-box")},{id:"learning-profile",title:"Personalize My Chat",description:"Send your learning profile to personalize the AI responses",icon:Rt,color:"from-cyan-500 to-cyan-600",onClick:async()=>{try{const F=await i();F?(await f(s,"AI Tutor","SEND_LEARNING_PROFILE","app_to_assistant",{profile:F,trigger:"manual_personalization"}),h({title:"Profile Sent",description:"Your learning profile has been shared to personalize responses."})):h({title:"No Profile Found",description:"Please create a learning profile first in the settings.",variant:"destructive"})}catch(F){console.error("Error sending learning profile:",F),h({title:"Error",description:"Failed to send learning profile.",variant:"destructive"})}}}],ce=(G?[...[{id:"bible-verses",title:"Bible Verses",description:"Generate random or context-smart Bible verses",icon:It,color:"from-amber-500 to-amber-600",onClick:()=>{j("bible-verses"),r("faith-tools")}},{id:"prayers",title:"Prayer Generator",description:"AI-generated prayers using Peggy assistant",icon:ot,color:"from-rose-500 to-rose-600",onClick:()=>{j("prayers"),r("faith-tools")}},{id:"memory-aids",title:"Memory Aids",description:"Create poems, raps, flashcards to remember concepts",icon:nt,color:"from-emerald-500 to-emerald-600",onClick:()=>{j("memory-aids"),r("faith-tools")}}],...Y]:Y).filter(F=>y(F.id)),oe=de.filter(F=>y(F.id)),ae=[...ce].sort((F,Q)=>{const S=N(F.id),z=N(Q.id);if(S!==z)return S-z;const V=d(F.id),q=d(Q.id);return V&&!q?-1:!V&&q?1:0}),K=A(3),O=g?.user_metadata?.role==="accountManager"||g?.user_metadata?.isDeveloper===!0;t.useEffect(()=>{const F=w.current?.querySelector("[data-radix-scroll-area-viewport]");if(!F)return;const Q=()=>{const{scrollTop:S,scrollHeight:z,clientHeight:V}=F,q=z-S-V;k(q>50&&z>V)};return F.addEventListener("scroll",Q),Q(),()=>F.removeEventListener("scroll",Q)},[ae,oe,K]);const W=()=>{const F=w.current?.querySelector("[data-radix-scroll-area-viewport]");F&&F.scrollTo({top:F.scrollHeight,behavior:"smooth"})},B=F=>{const Q=F.icon,S=d(F.id);return e.jsxs(te,{variant:"paper",className:"hover:border-primary/50 transition-colors cursor-pointer group",children:[e.jsx(Ee,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`p-2 rounded-lg bg-gradient-to-r ${F.color}`,children:e.jsx(Q,{className:"w-5 h-5 text-white"})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ae,{className:"text-sm font-semibold text-foreground group-hover:text-primary",children:F.title})}),e.jsx(_,{variant:"ghost",size:"sm",onClick:z=>{z.stopPropagation(),u(F.id)},className:"p-1 h-6 w-6 text-muted-foreground hover:text-yellow-400",children:e.jsx(Xs,{className:`w-4 h-4 ${S?"fill-current text-yellow-400":""}`})})]})}),e.jsxs(ie,{className:"pt-0",children:[e.jsx("div",{className:"paper-inset p-2 rounded-md mb-3",children:e.jsx("p",{className:"text-muted-foreground text-xs",children:F.description})}),e.jsxs(_,{onClick:F.onClick,size:"sm",className:`w-full bg-gradient-to-r ${F.color} hover:opacity-90 text-white text-xs`,children:[e.jsx(Q,{className:"w-3 h-3 mr-1"}),F.id==="prompt-engineer"?"Improve Prompt":"Start"]})]})]},F.id)};return e.jsxs("div",{className:"flex flex-col h-full",children:[!l&&e.jsx("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Learning Tools"})}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsxs(Ze,{ref:w,className:"h-full w-full",children:[e.jsxs("div",{className:"space-y-6 pr-4",children:[ae.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Featured Learning Tools"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",ae.length,")"]})]}),ae.map(B)]}),(K||O)&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Classroom Resources"})}),!O&&K&&e.jsxs(te,{className:"bg-card border-border shadow-sm",children:[e.jsx(Ee,{className:"pb-3",children:e.jsx(Ae,{className:"text-sm font-semibold text-foreground",children:K.title})}),e.jsx(ie,{className:"pt-0",children:e.jsx("div",{className:"aspect-video bg-muted rounded-lg overflow-hidden",children:e.jsx("iframe",{src:K.video_url,className:"w-full h-full",allowFullScreen:!0,title:"Classroom Tutorial"})})})]}),O&&e.jsxs(te,{className:"bg-card border-border hover:border-primary/50 shadow-sm transition-colors cursor-pointer group",onClick:()=>T(!0),children:[e.jsx(Ee,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-gradient-to-r from-blue-500 to-indigo-600",children:e.jsx(Is,{className:"w-5 h-5 text-white"})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ae,{className:"text-sm font-semibold text-foreground group-hover:text-primary",children:K?"Manage Tutorial":"Add Tutorial"})})]})}),e.jsxs(ie,{className:"pt-0",children:[e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:K?"Edit or replace the classroom-specific tutorial video":"Add a tutorial video for students in this classroom"}),e.jsxs(_,{size:"sm",className:"w-full bg-gradient-to-r from-blue-500 to-indigo-600 hover:opacity-90 text-white text-xs",children:[e.jsx(Is,{className:"w-3 h-3 mr-1"}),K?"Edit Tutorial":"Add Tutorial"]})]})]})]}),oe.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Communication Tools"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",oe.length,")"]})]}),oe.map(B)]})]}),e.jsx(xs,{orientation:"vertical"})]}),P&&e.jsxs(_,{onClick:W,size:"sm",variant:"secondary",className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10 shadow-lg animate-in fade-in slide-in-from-bottom-2",children:[e.jsx(zt,{className:"w-4 h-4 mr-1 animate-bounce"}),"Scroll for more"]})]}),e.jsx(zn,{open:n==="study-guide",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"Study Guide")}),e.jsx(Hn,{open:n==="interactive-quiz",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"Interactive Quiz"),chatMessages:p}),e.jsx(Ir,{open:n==="generate-challenge",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"Generate Challenge"),chatMessages:p}),e.jsx(Fr,{open:n==="scrape-youtube",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"YouTube Finder"),chatMessages:p}),e.jsx(la,{open:n==="suggestion-box",onOpenChange:F=>!F&&r(null)}),e.jsx(Dr,{open:n==="principle-injection",onOpenChange:F=>!F&&r(null),onSendToChat:F=>M(F,"Principle Injection"),classroomId:s}),e.jsx(Qn,{open:n==="roleplay",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"Roleplay"),chatMessages:p}),e.jsx(Lr,{open:n==="generate-image",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"Generate Image")}),e.jsx($r,{open:n==="generate-table",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"Generate Table"),chatMessages:p}),e.jsx(On,{open:n==="my-learning-aids",onOpenChange:F=>!F&&r(null)}),e.jsx(Rn,{open:n==="enhanced-study-guide",onOpenChange:F=>!F&&r(null),classroomId:s,onSendToChat:F=>M(F,"Enhanced Study Guide"),chatMessages:p}),G&&n==="faith-tools"&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",children:e.jsx("div",{className:"bg-background rounded-lg max-w-6xl w-full max-h-[90vh] overflow-hidden",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Faith Learning Tools"}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>r(null),children:"×"})]}),e.jsx("div",{className:"max-h-[80vh] overflow-y-auto",children:e.jsx(to,{chatContext:D(),defaultTab:v,onSendToChat:async(F,Q)=>{await M(`[${Q}] ${F}`,`Faith: ${Q}`),r(null)}})})]})})}),e.jsx(Mr,{isOpen:n==="flashcards",onClose:()=>r(null),context:{chatMessages:(p||[]).slice(-15).map(F=>({role:F.sender==="user"?"user":"assistant",content:F.content})),classroomId:s}}),n==="button-journal"&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",children:e.jsx("div",{className:"bg-background rounded-lg max-w-6xl w-full max-h-[90vh] overflow-hidden",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Journal + Vision Board"}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>r(null),children:"×"})]}),e.jsx("div",{className:"max-h-[80vh] overflow-y-auto",children:e.jsx(Kr,{classroomId:s,onSendToChat:x})})]})})}),n==="biblical-deep-dive"&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",children:e.jsx("div",{className:"bg-background rounded-lg max-w-6xl w-full max-h-[90vh] overflow-hidden",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Biblical Deep Dive"}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>r(null),children:"×"})]}),e.jsx("div",{className:"max-h-[80vh] overflow-y-auto",children:e.jsx(ro,{onSendToChat:x})})]})})}),n==="biblical-roleplay"&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",children:e.jsx("div",{className:"bg-background rounded-lg max-w-6xl w-full max-h-[90vh] overflow-hidden",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Teens in the Bible"}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>r(null),children:"×"})]}),e.jsx("div",{className:"max-h-[80vh] overflow-y-auto",children:e.jsx(no,{onSendToChat:x})})]})})}),e.jsx(io,{open:I,onOpenChange:T,classroomId:s})]})},_t=["#1e40af","#7c3aed","#dc2626","#059669","#d97706","#be185d","#4338ca","#0891b2"],kt=["linear-gradient(135deg, #667eea 0%, #764ba2 100%)","linear-gradient(135deg, #f093fb 0%, #f5576c 100%)","linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)","linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)","linear-gradient(135deg, #fa709a 0%, #fee140 100%)","linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)","linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)","linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)"],lo=({isOpen:s,onClose:a,customization:m,onSave:x,classroomId:p})=>{const[l,h]=t.useState(m),{isDeveloper:u}=Xe(),{tutors:d,addTutor:n,removeTutor:r,isLoading:v}=ua(p),{tutors:j,isLoading:b}=Zr();lt.useEffect(()=>{h(m)},[m]);const g=()=>{x(l),a()},c=(i,f)=>{h(y=>
167({...y,background_type:i,background_value:f}))},o=(i,f)=>{h(y=>({...y,header_type:i,header_value:f}))};return e.jsx(qe,{open:s,onOpenChange:a,children:e.jsxs(Oe,{className:"max-w-4xl max-h-[80vh] overflow-y-auto bg-background border-border",children:[e.jsx(Be,{children:e.jsx(Ve,{className:"text-foreground",children:"Customize Classroom"})}),e.jsxs(qt,{defaultValue:"background",className:"w-full",children:[e.jsxs(Ot,{className:`grid w-full ${u()?"grid-cols-3":"grid-cols-2"} bg-muted`,children:[e.jsx(Ye,{value:"background",className:"text-muted-foreground data-[state=active]:text-foreground",children:"Chat Background"}),e.jsx(Ye,{value:"header",className:"text-muted-foreground data-[state=active]:text-foreground",children:"Chat Header"}),u()&&e.jsx(Ye,{value:"tutors",className:"text-muted-foreground data-[state=active]:text-foreground",children:"AI Tutors"})]}),e.jsx(Ke,{value:"background",className:"space-y-4 mt-6",children:e.jsxs(te,{className:"bg-card border-border",children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"text-foreground flex items-center",children:[e.jsx(pt,{className:"w-5 h-5 mr-2"}),"Background Style"]})}),e.jsxs(ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{type:"radio",id:"bg-gradient",checked:l.background_type==="gradient",onChange:()=>c("gradient",kt[0]),className:"text-indigo-600"}),e.jsxs(Te,{htmlFor:"bg-gradient",className:"text-muted-foreground flex items-center",children:[e.jsx(pt,{className:"w-4 h-4 mr-2"}),"Gradient"]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:kt.map((i,f)=>e.jsx("button",{onClick:()=>c("gradient",i),className:`w-16 h-16 rounded-lg border-2 ${l.background_type==="gradient"&&l.background_value===i?"border-indigo-500":"border-border"}`,style:{background:i}},f))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{type:"radio",id:"bg-color",checked:l.background_type==="color",onChange:()=>c("color",_t[0]),className:"text-indigo-600"}),e.jsxs(Te,{htmlFor:"bg-color",className:"text-muted-foreground flex items-center",children:[e.jsx(Fs,{className:"w-4 h-4 mr-2"}),"Solid Color"]})]}),e.jsx("div",{className:"grid grid-cols-8 gap-2",children:_t.map((i,f)=>e.jsx("button",{onClick:()=>c("color",i),className:`w-12 h-12 rounded-lg border-2 ${l.background_type==="color"&&l.background_value===i?"border-indigo-500":"border-border"}`,style:{backgroundColor:i}},f))}),e.jsx(_e,{type:"color",value:l.background_type==="color"&&l.background_value||"#1e40af",onChange:i=>c("color",i.target.value),className:"w-20 h-10 bg-muted border-border"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{type:"radio",id:"bg-image",checked:l.background_type==="image",onChange:()=>c("image"),className:"text-indigo-600"}),e.jsxs(Te,{htmlFor:"bg-image",className:"text-muted-foreground flex items-center",children:[e.jsx(ut,{className:"w-4 h-4 mr-2"}),"Custom Image"]})]}),e.jsx(_e,{type:"url",placeholder:"Enter image URL...",value:l.background_type==="image"&&l.background_value||"",onChange:i=>c("image",i.target.value),className:"bg-muted border-border text-foreground"})]})]})]})}),e.jsx(Ke,{value:"header",className:"space-y-4 mt-6",children:e.jsxs(te,{className:"bg-card border-border",children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"text-foreground flex items-center",children:[e.jsx(pt,{className:"w-5 h-5 mr-2"}),"Header Style"]})}),e.jsxs(ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{type:"radio",id:"header-gradient",checked:l.header_type==="gradient",onChange:()=>o("gradient",kt[0]),className:"text-indigo-600"}),e.jsxs(Te,{htmlFor:"header-gradient",className:"text-muted-foreground flex items-center",children:[e.jsx(pt,{className:"w-4 h-4 mr-2"}),"Gradient"]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:kt.map((i,f)=>e.jsx("button",{onClick:()=>o("gradient",i),className:`w-16 h-16 rounded-lg border-2 ${l.header_type==="gradient"&&l.header_value===i?"border-indigo-500":"border-border"}`,style:{background:i}},f))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{type:"radio",id:"header-color",checked:l.header_type==="color",onChange:()=>o("color",_t[0]),className:"text-indigo-600"}),e.jsxs(Te,{htmlFor:"header-color",className:"text-muted-foreground flex items-center",children:[e.jsx(Fs,{className:"w-4 h-4 mr-2"}),"Solid Color"]})]}),e.jsx("div",{className:"grid grid-cols-8 gap-2",children:_t.map((i,f)=>e.jsx("button",{onClick:()=>o("color",i),className:`w-12 h-12 rounded-lg border-2 ${l.header_type==="color"&&l.header_value===i?"border-indigo-500":"border-border"}`,style:{backgroundColor:i}},f))}),e.jsx(_e,{type:"color",value:l.header_type==="color"&&l.header_value||"#1e40af",onChange:i=>o("color",i.target.value),className:"w-20 h-10 bg-muted border-border"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{type:"radio",id:"header-image",checked:l.header_type==="image",onCh
167ange:()=>o("image"),className:"text-indigo-600"}),e.jsxs(Te,{htmlFor:"header-image",className:"text-muted-foreground flex items-center",children:[e.jsx(ut,{className:"w-4 h-4 mr-2"}),"Custom Image"]})]}),e.jsx(_e,{type:"url",placeholder:"Enter image URL...",value:l.header_type==="image"&&l.header_value||"",onChange:i=>o("image",i.target.value),className:"bg-muted border-border text-foreground"})]})]})]})}),u()&&e.jsxs(Ke,{value:"tutors",className:"space-y-4 mt-6",children:[e.jsxs(te,{className:"bg-card border-border",children:[e.jsxs(Ee,{children:[e.jsxs(Ae,{className:"text-foreground flex items-center",children:[e.jsx(tt,{className:"w-5 h-5 mr-2"}),"Assigned Tutors"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Manage which AI tutors are available in this classroom"})]}),e.jsx(ie,{className:"space-y-4",children:v?e.jsx("div",{className:"text-muted-foreground",children:"Loading tutors..."}):e.jsxs(e.Fragment,{children:[(()=>{const i=Dt(p),f=i&&d.some(y=>y.assistant_id===i.assistant_id);return i&&!f?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"System Default Tutor"}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-blue-900/20 border border-blue-500/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:i.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i.specialty})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(_,{variant:"outline",size:"sm",onClick:async()=>{try{await n(i,p)}catch(y){console.error("Failed to add system tutor to roster:",y)}},className:"bg-green-600 hover:bg-green-700 text-white border-green-600",children:"Add to Roster"})})]})]}):null})(),d.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Active Tutors"}),d.map(i=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-green-900/20 border border-green-500/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:i.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i.specialty})]})]}),e.jsx(_,{variant:"outline",size:"sm",onClick:async()=>{try{await r(i.id,p)}catch(f){console.error("Failed to remove tutor:",f)}},className:"bg-red-600 hover:bg-red-700 text-white border-red-600",children:"Remove"})]},i.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No tutors assigned yet. Add tutors from the available list below."})]})})]}),e.jsxs(te,{className:"bg-card border-border",children:[e.jsx(Ee,{children:e.jsxs(Ae,{className:"text-foreground flex items-center",children:[e.jsx(tt,{className:"w-5 h-5 mr-2"}),"Available AI Tutors"]})}),e.jsx(ie,{className:"space-y-4",children:b?e.jsx("div",{className:"text-muted-foreground",children:"Loading available tutors..."}):e.jsx("div",{className:"space-y-2",children:j.filter(i=>!d.some(f=>f.id===i.id)).map(i=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:i.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i.specialty})]}),e.jsx(_,{variant:"outline",size:"sm",onClick:async()=>{try{await n(i,p)}catch(f){console.error("Failed to add tutor:",f)}},className:"bg-green-600 hover:bg-green-700 text-white border-green-600",children:"Add"})]},i.id))})})]})]})]}),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(_,{variant:"outline",onClick:a,className:"bg-card border-border text-muted-foreground",children:"Cancel"}),e.jsx(_,{onClick:g,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:"Save Changes"})]})]})})},co=s=>{const[a,m]=t.useState({background_type:"gradient",header_type:"gradient"}),[x,p]=t.useState(!0),{user:l}=Ge(),{toast:h}=we(),u=t.useCallback(async()=>
167{if(!(!l||!s)){p(!0);try{const{data:n,error:r}=await E.from("classroom_customizations").select("*").eq("user_id",l.id).eq("classroom_id",s).maybeSingle();if(r)throw r;n&&m({id:n.id,background_type:n.background_type,background_value:n.background_value||void 0,header_type:n.header_type,header_value:n.header_value||void 0})}catch(n){console.error("Error loading customization:",n)}finally{p(!1)}}},[l,s]),d=t.useCallback(async n=>{if(!l||!s){h({title:"Error",description:"User not authenticated or classroom ID missing.",variant:"destructive"});return}try{const r={...a,...n},{data:v,error:j}=await E.from("classroom_customizations").upsert({user_id:l.id,classroom_id:s,background_type:r.background_type,background_value:r.background_value,header_type:r.header_type,header_value:r.header_value}).select().single();if(j)throw j;m({id:v.id,background_type:v.background_type,background_value:v.background_value||void 0,header_type:v.header_type,header_value:v.header_value||void 0}),h({title:"Customization Saved",description:"Your classroom appearance has been updated."})}catch(r){console.error("Error saving customization:",r),h({title:"Failed to Update",description:`Error: ${r instanceof Error?r.message:"Unknown error occurred"}`,variant:"destructive"})}},[l,s,a,h]);return t.useEffect(()=>{u()},[u]),{customization:a,isLoading:x,saveCustomization:d}},uo=()=>{const[s,a]=t.useState([]),[m,x]=t.useState(!0),[p,l]=t.useState({}),h=async()=>{try{const{data:c,error:o}=await E.from("global_tutorial_videos").select("*").order("slot_number");if(o)throw o;a(c||[])}catch(c){console.error("Error fetching tutorials:",c),ne.error("Failed to load tutorial videos")}finally{x(!1)}};t.useEffect(()=>{h()},[]);const u=async c=>new Promise(o=>{const i=document.createElement("video"),f=document.createElement("canvas"),y=f.getContext("2d");i.preload="metadata",i.src=URL.createObjectURL(c),i.onloadeddata=()=>{i.currentTime=1},i.onseeked=()=>{f.width=i.videoWidth,f.height=i.videoHeight,y?.drawImage(i,0,0,f.width,f.height),f.toBlob(N=>{URL.revokeObjectURL(i.src),o(N)},"image/jpeg",.8)},i.onerror=()=>{URL.revokeObjectURL(i.src),o(null)}});return{tutorials:s,loading:m,uploading:p,uploadVideo:async(c,o)=>{l(i=>({...i,[c]:!0}));try{const i=`tutorial-${c}-${Date.now()}.${o.name.split(".").pop()}`,{data:f,error:y}=await E.storage.from("tutorial-videos").upload(i,o);if(y)throw y;const{data:{publicUrl:N}}=E.storage.from("tutorial-videos").getPublicUrl(i),A=await u(o);let w=null;if(A){const k=`tutorial-${c}-thumb-${Date.now()}.jpg`,{error:I}=await E.storage.from("tutorial-thumbnails").upload(k,A);if(!I){const{data:{publicUrl:T}}=E.storage.from("tutorial-thumbnails").getPublicUrl(k);w=T}}const{error:P}=await E.from("global_tutorial_videos").upsert({slot_number:c,title:`Tutorial Video ${c}`,video_url:N,auto_thumbnail_url:w,uploaded_by:(await E.auth.getUser()).data.user?.id});if(P)throw P;ne.success("Video uploaded successfully"),await h()}catch(i){console.error("Error uploading video:",i),ne.error("Failed to upload video")}finally{l(i=>({...i,[c]:!1}))}},saveVideoUrl:async(c,o,i)=>{l(f=>({...f,[c]:!0}));try{const{error:f}=await E.from("global_tutorial_videos").upsert({slot_number:c,title:i||`Tutorial Video ${c}`,video_url:o,auto_thumbnail_url:null,custom_thumbnail_url:null,uploaded_by:(await E.auth.getUser()).data.user?.id},{onConflict:"slot_number"});if(f)throw f;ne.success("Video URL saved successfully"),await h()}catch(f){console.error("Error saving video URL:",f),ne.error("Failed to save video URL")}finally{l(f=>({...f,[c]:!1}))}},uploadCustomThumbnail:async(c,o)=>{try{const i=`tutorial-${c}-custom-${Date.now()}.${o.name.split(".").pop()}`,{error:f}=await E.storage.from("tutorial-thumbnails").upload(i,o);if(f)throw f;const{data:{publicUrl:y}}=E.storage.from("tutorial-thumbnails").getPublicUrl(i),{error:N}=await E.from("global_tutorial_videos").update({custom_thumbnail_url:y}).eq("slot_number",c);if(N)throw N;ne.success("Custom thumbnail uploaded"),await h()}catch(i){console.error("Error uploading thumbnail:",i),ne.error("Failed to upload custom thumbnail")}},updateTitle:async(c,o)=>{try{const{error:i}=await E.from("global_tutorial_videos").update({title:o}).eq("slot_number",c);if(i)throw i;await h()}catch(i){console.error("Error updating title:",i),ne.error("Failed to update title")}},deleteVideo:async c=>{try{const o=s.find(f=>f.slot_number===c);if(!o)return;
167if(o.video_url){const f=o.video_url.split("/").pop();f&&await E.storage.from("tutorial-videos").remove([f])}if(o.auto_thumbnail_url){const f=o.auto_thumbnail_url.split("/").pop();f&&await E.storage.from("tutorial-thumbnails").remove([f])}if(o.custom_thumbnail_url){const f=o.custom_thumbnail_url.split("/").pop();f&&await E.storage.from("tutorial-thumbnails").remove([f])}const{error:i}=await E.from("global_tutorial_videos").delete().eq("slot_number",c);if(i)throw i;ne.success("Video deleted"),await h()}catch(o){console.error("Error deleting video:",o),ne.error("Failed to delete video")}},useAutoThumbnail:async c=>{try{const{error:o}=await E.from("global_tutorial_videos").update({custom_thumbnail_url:null}).eq("slot_number",c);if(o)throw o;ne.success("Switched to auto-generated thumbnail"),await h()}catch(o){console.error("Error switching thumbnail:",o),ne.error("Failed to switch thumbnail")}},getTutorialBySlot:c=>s.find(o=>o.slot_number===c),refetch:h}},mo=({open:s,onOpenChange:a})=>{const{preferences:m,loading:x,savePreferences:p}=ma(),[l,h]=t.useState("friendly"),[u,d]=t.useState([50]),[n,r]=t.useState([50]),[v,j]=t.useState(!0),[b,g]=t.useState(!0),[c,o]=t.useState(!1);t.useEffect(()=>{s&&m&&(h(m.tone),d([m.formality]),r([m.verbosity]),j(m.useEmojis),g(m.detailedExplanations))},[s,m]);const i=async()=>{o(!0);const f={tone:l,formality:u[0],verbosity:n[0],useEmojis:v,detailedExplanations:b};(await p(f)).success?(localStorage.setItem("chatPreferences",JSON.stringify(f)),ne.success("Chat preferences saved! Your tutor will adapt to your preferences."),a(!1)):ne.error("Failed to save preferences. Please try again."),o(!1)};return e.jsx(qe,{open:s,onOpenChange:a,children:e.jsxs(Oe,{className:"sm:max-w-[500px] bg-background border-border",children:[e.jsxs(Be,{children:[e.jsx(Ve,{className:"text-foreground",children:"Personalize Your Chat Experience"}),e.jsx(ra,{className:"text-muted-foreground",children:"Customize how your AI tutor communicates with you"})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Te,{className:"text-foreground",children:"Communication Tone"}),e.jsxs(bt,{value:l,onValueChange:h,children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(et,{value:"friendly",id:"friendly"}),e.jsx(Te,{htmlFor:"friendly",className:"text-muted-foreground cursor-pointer",children:"Friendly & Encouraging"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(et,{value:"professional",id:"professional"}),e.jsx(Te,{htmlFor:"professional",className:"text-muted-foreground cursor-pointer",children:"Professional & Direct"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(et,{value:"casual",id:"casual"}),e.jsx(Te,{htmlFor:"casual",className:"text-muted-foreground cursor-pointer",children:"Casual & Conversational"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(et,{value:"motivational",id:"motivational"}),e.jsx(Te,{htmlFor:"motivational",className:"text-muted-foreground cursor-pointer",children:"Motivational & Inspiring"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Te,{className:"text-foreground",children:"Formality Level"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Casual"}),e.jsx("span",{children:"Formal"})]}),e.jsx(vt,{value:u,onValueChange:d,max:100,step:1,className:"w-full"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Te,{className:"text-foreground",children:"Response Length"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Concise"}),e.jsx("span",{children:"Detailed"})]}),e.jsx(vt,{value:n,onValueChange:r,max:100,step:1,className:"w-full"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Te,{htmlFor:"emojis",className:"text-foreground",children:"Use Emojis"}),e.jsx(Ft,{id:"emojis",checked:v,onCheckedChange:j})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Te,{htmlFor:"detailed",className:"text-foreground",children:"Detailed Explanations"}),e.jsx(Ft,{id:"detailed",checked:b,onCheckedChange:g})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(_,{variant:"outline",onClick:()=>
167a(!1),disabled:c,children:"Cancel"}),e.jsx(_,{onClick:i,disabled:c||x,children:c?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):"Save Preferences"})]})]})})},dt={decayRates:{health:-2,hunger:-8,happiness:-3,energy:-5},actions:{feed:{type:"feed",cost:5,healthEffect:5,hungerEffect:40,happinessEffect:10,energyEffect:0,duration:2e3},play:{type:"play",cost:0,healthEffect:2,hungerEffect:-5,happinessEffect:30,energyEffect:-10,duration:3e3},heal:{type:"heal",cost:15,healthEffect:50,hungerEffect:0,happinessEffect:5,energyEffect:-5,duration:4e3},rest:{type:"rest",cost:0,healthEffect:0,hungerEffect:0,happinessEffect:0,energyEffect:60,duration:5e3},revive:{type:"revive",cost:100,healthEffect:50,hungerEffect:50,happinessEffect:30,energyEffect:50,duration:6e3}},lifecycleThresholds:{hungry:{hunger:{max:30}},sad:{happiness:{max:30}},tired:{energy:{max:30}},sick:{health:{max:30}},critical:{stats:{max:20,count:2}},dying:{health:{max:10}}}},ho=()=>{const[s,a]=t.useState([]),[m,x]=t.useState(!0),{toast:p}=we(),l=t.useCallback(async()=>{try{x(!0);const{data:n,error:r}=await E.from("pet_action_settings").select("*").order("action_name");if(r)throw r;a(n||[])}catch(n){console.error("Error loading pet action settings:",n),p({title:"Error loading settings",description:"Failed to load pet action settings.",variant:"destructive"})}finally{x(!1)}},[p]),h=t.useCallback(async(n,r)=>{try{const{error:v}=await E.from("pet_action_settings").update(r).eq("id",n);if(v)throw v;a(j=>j.map(b=>b.id===n?{...b,...r}:b)),p({title:"Setting updated",description:"Pet action setting has been updated successfully."})}catch(v){console.error("Error updating pet action setting:",v),p({title:"Error updating setting",description:"Failed to update pet action setting.",variant:"destructive"})}},[p]),u=t.useCallback(n=>s.find(v=>v.action_name===n)?.token_cost||0,[s]),d=t.useCallback(n=>s.find(v=>v.action_name===n)?.is_enabled!==!1,[s]);return t.useEffect(()=>{l()},[l]),{settings:s,isLoading:m,updateSetting:h,getActionCost:u,isActionEnabled:d,loadSettings:l}},Tt="mindcrafter_student_pet_care_state",go=6e4,Us={health:100,hunger:100,happiness:100,energy:100,lastFed:Date.now(),lastPlayed:Date.now(),lastCheckedIn:Date.now(),isAlive:!0,lifecycle:"healthy",daysSinceCreation:0,totalFeedings:0,totalPlayTime:0,deathCount:0},po=s=>{const[a,m]=t.useState(Us),[x,p]=t.useState(0),[l,h]=t.useState(!1),{getActionCost:u,isActionEnabled:d}=ho(),n=t.useRef();t.useEffect(()=>{s&&r()},[s]);const r=async()=>{if(s)try{const{data:i,error:f}=await E.from("student_profiles").select("total_tokens").eq("id",s).single();if(f)throw f;p(i?.total_tokens||0)}catch(i){console.error("Error loading student tokens:",i)}},v=async i=>{if(s)try{const{error:f}=await E.from("student_profiles").update({total_tokens:i}).eq("id",s);if(f)throw f;p(i)}catch(f){console.error("Error updating student tokens:",f),ne.error("Failed to update tokens")}};t.useEffect(()=>{const i=s?`${Tt}_${s}`:Tt,f=localStorage.getItem(i);if(f)try{const y=JSON.parse(f);m(N=>({...N,...y})),console.log("Loaded student pet care state from storage:",y)}catch(y){console.error("Failed to load student pet care state:",y)}},[s]),t.useEffect(()=>{const i=s?`${Tt}_${s}`:Tt;localStorage.setItem(i,JSON.stringify(a))},[a,s]);const j=t.useCallback(i=>{const{health:f,hunger:y,happiness:N,energy:A}=i,w=dt.lifecycleThresholds;return f<=0?"dead":f<=w.dying.health.max?"dying":f<=w.sick.health.max?"sick":[f<=w.critical.stats.max,y<=w.critical.stats.max,N<=w.critical.stats.max,A<=w.critical.stats.max].filter(Boolean).length>=w.critical.stats.count?"critical":y<=w.hungry.hunger.max?"hungry":N<=w.sad.happiness.max?"sad":A<=w.tired.energy.max?"tired":"healthy"},[]),b=t.useCallback(()=>{m(i=>{if(!i.isAlive)return i;const f=Date.now(),y=(f-i.lastCheckedIn)/(1e3*60*60);if(y<.1)return i;const N=dt.decayRates,A=N.health*y,w=N.hunger*y,P=N.happiness*y,k=N.energy*y;console.log("🔍 Decay calculation:",{hoursSinceLastCheck:y,config:N,changes:{health:A,hunger:w,happiness:P,energy:k},previousStats:{health:i.health,hunger:i.hunger,happiness:i.happiness,energy:i.energy}});const I={...i,health:Math.max(0,i.health+A),hunger:Math.max(0,i.hunger+w),happiness:Math.max(0,i.happiness+P),energy:Math.max(0,i.energy+k),lastCheckedIn:f,daysSinceCreation:Math.floor((f-(i.lastCheckedIn||f))/(1e3*60*60*24))};I.health<=0&&i.isAlive&&i.health>0?(I.isAlive=!1,I.deathCount=i.deathCount+1,ne.error("💀 Your pet has died! You can revive it with tokens."),console.log("💀 Pet died, state:",I)):I.health<=0&&(I.isAlive=!1),!i.isAlive&&I.health>
1670&&(console.log("⚠️ DEAD PET HEALTH INCREASED - this should not auto-revive the pet!"),I.health=0,I.isAlive=!1);const T=i.lifecycle;return I.lifecycle=j(I),T!==I.lifecycle&&console.log(`🔄 Pet lifecycle changed: ${T} → ${I.lifecycle}`),console.log("Applied decay, new state:",{health:I.health,hunger:I.hunger,happiness:I.happiness,energy:I.energy,lifecycle:I.lifecycle,isAlive:I.isAlive}),I})},[j]);t.useEffect(()=>(b(),n.current=setInterval(b,go),()=>{n.current&&clearInterval(n.current)}),[b]);const g=t.useCallback(async i=>{if(l)return!1;if(!d(i))return ne.error("This action is currently disabled"),!1;const f=u(i),y=dt.actions[i];if(!y)return ne.error(`Unknown action: ${i}`),!1;if(!a.isAlive&&i!=="revive")return ne.error("Your pet is dead! Revive it first."),!1;if(f>x)return ne.error(`Not enough tokens! Need ${f}, have ${x}`),!1;console.log(`Performing action: ${i}`,{action:y,tokenCost:f}),h(!0);try{if(f>0){const A=x-f;await v(A),ne.info(`Used ${f} tokens`)}m(A=>{const w={...A,health:Math.min(100,Math.max(0,A.health+y.healthEffect)),hunger:Math.min(100,Math.max(0,A.hunger+y.hungerEffect)),happiness:Math.min(100,Math.max(0,A.happiness+y.happinessEffect)),energy:Math.min(100,Math.max(0,A.energy+y.energyEffect)),lastCheckedIn:Date.now()};return i==="feed"?(w.lastFed=Date.now(),w.totalFeedings=A.totalFeedings+1):i==="play"?(w.lastPlayed=Date.now(),w.totalPlayTime=A.totalPlayTime+1):i==="revive"&&(w.isAlive=!0,ne.success("🎉 Your pet has been revived!")),w.lifecycle=j(w),console.log(`Action ${i} completed, new state:`,w),w});const N={feed:"🍖 Fed your pet!",play:"🎾 Played with your pet!",heal:"💊 Healed your pet!",rest:"😴 Your pet is resting...",revive:"✨ Pet revived successfully!"};return ne.success(N[i]||"Action completed!"),await new Promise(A=>setTimeout(A,y.duration)),!0}catch(N){return console.error(`Error performing action ${i}:`,N),ne.error("Action failed. Please try again."),!1}finally{h(!1)}},[a,x,l,j,u,d,v]),c=t.useCallback(()=>{const i={healthy:"happy",hungry:"neutral",sad:"sad",tired:"sleepy",sick:"sad",critical:"sad",dying:"sad",dead:"sad"},f={healthy:"idle",hungry:"eating",sad:"sad",tired:"sleeping",sick:"sad",critical:"sad",dying:"sad",dead:void 0};return{health:a.health,happiness:a.happiness,hunger:a.hunger,mood:i[a.lifecycle],currentAnimation:f[a.lifecycle]}},[a]),o=t.useCallback(()=>{m(Us),ne.success("Pet reset to initial state")},[]);return{careState:a,userTokens:x,isPerformingAction:l,spriteState:c(),actions:{feed:()=>g("feed"),play:()=>g("play"),heal:()=>g("heal"),rest:()=>g("rest"),revive:()=>g("revive")},resetPet:o,refreshTokens:r}},Bs="mindcrafter_pet_care_state",xo=6e4,Vs={health:100,hunger:100,happiness:100,energy:100,lastFed:Date.now(),lastPlayed:Date.now(),lastCheckedIn:Date.now(),isAlive:!0,lifecycle:"healthy",daysSinceCreation:0,totalFeedings:0,totalPlayTime:0,deathCount:0},fo=()=>{const[s,a]=t.useState(Vs),[m,x]=t.useState(1e3),[p,l]=t.useState(!1),h=t.useRef();t.useEffect(()=>{const g=localStorage.getItem(Bs);if(g)try{const c=JSON.parse(g);a(o=>({...o,...c})),console.log("Loaded pet care state from storage:",c)}catch(c){console.error("Failed to load pet care state:",c)}},[]),t.useEffect(()=>{localStorage.setItem(Bs,JSON.stringify(s))},[s]);const u=t.useCallback(g=>{const{health:c,hunger:o,happiness:i,energy:f}=g,y=dt.lifecycleThresholds;return c<=0?"dead":c<=y.dying.health.max?"dying":c<=y.sick.health.max?"sick":[c<=y.critical.stats.max,o<=y.critical.stats.max,i<=y.critical.stats.max,f<=y.critical.stats.max].filter(Boolean).length>=y.critical.stats.count?"critical":o<=y.hungry.hunger.max?"hungry":i<=y.sad.happiness.max?"sad":f<=y.tired.energy.max?"tired":"healthy"},[]),d=t.useCallback(()=>{a(g=>{if(!g.isAlive)return g;const c=Date.now(),o=(c-g.lastCheckedIn)/(1e3*60*60);if(o<.1)return g;const i=dt.decayRates,f={...g,health:Math.max(0,g.health+i.health*o),hunger:Math.max(0,g.hunger+i.hunger*o),happiness:Math.max(0,g.happiness+i.happiness*o),energy:Math.max(0,g.energy+i.energy*o),lastCheckedIn:c,daysSinceCreation:Math.floor((c-(g.lastCheckedIn||c))/(1e3*60*60*24))};f.health<=0&&g.isAlive&&g.health>0?(f.isAlive=!1,f.deathCount=g.deathCount+1,ne.error("💀 Your pet has died! You can revive it with tokens."),console.log("💀 Pet died! Health reached 0, state:",f)):f.health<=0&&(f.isAlive=!1),!g.isAlive&&f.health>
1670&&(console.log("⚠️ DEAD PET HEALTH INCREASED - this should not auto-revive the pet!"),f.health=0,f.isAlive=!1);const y=u(f);return y!==g.lifecycle&&console.log(`🔄 Pet lifecycle changed: ${g.lifecycle} → ${y}`),f.lifecycle=y,console.log("⏰ Applied decay, new state:",{health:f.health,lifecycle:f.lifecycle,isAlive:f.isAlive,hoursSinceLastCheck:o}),f})},[u]);t.useEffect(()=>(d(),h.current=setInterval(d,xo),()=>{h.current&&clearInterval(h.current)}),[d]);const n=t.useCallback(async g=>{if(p)return!1;const c=dt.actions[g];if(!c)return ne.error(`Unknown action: ${g}`),!1;if(!s.isAlive&&g!=="revive")return ne.error("Your pet is dead! Revive it first."),!1;if(c.cost>m)return ne.error(`Not enough tokens! Need ${c.cost}, have ${m}`),!1;console.log(`Performing action: ${g}`,c),l(!0);try{c.cost>0&&(x(i=>i-c.cost),ne.info(`Used ${c.cost} tokens`)),a(i=>{const f={...i,health:Math.min(100,Math.max(0,i.health+c.healthEffect)),hunger:Math.min(100,Math.max(0,i.hunger+c.hungerEffect)),happiness:Math.min(100,Math.max(0,i.happiness+c.happinessEffect)),energy:Math.min(100,Math.max(0,i.energy+c.energyEffect)),lastCheckedIn:Date.now()};return g==="feed"?(f.lastFed=Date.now(),f.totalFeedings=i.totalFeedings+1):g==="play"?(f.lastPlayed=Date.now(),f.totalPlayTime=i.totalPlayTime+1):g==="revive"&&(f.isAlive=!0,ne.success("🎉 Your pet has been revived!")),f.lifecycle=u(f),console.log(`Action ${g} completed, new state:`,f),f});const o={feed:"🍖 Fed your pet!",play:"🎾 Played with your pet!",heal:"💊 Healed your pet!",rest:"😴 Your pet is resting...",revive:"✨ Pet revived successfully!"};return ne.success(o[g]||"Action completed!"),await new Promise(i=>setTimeout(i,c.duration)),!0}catch(o){return console.error(`Error performing action ${g}:`,o),ne.error("Action failed. Please try again."),!1}finally{l(!1)}},[s,m,p,u]),r=t.useCallback(()=>{const g={healthy:"happy",hungry:"neutral",sad:"sad",tired:"sleepy",sick:"sad",critical:"sad",dying:"sad",dead:"sad"},c={healthy:"idle",hungry:"eating",sad:"sad",tired:"sleeping",sick:"sad",critical:"sad",dying:"sad",dead:void 0};return{health:s.health,happiness:s.happiness,hunger:s.hunger,mood:g[s.lifecycle],currentAnimation:c[s.lifecycle]}},[s]),v=t.useCallback(()=>{a(Vs),ne.success("Pet reset to initial state")},[]),j=t.useCallback(g=>{x(c=>c+g),ne.success(`Added ${g} tokens`)},[]),b=t.useCallback(()=>{a(g=>{const c={...g,health:0,isAlive:!1,lifecycle:"dead",deathCount:g.deathCount+1,lastCheckedIn:Date.now()};return console.log("🗡️ Pet manually killed for testing:",c),c}),ne.error("💀 Pet killed for testing purposes")},[]);return{careState:s,userTokens:m,isPerformingAction:p,spriteState:r(),actions:{feed:()=>n("feed"),play:()=>n("play"),heal:()=>n("heal"),rest:()=>n("rest"),revive:()=>n("revive")},resetPet:v,addTokens:j,killPet:b}},vo=({onPetClick:s})=>{const{isStudent:a}=Xe(),{currentStudentId:m,currentStudent:x}=at(),p=m||x?.id,l=fo(),h=po(p||void 0),u=a()?h:l,{careState:d,actions:n}=u,{settings:r}=ca(),[v,j]=t.useState(!1),[b,g]=t.useState(!1);t.useEffect(()=>{const P=()=>j(!0),k=()=>j(!1);return window.addEventListener("pet:entered-chat",P),window.addEventListener("pet:left-chat",k),()=>{window.removeEventListener("pet:entered-chat",P),window.removeEventListener("pet:left-chat",k)}},[]);const c=async()=>{await n.play(),s?.()},o=P=>{try{const k=x?.student_name||x?.name||"my owner",I={petName:r.petName,ownerName:k,action:"provide_full_context"};P.dataTransfer.setData("application/pet",JSON.stringify(I)),P.dataTransfer.effectAllowed="copyMove",g(!0)}catch(k){console.error("Failed to start pet drag:",k)}},i=()=>{v||g(!1)},[f,y]=lt.useState(null),N=P=>{const k=P.touches[0];y({x:k.clientX,y:k.clientY}),g(!0);const I=x?.student_name||x?.name||"my owner",T={action:"provide_full_context",petName:r.petName,ownerName:I};sessionStorage.setItem("dragging-pet-data",JSON.stringify(T))},A=P=>{if(!f)return;const k=P.touches[0];Math.sqrt(Math.pow(k.clientX-f.x,2)+Math.pow(k.clientY-f.y,2))>10&&g(!0)},w=P=>{if(!f)return;const k=P.changedTouches[0],I=document.elementFromPoint(k.clientX,k.clientY),T=document.querySelector('[data-chat-drop-zone="true"]');T&&T.contains(I)&&window.dispatchEvent(new CustomEvent("pet:dropped-on-chat-touch")),g(!1),y(null),sessionStorage.removeItem("dragging-pet-data")};
167return!a()||!d||v?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"relative w-48 h-48 cursor-pointer hover:scale-105 transition-transform",onClick:c,draggable:!0,onDragStart:o,onDragEnd:i,onTouchStart:N,onTouchMove:A,onTouchEnd:w,children:r.currentAvatar?r.currentAvatarType==="video"?e.jsx("video",{src:r.currentAvatar,autoPlay:!0,loop:!0,muted:!0,className:"w-48 h-48 object-contain rounded-lg"}):e.jsx("img",{src:r.currentAvatar,alt:r.petName,className:"w-48 h-48 object-contain rounded-lg"}):e.jsx("div",{className:"w-48 h-48 rounded-lg border border-border flex items-center justify-center text-muted-foreground bg-muted/50",children:"🐾"})})}),e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-lg font-medium text-foreground",children:r.petName}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Learning Companion"})]}),e.jsxs("div",{className:"space-y-2 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"h-4 w-4 text-red-400"}),e.jsx("div",{className:"flex-1",children:e.jsx(At,{value:d.health,className:"h-2"})}),e.jsxs("span",{className:"text-xs text-muted-foreground w-10 text-right",children:[Math.round(d.health),"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{className:"h-4 w-4 text-yellow-400"}),e.jsx("div",{className:"flex-1",children:e.jsx(At,{value:d.happiness,className:"h-2"})}),e.jsxs("span",{className:"text-xs text-muted-foreground w-10 text-right",children:[Math.round(d.happiness),"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{className:"h-4 w-4 text-green-400"}),e.jsx("div",{className:"flex-1",children:e.jsx(At,{value:100-d.hunger,className:"h-2"})}),e.jsxs("span",{className:"text-xs text-muted-foreground w-10 text-right",children:[Math.round(100-d.hunger),"%"]})]})]}),e.jsx("div",{className:"text-center text-xs text-muted-foreground pt-2 border-t border-border",children:"💡 Click to interact or drag to chat!"})]})},yo=({onSendToChat:s,showAllSlots:a=!1,classroomId:m})=>{const{classroomId:x}=fs(),p=m||x,{isStudent:l}=Xe(),{uploadVideo:h,saveVideoUrl:u,uploadCustomThumbnail:d,updateTitle:n,deleteVideo:r,useAutoThumbnail:v,getTutorialBySlot:j}=uo(),{uploadVideo:b,saveVideoUrl:g,updateTitle:c,deleteVideo:o,getClassroomTutorialBySlot:i}=ws(p),[f,y]=t.useState(!1),[N,A]=t.useState(!1),[w,P]=t.useState({}),[k,I]=t.useState({}),[T,M]=t.useState(!1),[G,D]=t.useState({}),[Y,de]=t.useState({}),[pe,xe]=t.useState({}),[ce,oe]=t.useState({}),[ae,K]=t.useState(!1),[O,W]=t.useState({}),[B,F]=t.useState({});lt.useEffect(()=>{(async()=>{const{data:{user:H}}=await E.auth.getUser();if(!H)return;const{data:ue}=await E.from("user_roles").select("role").eq("user_id",H.id).in("role",["developer","parent","youth_leader"]);if(ue&&ue.length>0){const ve=ue.some(le=>le.role==="developer"),re=ue.some(le=>["developer","parent","youth_leader"].includes(le.role));M(ve),K(re)}})()},[]);const Q=async(C,H)=>{const ue=H.target.files;if(!ue||ue.length===0)return;const ve=ue[0];if(ve.size>5*1024*1024){ne.error("Thumbnail must be under 5MB");return}if(!["image/jpeg","image/png","image/webp"].includes(ve.type)){ne.error("Please upload a valid image file (.jpg, .png, .webp)");return}await d(C,ve)},S=(C,H)=>{P(ue=>({...ue,[C]:!0})),I(ue=>({...ue,[C]:H}))},z=async C=>{const H=k[C],ve=!!i(C);H&&H.trim()&&(ve?await c(C,H.trim()):await n(C,H.trim())),P(re=>({...re,[C]:!1}))},V=C=>{if(!C)return null;if(C.includes("youtube.com")||C.includes("youtu.be")){const H=C.includes("youtu.be")?C.split("youtu.be/")[1]?.split("?")[0]:C.split("v=")[1]?.split("&")[0];return H?`https://www.youtube.com/embed/${H}?enablejsapi=1&origin=${window.location.origin}&rel=0`:null}if(C.includes("vimeo.com")){const H=C.split("vimeo.com/")[1]?.split("?")[0];return H?`https://player.vimeo.com/video/${H}`:null}if(C.includes("loom.com")){const H=C.split("share/")[1]?.split("?")[0];return H?`https://www.loom.com/embed/${H}`:null}return null},q=({slotNumber:C,classroomOnly:H=!1})=>{const ue=C===2||C===3,ve=i(C),re=!!ve,le=re?ve:j(C),Ne=le?.custom_thumbnail_url||le?.auto_thumbnail_url,ze=w[C],Re=k[C]||le?.title||`Tutorial Video ${C}`,R=G[C],$=le?.video_url&&!le.video_url.includes("tutorial-videos")&&!le.video_url.includes("classroom-tutorial-videos"),U=$?V(le.video_url):null,se=H?ce[C]||"audio":void 0;return!le&&!T&&!ae&&C!==3?null:e.jsx(te,{className:"bg-card border-border shadow-sm",children:e.jsxs(ie,{className:"p-4 space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between gap-2",children:(T||ae)&&ze?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{value:Re,onChange:ee=>I(J=>({...J,[C]:ee.target.value})),className:"bg-background border-input text-foreground",placeholder:"Enter title"}),e.jsx(_,{size:"sm",onClick:()=>z(C),children:"Save"})]}):e.jsx(e.Fragment,{children:le&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground text-sm",children:le?.title||(C===3?"🎓 Classroom Instructions":`Tutorial Video ${C}`)}),!re&&!H&&le&&e.jsxs("span",{className:"text-xs bg-blue-500/20 text-blue-400 px-2 py-0.5 rounded flex items-center gap-1",children:[e.jsx(gt,{className:"h-3 w-3"}),"Global"]}),re&&e.jsxs("span",{className:"text-xs bg-purple-500/20 text-purple-400 px-2 py-0.5 rounded flex items-center gap-1",children:[e.jsx(gt,{className:"h-3 w-3"}),"Classroom"]}
167)]}),(T||ae)&&le&&e.jsx(_,{size:"sm",variant:"ghost",onClick:()=>S(C,le.title),className:"h-8 w-8 p-0",children:e.jsx(Za,{className:"h-4 w-4"})})]})})}),H&&(T||ae)&&!le&&e.jsxs("div",{className:"flex items-center justify-center gap-2 pb-3 border-b border-border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Media Type:"}),e.jsxs(De,{value:se,onValueChange:ee=>oe(J=>({...J,[C]:ee})),children:[e.jsx(Le,{className:"w-32 bg-background border-input",children:e.jsx($e,{})}),e.jsxs(Me,{className:"bg-background border-input z-50",children:[e.jsx(Z,{value:"audio",children:"🎙️ Audio"}),e.jsx(Z,{value:"image",children:"🖼️ Image"})]})]})]}),le?.video_url?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"aspect-video bg-black rounded-lg overflow-hidden",children:se==="audio"?e.jsxs("div",{className:"relative h-full flex flex-col items-center justify-center bg-gradient-to-br from-purple-900 to-blue-900",children:[e.jsx("img",{src:"/audio-placeholder.png",alt:"Audio content",className:"w-24 h-24 opacity-70 mb-4",onError:ee=>{ee.currentTarget.style.display="none";const J=ee.currentTarget.parentElement;if(J&&!J.querySelector(".emoji-fallback")){const ge=document.createElement("div");ge.className="text-6xl mb-4 emoji-fallback",ge.textContent="🎙️",J.insertBefore(ge,ee.currentTarget.nextSibling)}}}),e.jsxs("audio",{controls:!0,className:"w-full px-6",children:[e.jsx("source",{src:le.video_url,type:"audio/mpeg"}),"Your browser does not support audio playback."]})]}):se==="image"?e.jsx("img",{src:le.video_url,alt:"Classroom instructions",className:"w-full h-full object-contain"}):U?e.jsx("iframe",{src:U,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:le.video_url,controls:!0,controlsList:"nodownload",poster:Ne||void 0,className:"w-full h-full object-contain"})}),(T||ae&&H)&&e.jsxs("div",{className:"space-y-2",children:[ue&&e.jsxs("div",{className:"space-y-2 p-3 bg-muted/50 rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Content Source:"}),e.jsxs("span",{className:re?"text-purple-400 font-medium flex items-center gap-1":"text-blue-400 font-medium flex items-center gap-1",children:[e.jsx(gt,{className:"h-3 w-3"}),re?"This Classroom":"All Classrooms (Global)"]})]}),e.jsx("div",{className:"flex gap-2",children:re?e.jsxs(e.Fragment,{children:[e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>D(ee=>({...ee,[C]:!0})),className:"flex-1",children:[e.jsx(Et,{className:"h-4 w-4 mr-2"}),"Replace"]}),e.jsxs(_,{size:"sm",variant:"outline",onClick:async()=>{confirm("Remove classroom override and use global content?")&&await o(C)},className:"border-blue-500/50 hover:bg-blue-500/10 text-blue-400",title:"Use global content",children:[e.jsx(gt,{className:"h-4 w-4 mr-2"}),"Use Global"]})]}):e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>D(ee=>({...ee,[C]:!0})),className:"flex-1 border-purple-500/50 hover:bg-purple-500/10 text-purple-400",children:[e.jsx(Et,{className:"h-4 w-4 mr-2"}),"Override for This Classroom"]})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:re?"This content is only visible in this classroom":"This content is shared across all classrooms"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"flex-1 cursor-pointer",children:[e.jsx("input",{type:"file",accept:se==="audio"?"audio/*":se==="image"?"image/*":"video/*",onChange:async ee=>{const J=ee.target.files;if(!J||J.length===0)return;const ge=J[0],je=se==="image"?5:se==="audio"?10:50;if(ge.size>je*1024*1024){ne.error(`File must be under ${je}MB`);return}if(C===3&&(se==="image"||se==="audio"))try{const Se=Date.now(),Ue=ge.name.replace(/[^a-zA-Z0-9.-]/g,"_"),fe=re&&p?`classroom-media/${p}/slot${C}_${Se}_${Ue}`:`tutorial-videos/slot${C}_${Se}_${Ue}`,{data:he,error:Fe}=await E.storage.from("tutorial-videos").upload(fe,ge,{upsert:!0});if(Fe)throw Fe;const{data:{publicUrl:ht}}=E.storage.from("tutorial-videos").getPublicUrl(fe);re&&p?await g(C,ht):await u(C,ht),ne.success(`${se==="image"?"Image":"Audio"} uploaded successfully`)}catch(Se){console.error("Upload error:",Se),ne.error("Failed to upload file")}else re?b(C,ge):h(C,ge)},className:"hidden"}),e.jsxs("div",{className:"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2 w-full",children:[e.jsx(Et,{className:"h-4 w-4 mr-2"}),"Replace ",se==="audio"?"Audio":se==="image"?"Image":"Video"]})]}),e.jsx(_,{size:"sm",variant:"outline",onClick:()=>D(ee=>({...ee,[C]:!ee[C]})),className:"w-auto",children:e.jsx(ns,{className:"h-4 w-4"})}),e.jsx(_,{size:"sm",variant:"outline",onClick:async()=>{confirm("Are you sure you want to delete this tutorial video?")&&(re?await o(C):await r(C))},className:"text-red-400 hover:text-red-300",children:e.jsx(yt,{className:"h-4 w-4"})})]}),R&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{placeholder:"https://youtube.com/watch?v=...",value:Y[C]||"",onChange:ee=>de(J=>({...J,[C]:ee.target.value})),className:"bg-background border-input text-foreground"}),e.jsx(_,{size:"sm",onClick:async()=>{const ee=Y[C];if(!ee||!ee.trim()){ne.error("Please enter a valid video URL");return}re?await g(C,ee.trim()):await u(C,ee.trim()),D(J=>({...J,[C]:!1})),de(J=>({...J,[C]:""}))},children:"Save URL"})]}),!$&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"flex-1",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ee=>Q(C,ee),className:"hidden"}),e.jsx(_,{size:"sm",variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("span",{children:[e.jsx(ut,{className:"h-4 w-4 mr-2"}
167),le.custom_thumbnail_url?"Change":"Add"," Custom Thumbnail"]})})]}),le.custom_thumbnail_url&&e.jsx(_,{size:"sm",variant:"outline",onClick:()=>v(C),children:"Use Auto"})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[C===3&&!le&&e.jsxs(e.Fragment,{children:[!l()&&e.jsx("div",{className:"p-2 bg-muted/30 border border-border/50 rounded-md mb-3",children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:["💡 ",e.jsx("span",{className:"font-medium",children:"Manager Note:"})," When no classroom content is uploaded here, the student's pet appears in this spot in the student view."]})}),l()&&e.jsx(vo,{})]}),(T||ae)&&e.jsxs(e.Fragment,{children:[C===3&&!le&&e.jsx("div",{className:"border-t border-border pt-4 mt-4"}),e.jsxs("div",{className:"aspect-video bg-muted/50 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center p-6 text-center",children:[e.jsx("div",{className:"text-4xl mb-3",children:ue?"🏢":"🌍"}),e.jsxs("h4",{className:"text-foreground font-medium mb-2",children:["No ",ue?"Content":"Global Content"," Set"]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:ue?"Add classroom-specific content or set global default for all classrooms":"Add global content that will appear in all classrooms"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:se==="audio"?"audio/*":"image/*",onChange:ee=>{const J=ee.target.files;if(!J||J.length===0)return;const ge=J[0],je=se==="image"?5:10;if(ge.size>je*1024*1024){ne.error(`File must be under ${je}MB`);return}let Se=[];if(se==="audio"?Se=["audio/mpeg","audio/mp3","audio/wav","audio/ogg","audio/mp4","audio/webm"]:se==="image"&&(Se=["image/jpeg","image/png","image/webp","image/gif"]),!Se.includes(ge.type)){ne.error(`Please upload a valid ${se} file`);return}re?b(C,ge):h(C,ge)},className:"hidden"}),e.jsx(_,{variant:"outline",size:"sm",className:"cursor-pointer",children:se==="audio"?e.jsxs(e.Fragment,{children:[e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Upload Audio"]}):e.jsxs(e.Fragment,{children:[e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Upload Image"]})})]})]}),se==="audio"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-center text-muted-foreground text-xs",children:"or"}),e.jsxs("div",{className:"border-t border-border pt-3",children:[e.jsx("div",{className:"flex items-center justify-center gap-4",children:e.jsx(_,{variant:O[C]?"destructive":"default",size:"lg",onClick:async()=>{if(O[C])B[C]?.stop();else try{const ee=await navigator.mediaDevices.getUserMedia({audio:!0}),J=new MediaRecorder(ee),ge=[];J.ondataavailable=je=>ge.push(je.data),J.onstop=async()=>{const je=new Blob(ge,{type:"audio/webm"});if(je.size>10*1024*1024){ne.error("Recording must be under 10MB"),ee.getTracks().forEach(Ue=>Ue.stop()),W({...O,[C]:!1});return}const Se=new File([je],`recording-${Date.now()}.webm`,{type:"audio/webm"});re?await b(C,Se):await h(C,Se),ee.getTracks().forEach(Ue=>Ue.stop()),W({...O,[C]:!1})},J.start(),F({...B,[C]:J}),W({...O,[C]:!0})}catch{ne.error("Microphone access denied")}},children:O[C]?e.jsxs(e.Fragment,{children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Stop Recording"]}):e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Record Audio"]})})}),O[C]&&e.jsx("p",{className:"text-center text-sm text-red-400 mt-2 animate-pulse",children:"Recording in progress..."})]})]}),e.jsx("div",{className:"text-center text-muted-foreground text-xs",children:"or"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{placeholder:`Paste ${se} URL or video link (YouTube, Vimeo, etc.)`,value:Y[C]||"",onChange:ee=>de(J=>({...J,[C]:ee.target.value})),className:"bg-background border-input text-foreground text-sm"}),e.jsx(_,{size:"sm",onClick:async()=>{const ee=Y[C];if(!ee||!ee.trim()){ne.error("Please enter a valid URL");return}re?await g(C,ee.trim()):await u(C,ee.trim()),de(J=>({...J,[C]:""}))},children:e.jsx(ns,{className:"h-4 w-4"})})]})]})]})]})})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 ${a?"lg:grid-cols-4":"lg:grid-cols-2"} gap-4`,children:[a&&e.jsx(q,{slotNumber:1}),a&&e.jsx(q,{slotNumber:2}),e.jsx(q,{slotNumber:3}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(te,{className:"glass-card bg-card border-green-500/30 cursor-pointer hover:scale-[1.02] transition-all duration-300 group flex-1 shadow-sm",onClick:()=>y(!0),children:e.jsxs(ie,{className:"p-3 h-full flex flex-col justify-between",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(it,{className:"h-6 w-6 text-green-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-sm text-green-500",children:"Suggestion Box"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Share feedback"})]})]}),e.jsx(_,{size:"sm",className:"w-full mt-2 bg-green-500/20 hover:bg-green-500/30 text-green-500 border-green-500/50",onClick:C=>{C.stopPropagation(),y(!0)},children:"Give Feedback"})]})}),e.jsx(te,{className:"glass-card bg-card border-pink-500/30 cursor-pointer hover:scale-[1.02] transition-all duration-300 group flex-1 shadow-sm",onClick:()=>A(!0),children:e.jsxs(ie,{className:"p-3 h-full flex flex-col justify-between",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ds,{className:"h-6 w-6 text-pink-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-sm text-pink-500",children:"Personalize Chat"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Customize style"})]})]}),e.jsx(_,{size:"sm",className:"w-full mt-2 bg-pink-500/20 hover:bg-pink-500/30 text-pink-500 border-pink-500/50",onClick:C=>{C.stopPropagation(),A(!0)},children:"Customize"})]})})]})]}),e.jsx(la,{open:f,onOpenChange:y}),e.jsx(mo,{open:N,onOpenChange:A})]})},jo=(s,a,m)=>{const p=new Date().toDateString().split("").reduce((u,d)=>
167u+d.charCodeAt(0),0),l=p%s.length,h=(p+1)%a.length;return`${s[l]}, ${m}${a[h]}`},bo=()=>{const[s,a]=t.useState(""),[m,x]=t.useState(!0),{user:p}=Ge();return t.useEffect(()=>{if(!p){x(!1);return}(async()=>{try{const{data:h,error:u}=await E.from("admin_settings").select("setting_value").eq("setting_category","greetings").eq("setting_key","classroom_greetings").maybeSingle(),{data:d,error:n}=await E.from("admin_settings").select("setting_value").eq("setting_category","greetings").eq("setting_key","greeting_punctuation").maybeSingle();if(u||n){console.error("Error loading greeting settings:",u||n),a(`Hello, ${p.email?.split("@")[0]||"there"}!`);return}const r=["Welcome","Hello","Hi"],v=["!","."," 🙂"],j=h?.setting_value,b=d?.setting_value,g=Array.isArray(j)?j:typeof j=="string"?JSON.parse(j):r,c=Array.isArray(b)?b:typeof b=="string"?JSON.parse(b):v,{data:o}=await E.from("profiles").select("display_name, first_name").eq("id",p.id).maybeSingle(),i=o?.display_name||o?.first_name||p.email?.split("@")[0]||"there",f=jo(g,c,i);a(f)}catch(h){console.error("Error generating greeting:",h),a(`Hello, ${p.email?.split("@")[0]||"there"}!`)}finally{x(!1)}})()},[p]),{greeting:s,loading:m}},wo=()=>{t.useEffect(()=>{const s=a=>{if(!(a.target instanceof HTMLInputElement||a.target instanceof HTMLTextAreaElement||a.target instanceof HTMLElement&&a.target.contentEditable==="true"))return;(a.ctrlKey||a.metaKey)&&(a.key==="n"||a.key==="N"||a.key==="t"||a.key==="T"||a.shiftKey&&(a.key==="n"||a.key==="N"))&&(console.log("🚫 Global prevention of new window shortcut:",a.key),a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation())};return document.addEventListener("keydown",s,!0),()=>{document.removeEventListener("keydown",s,!0)}},[])},No=({classroomId:s})=>{const{user:a}=Ge(),{currentStudent:m}=at(),{markTaskCompleteAsTutor:x}=xr(),[p,l]=t.useState([]),[h,u]=t.useState(!1),[d,n]=t.useState({}),[r,v]=t.useState({}),j=a&&!m;t.useEffect(()=>{if(!j||!a?.id)return;const g=async()=>{u(!0);try{const{data:o,error:i}=await E.from("simple_task_assignments").select(`
168            id,
169            task_id,
170            student_id,
171            status,
172            created_at,
173            simple_tasks!inner (
174              id,
175              title,
176              goal,
177              proof_type,
178              destination_classroom_id
179            ),
180            student_profiles!inner (
181              student_name,
182              student_auth_id
183            )
184          `).in("status",["in_progress","assigned"]).eq("simple_tasks.destination_classroom_id",s);if(i)throw i;const{data:f,error:y}=await E.from("student_account_managers").select("student_auth_id").eq("account_manager_id",a.id);if(y)throw y;const N=new Set(f?.map(w=>w.student_auth_id)||[]),A=(o||[]).filter(w=>N.has(w.student_profiles.student_auth_id));l(A)}catch(o){console.error("Error fetching pending tasks:",o)}finally{u(!1)}};g();const c=E.channel("task_assignments_updates").on("postgres_changes",{event:"*",schema:"public",table:"simple_task_assignments"},()=>{g()}).subscribe();return()=>{E.removeChannel(c)}},[j,a?.id,s]);const b=async g=>{v(c=>({...c,[g]:!0}));try{await x(g,d[g]),ne.success("Task marked as complete!"),n(c=>{const o={...c};return delete o[g],o}),l(c=>c.filter(o=>o.id!==g))}catch(c){console.error("Error marking task complete:",c),ne.error("Failed to mark task as complete")}finally{v(c=>({...c,[g]:!1}))}};return!j||h||p.length===0?null:e.jsxs(te,{className:"mb-6",children:[e.jsxs(Ee,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-5 h-5"}),"Pending Student Tasks"]}),e.jsx(fr,{children:"Mark tasks as complete for your students after verifying their work in this classroom"})]}),e.jsx(ie,{className:"space-y-4",children:p.map(g=>e.jsx(te,{className:"border-muted",children:e.jsxs(ie,{className:"pt-4 space-y-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:g.student_profiles.student_name}),e.jsx(me,{variant:"secondary",className:"text-xs",children:g.status==="in_progress"?"In Progress":"Assigned"})]}),e.jsx("h4",{className:"font-medium text-sm",children:g.simple_tasks.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g.simple_tasks.goal}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ea,{className:"w-3 h-3"}),"Started ",new Date(g.created_at).toLocaleDateString()]})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(rt,{placeholder:"Add notes about the student's completion (optional)",value:d[g.id]||"",onChange:c=>n(o=>({...o,[g.id]:c.target.value})),rows:2,className:"text-sm"}),e.jsxs(_,{onClick:()=>b(g.id),disabled:r[g.id],size:"sm",className:"w-full",children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),r[g.id]?"Marking Complete...":"Mark as Complete"]})]})]})},g.id))})]})},Hs=({open:s,onOpenChange:a,classroomId:m,onActionComplete:x,onHomeworkSubmit:p,onSendToChat:l,chatMessages:h})=>e.jsx(en,{open:s,onOpenChange:a,children:e.jsxs(tn,{className:"max-h-[85vh]",children:[e.jsxs(sn,{children:[e.jsx(an,{children:"Learning Tools"}),e.jsx(rn,{children:"Select a tool to enhance your learning experience"})]}),e.jsx("div",{className:"px-4 pb-4 overflow-y-auto",children:e.jsx(ls,{classroomId:m,onActionComplete:x,onHomeworkSubmit:p,onSendToChat:l,chatMessages:h,hideHeader:!0})})]})}),Co=({classroomId:s})=>{const{classroomId:a}=fs(),m=Sr(),x=s||a||"default-classroom",{user:p}=Ge(),{currentStudent:l}=at(),h=vr(),u=!h&&window.innerWidth<1024,[d,n]=t.useState(!1),[r,v]=t.useState(!1),[j,b]=t.useState(h);t.useEffect(()=>{const R=()=>{u?v($=>!$):h&&n($=>!$)};return window.addEventListener("toggle-learning-tools",R),()=>window.removeEventListener("toggle-learning-tools",R)},[u,h]),wo();const{greeting:g,loading:c}=bo(),{customization:o,saveCustomization:i}=co(x),[f,y]=t.useState(5);t.useEffect(()=>{(async()=>
184{if(l?.id){const{data:$,error:U}=await E.from("student_profiles").select("complexity_level").eq("id",l.id).maybeSingle();!U&&$?.complexity_level&&y($.complexity_level)}})()},[l?.id]);const{tutors:N,isLoading:A}=ua(x),[w,P]=t.useState(null);t.useEffect(()=>{(async()=>{if(!p?.id){console.log("❌ [ClassroomRoomContent] No user ID available for assignment lookup"),P(null);return}try{console.log(`🔍 [ClassroomRoomContent] Looking for assignment for classroom "${x}"`);const{data:$,error:U}=await E.from("classroom_assistant_assignments").select("assistant_id").eq("classroom_id",x).maybeSingle();if(U){console.error("Error fetching assignment:",U),P(null);return}let se=null;if($?.assistant_id){const{data:ee,error:J}=await E.from("ai_personalities").select("name").eq("assistant_id",$.assistant_id).is("user_id",null).eq("is_active",!0).maybeSingle();J&&console.warn("No matching AI personality found for assistant_id:",$.assistant_id,J),se=ee?.name??null}console.log(`🔍 Assignment lookup for classroom "${x}":`,{assistant_id:$?.assistant_id,personality_name:se}),P($?{assistant_id:$.assistant_id,personality_name:se||"Assigned Tutor"}:null)}catch($){console.error("Error in assignment fetch:",$)}})()},[x,p?.id]);const I=(()=>{if(console.log(`🎯 Resolving tutor for classroom "${x}" (User: ${p?.email||"no user"})`),console.log(`📊 Roster state: loading=${A}, tutors=${N.length}, names=[${N.map($=>$.name).join(", ")}]`),N.length>0){const $=N[0];console.log(`✅ Using database roster tutor: ${$.name} (${$.id}) - Assistant ID: ${$.assistant_id}`);const U=Dt(x);return U&&U.assistant_id!==$.assistant_id&&console.warn(`⚠️ MISMATCH: Roster has ${$.name} (${$.assistant_id}) but static map expects ${U.name} (${U.assistant_id}) for classroom "${x}"`),$}const R=Dt(x);if(R)return console.log(`✅ Using static mapping tutor: ${R.name} - Assistant ID: ${R.assistant_id}`),R;if(w){const $={id:`assigned-${w.assistant_id}`,name:w.personality_name,assistant_id:w.assistant_id,specialty:"Assigned Tutor",description:"Custom assigned tutor for this classroom",department:"General",role:"Tutor",expertise_areas:[],is_active:!0,user_id:null};return console.log(`✅ Using assigned assistant tutor: ${$.name}`),$}return console.log(`⚠️ No tutor found for classroom "${x}" - using fallback`),{id:`fallback-${x}`,name:"General Assistant",assistant_id:"fallback",specialty:"General Learning Support",description:"General learning assistant for this classroom",department:"Learning",role:"Assistant",expertise_areas:["general"],is_active:!0,user_id:null}})(),T=t.useMemo(()=>{if(N.length>0){if(x==="homework-hero"){const R=["tutor-maya","tutor-alex","tutor-sage","tutor-nova","tutor-jurnee"],$=new Map(N.map(se=>[se.id,se])),U=[...N];return R.forEach(se=>{if(!$.has(se)){const ee=is.find(J=>J.id===se);ee&&U.push(ee)}}),U}return N}return I?[I]:[]},[N,x,I]);if(!I)return e.jsxs("div",{className:"p-8 text-center",children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Classroom Not Available"}),e.jsx("p",{className:"text-muted-foreground",children:"This classroom is being set up. Please try again later."})]});const M=t.useRef(null),{messages:G,isLoading:D,sendMessage:Y,addWelcomeMessage:de,canUseAI:pe,availableCredits:xe,createNewSession:ce,saveMessage:oe,setActiveTutorId:ae,activeTutorName:K}=Mn(x,T,M,f),{handleButtonClick:O,activeButtons:W}=cn(x),[B,F]=t.useState(!1),[Q,S]=t.useState(!1),{activeToolConfig:z,launchTool:V,closeTool:q}=Xr();t.useEffect(()=>{const R=qr(),$=se=>{const J=se.detail?.gameId||"verified-solo",ge=R.find(je=>je.id==="mini-game");if(!ge){console.warn("Mini-game tool not registered");return}V({tool:ge,context:{gameId:J}})},U=se=>{const ee=se,{toolId:J,context:ge}=ee.detail||{};if(!J)return;const je=R.find(Se=>Se.id===J);if(!je){console.warn("Unknown toolId:",J);return}V({tool:je,context:ge})};return window.addEventListener("launch-mini-game",$),window.addEventListener("launch-learning-tool",U),()=>{window.removeEventListener("launch-mini-game",$),window.removeEventListener("launch-learning-tool",U)}},[V]);const C=R=>{console.log("TTS settings updated:",R)},H=lt.useMemo(()=>
184{if(m.state?.taskContext)return console.log("🎯 Task context from location.state:",m.state.taskContext),m.state.taskContext;const R=new URLSearchParams(m.search),$=R.get("taskContext"),U=R.get("taskId");if(console.log("🎯 Checking for task context - taskContext param:",$,"taskId param:",U),$)try{return JSON.parse(decodeURIComponent($))}catch(se){return console.error("Failed to parse task context:",se),null}return U?{taskId:U}:null},[m.search,m.state]),[ue,ve]=t.useState(!1);t.useEffect(()=>{if(H&&I&&G.length===0&&!ue){if(console.log("🎯 Task context found, preparing message for tutor:",H),H.taskId&&!H.goal){re(H.taskId);return}const R=le(H,I.name);console.log("🎯 Sending task context to tutor:",R),ve(!0),setTimeout(()=>{Y(R)},1e3)}},[H,I,G.length,Y,ue]);const re=async R=>{try{console.log("🔍 Fetching task details for ID:",R);const{data:$,error:U}=await E.from("simple_tasks").select("*").eq("id",R).single();if(U){console.error("Error fetching task details:",U);return}if($){console.log("✅ Task details loaded:",$);const se={taskId:$.id,title:$.title,goal:$.goal,reflection_prompt:$.reflection_prompt,proof_type:$.proof_type},ee=le(se,I.name);console.log("🎯 Sending enriched task context to tutor:",ee),ve(!0),setTimeout(()=>{Y(ee)},1e3)}}catch($){console.error("Error in fetchTaskDetails:",$)}},le=(R,$)=>{let U=`[TASK CONTEXT] Student has arrived to complete a task: "${R.title||R.taskTitle}". `;return R.goal&&(U+=`Task Goal: ${R.goal}. `),R.reflection_prompt&&(U+=`Reflection Prompt: ${R.reflection_prompt}. `),R.proof_type&&(U+=`Proof Required: ${R.proof_type.replace("_"," ")}. `),R.instructions&&(U+=`Additional Instructions: ${R.instructions}. `),R.promptInjections&&R.promptInjections.length>0&&(U+="Special Instructions: ",R.promptInjections.forEach((se,ee)=>{se.targetSystem==="tutor"&&(U+=`${se.message} `)})),U+="Please help the student complete this task by providing appropriate guidance and support. Start by acknowledging the task and offering specific help based on the goal and requirements.",U};t.useEffect(()=>{const R=G[G.length-1];R?.sender==="tutor"&&R?.content&&yr.autoReadMessage(R.content)},[G]);const Ne=t.useMemo(()=>(W||[]).filter(R=>R.buttonType==="TOKEN_REWARD"),[W]);t.useEffect(()=>{Ne.length>0&&F(!0)},[Ne.length]),t.useEffect(()=>{I&&de(x)},[I,x,de]);const ze=async R=>{const $=await O(R,I?.name||"Tutor");$?.contextMessage&&Y($.contextMessage)},Re=async R=>{const $=R.slice(G.length);if($.length)for(const U of $)U.sender==="user"?await Y(U.content):U.sender==="tutor"&&await oe({content:U.content,sender:"tutor",tutorName:U.tutorName||"Pet"})};return e.jsxs(e.Fragment,{children:[e.jsx(un,{}),e.jsx(mn,{classroomSubject:x}),e.jsxs("div",{className:"container mx-auto p-4",children:[!c&&g&&e.jsx(te,{variant:"paper",className:"mb-6 p-6 text-center",children:e.jsxs("div",{className:"paper-inset p-4 rounded-lg",children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground mb-2",children:g}),e.jsx("p",{className:"text-muted-foreground",children:"Welcome to your classroom"})]})}),e.jsx(No,{classroomId:x}),x==="welcome"&&e.jsx("div",{className:"mb-4",children:e.jsx(Wt,{title:"Quick Actions & Tutorials",description:"Tutorial videos, suggestion box, and chat personalization",defaultOpen:!0,children:e.jsx(yo,{classroomId:x,showAllSlots:!0,onSendToChat:R=>Y(R)})})}),h?e.jsxs("div",{className:"h-[calc(100vh-120px)] flex flex-col",children:[e.jsxs(te,{variant:"paper",className:"bg-card/50 border-border/50 backdrop-blur-sm shadow-xl flex-1 flex flex-col",children:[e.jsxs(Ee,{className:"flex items-center justify-between flex-shrink-0 py-3 px-4",children:[e.jsx(Ae,{className:"text-lg",children:"Chat"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(_,{size:"sm",onClick:ce,className:"gap-1 bg-gradient-to-r from-purple-500 to-orange-500 text-white px-2 py-1 text-xs",children:[e.jsx(Ct,{className:"h-3 w-3"}),"New"]}),e.jsx(_,{size:"sm",onClick:()=>n(!0),className:"gap-1 bg-gradient-to-r from-blue-500 to-cyan-500 text-white px-2 py-1 text-xs",children:"Tools"})]})]}),e.jsx(ie,{className:"p-0 flex-1 min-h-0",children:e.jsx(xt,{ref:M,classroomId:x,messages:G,onMessagesChange:Re,isLoading:D,onLoadingChange:()=>{},dynamicButtons:W,onDynamicButtonClick:(R,$)=>O(R,$),customization:o,canUseAI:pe,availableCredits:xe,studentId:l?.id,complexityLevel:f,onComplexityChange:y,activeTutorName:K,onSwitchTutor:()=>ae(null)})})]}),e.jsx(Hs,{open:d,onOpenChange:n,classroomId:x,onHomeworkSubmit:R=>Y(R),onSendToChat:R=>Y(R),chatMessages:G})]}):u?e.jsxs("div",{className:"h-[calc(100vh-200px)]",children:[r?e.jsxs(nn,{direction:"horizontal",className:"h-full",children:[e.jsx(zs,{defaultSize:70,minSize:50,children:e.jsxs(te,{variant:"paper",className:"bg-card/50 border-border/50 backdrop-blur-sm shadow-xl h-full flex flex-col",children:[e.jsxs(Ee,{className:"flex items-center justify-between flex-shrink-0",children:[e.jsx(Ae,{children:"Classroom Chat"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>v(!1),children:[e.jsx(Ls,{className:"h-4 w-4 mr-2"}),"Hide Tools"]}),e.jsxs(_,{size:"sm",onClick:ce,className:"gap-2 bg-gradient-to-r from-purple-500 to-orange-500 text-white",children:[e.jsx(Ct,{className:"h-4 w-4"}),"New Chat"]}),e.jsx(Zt,{onSettingsChange:C})]})]}),e.jsx(ie,{className:"p-0 flex-1 min-h-0",children:e.jsx(xt,{ref:M,classroomId:x,messages:G,onMessagesChange:Re,isLoading:D,onLoadingChange:()=>{},dynamicButtons:W,onDynamicButtonClick:(R,$)=>O(R,$),customization:o,canUseAI:pe,availableCredits:xe,studentId:l?.id,complexityLevel:f,onComplexityChange:y,activeTutorName:K,onSwitchTutor:()=>ae(null)})})]})}),e.jsx(on,{withHandle:!0}),e.jsx(zs,{defaultSize:30,minSize:25,children:e.jsx(Wt,{title:"Learning Tools",description:"Access learning tools",defaultOpen:!0,className:"h-full",children:e.jsx(ls,{classroomId:x,onHomeworkSubmit:R=>Y(R),onSendToChat:R=>Y(R),chatMessages:G})})})]}):e.jsxs(te,{variant:"paper",className:"bg-card/50 border-border/50 backdrop-blur-sm shadow-xl h-full flex flex-col",children:[e.jsxs(Ee,{className:"flex items-center justify-between flex-shrink-0",children:[e.jsx(Ae,{children:"Classroom Chat"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>v(!0),children:[e.jsx(Ls,{className:"h-4 w-4 mr-2"}),"Show Tools"]}),e.jsxs(_,{size:"sm",onClick:ce,className:"gap-2 bg-gradient-to-r from-purple-500 to-orange-500 text-white",children:[e.jsx(Ct,{className:"h-4 w-4"}),"New Chat"]}),e.jsx(Zt,{onSettingsChange:C})]})]}),e.jsx(ie,{className:"p-0 flex-1 min-h-0",children:e.jsx(xt,{ref:M,classroomId:x,messages:G,onMessagesChange:Re,isLoading:D,onLoadingChange:()=>{},dynamicButtons:W,onDynamicButtonClick:(R,$)=>O(R,$),customization:o,canUseAI:pe,availableCredits:xe,studentId:l?.id,complexityLevel:f,onComplexityChange:y,activeTutorName:K,onSwitchTutor:()=>ae(null)})})]}),e.jsx(Hs,{open:d,onOpenChange:n,classroomId:x,onHomeworkSubmit:R=>Y(R),onSendToChat:R=>Y(R),chatMessages:G})]}):e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(te,{variant:"paper",className:"bg-card/50 border-border/50 backdrop-blur-sm shadow-xl h-[80vh] flex flex-col",children:[e.jsxs(Ee,{className:"flex items-center justify-between flex-shrink-0",children:[e.jsxs(Ae,{children:["Classroom Chat: ",x]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(_,{size:"sm",onClick:ce,className:"gap-2 bg-gradient-to-r from-purple-500 to-orange-500 text-white hover:from-purple-600 hover:to-orange-600 border-0 shadow-md hover:shadow-lg transition-all duration-200 hover:scale-105",children:[e.jsx(Ct,{className:"h-4 w-4"}),"New Chat"]}),e.jsx(Zt,{onSettingsChange:C}),e.jsx(_,{size:"sm",onClick:()=>S(!0),className:"bg-gradient-to-r from-pink-500 to-rose-400 text-white hover:from-pink-600 hover:to-rose-500 border-0 shadow-md hover:shadow-lg transition-all duration-200 hover:scale-105",children:"Customize"})]})]}),e.jsx(ie,{className:"p-0 flex-1 min-h-0",children:e.jsx(xt,{ref:M,classroomId:x,messages:G,onMessagesChange:Re,isLoading:D,onLoadingChange:()=>{},dynamicButtons:W,onDynamicButtonClick:(R,$)=>O(R,$),customization:o,canUseAI:pe,availableCredits:xe,studentId:l?.id,complexityLevel:f,onComplexityChange:y,activeTutorName:K,onSwitchTutor:()=>ae(null)})})]})}),e.jsx("div",{className:"lg:col-span-1 min-h-0 relative z-10",children:e.jsx(Wt,{title:"Learning Tools",description:"",defaultOpen:!j,className:"h-[80vh]",hideTitle:!0,children:e.jsx(ls,{classroomId:x,onHomeworkSubmit:R=>Y(R),onSendToChat:R=>Y(R),chatMessages:G,hideHeader:!0})})})]})]}),e.jsx("div",{className:"fixed bottom-6 right-6 z-[55]",children:e.jsxs(_,{variant:"secondary",className:"shadow-lg gap-2",onClick:()=>F(!0),children:[e.jsx(ds,{className:"h-4 w-4"}),"Rewards",Ne.length>0&&e.jsx("span",{className:"ml-2 inline-flex h-5 min-w-[20px] items-center justify-center rounded-full bg-primary/20 text-primary text-xs px-2",children:Ne.length})]})}),e.jsx(hn,{open:B,onOpenChange:F,offers:Ne,onCollect:ze}),e.jsx(lo,{isOpen:Q,onClose:()=>S(!1),customization:o,onSave:i,classroomId:x}),z&&e.jsx(zr,{config:z,onClose:q})]})},gi=()=>{const{classroomId:s}=fs();return console.log("ClassroomRoom: classroomId from URL params:",s),e.jsxs(jr,{variant:"floating-shapes",children:[e.jsx("div",{className:"mb-4",children:e.jsx(_,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(da,{to:"/app/classrooms",children:[e.jsx(er,{className:"w-4 h-4 mr-2"}),"Back to Classrooms"]})})}),e.jsx(br,{featureName:"AI Classroom",children:e.jsx(Co,{classroomId:s})})]})};export{gi as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.