@turnix-co/konva-editor 2.0.44 → 2.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- export{default as Konva}from'konva';import*as be from'react';import be__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,createElement,useMemo,useId,useLayoutEffect}from'react';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,configureStore}from'@reduxjs/toolkit';import Hl from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,SidebarSimple,Plus,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp as CloudArrowUp$1,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {CaretLeft,CloudArrowUp,EyeIcon,Stack as Stack$1,X as X$1,DotsSixVertical,ArrowUp,ArrowDown,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {createPortal}from'react-dom';import Hd from'use-image';import {motion,AnimatePresence,Reorder}from'framer-motion';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Rl=e=>{throw TypeError(e)};var Dl=(e,o,t)=>o.has(e)||Rl("Cannot "+t);var K=(e,o,t)=>(Dl(e,o,"read from private field"),t?t.call(e):o.get(e)),Te=(e,o,t)=>o.has(e)?Rl("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),ke=(e,o,t,a)=>(Dl(e,o,"write to private field"),o.set(e,t),t);var Fl=(e,o,t,a)=>({set _(r){ke(e,o,r);},get _(){return K(e,o,a)}});var xe=()=>useDispatch(),ee=e=>useSelector(e),qt=xe,aa=ee;var rs=20,El=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now()}),os=El("Slide 1"),Qf={slides:[os],currentSlideId:os.id,history:{[os.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null},Bl=createSlice({name:"canvas",initialState:Qf,reducers:{addSlide:e=>{if(e.slides.length>=rs)return;let o=El(`Slide ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{if(e.slides.length<=1)return;let t=e.slides.findIndex(a=>a.id===o.payload);if(t!==-1&&(e.slides.splice(t,1),delete e.history[o.payload],e.currentSlideId===o.payload)){let a=Math.max(0,t-1);e.currentSlideId=e.slides[a].id;}},duplicateSlide:(e,o)=>{if(e.slides.length>=rs)return;let t=e.slides.findIndex(n=>n.id===o.payload);if(t===-1)return;let a=e.slides[t],r={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[r]=e.slides.splice(t,1);e.slides.splice(a,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(r=>r.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload);if(a){let r={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(r),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,newTimestamp:n}=o.payload;switch(r){case "image":let s=t.images.find(g=>g.id===a);s&&(s.timestamp=n);break;case "video":let i=t.videos.find(g=>g.id===a);i&&(i.timestamp=n);break;case "shape":let u=t.shapes.find(g=>g.id===a);u&&(u.timestamp=n);break;case "text":let l=t.texts.find(g=>g.id===a);l&&(l.timestamp=n);break;case "flashcard":let c=t.flashcards.find(g=>g.id===a);c&&(c.timestamp=n);break;case "photoFrame":let d=t.photoFrames.find(g=>g.id===a);d&&(d.timestamp=n);break;case "mcq":let p=t.multipleChoices.find(g=>g.id===a);p&&(p.timestamp=n);break;case "trueFalse":let f=t.trueFalses.find(g=>g.id===a);f&&(f.timestamp=n);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=n);break;case "longAnswer":let x=t.LongAnswer.find(g=>g.id===a);x&&(x.timestamp=n);break;case "fillInTheBlanks":let m=t.fillInTheBlanks.find(g=>g.id===a);m&&(m.timestamp=n);break;case "line":let v=t.lines.find(g=>g.id===a);v&&(v.timestamp=n);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);if(a){let r={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(r),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);if(a){let r={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(r),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(r),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let r=t.multipleChoices[t.multipleChoices.length-1];a.x=r.x+20,a.y=r.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(r=>r.id===o.payload);if(a){let r={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(r),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let r=t.trueFalses[t.trueFalses.length-1];a.x=r.x+20,a.y=r.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(r),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let r=t.shortAnswers[t.shortAnswers.length-1];a.x=r.x+20,a.y=r.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(r=>r.id===o.payload);if(a){let r={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(r),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let r=t.LongAnswer[t.LongAnswer.length-1];a.x=r.x+20,a.y=r.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload);if(a){let r={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(r),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let r=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=r.x+20,a.y=r.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(r=>r.id===o.payload);if(a){let r={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(r),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.push(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.push(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.push(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.push(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.push(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.push(s);}}else if(r==="trueFalse"){let n=t.trueFalses.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.trueFalses.splice(n,1);t.trueFalses.push(s);}}else if(r==="shortAnswer"){let n=t.shortAnswers.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shortAnswers.splice(n,1);t.shortAnswers.push(s);}}else if(r==="fillInTheBlanks"){let n=t.fillInTheBlanks.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.fillInTheBlanks.splice(n,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.unshift(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.unshift(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.unshift(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.unshift(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.unshift(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.unshift(s);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload,s=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,link:n}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="mcq"?t.multipleChoices:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.link=n,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,altText:n}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.altText=n,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,audioData:n}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.audioData=n,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(r=>r.id===o.payload);if(a){let r={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(r),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a){let r={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(r),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let r=a.images.map((n,s)=>s).filter(n=>n!==a.currentIndex);if(r.length>0){let n=r[Math.floor(Math.random()*r.length)];a.navigationHistory.push(n),a.currentIndex=n;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);if(a){let r={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(r),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let r=o.past.pop();e.slides[t]=r;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let r=o.future.shift();e.slides[t]=r;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let r=JSON.parse(JSON.stringify(t));a.past.push(r),a.future=[],a.past.length>20&&a.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;}}}),{addSlide:ns,deleteSlide:ss,duplicateSlide:is,setCurrentSlide:ls,updateSlideThumbnail:ds,setBackgroundColor:us,reorderSlides:em,loadSlides:cs,addLine:fs,removeLine:qr,addImage:ms,updateImage:Xa,deleteImage:ps,duplicateImage:Ur,addVideo:Hr,updateVideo:zr,deleteVideo:hs,duplicateVideo:Wr,toggleVideoPlaying:Do,addShape:gs,updateShape:Ya,duplicateShape:Gr,deleteShape:xs,addText:bs,updateText:yt,deleteText:vs,duplicateText:Kr,addFlashcard:ys,updateFlashcard:Ja,deleteFlashcard:ws,duplicateFlashcard:_r,editFlashcard:Fo,nextFlashcard:Ls,previousFlashcard:Ss,addPhotoFrame:Is,updatePhotoFrame:Pa,deletePhotoFrame:Cs,duplicatePhotoFrame:jr,toggleImageDrawingMode:ks,addImageAnnotation:Ms,updateImageAnnotation:tm,clearImageAnnotations:am,togglePhotoFrameDrawingMode:Ts,addPhotoFrameAnnotation:As,updatePhotoFrameAnnotation:om,clearPhotoFrameAnnotations:rm,addMultipleChoice:Ps,updateMultipleChoice:oa,editMultipleChoice:nm,deleteMultipleChoice:Rs,duplicateMultipleChoice:$r,addTrueFalse:Ds,updateTrueFalse:ra,deleteTrueFalse:Fs,duplicateTrueFalse:Xr,addShortAnswer:Es,updateShortAnswer:Eo,deleteShortAnswer:Bs,duplicateShortAnswer:Yr,addLongAnswer:Os,updateLongAnswer:Bo,deleteLongAnswer:Ns,duplicateLongAnswer:Jr,addFillInTheBlanks:Vs,updateFillInTheBlanks:Oo,deleteFillInTheBlanks:qs,duplicateFillInTheBlanks:Zr,setShowMcqForm:na,setShowFlashcardForm:Ra,setActivityType:Us,setEditingActivity:No,bringToFront:Hs,sendToBack:zs,toggleLock:Ws,setLink:Qr,setAltText:en,setAudioData:tn,updateLastLine:sm,finalizeDrawing:Gs,setLines:im,updateLinePosition:lm,updateLineTransform:an,deleteLineById:Ks,duplicateLine:_s,updateElementOrder:Vo,clearCanvas:js,undo:$s,redo:Xs,saveToHistory:ue,toggleSketchMode:dm,setSketchMode:dt,setEditingTextId:qo}=Bl.actions,Uo=e=>e.canvas.currentSlideId,ge=e=>{let o=e.canvas.currentSlideId,t=e.canvas.slides.findIndex(a=>a.id===o);return t>=0?e.canvas.slides[t]:void 0},Ho=e=>e.canvas.slides,Ys=e=>e.canvas.slides.length<rs,um=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},Ol=Bl.reducer;var Vl=e=>{let o=xe(),t=useRef(null),a=useRef(false),r=ee(f=>f.toolbar.selectedTool),n=ee(f=>f.toolbar.penColor),s=ee(f=>f.toolbar.strokeWidth),i=ee(f=>f.canvas.isSketchMode),u=ee(f=>f.canvas.slides.find(x=>x.id===f.canvas.currentSlideId)?.lines||[]),l=useCallback(f=>{t.current=f;},[]),c=useCallback(f=>{r==="pen"&&t.current&&(o(ue()),t.current.startDrawing(f),a.current=true);},[r,o]),d=useCallback(f=>{!t.current||!a.current||t.current.draw(f);},[]),p=useCallback(()=>{if(!t.current||!a.current)return;let f=t.current.stopDrawing();a.current=false,f&&f.points.length>=4&&o(fs(f)),o(Gs()),e?.();},[o,e]);return {lines:u,tool:r,color:n,strokeWidth:s,isSketchMode:i,setCanvasRef:l,startDrawing:c,draw:d,stopDrawing:p}};var zl=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:n,style:s},i)=>{let u=useRef(null),l=useRef(false),c=useRef([]),d=useRef(null),p=useRef(t),f=useRef(a),h=useRef(r),x=useRef(n);useEffect(()=>{p.current=t,f.current=a,h.current=r,x.current=n;},[t,a,r,n]);let m=useCallback(()=>{let g=u.current;if(!g)return;let b=g.getContext("2d");b&&b.clearRect(0,0,g.width,g.height);},[]),v=useCallback(()=>{let g=u.current,b=c.current;if(!g||b.length<1)return;let y=g.getContext("2d");if(!y)return;if(y.clearRect(0,0,g.width,g.height),p.current==="eraser"?(y.globalCompositeOperation="destination-out",y.fillStyle="rgba(0,0,0,1)"):(y.globalCompositeOperation="source-over",y.fillStyle=f.current),b.length===1){y.beginPath(),y.arc(b[0].x,b[0].y,h.current/2,0,Math.PI*2),y.fill();return}let I=Hl(b,{size:h.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:C=>C,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(I.length<2)){y.beginPath(),y.moveTo(I[0][0],I[0][1]);for(let C=1;C<I.length;C++)y.lineTo(I[C][0],I[C][1]);y.closePath(),y.fill();}},[]);return useImperativeHandle(i,()=>({startDrawing:g=>{l.current=true,c.current=[{x:g.x,y:g.y}],d.current=g,v();},draw:g=>{if(!l.current||!d.current)return;let b=g.x-d.current.x,y=g.y-d.current.y;Math.sqrt(b*b+y*y)<2||(c.current.push({x:g.x,y:g.y}),d.current=g,v());},stopDrawing:()=>{if(!l.current)return null;if(l.current=false,c.current.length<2)return c.current=[],d.current=null,m(),null;let b=Hl(c.current,{size:h.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:S=>S,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(S=>[S[0],S[1]]),y={tool:p.current,points:b,color:f.current,strokeWidth:h.current,isSketch:true};return c.current=[],d.current=null,m(),y},clear:()=>{m(),c.current=[],d.current=null,l.current=false;},isDrawing:()=>l.current,getCanvasElement:()=>u.current}),[m,v]),useEffect(()=>{let g=u.current;g&&(g.width=e,g.height=o);},[e,o]),jsx("canvas",{ref:u,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});zl.displayName="DirectDrawingCanvas";var Wl=zl;var Kl=e=>{let o=xe(),a=ee(ge)?.images||[],r=useRef(new Map),n=useRef(new Map),s=useRef(new Set);useEffect(()=>{let c=new Set(a.map(d=>d.id));s.current.forEach(d=>{if(!c.has(d)){let p=n.current.get(d);p&&(p.src="",n.current.delete(d)),r.current.delete(d);}}),s.current=c;},[a]),useEffect(()=>()=>{n.current.forEach(c=>{c.src="";}),n.current.clear(),r.current.clear();},[]);let i=useCallback(c=>{if(n.current.has(c.id))return n.current.get(c.id);let d=new window.Image;return d.src=c.src,n.current.set(c.id,d),d},[]),u=useCallback((c,d)=>{let p=c.target,f=p.id();a.find(x=>x.id===f)&&(o(Xa({id:f,x:p.x(),y:p.y(),width:p.width(),height:p.height(),rotation:p.rotation()})),d?.());},[a,o]),l=useCallback((c,d)=>{let p=d.target,f=r.current.get(c);if(!f){console.error("\u274C Image node not found for id:",c);return}let h=p.scaleX(),x=p.scaleY(),m=p.rotation(),v=f.width(),g=f.height(),b=Math.max(5,v*h),y=Math.max(5,g*x);p.scaleX(1),p.scaleY(1),f.width(b),f.height(y),o(Xa({id:c,width:b,height:y,x:p.x(),y:p.y(),rotation:m})),p.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:i,imageRefs:r,handleDragEnd:u,handleImageTransformEnd:l}};var _l=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),n=useCallback((i,u)=>{let l=u.target,c=l.scaleX(),d=l.scaleY(),p=l.rotation(),f=Math.max(5,l.width()*c),h=Math.max(5,l.height()*d);l.scaleX(1),l.scaleY(1),l.width(f),l.height(h),o(oa({id:i,width:f,height:h,x:l.x(),y:l.y(),rotation:p})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:n,mcqRefs:a,handleDragEnd:(i,u)=>{o(oa({id:u,x:i.target.x(),y:i.target.y()})),e?.();}}};var jl=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),n=useCallback((i,u)=>{let l=u.target,c=l.scaleX(),d=l.scaleY(),p=l.rotation(),f=Math.max(5,l.width()*c),h=Math.max(5,l.height()*d);l.scaleX(1),l.scaleY(1),l.width(f),l.height(h),o(ra({id:i,width:f,height:h,x:l.x(),y:l.y(),rotation:p})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:n,handleTrueFalseDragEnd:(i,u)=>{o(ra({id:u,x:i.target.x(),y:i.target.y()})),e?.();},trueFalseRefs:a}};var $l=e=>{let o=xe(),a=ee(ge)?.videos||[],r=useRef(new Map),n=useCallback(u=>{o(Do(u));},[o]),s=useCallback((u,l)=>{let c=l.target;o(zr({id:u,x:c.x(),y:c.y()})),e?.();},[o,e]),i=useCallback((u,l)=>{let c=l.target,d=c.scaleX(),p=c.scaleY(),f=c.rotation(),h=Math.max(5,c.width()*d),x=Math.max(5,c.height()*p);c.scaleX(1),c.scaleY(1),c.width(h),c.height(x),o(zr({id:u,width:h,height:x,x:c.x(),y:c.y(),rotation:f})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:n,handleVideoDragEnd:s,handleVideoTransformEnd:i}};var Jl=e=>{let o=xe(),a=ee(ge)?.shapes||[],r=useRef(new Map),n=useRef(new Map),[s,i]=useState(false),u=useCallback((c,d)=>{let p=d.target;o(Ya({id:c,x:p.x(),y:p.y()})),e?.();},[o,e]),l=useCallback((c,d)=>{let p=d.target,f=a.find(b=>b.id===c);if(!f)return;let h=p.scaleX(),x=p.scaleY(),m=f.type?.toLowerCase();m==="arrow"||m==="line"||(p.scaleX(1),p.scaleY(1));let g={id:c,x:p.x(),y:p.y(),width:Math.max(5,p.width()*h),height:Math.max(5,p.height()*x),rotation:p.rotation()};switch(m){case "circle":g.radius=p.width()*h/2;break;case "star":g.innerRadius=p.width()*h/4,g.outerRadius=p.width()*h/2;break;case "triangle":g.radius=p.width()*h/2;break;case "ellipse":g.radiusX=p.width()*h/2,g.radiusY=p.height()*x/2;break;case "polygon":g.radius=p.width()*h/2;break;case "ring":let b=h;g.innerRadius=f.innerRadius&&f.innerRadius*b,g.outerRadius=f.outerRadius&&f.outerRadius*b;break;case "wedge":g.radius=f.radius&&f.radius*h;break;case "arc":g.innerRadius=f.innerRadius&&f.innerRadius*h,g.outerRadius=f.outerRadius&&f.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=x,delete g.width,delete g.height;break}}o(Ya(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:s,loadedShapesRef:n,handleShapeDragEnd:u,handleShapeResizeEnd:l}};var Ql=(e,o)=>{let t=qt(),r=ee(ge)?.texts||[],n=useRef(new Map),[s,i]=useState(null),[u,l]=useState("");return {texts:r,textRefs:n,handleDragEnd:(m,v)=>{let g=m.target;t(ue()),t(yt({id:v,x:g.x(),y:g.y()})),e();},handleTransformEnd:m=>{let v=n.current.get(m);if(!v)return;let g=v.scaleX(),b=v.scaleY(),y=r.find(I=>I.id===m);if(!y)return;let S=(g+b)/2;v.scaleX(1),v.scaleY(1),t(ue()),t(yt({id:m,x:v.x(),y:v.y(),width:Math.max(5,(y.width||100)*g),height:Math.max(5,(y.height||50)*b),fontSize:Math.round(Math.max(8,y.fontSize*S)),rotation:v.rotation()})),e();},handleDoubleClick:m=>{let v=r.find(g=>g.id===m);v&&!v.locked&&(i(m),l(v.text));},startEditing:m=>{let v=r.find(g=>g.id===m);v&&!v.locked&&(i(m),l(v.text));},editingTextId:s,editingValue:u,handleEditingChange:m=>{l(m);},finishEditing:()=>{if(s){let m=n.current.get(s),v=r.find(b=>b.id===s);t(ue());let g={id:s,text:u};if(v&&(v.fontWeight!==void 0&&(g.fontWeight=v.fontWeight),v.fontStyle!==void 0&&(g.fontStyle=v.fontStyle),v.textDecoration!==void 0&&(g.textDecoration=v.textDecoration)),o?.current&&u.trim()){let b=o.current,y=b.offsetWidth,S=b.offsetHeight,I=1;if(m){let H=m.getStage();H&&(I=H.scaleX());}let C=14,L=(y-C)/I,P=(S-C)/I,A=u.split(`
3
- `).length,F=r.find(H=>H.id===s)?.fontSize||24,D=A*F*1.2+10;g.width=Math.max(200,L),g.height=Math.max(50,P,D);}else if(m&&u.trim()){let b=m.text(),y=m.width();m.text(u),m.width(void 0);let S=m.width(),I=m.height();m.text(b),m.width(y),g.width=Math.max(200,S+20),g.height=Math.max(50,I+20);}t(yt(g)),i(null),l(""),t(qo(null)),e();}}}};var ed=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),n=useCallback((s,i)=>{let u=s.target;o(Eo({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var td=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,s)=>{let i=n.target;o(Bo({id:s,x:i.x(),y:i.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var od=e=>{let o=xe(),a=ee(ge)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),s=useCallback((d,p)=>{if(n.current.has(p))return n.current.get(p);let f=new window.Image;return f.src=d,n.current.set(p,f),f},[]),i=useCallback((d,p)=>{let f=d.target,h=f.id();a.find(m=>m.id===h)&&(o(Ja({id:h,x:f.x(),y:f.y()})),p?.());},[a,o]),u=useCallback((d,p)=>{let f=p.target,h=f.scaleX(),x=f.scaleY(),m=f.rotation(),v=Math.max(50,f.width()*h),g=Math.max(50,f.height()*x);f.scaleX(1),f.scaleY(1),f.width(v),f.height(g),o(Ja({id:d,width:v,height:g,x:f.x(),y:f.y(),rotation:m})),f.getLayer()?.batchDraw(),e?.();},[o,e]),l=useCallback(d=>{o(Ls(d)),e?.();},[o,e]),c=useCallback(d=>{o(Ss(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:r,handleDragEnd:i,handleFlashcardTransformEnd:u,handleNext:l,handlePrevious:c}};var sd=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],r=useRef(new Map),[n,s]=useState(new Map),i=useCallback((f,h)=>{console.log("handleDragEnd"),o(Pa({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),u=useCallback((f,h)=>{let x=h.target,m=x.scaleX(),v=x.scaleY(),g=x.rotation(),b=a.find(I=>I.id===f);if(!b)return;let y=Math.max(100,b.width*m),S=Math.max(100,b.height*v);x.scaleX(1),x.scaleY(1),o(Pa({id:f,width:y,height:S,x:x.x(),y:x.y(),rotation:g})),x.getLayer()?.batchDraw(),e?.();},[o,e,a]),l=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(x=>{let m=new Map(x);return m.set(f,h),m}),o(Pa({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),c=useCallback(f=>{let h=n.get(f);h&&(h.getTracks().forEach(x=>x.stop()),s(x=>{let m=new Map(x);return m.delete(f),m}),o(Pa({id:f,isCapturing:false})),e?.());},[n,o,e]),d=useCallback((f,h)=>{let x=document.createElement("canvas");x.width=h.videoWidth,x.height=h.videoHeight;let m=x.getContext("2d");if(m){m.drawImage(h,0,0,x.width,x.height);let v=x.toDataURL("image/jpeg",.8);return o(Pa({id:f,capturedImageUrl:v,isCapturing:false})),c(f),e?.(),v}return null},[o,c,e]),p=useRef(n);return useEffect(()=>{p.current=n;},[n]),useEffect(()=>()=>{p.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:i,handlePhotoFrameTransformEnd:u,startCamera:l,stopCamera:c,capturePhoto:d,cameraStreams:n}};var id=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((n,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((n,s,i,u,l,c,d=[])=>{if(e.current){if(n&&!d.find(h=>h.id===n)?.isPlaying){let h=s.get(n)||i.get(n)||u.get(n)||l.get(n)||c.get(n);if(h){e.current.boundBoxFunc(t),e.current.nodes([h]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var Vm=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},cd=(e,o)=>{let t=qt(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let s=o.current.toDataURL({pixelRatio:.2,mimeType:"image/jpeg",quality:.6});t(ds({id:a.current,thumbnail:s}));}catch(s){console.error("Error generating thumbnail:",s);}},[o,t]),n=Vm(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var Um=e=>e.flatMap(o=>[o[0],o[1]]),rn=(e,o)=>{let t=Hl(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return Um(t)};var fd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null),i=ee(b=>b.toolbar.selectedTool),u=ee(b=>b.toolbar.penColor),l=ee(b=>b.toolbar.strokeWidth),c=ee(b=>b.canvas.isSketchMode),d=ee(b=>b.canvas.slides.find(S=>S.id===b.canvas.currentSlideId)?.images.find(S=>S.id===e)),p=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,x=d?.height||1,m=useCallback(b=>{if(i!=="pen"&&i!=="eraser")return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let y=b.x/h,S=b.y/x;s({tool:i,points:[y,S],color:u,strokeWidth:l/h,isSketch:c});},[i,u,l,c,h,x]),v=useCallback(b=>{if(!t.current||!n)return;a.current=true;let y=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-y.x,2)+Math.pow(b.y-y.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(c)I=rn(r.current,{size:l*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((L,P)=>P%2===0?L/h:L/x);else {let C=b.x/h,L=b.y/x;I=[...n.points,C,L];}s(C=>C?{...C,points:I}:null);},[c,l,n,h,x]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Ms({imageId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:p,activeLine:n,isDrawingMode:f,startDrawing:m,draw:v,stopDrawing:g,tool:i}};var gd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>{let{annotations:i,activeLine:u,stopDrawing:p,tool:f}=fd(e.id);useEffect(()=>{let g=t.current.get(e.id);g&&(g.width()!==e.width||g.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:g.width(),konvaHeight:g.height()}),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let h=false;useEffect(()=>{return;},[p,h]);let x=g=>{{n(e.id);return}},m=g=>{return;},v=g=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:g=>{if(g){t.current.set(e.id,g),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw();let b=g.getStage()?.container();if(b){let y=S=>{let I=g.getStage()?.getPointerPosition();if(I){let C={x:e.x,y:e.y,width:e.width,height:e.height};I.x>=C.x&&I.x<=C.x+C.width&&I.y>=C.y&&I.y<=C.y+C.height&&s(S,e.id,"image");}};b.addEventListener("contextmenu",y),g._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",y);};}}else {let b=t.current.get(e.id);b?._contextMenuCleanup&&b._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:g=>r(e.id,g),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...f!=="pen"&&f!=="eraser"?{onClick:x,onTap:x,onMouseDown:x,onTouchStart:x,onMouseMove:m,onTouchMove:m,onMouseUp:v,onTouchEnd:v}:{}}),i?.map((g,b)=>{let y=g.points.map((I,C)=>C%2===0?I*e.width+e.x:I*e.height+e.y),S=g.strokeWidth*e.width;return jsx(Line,{points:y,stroke:g.tool==="eraser"?"white":g.color,strokeWidth:S,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:g.tool==="eraser"?"destination-out":"source-over",fill:g.isSketch?g.color:void 0,closed:g.isSketch,listening:false},b)}),u&&jsx(Line,{points:u.points.map((g,b)=>b%2===0?g*e.width+e.x:g*e.height+e.y),stroke:u.tool==="eraser"?"white":u.color,strokeWidth:u.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:u.tool==="eraser"?"destination-out":"source-over",fill:u.isSketch?u.color:void 0,closed:u.isSketch,listening:false},"active")]})});gd.displayName="ImageWithDrawing";var oi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(i=>{let u=o(i);return u?jsx(gd,{img:i,loadedImage:u,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s},i.id):null})}));oi.displayName="ImageLayer";var Ym=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:s,rotation:i=0,onTransformEnd:u,onDragEnd:l})=>{let c=xe(),d=useRef(null),p=f=>{c(Do(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:i,onDragEnd:l,onTransformEnd:u,children:[jsx(Rect,{width:r,height:n,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${n}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>p(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},xd=Ym;var rp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:s})=>{let[i,u]=useState(null),l=useSelector(x=>x.toolbar.selectedTool),c=l==="pen"||l==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let x=new window.Image;x.src=e.thumbnailDataUrl,x.onload=()=>{u(x);};}},[e.thumbnailDataUrl]),!i)return null;let d=e.width/2,p=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:a,onTransformEnd:r},ref:x=>{if(s(x),x){let m=x.getStage()?.container();if(m){let v=g=>{let b=x.getStage()?.getPointerPosition();if(b){let y={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=y.x&&b.x<=y.x+y.width&&b.y>=y.y&&b.y<=y.y+y.height&&n(g);}};m.addEventListener("contextmenu",v),x._contextMenuCleanup=()=>{m.removeEventListener("contextmenu",v);};}}},children:[jsx(Image$1,{image:i,width:e.width,height:e.height,listening:!c,...c?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:d,y:p,radius:h,fill:"white",listening:!c,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...c?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:p,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!c,...c?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:p,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!c,...c?{}:{onClick:t,onTap:t}})]})},vd=rp;var si=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(i=>jsxs(be__default.Fragment,{children:[jsx(vd,{video:i,isSelected:!i.isPlaying&&o===i.id,onClick:()=>a(i.id),onDragEnd:u=>r(i.id,u),onTransformEnd:u=>n(i.id,u),onContextMenu:u=>s(u,i.id,"video"),nodeRef:u=>{u?t.current.set(i.id,u):t.current.delete(i.id);}}),i.isPlaying&&(()=>{let u=i.x,l=i.y;if(i.isRecorded){let c=typeof window<"u"?window.innerWidth:i.width,d=typeof window<"u"?window.innerHeight:i.height;u=(c-i.width)/2,l=(d-i.height)/2;}return jsx(xd,{id:i.id,src:i.objectUrl,x:u,y:l,width:i.width,height:i.height,isSelected:false,rotation:i.rotation,onTransformEnd:c=>n(i.id,c),onDragEnd:c=>r(i.id,c)})})()]},i.id))}));si.displayName="VideoLayer";var ii=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:s})=>{let i=useSelector(l=>l.toolbar.selectedTool),u=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map((l,c)=>{let d=l.id||c,p={id:l.id,x:l.x,y:l.y,rotation:l.rotation,draggable:!l.locked&&!u,listening:!u,fill:l.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(l.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},radius:l.radius||l.width/2,width:l.width,height:l.width},d);case "star":return jsx(Star,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},numPoints:5,innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},d);case "triangle":return jsx(RegularPolygon,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},sides:3,radius:l.radius||l.width/2},d);case "polygon":return jsx(RegularPolygon,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},sides:l.sides||6,radius:l.radius||l.width/2},d);case "ellipse":return jsx(Ellipse,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},radiusX:l.radiusX||l.width/2,radiusY:l.radiusY||l.height/2},d);case "ring":return jsx(Ring,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},d);case "wedge":return jsx(Wedge,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},radius:l.radius||l.width/2,angle:l.angle||60},d);case "arrow":return jsx(Arrow,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},points:l.points||[0,0,l.width,0],pointerLength:l.pointerLength||10,pointerWidth:l.pointerWidth||10,stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},d);case "line":return jsx(Line,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},points:l.points||[0,0,l.width,0],stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},d);case "arc":return jsx(Arc,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2,angle:l.angle||90},d);case "rectangle":default:return jsx(Rect,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...p,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{n?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),s(f.evt,l.id,"shape");}},width:l.width,height:l.height,cornerRadius:l.type==="rounded-rectangle"?10:0},d)}})})});ii.displayName="ShapeLayer";var Ld=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:s,editingTextId:i})=>{let u=useSelector(c=>c.toolbar.selectedTool),l=u==="pen"||u==="eraser";return jsx(Fragment,{children:e.map(c=>{let d=c.id===i,p=c.fontWeight==="bold",f=p?Math.max(1,c.fontSize/25):0;return jsx(Text,{id:c.id,ref:h=>{h?o.current.set(c.id,h):o.current.delete(c.id);},text:c.text,x:c.x,y:c.y,width:c.width,height:c.height,rotation:c.rotation,draggable:!c.locked&&!d&&!l,listening:!l,fontSize:c.fontSize,fontFamily:c.fontFamily,fontStyle:c.fontStyle,fontWeight:c.fontWeight,textDecoration:c.textDecoration,fill:c.fill,stroke:p?c.fill:void 0,strokeWidth:f,align:c.align,wrap:"none",lineHeight:1.2,opacity:d?0:1,visible:!d,...l?{}:{onClick:()=>r(c.id),onTap:()=>r(c.id),onDblClick:()=>s(c.id),onDblTap:()=>s(c.id),onDragEnd:h=>t(h,c.id),onTransformEnd:()=>a(c.id),onContextMenu:h=>{h.evt.preventDefault();let x=h.evt;n(x,c.id,"text");}}},c.id)})})};var Ap=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:s,onPrevious:i,nodeRef:u})=>{let[l,c]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let m=new window.Image;m.src=e.images[e.currentIndex],m.onload=()=>{c(m);};}},[e.images,e.currentIndex]),!l||e.images.length===0)return null;let d=8,p=2,f=Math.min(e.width,e.height)*.08,h=Math.max(16,Math.min(f,32)),x=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,ref:m=>{if(u(m),m){let v=m.getStage()?.container();if(v){let g=b=>{let y=m.getStage()?.getPointerPosition();if(y){let S={x:e.x,y:e.y,width:e.width,height:e.height};y.x>=S.x&&y.x<=S.x+S.width&&y.y>=S.y&&y.y<=S.y+S.height&&n(b);}};v.addEventListener("contextmenu",g),m._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",g);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:d,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:d,stroke:"#E5E7EB",strokeWidth:p,listening:false}),jsx(Image$1,{x:p+4,y:p+4,image:l,width:e.width-(p+4)*2,height:e.height-(p+4)*2,cornerRadius:d-p,onClick:t,onTap:t}),jsx(Rect,{x:p,y:e.height-50,width:e.width-p*2,height:50,cornerRadius:[0,0,d-p,d-p],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:x+h,y:e.height/2,onClick:m=>{m.cancelBubble=true,i();},onTap:m=>{m.cancelBubble=true,i();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-x-h,y:e.height/2,onClick:m=>{m.cancelBubble=true,s();},onTap:m=>{m.cancelBubble=true,s();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Cd=Ap;var ui=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:s,onPrevious:i,onContextMenu:u})=>jsx(Fragment,{children:e.map(l=>jsx(Cd,{flashcard:l,isSelected:t===l.id,onClick:()=>n(l.id),onDragEnd:a,onTransformEnd:c=>r(l.id,c),onContextMenu:c=>u(c,l.id,"flashcard"),onNext:()=>s(l.id),onPrevious:()=>i(l.id),nodeRef:c=>{c?o.current.set(l.id,c):o.current.delete(l.id);}},l.id))}));ui.displayName="FlashcardLayer";var Md=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null);ee(b=>b.toolbar.selectedTool);let u=ee(b=>b.toolbar.penColor),l=ee(b=>b.toolbar.strokeWidth),c=ee(b=>b.canvas.isSketchMode),d=ee(b=>b.canvas.slides.find(S=>S.id===b.canvas.currentSlideId)?.photoFrames.find(S=>S.id===e)),p=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,x=d?.height||1,m=useCallback(b=>{if(!f)return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let y=b.x/h,S=b.y/x;s({tool:"pen",points:[y,S],color:u,strokeWidth:l/h,isSketch:c});},[f,u,l,c,h,x]),v=useCallback(b=>{if(!t.current||!n)return;a.current=true;let y=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-y.x,2)+Math.pow(b.y-y.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(c)I=rn(r.current,{size:l*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((L,P)=>P%2===0?L/h:L/x);else {let C=b.x/h,L=b.y/x;I=[...n.points,C,L];}s(C=>C?{...C,points:I}:null);},[c,l,n,h,x]),g=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(As({frameId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:p,activeLine:n,isDrawingMode:f,startDrawing:m,draw:v,stopDrawing:g}};var Vp=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:s,onCapture:i,cameraStream:u,nodeRef:l})=>{let[c,d]=useState(null),[p,f]=useState(null),h=useRef(null),x=useRef(null),m=useRef(null),v=useRef(null),g=useRef(0),b=33,y=useSelector(R=>R.toolbar.selectedTool),S=y==="pen"||y==="eraser",{annotations:I,activeLine:C,isDrawingMode:L,startDrawing:P,draw:A,stopDrawing:U}=Md(e.id);useEffect(()=>{if(!L)return;let R=()=>{U();},z=()=>{U();};return window.addEventListener("mouseup",R),window.addEventListener("touchend",z),()=>{window.removeEventListener("mouseup",R),window.removeEventListener("touchend",z);}},[U,L]),useEffect(()=>{if(e.capturedImageUrl){let R=new window.Image;R.src=e.capturedImageUrl,R.onload=()=>{d(R);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&u){h.current||(h.current=document.createElement("video"),h.current.autoplay=true,h.current.playsInline=true),x.current||(x.current=document.createElement("canvas"));let R=h.current,z=x.current;R.srcObject=u;let X=()=>{z.width=R.videoWidth||640,z.height=R.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",z.width,z.height);let _=Y=>{if(Y-g.current<b){m.current=requestAnimationFrame(_);return}g.current=Y;let Z=z.getContext("2d");if(Z&&R.readyState===R.HAVE_ENOUGH_DATA){Z.drawImage(R,0,0,z.width,z.height);let Q=z.toDataURL("image/jpeg",.6),pe=new window.Image;pe.onload=()=>{f(pe);},pe.src=Q;}m.current=requestAnimationFrame(_);};m.current=requestAnimationFrame(_);};return R.onloadedmetadata=X,R.readyState>=R.HAVE_METADATA&&X(),R.play().catch(_=>console.error("Error playing video:",_)),()=>{m.current&&(cancelAnimationFrame(m.current),m.current=null);}}return ()=>{f(null),v.current&&(v.current.src="");}},[e.isCapturing,u]);let F=()=>{h.current&&e.isCapturing&&i(h.current);},E=R=>{if(e.capturedImageUrl){if(!L){t();return}let z=R.currentTarget,X=z.getAbsoluteTransform().copy(),Y=z.getStage()?.getPointerPosition();if(Y){X.invert();let Z=X.point(Y);P(Z);}R.cancelBubble=true;}else t();},D=R=>{if(!L||!e.capturedImageUrl)return;let z=R.currentTarget,X=z.getAbsoluteTransform().copy(),Y=z.getStage()?.getPointerPosition();if(Y){X.invert();let Z=X.point(Y);A(Z);}},H=()=>{!L||!e.capturedImageUrl||U();},N=e.isCapturing?p:c,te=Math.min(e.width,e.height)*.12,q=Math.max(25,Math.min(te,50)),G=e.width/2,oe=e.height/2;return jsxs(Group,{id:e.id,draggable:!L&&!S,listening:true,x:e.x,y:e.y,...S?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:R=>{if(l(R),R){let z=R.getStage()?.container();if(z){let X=_=>{let Y=R.getStage()?.getPointerPosition();if(Y){let Z={x:e.x,y:e.y,width:e.width,height:e.height};Y.x>=Z.x&&Y.x<=Z.x+Z.width&&Y.y>=Z.y&&Y.y<=Z.y+Z.height&&n(_);}};z.addEventListener("contextmenu",X),R._contextMenuCleanup=()=>{z.removeEventListener("contextmenu",X);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:N?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),N&&jsx(Image$1,{image:N,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:E,onTap:E,onMouseDown:E,onTouchStart:E,onMouseMove:D,onTouchMove:D,onMouseUp:H,onTouchEnd:H,...S?{}:{onDragEnd:a,onTransformEnd:r}}),I?.map((R,z)=>{let X=R.points.map((Y,Z)=>Z%2===0?Y*e.width:Y*e.height),_=R.strokeWidth*e.width;return jsx(Line,{points:X,stroke:R.tool==="eraser"?"white":R.color,strokeWidth:_,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:R.tool==="eraser"?"destination-out":"source-over",fill:R.isSketch?R.color:void 0,closed:R.isSketch,listening:false},z)}),C&&jsx(Line,{points:C.points.map((R,z)=>z%2===0?R*e.width:R*e.height),stroke:C.tool==="eraser"?"white":C.color,strokeWidth:C.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:C.tool==="eraser"?"destination-out":"source-over",fill:C.isSketch?C.color:void 0,closed:C.isSketch,listening:false},"active"),!N&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:oe-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:G-q+6,y:oe-60,width:q*1.6,height:q*1.6,radius:q,fill:"white",cornerRadius:8,listening:true,onClick:R=>{R.cancelBubble=true,e.isCapturing?F():s();},onTap:R=>{R.cancelBubble=true,e.isCapturing?F():s();}}),jsx(Html,{groupProps:{x:G-12,y:oe-40,width:q*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:R=>{R.stopPropagation(),e.isCapturing?F():s();}})})]}),jsx(Text,{x:0,y:oe,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:oe+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:G-24,y:oe+104,width:q*1.6,height:q*1.6,radius:q,fill:"#096B76",cornerRadius:q,listening:true,onClick:R=>{R.cancelBubble=true,e.isCapturing?F():s();},onTap:R=>{R.cancelBubble=true,e.isCapturing?F():s();}}),jsx(Html,{groupProps:{x:G-8,y:oe+120,width:q*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:R=>{R.stopPropagation(),e.isCapturing?F():s();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"})]})]})},Rd=Vp;var hi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:s,onCapture:i,cameraStreams:u,onContextMenu:l})=>jsx(Fragment,{children:e.map(c=>jsx(Rd,{photoFrame:c,isSelected:t===c.id,onClick:()=>n(c.id),onDragEnd:d=>a(d,c.id),onTransformEnd:d=>r(c.id,d),onContextMenu:d=>l(d,c.id,"photoFrame"),onStartCamera:()=>s(c.id),onCapture:d=>i(c.id,d),cameraStream:u.get(c.id),nodeRef:d=>{d?o.current.set(c.id,d):o.current.delete(c.id);}},c.id))}));hi.displayName="PhotoFrameLayer";var Bd=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:s,menuRef:i})=>{useEffect(()=>{let d=f=>{i?.current&&!i.current.contains(f.target)&&a();},p=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",p),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",p);}},[a]);let u=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:s?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(p=>!(p.showForTypes&&!p.showForTypes.includes(r)||p.hideForTypes&&p.hideForTypes.includes(r))),[r,s]),l=(d,p)=>{d==="order"||d==="lock"?t(d,p):(t(d),a());},c=jsx("div",{ref:i,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:u.map((d,p)=>jsxs("button",{onClick:f=>l(d.action,f),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},p))})});return createPortal(c,document.body)};var Od=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let n=s=>{r.current&&!r.current.contains(s.target)&&a();};return document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n);}},[a]),jsx("div",{ref:r,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((n,s)=>jsx("button",{onClick:()=>{n.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:n.label})},s))})})};var Nd=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[s,i]=useState(a),u=useRef(null);useEffect(()=>{u.current?.focus();},[]);let l=()=>{r(s),n();};return jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:n,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:u,type:"text",value:s,onChange:d=>i(d.target.value),onKeyDown:d=>{d.key==="Enter"?l():d.key==="Escape"&&n();},placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:n,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:l,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})})};var Vd=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null);useEffect(()=>{let c=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]);let s=c=>{c.preventDefault(),o(a);},i=(c,d,p)=>{p/=100;let f=d*Math.min(p,1-p)/100,h=x=>{let m=(x+c/30)%12,v=p-f*Math.max(Math.min(m-3,9-m,1),-1);return Math.round(255*v).toString(16).padStart(2,"0")};return `#${h(0)}${h(8)}${h(4)}`},l=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:c=>c.stopPropagation(),onMouseUp:c=>c.stopPropagation(),onMouseMove:c=>c.stopPropagation(),onTouchStart:c=>c.stopPropagation(),onTouchMove:c=>c.stopPropagation(),onTouchEnd:c=>c.stopPropagation(),children:jsxs("div",{ref:n,className:"pointer-events-auto max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:c=>c.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Shape Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:s,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:c=>r(c.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:c=>r(c.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:c=>{let d=parseInt(c.target.value),p=i(d,100,50);r(p);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"].map(c=>jsx("button",{type:"button",onClick:()=>r(c),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===c.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:c},title:c},c))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(l,document.body)};var wh=({imageSrc:e,onCrop:o})=>{let[t]=Hd(e),a=useRef(null),r=useRef(null),n=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),i=useMemo(()=>{let p=s.width*.5,f=s.height*.5,h=(s.width-p)/2,x=(s.height-f)/2;return {x:h,y:x,width:p,height:f}},[s]),[u,l]=useState(i);useEffect(()=>{l(i);},[i]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[u]),useEffect(()=>{o(u.x,u.y,u.width,u.height);},[u,o]);let c=()=>{let p=r.current;if(!p)return;let f=p.scaleX(),h=p.scaleY();p.scaleX(1),p.scaleY(1),l({x:p.x(),y:p.y(),width:Math.max(20,p.width()*f),height:Math.max(20,p.height()*h)});},d=()=>{let p=r.current;p&&l({x:p.x(),y:p.y(),width:p.width(),height:p.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:u.x,y:u.y,width:u.width,height:u.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:u.x,y:u.y,width:u.width,height:u.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:c,dragBoundFunc:p=>{let f=Math.max(0,Math.min(p.x,s.width-u.width)),h=Math.max(0,Math.min(p.y,s.height-u.height));return {x:f,y:h}}}),jsx(Transformer,{ref:n,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(p,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>s.width||f.y+f.height>s.height?p:f})]})})},zd=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[s]=Hd(e);return useEffect(()=>{let c=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:c=>c.stopPropagation(),onMouseUp:c=>c.stopPropagation(),onMouseMove:c=>c.stopPropagation(),onTouchStart:c=>c.stopPropagation(),onTouchMove:c=>c.stopPropagation(),onTouchEnd:c=>c.stopPropagation(),children:jsxs("div",{ref:a,className:"pointer-events-auto max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:c=>c.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(wh,{imageSrc:e,onCrop:(c,d,p,f)=>{n({x:c,y:d,width:p,height:f});}})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:()=>{if(!s)return;let p=Math.min(600/s.width,400/s.height),f=r.x/p,h=r.y/p,x=r.width/p,m=r.height/p,v=document.createElement("canvas");v.width=x,v.height=m;let g=v.getContext("2d");if(!g)return;g.drawImage(s,f,h,x,m,0,0,x,m);let b=v.toDataURL("image/png");o(b);},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),document.body)};var Xo=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,n]=useState(false),[s,i]=useState(null),[u,l]=useState(0),[c,d]=useState(true),p=useRef(null),f=useRef([]),h=useRef(null),x=useRef(null),m=useRef(null),v=useRef(null),g=useRef(null),b=useRef(null);useEffect(()=>()=>{m.current&&cancelAnimationFrame(m.current),h.current&&clearInterval(h.current),x.current&&x.current.getTracks().forEach(L=>L.stop());},[]);let y=async()=>{try{let L,P=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let D=o.current.getLayers();console.log("Konva layers:",D.length),D.forEach((z,X)=>{let _=z.getChildren();console.log(`Layer ${X} children count:`,_.length);});let H=document.createElement("canvas");H.width=o.current.width(),H.height=o.current.height();let N=H.getContext("2d",{willReadFrequently:!1});if(!N){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",H.width,"x",H.height),g.current=H;let te=()=>{if(N.clearRect(0,0,H.width,H.height),D.forEach(z=>{let X=z.getCanvas()._canvas;X&&N.drawImage(X,0,0);}),a?.current){let z=a.current;N.drawImage(z,0,0);}};b.current=te,o.current.draw(),te(),await new Promise(z=>setTimeout(z,100)),console.log("Creating captureStream..."),L=H.captureStream(30),console.log("Canvas stream created, tracks:",L.getTracks().length);let G=L.getVideoTracks()[0];G&&console.log("Video track:",G.label,"state:",G.readyState);let oe=0,R=()=>{te(),o?.current&&(o.current.getLayers().forEach(X=>{X.batchDraw();}),oe++,oe%60===0&&console.log("Drawing frame:",oe)),m.current=requestAnimationFrame(R);};R();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(c)try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(D){console.warn("Microphone access denied:",D);}let A=[...L.getVideoTracks()];P&&A.push(...P.getAudioTracks());let U=new MediaStream(A);x.current=U;let F="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?F="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?F="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?F="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(F="video/webm;codecs=vp8"),console.log("Using mimeType:",F);let E=new MediaRecorder(U,{mimeType:F,videoBitsPerSecond:25e5});p.current=E,f.current=[],E.ondataavailable=D=>{console.log("Data available, size:",D.data.size),D.data.size>0&&f.current.push(D.data);},E.onstop=()=>{console.log("Recording stopped, chunks:",f.current.length);let D=new Blob(f.current,{type:F});console.log("Final blob size:",D.size),o?.current&&b.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(N=>{N.batchDraw();}),b.current(),v.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",v.current.length)),U.getTracks().forEach(H=>H.stop()),h.current&&clearInterval(h.current),m.current&&(cancelAnimationFrame(m.current),m.current=null),i(D);},E.onerror=D=>{console.error("MediaRecorder error:",D);},console.log("Starting recording..."),E.start(1e3),n(!0),l(0),h.current=setInterval(()=>{l(D=>D+1);},1e3);}catch(L){console.error("Error starting screen recording:",L),alert("Failed to start recording. Please ensure you granted permission.");}},S=()=>{p.current&&r&&(console.log("Stopping recording, state:",p.current.state),p.current.state!=="inactive"&&(p.current.requestData(),setTimeout(()=>{p.current&&p.current.state!=="inactive"&&p.current.stop();},100)),n(false));},I=()=>{if(s){let L=URL.createObjectURL(s),P=document.createElement("a");P.href=L,P.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(L);}},C=L=>{let P=Math.floor(L/60),A=L%60;return `${P.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:C(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:S,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!s&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>d(!c),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${c?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:c?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:y,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),s&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(s),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",C(u)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&s&&v.current&&(t(s,v.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),l(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})})};var Gd=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[n,s]=useState(false),[i,u]=useState(null),[l,c]=useState(false),[d,p]=useState(0),f=useRef(null),h=useRef([]),x=useRef(null),m=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(L=>L.blob()).then(L=>u(L)).catch(L=>console.error("Error loading audio:",L));},[o,i]);let v=async()=>{try{let L=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),P=new MediaRecorder(L);f.current=P,h.current=[],P.ondataavailable=A=>{A.data.size>0&&h.current.push(A.data);},P.onstop=()=>{let A=new Blob(h.current,{type:"audio/webm"});u(A),L.getTracks().forEach(U=>U.stop()),x.current&&clearInterval(x.current);},P.start(),s(!0),p(0),x.current=setInterval(()=>{p(A=>A+1);},1e3);}catch(L){console.error("Error starting audio recording:",L),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{f.current&&n&&(f.current.stop(),s(false));},b=()=>{if(i){let L=URL.createObjectURL(i),P=new Audio(L);m.current=P,P.onended=()=>{c(false),URL.revokeObjectURL(L);},P.play(),c(true);}},y=()=>{m.current&&(m.current.pause(),m.current.currentTime=0,c(false));},S=async()=>{if(i){let L=new FileReader;L.onloadend=()=>{let P=L.result;t(P),r();},L.readAsDataURL(i);}},I=()=>{u(null),a();},C=L=>{let P=Math.floor(L/60),A=L%60;return `${P.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`};return n?jsxs("div",{className:"fixed top-4 left-1/2 z-103 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:C(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-103 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:v,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:l?y:b,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),l?"Playing...":"Play Audio"]}),jsx("button",{onClick:I,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:S,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})})};var Lt=({audioData:e,x:o,y:t,width:a})=>{let[r,n]=useState(false),s=useRef(null);return jsx("button",{onClick:u=>{if(u.stopPropagation(),r&&s.current)s.current.pause(),s.current.currentTime=0,n(false);else {let l=new Audio(e);s.current=l,l.onended=()=>{n(false);},l.onerror=()=>{console.error("Error playing audio"),n(false);},l.play(),n(true);}},className:`absolute flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${r?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${o+a-35}px`,top:`${t+5}px`,width:"30px",height:"30px",zIndex:99},title:r?"Stop Audio":"Play Audio",children:r?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var jd=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=ee(ge),n=useMemo(()=>{if(!r)return [];let x=[];return r.images?.forEach(m=>{x.push({id:m.id,type:"image",name:"Image",timestamp:m.timestamp||0});}),r.videos?.forEach(m=>{x.push({id:m.id,type:"video",name:"Video",timestamp:m.timestamp||0});}),r.shapes?.forEach(m=>{x.push({id:m.id,type:"shape",name:`${m.type} Shape`,timestamp:m.timestamp||0});}),r.texts?.forEach(m=>{x.push({id:m.id,type:"text",name:m.text.substring(0,20)+(m.text.length>20?"...":""),timestamp:m.timestamp||0});}),r.flashcards?.forEach(m=>{x.push({id:m.id,type:"flashcard",name:`Flashcard (${m.images.length} images)`,timestamp:m.timestamp||0});}),r.photoFrames?.forEach(m=>{x.push({id:m.id,type:"photoFrame",name:"Photo Frame",timestamp:m.timestamp||0});}),r.multipleChoices?.forEach(m=>{x.push({id:m.id,type:"mcq",name:"Multiple Choice",timestamp:m.timestamp||0});}),r.trueFalses?.forEach(m=>{x.push({id:m.id,type:"trueFalse",name:"True/False",timestamp:m.timestamp||0});}),r.shortAnswers?.forEach(m=>{x.push({id:m.id,type:"shortAnswer",name:"Short Answer",timestamp:m.timestamp||0});}),r.LongAnswer?.forEach(m=>{x.push({id:m.id,type:"longAnswer",name:"Long Answer",timestamp:m.timestamp||0});}),r.fillInTheBlanks?.forEach(m=>{x.push({id:m.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:m.timestamp||0});}),r.lines?.forEach(m=>{m.id&&x.push({id:m.id,type:"line",name:"Drawn Line",timestamp:m.timestamp||0});}),x.sort((m,v)=>v.timestamp-m.timestamp)},[r]),[s,i]=useState(n),[u,l]=useState(false);useEffect(()=>{u||i(n);},[n]);let c=x=>{let m="h-5 w-5";switch(x){case "image":return jsx(Image$3,{className:m});case "video":return jsx(VideoCamera,{className:m});case "shape":return jsx(Shapes$1,{className:m});case "text":return jsx(TextT,{className:m});case "flashcard":return jsx(Cards$1,{className:m});case "photoFrame":return jsx(FrameCorners,{className:m});case "line":return jsx("span",{className:m,children:"\u270F\uFE0F"});default:return jsx(Question,{className:m})}},d=x=>{if(x===0)return;let m=s[x],v=s[x-1];a(Vo({id:m.id,type:m.type,newTimestamp:v.timestamp+1}));},p=x=>{if(x===s.length-1)return;let m=s[x],v=s[x+1];a(Vo({id:m.id,type:m.type,newTimestamp:v.timestamp-1}));},f=x=>{l(true),i(x);},h=()=>{l(false);let x=Date.now();s.forEach((m,v)=>{let g=x-v;a(Vo({id:m.id,type:m.type,newTimestamp:g}));});};return jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-gray-200 bg-white shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 p-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Stack$1,{className:"h-5 w-5 text-gray-700",weight:"bold"}),jsx("h3",{className:"font-semibold text-gray-900",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto p-2",children:s.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:s,onReorder:f,className:"space-y-1",children:s.map((x,m)=>{let v=x.id===e;return jsxs(Reorder.Item,{value:x,onDragEnd:h,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${v?"border border-blue-200 bg-blue-50":"border border-transparent hover:bg-gray-50"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-4 w-4",weight:"bold"})}),jsxs("div",{onClick:()=>t(x.id,x.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${v?"text-blue-600":"text-gray-600"}`,children:c(x.type)}),jsx("span",{className:`text-sm ${v?"font-medium text-blue-900":"text-gray-700"}`,children:x.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:g=>{g.stopPropagation(),d(m);},disabled:m===0,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move up (forward)",children:jsx(ArrowUp,{className:"h-4 w-4"})}),jsx("button",{onClick:g=>{g.stopPropagation(),p(m);},disabled:m===s.length-1,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move down (backward)",children:jsx(ArrowDown,{className:"h-4 w-4"})})]})]},x.id)})})}),jsx("div",{className:"border-t border-gray-200 p-3 text-xs text-gray-500",children:jsx("p",{children:"Drag to reorder \u2022 Top layers appear above bottom layers"})})]})]})};var $d=memo(({multipleChoice:e,handleMcqTransform:o,mcqRefs:t,handleDragEnd:a,onContextMenu:r})=>{let n=useSelector(G=>G.toolbar.selectedTool),s=n==="pen"||n==="eraser",[i,u]=useState(new Set),[l,c]=useState(false),[d,p]=useState(null),f=useRef(null);useEffect(()=>{let G=f.current;if(G)return t.current.set(e.id,G),()=>{t.current.delete(e.id);}},[e.id]);let h=new Set(e.data.responseOptions.correctIndex),x=h.size>1,m=G=>{l||u(x?oe=>{let R=new Set(oe);return R.has(G)?R.delete(G):R.add(G),R}:new Set([G]));},v=()=>{i.size>0&&c(true);},g=()=>{c(false),u(new Set);},b=i.size===h.size&&Array.from(i).every(G=>h.has(G)),y=Array.from(i).filter(G=>h.has(G)),S=x&&y.length>0&&!b,I=()=>b?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${y.length}/${h.size})`:"\u2717 Try again!",C=()=>b?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},L=55,P=8,A=24,U=60,F=60,E=x&&!l?25:0,D=e.data.feedbackMode==="practice"?48:0,H=12,N=U+E+(l?F:0),te=e.data.responseOptions.options.length*(L+P),q=N+te+H+D+A;return jsxs(Group,{ref:f,name:"mcq-element",draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...s?{}:{onDragEnd:a,onContextMenu:G=>{let oe=f.current?.getStage()?.getPointerPosition();if(oe){let R={x:e.x,y:e.y,width:e.width,height:e.height};if(oe.x>=R.x&&oe.x<=R.x+R.width&&oe.y>=R.y&&oe.y<=R.y+R.height){let z=G.evt;r(z,e.id,"mcq");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:q,width:e.width,onTransformEnd:G=>o(e.id,G)}),jsx(Text,{x:A+8,y:A,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-A*2,listening:false}),x&&!l&&e.data.feedbackMode==="practice"?jsx(Text,{x:A,y:A+35,text:`Select ${h.size} answers (${i.size}/${h.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-A*2,listening:false}):null,l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:A+24,y:U+E,width:e.width-A*2-40,height:F-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:A,y:U+E,width:e.width-A*2,height:F-20,text:I(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,oe)=>{let R=h.has(oe),z=i.has(oe),X=N+oe*(L+P),_="#e5e7eb",Y="#ffffff",Z="#111827";return l&&R?(_="#22c55e",Y="#dcfce7",Z="#1B9D2C"):l&&z&&!R?(_="#ef4444",Y="#fee2e2",Z="#ef4444"):z&&(_="#096B76",Y="#ECFFF8",Z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:A+12,y:X+(L-20)/2,width:20,height:20,fill:z?"#096B76":"white",stroke:z?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:x?4:10,listening:false}),z&&jsx(Text,{x:A+12,y:X+(L-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:A+44,y:X,width:e.width-A*2-60,height:L,fill:Y,stroke:_,strokeWidth:2,cornerRadius:8,onClick:Q=>{Q.cancelBubble=true,m(oe);},onTap:Q=>{Q.cancelBubble=true,m(oe);}}),jsx(Text,{x:A+60,y:X,width:e.width-A*2-80,height:L,text:G,fontSize:16,fill:Z,verticalAlign:"middle",listening:false})]},oe)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:N+e.data.responseOptions.options.length*(L+P)+12,children:[jsxs(Group,{onMouseDown:G=>{G.cancelBubble=true,p("check");},onMouseUp:G=>{G.cancelBubble=true,p(null),v();},onMouseLeave:G=>{G.cancelBubble=true,p(null);},onTouchStart:G=>{G.cancelBubble=true,p("check");},onTouchEnd:G=>{G.cancelBubble=true,p(null),v();},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:A+14,width:(e.width-A*2-24)/(l?2:1),height:48,fill:i.size===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:A+14,width:(e.width-A*2-24)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-A*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:A,width:(e.width-A*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:A,width:(e.width-A*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});$d.displayName="MultipleChoice";var Xd=$d;var vi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t})=>{let a=useDispatch(),r=useSelector(R=>R.toolbar.selectedTool),n=r==="pen"||r==="eraser",[s,i]=useState(false),[u,l]=useState(new Set),[c,d]=useState(false),[p,f]=useState(false),[h,x]=useState(0),m=340,v=100,g=window.innerWidth*.4,b=window.innerHeight*.5,y=m+20,S=v+60,I=g-40,C=b-300,L=useRef(null),P=R=>{a(oa({id:e.id,x:R.target.x(),y:R.target.y()}));},A=R=>{let z=R.target,X=z.x(),_=z.y(),Y=window.innerWidth*.2,Q=X+Y>y&&X<y+I&&_+50>S&&_<S+C;i(Q);},U=(R,z)=>{let X=z.target,_=X.x(),Y=X.y(),Z=window.innerWidth*.2,pe=_+Z>y&&_<y+I&&Y+50>S&&Y<S+C;l(pe?we=>new Set(we).add(R):we=>{let Re=new Set(we);return Re.delete(R),Re}),i(false);},F=()=>{d(true);},E=()=>{d(false),l(new Set),x(R=>R+1);},D=new Set(e.data.responseOptions.correctIndex),H=u.size===D.size&&Array.from(u).every(R=>D.has(R)),N=Array.from(u).filter(R=>D.has(R)),te=N.length>0&&!H,q=()=>H?"\u2713 Correct! Great job!":te?`\u26A0 Partially correct (${N.length}/${D.size})`:"\u2717 Try again!",G=()=>H?{bg:"#dcfce7",text:"#166534"}:te?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},oe=()=>c?H?"#4CAF50":te?"#f59e0b":"#ef4444":s?"#4CAF50":"#075560";return jsxs(Group,{ref:L,name:"mcq-element",width:g,height:b,draggable:!n,listening:!n,...n?{}:{onContextMenu:R=>{R.evt.preventDefault(),o(R.evt,e.id,"mcq");}},children:[jsxs(Group,{x:m,y:v,rotation:e.rotation,onDragEnd:P,children:[jsx(Rect,{fill:"white",stroke:s?"#4CAF50":"#e5e7eb",strokeWidth:s?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?b-100:b-50,width:g,shadowColor:s?"#4CAF50":"transparent",shadowBlur:s?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:g-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:I,height:C,fill:"#EBF6F7",stroke:oe(),strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:C+18,width:I-5,height:60,fill:G().bg,cornerRadius:8}),jsx(Text,{x:20,y:C+20,width:I,height:60,text:q(),fontSize:18,fontStyle:"bold",fill:G().text,align:"center",verticalAlign:"middle"})]}),u.size===0&&!c&&jsx(Text,{x:20,y:60,width:I,height:C-60,text:D.size>1?`Drop ${D.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:c?b-200:b-160,children:[jsxs(Group,{onMouseDown:()=>{f(true),F();},onMouseUp:()=>f(false),onMouseLeave:()=>f(false),onTouchStart:()=>{f(true),F();},onTouchEnd:()=>f(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((R,z)=>{let X=z%2,_=Math.floor(z/2),Y=window.innerWidth*.2,Z=50,Q=10,pe=u.has(z),we=D.has(z),Re=c&&pe,Me="transparent";return Re?Me=we?"#4CAF50":"#ef4444":pe&&(Me="#4CAF50"),jsxs(Group,{x:340+X*(Y+Q),y:v+b-80+_*(Z+Q),draggable:!c,onDragMove:A,onDragEnd:Ue=>U(z,Ue),opacity:c&&!pe?.5:1,children:[jsx(Rect,{width:Y-20,height:Z,fill:"white",stroke:Me,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Y-20,height:Z,text:R,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${z}-${h}`)})]})};vi.displayName="MultipleChoiceDragAndDrop";var Yd=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(Xd,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:i=>r(i,s.id),onContextMenu:n},s.id):jsx(vi,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:n},s.id))});var Jd=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(N=>N.toolbar.selectedTool),i=s==="pen"||s==="eraser",[u,l]=useState(null),[c,d]=useState(false),[p,f]=useState(null),h=useRef(null);useEffect(()=>{let N=h.current;if(N)return a.current.set(e.id,N),()=>{a.current.delete(e.id);}},[e.id]);let x=()=>{u!==null&&d(true);},m=()=>{d(false),l(null);},v=e.data.responseOptions.correctAnswer,g=u===v,b=N=>{c||l(N);},y=()=>g?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",S=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=70,C=12,L=24,P=60,A=60,U=e.data.feedbackMode==="practice"?48:0,F=12,E=P+(c?A:0),D=2*(I+C),H=E+D+F+U+L;return jsxs(Group,{ref:h,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:N=>n(N,e.id),onClick:N=>t(e.id),onTap:N=>t(e.id),onContextMenu:N=>{let te=h.current?.getStage()?.getPointerPosition();if(te){let q={x:e.x,y:e.y,width:e.width,height:e.height};if(te.x>=q.x&&te.x<=q.x+q.width&&te.y>=q.y&&te.y<=q.y+q.height){let G=N.evt;r(G,e.id,"trueFalse");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:H-20,width:e.width,onTransformEnd:N=>o(e.id,N)}),jsx(Text,{x:L,y:L,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),c&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:L,y:P,width:e.width-L*2,height:A-10,fill:S().bg,cornerRadius:8}),jsx(Text,{x:L,y:P,width:e.width-L*2,height:A-10,text:y(),fontSize:16,fontStyle:"bold",fill:S().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((N,te)=>{let q=v===N.value,G=u===N.value,oe=(e.width-L*3)/2,R=L+te*(oe+L),z=E,X=N.value===true,_=X?"#10b981":"#ef4444",Y="#ffffff",Z="#ffffff",Q="#e5e7eb";return c&&(q?(Z=X?"#f0fdf4":"#fef2f2",Q=X?"#86efac":"#fecaca"):G&&!q&&(Z="#fee2e2",Q="#ef4444")),G&&!c&&(Q="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:R,y:z,width:oe,height:I+50,fill:Z,stroke:Q,strokeWidth:2,cornerRadius:12,onClick:pe=>{pe.cancelBubble=true,b(N.value);},onTap:pe=>{pe.cancelBubble=true,b(N.value);}}),jsx(Circle,{x:R+oe/2,y:z+40,radius:28,fill:_,listening:false}),X?jsx(Text,{x:R+oe/2-14,y:z+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:R+oe/2-14,y:z+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:R,y:z+85,width:oe,height:30,text:N.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},N.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:E+2*(I+C),children:[jsxs(Group,{onMouseDown:N=>{N.cancelBubble=true,f("check");},onMouseUp:N=>{N.cancelBubble=true,f(null),x();},onMouseLeave:N=>{N.cancelBubble=true,f(null);},onTouchStart:N=>{N.cancelBubble=true,f("check");},onTouchEnd:N=>{N.cancelBubble=true,f(null),x();},scaleX:p==="check"?.95:1,scaleY:p==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(c?2:1),height:48,fill:u===null||c?"#9ca3af":"#096B76",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(c?2:1),height:48,text:c?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>f("reset"),onMouseUp:()=>{f(null),m();},onMouseLeave:()=>f(null),onTouchStart:()=>f("reset"),onTouchEnd:()=>{f(null),m();},scaleX:p==="reset"?.95:1,scaleY:p==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Jd.displayName="TrueFalse";var Zd=Jd;var bg="#FFFFFF",Li=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(_=>_.toolbar.selectedTool),n=r==="pen"||r==="eraser",[s,i]=useState(false),[u,l]=useState(null),[c,d]=useState(false),[p,f]=useState(false),[h,x]=useState(0),[m,v]=useState(false),g=340,b=100,y=window.innerWidth*.4,S=window.innerHeight*.5,I=y-40,C=S-300,L=20,P=60,A=I,U=C,F=y*.2-40,E=50,D=useRef(null),H=_=>{a(ra({id:e.id,x:_.target.x(),y:_.target.y()}));},N=_=>{let Y=_.target,Z=Y.x(),Q=Y.y(),pe=Math.max(0,Math.min(Z+F,L+A)-Math.max(Z,L)),we=Math.max(0,Math.min(Q+E,P+U)-Math.max(Q,P)),Re=pe*we,Me=F*E;i(Re/Me>=.5);},te=(_,Y)=>{let Z=Y.target,Q=Z.x(),pe=Z.y(),we=Math.max(0,Math.min(Q+F,L+A)-Math.max(Q,L)),Re=Math.max(0,Math.min(pe+E,P+U)-Math.max(pe,P)),Me=we*Re,Ue=F*E;if(Me/Ue>=.5)l(_);else return;i(false);},q=()=>{d(true);},G=()=>{d(false),l(null),x(_=>_+1);},oe=e.data.responseOptions.correctAnswer,R=u===oe,z=()=>R?"\u2713 Correct! Great job!":"\u2717 Try again!",X=()=>R?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:D,name:"trueFalse-element",width:y,height:S,draggable:!n,listening:!n,...n?{}:{onContextMenu:_=>{_.evt.preventDefault(),o(_.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:g,y:b,rotation:e.rotation,onDragEnd:H,children:[jsx(Rect,{fill:"white",stroke:s?"#4CAF50":"#e5e7eb",strokeWidth:s?4:2,cornerRadius:12,height:c?S:e.data.feedbackMode==="practice"?S-50:S-100,width:y,shadowColor:s?"#4CAF50":"transparent",shadowBlur:s?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:y-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:I,height:C,fill:"transparent",stroke:s?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:I,height:60,fill:X().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:I,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:X().text,align:"center",verticalAlign:"middle"})]}),u===null&&!c&&jsx(Text,{x:20,y:60,width:I,height:C-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:S-100,children:[jsxs(Group,{onMouseDown:()=>{u!==null&&(f(true),q());},onMouseUp:()=>f(false),onMouseLeave:()=>f(false),onTouchStart:()=>{u!==null&&(f(true),q());},onTouchEnd:()=>f(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:u===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:G,onTouchStart:G,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((_,Y)=>{let Z=window.innerWidth*.2,Q=50,pe=10,we=u===_.value,Re=oe===_.value,Me=c&&we,Ue="transparent";return Me?Ue=Re?"#4CAF50":"#ef4444":we&&(Ue="#4CAF50"),jsxs(Group,{x:16+Y*(Z+pe),y:b+S-300,draggable:!c,onDragMove:N,onDragEnd:re=>te(_.value,re),opacity:c&&!we?.5:1,children:[jsx(Rect,{width:Z-40,height:Q,fill:"#075560",stroke:Ue,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:Q,text:_.label,fontSize:18,fontStyle:"bold",fill:bg,align:"center",verticalAlign:"middle",listening:false})]},`${_.value}-${h}`)})]})})};Li.displayName="TrueFalseDragAndDrop";var Qd=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(Zd,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r},s.id):jsx(Li,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n},s.id))});var da=new WeakMap,co=new WeakMap,tr={current:[]},Ii=false,er=0,Qo=new Set,gn=new Map;function eu(e){let o=Array.from(e).sort((t,a)=>t instanceof Dt&&t.options.deps.includes(a)?1:a instanceof Dt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(tr.current.includes(t))continue;tr.current.push(t),t.recompute();let a=co.get(t);if(a)for(let r of a){let n=da.get(r);n&&eu(n);}}}function wg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Lg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function xn(e){if(er>0&&!gn.has(e)&&gn.set(e,e.prevState),Qo.add(e),!(er>0)&&!Ii)try{for(Ii=!0;Qo.size>0;){let o=Array.from(Qo);Qo.clear();for(let t of o){let a=gn.get(t)??t.prevState;t.prevState=a,wg(t);}for(let t of o){let a=da.get(t);a&&(tr.current.push(t),eu(a));}for(let t of o){let a=da.get(t);if(a)for(let r of a)Lg(r);}}}finally{Ii=false,tr.current=[],gn.clear();}}function ft(e){er++;try{e();}finally{if(er--,er===0){let o=Qo.values().next().value;o&&xn(o);}}}function tu(e){return typeof e=="function"}var zt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,n;this.listeners.add(a);let s=(n=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:n.call(r,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,r;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):tu(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),xn(this);}};var Dt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let n=0;n<t;n++){let s=this.options.deps[n];a[n]=s.prevState,r[n]=s.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let n of this.options.deps)n instanceof e&&n.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let n=0;n<r.length;n++)if(r[n]!==a[n]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,r;this.listeners.add(t);let n=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof zt){let a=da.get(t);a||(a=new Set,da.set(t,a)),a.add(this);let r=co.get(this);r||(r=new Set,co.set(this,r)),r.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof zt){let a=da.get(t);a&&a.delete(this);let r=co.get(this);r&&r.delete(t);}}};function Sg(e){return typeof e=="function"}function Ci(e,...o){return Sg(e)?e(...o):e}function au(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ua,rt,et,ar,ca,Oa,jt,fo,or,bn,rr,mo,Na=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Te(this,ua,true);Te(this,rt);Te(this,et);Te(this,ar);Te(this,ca);Te(this,Oa);Te(this,jt);Te(this,fo);Te(this,or,0);Te(this,bn,5);Te(this,rr,()=>{this.debugLog("Connected to event bus"),ke(this,Oa,true),this.debugLog("Emitting queued events",K(this,ca)),K(this,ca).forEach(o=>this.emitEventToBus(o)),ke(this,ca,[]),this.stopConnectLoop(),K(this,et).call(this).removeEventListener("tanstack-connect-success",K(this,rr));});Te(this,mo,()=>{if(K(this,et).call(this).addEventListener("tanstack-connect-success",K(this,rr)),K(this,or)<K(this,bn)){Fl(this,or)._++,this.dispatchCustomEvent("tanstack-connect",{});return}K(this,et).call(this).removeEventListener("tanstack-connect",K(this,mo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});ke(this,rt,o),ke(this,ua,a),ke(this,et,this.getGlobalTarget),ke(this,ar,t),this.debugLog(" Initializing event subscription for plugin",K(this,rt)),ke(this,ca,[]),ke(this,Oa,false),ke(this,jt,null),ke(this,fo,r);}startConnectLoop(){K(this,jt)!==null||K(this,Oa)||(this.debugLog(`Starting connect loop (every ${K(this,fo)}ms)`),ke(this,jt,setInterval(K(this,mo),K(this,fo))));}stopConnectLoop(){K(this,jt)!==null&&(clearInterval(K(this,jt)),ke(this,jt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){K(this,ar)&&console.log(`\u{1F334} [tanstack-devtools:${K(this,rt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return K(this,rt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});K(this,et).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{K(this,et).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!K(this,ua)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!K(this,Oa)){this.debugLog("Bus not available, will be pushed as soon as connected"),K(this,ca).push({type:`${K(this,rt)}:${o}`,payload:t,pluginId:K(this,rt)}),typeof CustomEvent<"u"&&(K(this,mo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${K(this,rt)}:${o}`,payload:t,pluginId:K(this,rt)})}on(o,t){let a=`${K(this,rt)}:${o}`;if(!K(this,ua))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=n=>{this.debugLog("Received event from bus",n.detail),t(n.detail);};return K(this,et).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{K(this,et).call(this).removeEventListener(a,r);}}onAll(o){if(!K(this,ua))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return K(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!K(this,ua))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;K(this,rt)&&r.pluginId!==K(this,rt)||o(r);};return K(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}};ua=new WeakMap,rt=new WeakMap,et=new WeakMap,ar=new WeakMap,ca=new WeakMap,Oa=new WeakMap,jt=new WeakMap,fo=new WeakMap,or=new WeakMap,bn=new WeakMap,rr=new WeakMap,mo=new WeakMap;var ki=class extends Na{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},ou=(e,o)=>{Mi.emit(e,o);},Mi=new ki;function ru(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Ig={enabled:true,leading:true,trailing:true,wait:0},fa,mt,Va,qa,Ua,po,vn=class{constructor(o,t){Te(this,fa);Te(this,mt);Te(this,Va);Te(this,qa);Te(this,Ua);Te(this,po);this.fn=o,this.store=new zt(ru()),this.setOptions=a=>{this.options={...this.options,...a},K(this,Va).call(this)||this.cancel();},ke(this,mt,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:s}=n;return {...n,status:K(this,Va).call(this)?s?"pending":"idle":"disabled"}}),ou("Throttler",this);}),ke(this,Va,()=>!!Ci(this.options.enabled,this)),ke(this,qa,()=>Ci(this.options.wait,this)),this.maybeExecute=(...a)=>{K(this,mt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,s=K(this,qa).call(this);if(this.options.leading&&n>=s)K(this,Ua).call(this,...a);else if(K(this,mt).call(this,{lastArgs:a}),!K(this,fa)&&this.options.trailing){let i=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,u=s-i;K(this,mt).call(this,{isPending:true}),ke(this,fa,setTimeout(()=>{let{lastArgs:l}=this.store.state;l!==void 0&&K(this,Ua).call(this,...l);},u));}},ke(this,Ua,(...a)=>{if(!K(this,Va).call(this))return;this.fn(...a);let r=Date.now(),n=r+K(this,qa).call(this);K(this,po).call(this),K(this,mt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:n,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||K(this,mt).call(this,{nextExecutionTime:void 0});},K(this,qa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&K(this,Ua).call(this,...this.store.state.lastArgs);},ke(this,po,()=>{K(this,fa)&&(clearTimeout(K(this,fa)),ke(this,fa,void 0));}),this.cancel=()=>{K(this,po).call(this),K(this,mt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{K(this,mt).call(this,ru());},this.key=au(t.key),this.options={...Ig,...t},K(this,mt).call(this,this.options.initialState??{}),Mi.on("d-Throttler",a=>{a.payload.key===this.key&&(K(this,mt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};fa=new WeakMap,mt=new WeakMap,Va=new WeakMap,qa=new WeakMap,Ua=new WeakMap,po=new WeakMap;function Ti(e,o){return new vn(e,o).maybeExecute}function ma(e,o){return typeof e=="function"?e(o):e}function pa(e,o){return Sn(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function ho(e,o,t){let a=Sn(o);function r(n){if(!a.length)return ma(t,n);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(n))return typeof n=="object"?(n===null&&(n={}),{...n,[s]:r(n[s])}):{[s]:r()};if(Array.isArray(n)&&typeof s=="number"){let i=n.slice(0,s);return [...i.length?i:new Array(s),r(n[s]),...n.slice(s+1)]}return [...new Array(s),r()]}return r(e)}function Pi(e,o){let t=Sn(o);function a(r){if(!r)return;if(t.length===1){let s=t[0];if(Array.isArray(r)&&typeof s=="number")return r.filter((l,c)=>c!==s);let{[s]:i,...u}=r;return u}let n=t.shift();if(typeof n=="string"&&typeof r=="object")return {...r,[n]:a(r[n])};if(typeof n=="number"&&Array.isArray(r)){if(n>=r.length)return r;let s=r.slice(0,n);return [...s.length?s:new Array(n),a(r[n]),...r.slice(n+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Cg=/^(\d+)$/gm,kg=/\.(\d+)(?=\.)/gm,Mg=/^(\d+)\./gm,Tg=/\.(\d+$)/gm,Ag=/\.{2,}/gm,Ai="__int__",yn=`${Ai}$1`;function Sn(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(Cg,yn).replace(kg,`.${yn}.`).replace(Mg,`${yn}.`).replace(Tg,`.${yn}`).replace(Ag,".").split(".").map(o=>{if(o.startsWith(Ai)){let t=o.substring(Ai.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Ri(e){return !(Array.isArray(e)&&e.length===0)}function go(e,o){let t=a=>a.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function xo(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},s=t??0,i=u=>u.validators.filter(Boolean).map(l=>{let c=l?.cause||e,d=s;switch(c){case "change":d=r??s;break;case "blur":d=a??s;break;case "dynamic":d=n??s;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:c,validate:l.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:i})}var nr=e=>!!e&&typeof e=="object"&&"fields"in e;function ha(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,n]of e)if(!o.has(r)||!Object.is(n,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!ha(e[r],o[r]))return false;return true}var In=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},Cn=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Ge(e,o){return e==null?o:{...e,...o}}var Ha=256,Ln=[],wn;for(;Ha--;)Ln[Ha]=(Ha+256).toString(16).substring(1);function Di(){let e=0,o,t="";if(!wn||Ha+16>256){for(wn=new Array(256),e=256;e--;)wn[e]=256*Math.random()|0;e=0,Ha=0;}for(;e<16;e++)o=wn[Ha+e],e===6?t+=Ln[o&15|64]:e===8?t+=Ln[o&63|128]:t+=Ln[o],e&1&&e>1&&e<11&&(t+="-");return Ha++,t}var ga=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},n={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,n,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Pg(e,o){let t=new Map;for(let a of e){let r=a.path??[],n=o,s="";for(let i=0;i<r.length;i++){let u=r[i];if(u===void 0)continue;let l=typeof u=="object"?u.key:u,c=Number(l);Array.isArray(n)&&!Number.isNaN(c)?s+=`[${c}]`:s+=(i>0?".":"")+String(l),typeof n=="object"&&n!==null?n=n[l]:n=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var nu=(e,o)=>{let t=Pg(e,o);return {form:t,fields:t}},xa={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:nu(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:nu(a.issues,e)}},kn=e=>!!e&&"~standard"in e;var bo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function sr(e){function o(d,p,f,h){let x=a(d,p,f,h);({insert:()=>i(x,d,p),remove:()=>u(x),swap:()=>h!==void 0&&c(x,d,p,h),move:()=>h!==void 0&&l(x,d,p,h)})[f]();}function t(d,p){return `${d}[${p}]`}function a(d,p,f,h){let x=[t(d,p)];if(f==="swap")x.push(t(d,h));else if(f==="move"){let[m,v]=[Math.min(p,h),Math.max(p,h)];for(let g=m;g<=v;g++)x.push(t(d,g));}else {let m=e.getFieldValue(d),v=Array.isArray(m)?m.length:0;for(let g=p+1;g<v;g++)x.push(t(d,g));}return Object.keys(e.fieldInfo).filter(m=>x.some(v=>m.startsWith(v)))}function r(d,p){return d.replace(/\[(\d+)\]/,(f,h)=>{let x=parseInt(h,10);return `[${p==="up"?x+1:Math.max(0,x-1)}]`})}function n(d,p){(p==="up"?d:[...d].reverse()).forEach(h=>{let x=r(h.toString(),p),m=e.getFieldMeta(x);m?e.setFieldMeta(h,m):e.setFieldMeta(h,s());});}let s=()=>bo,i=(d,p,f)=>{n(d,"down"),d.forEach(h=>{h.toString().startsWith(t(p,f))&&e.setFieldMeta(h,s());});},u=d=>{n(d,"up");},l=(d,p,f,h)=>{let x=new Map(Object.keys(e.fieldInfo).filter(m=>m.startsWith(t(p,f))).map(m=>[m,e.getFieldMeta(m)]));n(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(m=>m.startsWith(t(p,h))).forEach(m=>{let v=m.replace(t(p,h),t(p,f)),g=x.get(v);g&&e.setFieldMeta(m,g);});},c=(d,p,f,h)=>{d.forEach(x=>{if(!x.toString().startsWith(t(p,f)))return;let m=x.toString().replace(t(p,f),t(p,h)),[v,g]=[e.getFieldMeta(x),e.getFieldMeta(m)];v&&e.setFieldMeta(m,v),g&&e.setFieldMeta(x,g);});};return {handleArrayFieldMetaShift:o}}var Fi=class extends Na{constructor(){super({pluginId:"form-devtools"});}},pt=new Fi;function Ei(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var lr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),pt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),n},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let n=!!a.transform?.deps?.some((u,l)=>u!==this.prevTransformArray[l]),s=a.defaultValues&&!ha(a.defaultValues,r.defaultValues)&&!this.state.isTouched,i=!ha(a.defaultState,r.defaultState)&&!this.state.isTouched;!s&&!i&&!n||(ft(()=>{this.baseStore.setState(()=>Ei(Object.assign({},this.state,i?a.defaultState:{},s?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:n}=this.state,s=this.resetFieldMeta(n);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Ei({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let r=[];return ft(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let i=s.instance;r.push(Promise.resolve().then(()=>i.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(u=>({...u,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,n)=>{let s=this.getFieldValue(a),i=Array.isArray(s)?Math.max(s.length-1,0):null,u=[`${a}[${r}]`];for(let p=r+1;p<=(i??0);p++)u.push(`${a}[${p}]`);let l=Object.keys(this.fieldInfo).filter(p=>u.some(f=>p.startsWith(f))),c=[];return ft(()=>{l.forEach(p=>{c.push(Promise.resolve().then(()=>this.validateField(p,n)));});}),(await Promise.all(c)).flat()},this.validateField=(a,r)=>{let n=this.fieldInfo[a]?.instance;return n?(n.state.meta.isTouched||n.setMeta(s=>({...s,isTouched:true})),n.validate(r)):[]},this.validateSync=a=>{let r=go(a,{...this.options,form:this,validationLogic:this.options.validationLogic||ga}),n=false,s={};return ft(()=>{for(let l of r){if(!l.validate)continue;let c=this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:p}=Mn(c),f=ir(l.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let x=this.getFieldMeta(h);if(!x)continue;let{errorMap:m,errorSourceMap:v}=x,g=p?.[h],{newErrorValue:b,newSource:y}=In({newFormValidatorError:g,isPreviousErrorFromFormValidator:v?.[f]==="form",previousErrorValue:m?.[f]});y==="form"&&(s[h]={...s[h],[f]:g}),m?.[f]!==b&&this.setFieldMeta(h,S=>({...S,errorMap:{...S.errorMap,[f]:b},errorSourceMap:{...S.errorSourceMap,[f]:y}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||p)&&(n=!0);}let i=ir("submit");this.state.errorMap?.[i]&&a!=="submit"&&!n&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[i]:void 0}}));let u=ir("server");this.state.errorMap?.[u]&&a!=="server"&&!n&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[u]:void 0}}));}),{hasErrored:n,fieldsErrorMap:s}},this.validateAsync=async a=>{let r=xo(a,{...this.options,form:this,validationLogic:this.options.validationLogic||ga});this.state.isFormValidating||this.baseStore.setState(l=>({...l,isFormValidating:true}));let n=[],s;for(let l of r){if(!l.validate)continue;let c=ir(l.cause);this.state.validationMetaMap[c]?.lastAbortController.abort();let p=new AbortController;this.state.validationMetaMap[c]={lastAbortController:p},n.push(new Promise(async f=>{let h;try{h=await new Promise((g,b)=>{setTimeout(async()=>{if(p.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:p.signal},type:"validateAsync"}));}catch(y){b(y);}},l.debounceMs);});}catch(g){h=g;}let{formError:x,fieldErrors:m}=Mn(h);m&&(s=s?{...s,...m}:m);let v=ir(l.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let b=this.getFieldMeta(g);if(!b)continue;let{errorMap:y,errorSourceMap:S}=b,I=s?.[g],{newErrorValue:C,newSource:L}=In({newFormValidatorError:I,isPreviousErrorFromFormValidator:S?.[v]==="form",previousErrorValue:y?.[v]});y?.[v]!==C&&this.setFieldMeta(g,P=>({...P,errorMap:{...P.errorMap,[v]:C},errorSourceMap:{...P.errorSourceMap,[v]:L}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[v]:x}})),f(s?{fieldErrors:s,errorMapKey:v}:void 0);}));}let i=[],u={};if(n.length){i=await Promise.all(n);for(let l of i)if(l?.fieldErrors){let{errorMapKey:c}=l;for(let[d,p]of Object.entries(l.fieldErrors)){let h={...u[d]||{},[c]:p};u[d]=h;}}}return this.baseStore.setState(l=>({...l,isFormValidating:false})),u},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>pa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,r)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:ma(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let s=n;return r[s]=bo,r},{}),this.setFieldValue=(a,r,n)=>{let s=n?.dontUpdateMeta??false,i=n?.dontRunListeners??false,u=n?.dontValidate??false;ft(()=>{s||this.setFieldMeta(a,l=>({...l,isTouched:!0,isDirty:!0,errorMap:{...l?.errorMap,onMount:void 0}})),this.baseStore.setState(l=>({...l,values:ho(l.values,a,r)}));}),i||this.getFieldInfo(a).instance?.triggerOnChangeListener(),u||this.validateField(a,"change");},this.deleteField=a=>{let n=[...Object.keys(this.fieldInfo).filter(s=>{let i=a.toString();return s!==i&&s.startsWith(i)}),a];this.baseStore.setState(s=>{let i={...s};return n.forEach(u=>{i.values=Pi(i.values,u),delete this.fieldInfo[u],delete i.fieldMetaBase[u];}),i});},this.pushFieldValue=(a,r,n)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],r],n);},this.insertFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,u=>[...u.slice(0,r),n,...u.slice(r)],Ge(s,{dontValidate:true}));let i=s?.dontValidate??false;i||await this.validateField(a,"change"),sr(this).handleArrayFieldMetaShift(a,r,"insert"),i||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,u=>u.map((l,c)=>c===r?n:l),Ge(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,n)=>{let s=this.getFieldValue(a),i=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,l=>l.filter((c,d)=>d!==r),Ge(n,{dontValidate:true})),sr(this).handleArrayFieldMetaShift(a,r,"remove"),i!==null){let l=`${a}[${i}]`;this.deleteField(l);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,s)=>{this.setFieldValue(a,u=>{let l=u[r],c=u[n];return ho(ho(u,`${r}`,c),`${n}`,l)},Ge(s,{dontValidate:true})),sr(this).handleArrayFieldMetaShift(a,r,"swap",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.moveFieldValues=(a,r,n,s)=>{this.setFieldValue(a,u=>{let l=[...u];return l.splice(n,0,l.splice(r,1)[0]),l},Ge(s,{dontValidate:true})),sr(this).handleArrayFieldMetaShift(a,r,"move",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.clearFieldValues=(a,r)=>{let n=this.getFieldValue(a),s=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,[],Ge(r,{dontValidate:true})),s!==null)for(let u=0;u<=s;u++){let l=`${a}[${u}]`;this.deleteField(l);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:bo},values:this.options.defaultValues?ho(r.values,a,pa(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,n])=>(Object.keys(n).length&&n.errors.length&&(a[r]={errors:n.errors,errorMap:n.errorMap}),a),{})}),this.parseValuesWithSchema=a=>xa.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>xa.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Di(),this._devtoolsSubmissionOverride=false,this.baseStore=new zt(Ei({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Dt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,i=a?.[0],u=r[0],l=0,c={};for(let d of Object.keys(u.fieldMetaBase)){let p=u.fieldMetaBase[d],f=i?.fieldMetaBase[d],h=s?.[d],x=pa(u.values,d),m=h?.errors;if(!f||p.errorMap!==f.errorMap){m=Object.values(p.errorMap??{}).filter(S=>S!==void 0);let y=this.getFieldInfo(d)?.instance;y&&!y.options.disableErrorFlat&&(m=m?.flat(1));}let v=!Ri(m??[]),g=!p.isDirty,b=ha(x,pa(this.options.defaultValues,d))||ha(x,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===v&&h.isDefaultValue===b&&h.errors===m&&p===f){c[d]=h,l++;continue}c[d]={...p,errors:m,isPristine:g,isValid:v,isDefaultValue:b};}return Object.keys(u.fieldMetaBase).length&&s&&l===Object.keys(u.fieldMetaBase).length?s:c}}),this.store=new Dt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,i=a?.[0],u=r[0],l=r[1],c=Object.values(l).filter(Boolean),d=c.some(D=>D.isValidating),p=c.every(D=>D.isValid),f=c.some(D=>D.isTouched),h=c.some(D=>D.isBlurred),x=c.every(D=>D.isDefaultValue),m=f&&u.errorMap?.onMount,v=c.some(D=>D.isDirty),g=!v,b=!!(u.errorMap?.onMount||c.some(D=>D?.errorMap?.onMount)),y=!!d,S=s?.errors??[];(!i||u.errorMap!==i.errorMap)&&(S=Object.values(u.errorMap).reduce((D,H)=>H===void 0?D:H&&nr(H)?(D.push(H.form),D):(D.push(H),D),[]));let I=S.length===0,C=p&&I,L=this.options.canSubmitWhenInvalid??false,P=u.submissionAttempts===0&&!f&&!b||!y&&!u.isSubmitting&&C||L,A=u.errorMap;if(m&&(S=S.filter(D=>D!==u.errorMap.onMount),A=Object.assign(A,{onMount:void 0})),s&&i&&s.errorMap===A&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===S&&s.isFieldsValidating===d&&s.isFieldsValid===p&&s.isFormValid===I&&s.isValid===C&&s.canSubmit===P&&s.isTouched===f&&s.isBlurred===h&&s.isPristine===g&&s.isDefaultValue===x&&s.isDirty===v&&ha(i,u))return s;let U={...u,errorMap:A,fieldMeta:this.fieldMetaDerived.state,errors:S,isFieldsValidating:d,isFieldsValid:p,isFormValid:I,isValid:C,canSubmit:P,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:x,isDirty:v},F=this.options.transform?.deps??[];if(F.length!==this.prevTransformArray.length||F.some((D,H)=>D!==this.prevTransformArray[H])){let D=Object.assign({},this,{state:U});this.options.transform?.fn(D),U=D.state,this.prevTransformArray=F;}return U}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Ti(a=>pt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),pt.on("request-form-state",a=>{a.payload.id===this._formId&&pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),pt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),pt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return kn(o.validate)?xa[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(r=>({...r,isSubmitted:false,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:false})),ft(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(n=>({...n,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ft(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ft(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){ft(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(nr(a)){let{formError:n,fieldErrors:s}=Mn(a);for(let i of Object.keys(this.fieldInfo))this.getFieldMeta(i)&&this.setFieldMeta(i,l=>({...l,errorMap:{...l.errorMap,[r]:s?.[i]},errorSourceMap:{...l.errorSourceMap,[r]:"form"}}));this.baseStore.setState(i=>({...i,errorMap:{...i.errorMap,[r]:n}}));}else this.baseStore.setState(n=>({...n,errorMap:{...n.errorMap,[r]:a}}));});});}};function Mn(e){if(e){if(nr(e)){let o=Mn(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function ir(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var dr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let n=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});n&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:n},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=pa(t.form.options.defaultValues,t.name),n=t.defaultValue??r;a?this.setValue(s=>s||n,{dontUpdateMeta:true}):n!==void 0&&this.setValue(n,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Ge(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Ge(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let n of a){if(!n.instance)continue;let{onChangeListenTo:s,onBlurListenTo:i}=n.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&r.push(n.instance),t==="blur"&&i?.includes(this.name)&&r.push(n.instance);}return r},this.validateSync=(t,a)=>{let r=go(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ga}),s=this.getLinkedFields(t).reduce((l,c)=>{let d=go(t,{...c.options,form:c.form,validationLogic:c.form.options.validationLogic||ga});return d.forEach(p=>{p.field=c;}),l.concat(d)},[]),i=false;ft(()=>{let l=(c,d)=>{let p=Tn(d.cause),f=d.validate?su(c.runValidator({validate:d.validate,value:{value:c.store.state.value,validationSource:"field",fieldApi:c},type:"validate"})):void 0,h=a[p],{newErrorValue:x,newSource:m}=Cn({formLevelError:h,fieldLevelError:f});c.state.meta.errorMap?.[p]!==x&&c.setMeta(v=>({...v,errorMap:{...v.errorMap,[p]:x},errorSourceMap:{...v.errorSourceMap,[p]:m}})),x&&(i=!0);};for(let c of r)l(this,c);for(let c of s)c.validate&&l(c.field,c);});let u=Tn("submit");return this.state.meta.errorMap?.[u]&&t!=="submit"&&!i&&this.setMeta(l=>({...l,errorMap:{...l.errorMap,[u]:void 0},errorSourceMap:{...l.errorSourceMap,[u]:void 0}})),{hasErrored:i}},this.validateAsync=async(t,a)=>{let r=xo(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ga}),n=await a,s=this.getLinkedFields(t),i=s.reduce((p,f)=>{let h=xo(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||ga});return h.forEach(x=>{x.field=f;}),p.concat(h)},[]);this.state.meta.isValidating||this.setMeta(p=>({...p,isValidating:true}));for(let p of s)p.setMeta(f=>({...f,isValidating:true}));let u=[],l=[],c=(p,f,h)=>{let x=Tn(f.cause);p.getInfo().validationMetaMap[x]?.lastAbortController.abort();let v=new AbortController;this.getInfo().validationMetaMap[x]={lastAbortController:v},h.push(new Promise(async g=>{let b;try{b=await new Promise((L,P)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(v.signal.aborted)return L(void 0);try{L(await this.runValidator({validate:f.validate,value:{value:p.store.state.value,fieldApi:p,signal:v.signal,validationSource:"field"},type:"validateAsync"}));}catch(A){P(A);}},f.debounceMs);});}catch(L){b=L;}if(v.signal.aborted)return g(void 0);let y=su(b),S=n[this.name]?.[x],{newErrorValue:I,newSource:C}=Cn({formLevelError:S,fieldLevelError:y});p.setMeta(L=>({...L,errorMap:{...L?.errorMap,[x]:I},errorSourceMap:{...L.errorSourceMap,[x]:C}})),g(I);}));};for(let p of r)p.validate&&c(this,p,u);for(let p of i)p.validate&&c(p.field,p,l);let d=[];(u.length||l.length)&&(d=await Promise.all(u),await Promise.all(l)),this.setMeta(p=>({...p,isValidating:false}));for(let p of s)p.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:n}=this.validateSync(t,r[this.name]??{});if(n&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Tn(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>xa.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>xa.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Dt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...bo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return kn(o.validate)?xa[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function su(e){if(e)return e}function Tn(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function An(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Dg)}function Dg(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,r]of e)if(!o.has(a)||!Object.is(r,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=iu(e);if(t.length!==iu(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function iu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var vo=typeof window<"u"?useLayoutEffect:useEffect;function qg(e){let[o]=useState(()=>{let a=new dr({...e,form:e.form,name:e.name});return a.Field=Bi,a});return vo(o.mount,[o]),vo(()=>{o.update(e);}),An(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Bi=(({children:e,...o})=>{let t=qg(o),a=useMemo(()=>ma(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function zg({form:e,selector:o,children:t}){let a=An(e.store,o);return ma(t,a)}function Oi(e){let o=useId(),[t]=useState(()=>{let a=new lr({...e,formId:o}),r=a;return r.Field=function(s){return jsx(Bi,{...s,form:a})},r.Subscribe=function(s){return jsx(zg,{form:a,selector:s.selector,children:s.children})},r});return vo(t.mount,[]),vo(()=>{t.update(e);}),t}function Ni({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var Zg=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[s,i]=useState(n),u=Oi({defaultValues:{questionType:n,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:d})=>{if(d.questionType==="true-false"){let p={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctAnswer:d.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?ra(p):Ds(p));}else if(d.questionType==="multiple-choice"){let p={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctIndex:d.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?oa(p):Ps(p));}else if(d.questionType==="short-answer"){let p={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Eo(p):Es(p));}else if(d.questionType==="fill-in-the-blank"){let p={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Oo(p):Vs(p));}else if(d.questionType==="long-answer"){let p={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctLongAnswer:d.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Bo(p):Os(p));}o(na(false));}}),l=()=>{o(na(false));},c=jsx("div",{className:"fixed inset-0 z-106 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-6 shadow-lg",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-240px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-100px)] w-full flex-col gap-1 rounded-lg bg-white p-4",onSubmit:d=>{d.preventDefault(),d.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-4",children:[jsxs("div",{className:"flex flex-col gap-1",children:[jsx("h2",{className:"text-2xl font-bold text-[#000000CC]",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"font-semibold text-[#00000099]",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-8 w-8 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600",onClick:()=>{l();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(u.Field,{name:"questionType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:p=>{d.handleChange(p.target.value),i(p.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 font-semibold text-[#000000CC] ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Question type cannot be changed when editing"}),jsx(Ni,{field:d})]})}),s&&!["short-answer","fill-in-the-blank","long-answer"].includes(s)&&jsx(u.Field,{name:"responseType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:p=>d.handleChange(p.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-4 py-3 pr-10 font-semibold text-[#000000CC]",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Ni,{field:d})]})})]}),jsx(u.Field,{name:"feedbackMode",children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-2 rounded-lg bg-gray-100 p-1.5 ${s==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>d.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",size:16}),"Practice Mode"]}),jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>d.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",size:16}),"Assessment Mode"]})]}),s==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(Ni,{field:d})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:d})=>d?void 0:"A question is required"},children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-4 py-3 text-gray-900",value:d.state.value,onChange:p=>d.handleChange(p.target.value),onBlur:d.handleBlur,placeholder:"Enter Your Question"})}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),s==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:d=>{let p=d.state.value;return jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{className:"text-base font-semibold text-[#00000066] uppercase",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-4",children:[jsxs("button",{type:"button",onClick:()=>d.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${p===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"True"}),p===true&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>d.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${p===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"False"}),p===false&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]})]}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Select the correct answer for this true/false question"})]})}}),s==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:d})=>{if(d.options.filter(f=>!f.trim()).length>0)return "All options must have text";if(!d.correctIndex||d.correctIndex.length===0)return "Please select at least one correct answer"}},children:d=>{let p=(m,v)=>{let g=[...d.state.value.options];g[m]=v,d.handleChange({...d.state.value,options:g});},f=()=>{if(d.state.value.options.length>=6){alert("Maximum 6 options allowed");return}d.handleChange({...d.state.value,options:[...d.state.value.options,""]});},h=m=>{if(d.state.value.options.length<=2){alert("Minimum 2 options required");return}let v=d.state.value.options.filter((b,y)=>y!==m),g=d.state.value.correctIndex?.filter(b=>b!==m).map(b=>b>m?b-1:b);d.handleChange({...d.state.value,options:v,correctIndex:g});},x=m=>{let v=d.state.value.correctIndex||[];if(v.includes(m))d.handleChange({...d.state.value,correctIndex:v.filter(b=>b!==m)});else {if(v.length>=6){alert("Maximum 6 correct answers allowed");return}d.handleChange({...d.state.value,correctIndex:[...v,m]});}};return jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:d.name,className:"mb-2 text-base font-semibold text-gray-900",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-4 flex flex-col gap-3",children:d.state.value.options.map((m,v)=>{let g=!m.trim(),b=d.state.value.correctIndex?.includes(v),y=d.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>x(v),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${b?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:b&&jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-4 py-3 transition-colors ${y?"border-red-500 bg-red-50":b?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${v+1}`,value:m,onChange:S=>p(v,S.target.value),onBlur:d.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),d.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>h(v),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},v)})}),jsx("button",{type:"button",onClick:f,disabled:d.state.value.options.length>=6,className:"mx-2 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-3 text-lg font-semibold text-[#00000066] disabled:cursor-not-allowed",children:"+ Add Option"}),d.state.value.correctIndex.length===0||d.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:d.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill"}),jsx("p",{className:"",children:"Correct answer selected"})]})]})}}),(s==="short-answer"||s==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:d.state.value,onChange:p=>{d.handleChange(p.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Learners must write this answer exactly (case-insensitive)."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),s==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-gray-900",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:d.state.value,onChange:p=>{d.handleChange(p.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"This will be used as a reference answer for manual grading."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:d=>[d.canSubmit,d.isSubmitting],children:([d,p])=>jsx("button",{type:"submit",disabled:!d,className:"mt-2 mb-4 w-full rounded-lg bg-[#096B76] px-6 py-3 font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50",children:p?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(c,document.body)},uu=Zg;var cu=({text:e,position:o})=>{let t=xe(),a=l=>{t(ue()),t(yt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+l))}));},r=l=>{t(ue()),t(yt({id:e.id,fill:l}));},n=()=>{t(ue()),t(yt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},s=()=>{t(ue()),t(yt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},i=()=>{t(ue()),t(yt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},u=l=>{t(ue()),t(yt({id:e.id,fontFamily:l}));};return jsxs("div",{className:"fixed z-1001 flex items-center gap-1 rounded-lg border border-gray-200 bg-white p-2 shadow-2xl",style:{left:`${o.x}px`,top:`${o.y-60}px`,transform:"translateX(-50%)"},onClick:l=>l.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:l=>u(l.target.value),className:"rounded border border-gray-300 bg-white px-2 py-1 text-xs hover:bg-gray-50",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-8 text-center text-xs font-medium",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:n,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:jsx(TextB,{size:16,weight:"bold"})}),jsx("button",{onClick:s,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:jsx(TextItalic,{size:16,weight:"bold"})}),jsx("button",{onClick:i,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:jsx(TextUnderline,{size:16,weight:"bold"})})]}),jsx("div",{className:"ml-1 border-l border-gray-200 pl-1",children:jsx("div",{className:"relative",children:jsx("input",{type:"color",value:e.fill,onChange:l=>r(l.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var mu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:s})=>{let i=useRef(null),u=useMemo(()=>({fontSize:`${e.fontSize*n}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,n]),l=useCallback(c=>{c.style.height="auto",c.style.height=`${c.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(c).font,d.style.fontSize=c.style.fontSize,d.style.fontFamily=c.style.fontFamily,d.style.fontWeight=c.style.fontWeight,d.style.fontStyle=c.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let p=c.value.split(`
4
- `),f=0;document.body.appendChild(d);for(let x of p){d.textContent=x||" ";let m=d.offsetWidth;m>f&&(f=m);}document.body.removeChild(d);let h=10;c.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let c=i.current;c&&(c.style.fontSize=`${e.fontSize*n}px`,c.style.fontFamily=e.fontFamily,c.style.fontStyle=e.fontStyle,c.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",c.style.textDecoration=e.textDecoration,c.style.color=e.fill,l(c));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,l]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:c=>{if(i.current=c,s.current=c,c){c.focus();let d=c.value.length;c.setSelectionRange(d,d),l(c);}},value:o,onChange:c=>{t(c.target.value);},onKeyDown:c=>{c.key==="Escape"&&a();},style:u},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var pu=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(E=>E.toolbar.selectedTool),i=s==="pen"||s==="eraser",u=useRef(null),[l,c]=useState(""),[d,p]=useState(false),[f,h]=useState(null);useEffect(()=>{let E=u.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id,a]);let x=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",m=d&&l.trim().toLowerCase()===x,v=()=>{p(false),c("");},g=()=>m?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",b=()=>m?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},y=24,S=60,I=d?50:0,C=50,L=12,P=e.data.feedbackMode==="practice"?48:0,A=12,U=30,F=S+I+U+C+L+A+P+y;return jsxs(Group,{ref:u,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"sa-element",...i?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let D=u.current?.getStage()?.getPointerPosition();if(!D)return;let H={x:e.x,y:e.y,width:e.width,height:e.height};D.x>=H.x&&D.x<=H.x+H.width&&D.y>=H.y&&D.y<=H.y+H.height&&r(E.evt,e.id,"shortAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:F,onTransformEnd:E=>t(e.id,E)}),jsx(Text,{text:e.data.question,x:y,y,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:y,y:S,width:e.width-y*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:I,text:g(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer:",x:y,y:S+I+L,fontSize:14,fill:"#6b7280",width:e.width-y*2,listening:false}),jsx(Rect,{x:y,y:S+I+U,width:e.width-y*2,height:C,fill:"#ffffff",stroke:m?"#22c55e":d?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${S+I+U}px`,left:`${y}px`,width:`${e.width-y*2}px`,height:`${C}px`,pointerEvents:d?"none":"auto"}},children:jsx("input",{type:"text",value:l,onChange:E=>c(E.target.value),disabled:d,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:d?"none":"auto"}})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S+I+U+C+L+A,children:[!d&&jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,h("check");},onMouseUp:E=>{E.cancelBubble=true,h(null),l.length>0&&p(true);},onMouseLeave:E=>{E.cancelBubble=true,h(null);},onTouchStart:E=>{E.cancelBubble=true,h("check");},onTouchEnd:E=>{E.cancelBubble=true,h(null),l.length>0&&p(true);},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:l.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});pu.displayName="ShortAnswer";var hu=pu;var xu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(hu,{shortAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>n(i,s.id)},s.id))});var bu=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((s,i)=>{let u=s.target;o(Oo({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var vu=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r})=>{let n=useSelector(F=>F.toolbar.selectedTool),s=n==="pen"||n==="eraser",i=useRef(null),[u,l]=useState(""),[c,d]=useState(false),[p,f]=useState(null);useEffect(()=>{if(i.current)return ()=>{}},[e.id]);let h=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=c&&u.trim().toLowerCase()===h,m=()=>{d(false),l("");},v=()=>x?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",g=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=24,y=80,S=c?50:0,I=45,C=8,L=20,P=e.data.feedbackMode==="practice"?48:0,A=12,U=y+S+C+L+C+A+P+b;return jsxs(Group,{ref:i,draggable:!s,listening:!s,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...s?{}:{onDragEnd:F=>a(F,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:F=>{let E=i.current?.getStage()?.getPointerPosition();if(!E||!r)return;let D={x:e.x,y:e.y,width:e.width,height:e.height};E.x>=D.x&&E.x<=D.x+D.width&&E.y>=D.y&&E.y<=D.y+D.height&&r(F.evt,e.id,"fillInTheBlanks");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:U,onTransformEnd:F=>t(e.id,F)}),jsx(Text,{text:e.data.question,x:b,y:b,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2-200,listening:false}),jsx(Rect,{x:e.width-b-180,y:b+10,width:180,height:I,fill:"#ffffff",stroke:x?"#22c55e":c?"#ef4444":"#096B76",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${b+10}px`,left:`${e.width-b-180}px`,width:"180px",height:`${I}px`,pointerEvents:c?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:F=>l(F.target.value),disabled:c,placeholder:"__________",className:"h-full w-full border-0 bg-white px-2 text-center text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:c?"none":"auto"}})}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:b,y,width:e.width-b*2,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:b,y,width:e.width-b*2,height:S,text:v(),fontSize:16,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"\u26A0\uFE0F Answer is case sensitive",x:b,y:y+S+C,fontSize:10,fontStyle:"italic",fill:"#6b7280",width:e.width-b*2,listening:false}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:y+S+C+L+C+A,children:[!c&&jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,f("check");},onMouseUp:F=>{F.cancelBubble=true,f(null),u.length>0&&d(true);},onMouseLeave:F=>{F.cancelBubble=true,f(null);},onTouchStart:F=>{F.cancelBubble=true,f("check");},onTouchEnd:F=>{F.cancelBubble=true,f(null),u.length>0&&d(true);},scaleX:p==="check"?.95:1,scaleY:p==="check"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:u.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{onMouseDown:()=>f("reset"),onMouseUp:()=>{f(null),m();},onMouseLeave:()=>f(null),onTouchStart:()=>f("reset"),onTouchEnd:()=>{f(null),m();},scaleX:p==="reset"?.95:1,scaleY:p==="reset"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});vu.displayName="FillInTheBlanks";var yu=vu;var Lu=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(yu,{fillInTheBlank:n,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r},n.id))});var Wi=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(E=>E.toolbar.selectedTool),i=s==="pen"||s==="eraser",u=useRef(null),[l,c]=useState(""),[d,p]=useState(false),[f,h]=useState(null);useEffect(()=>{let E=u.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id,a]);let x=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",m=d&&l.trim().toLowerCase()===x,v=()=>{p(false),c("");},g=()=>m?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",b=()=>m?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},y=24,S=60,I=d?60:0,C=120,L=12,P=48,A=12,U=30,F=S+I+U+C+L+A+P+y;return jsxs(Group,{ref:u,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...i?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let D=u.current?.getStage()?.getPointerPosition();if(!D||!r)return;let H={x:e.x,y:e.y,width:e.width,height:e.height};D.x>=H.x&&D.x<=H.x+H.width&&D.y>=H.y&&D.y<=H.y+H.height&&r(E.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:F,onTransformEnd:E=>t(e.id,E)}),jsx(Text,{text:e.data.question,x:y,y,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:y,y:S,width:e.width-y*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:I,text:g(),fontSize:14,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:y,y:S+I+L,fontSize:14,fill:"#6b7280",width:e.width-y*2,listening:false}),jsx(Rect,{x:y,y:S+I+U,width:e.width-y*2,height:C,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${S+I+U}px`,left:`${y}px`,width:`${e.width-y*2}px`,height:`${C}px`,pointerEvents:d?"none":"auto"}},children:jsx("textarea",{value:l,onChange:E=>c(E.target.value),disabled:d,placeholder:`Type your extended answer here...\r
2
+ export{default as Konva}from'konva';import*as be from'react';import be__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,createElement,useMemo,useId,useLayoutEffect}from'react';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,configureStore}from'@reduxjs/toolkit';import Ul from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,SidebarSimple,Plus,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp as CloudArrowUp$1,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {CaretLeft,CloudArrowUp,EyeIcon,Stack as Stack$1,X as X$1,DotsSixVertical,ArrowUp,ArrowDown,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {createPortal}from'react-dom';import Ud from'use-image';import {motion,AnimatePresence,Reorder}from'framer-motion';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Rl=e=>{throw TypeError(e)};var Dl=(e,o,t)=>o.has(e)||Rl("Cannot "+t);var K=(e,o,t)=>(Dl(e,o,"read from private field"),t?t.call(e):o.get(e)),Te=(e,o,t)=>o.has(e)?Rl("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),ke=(e,o,t,a)=>(Dl(e,o,"write to private field"),o.set(e,t),t);var Fl=(e,o,t,a)=>({set _(r){ke(e,o,r);},get _(){return K(e,o,a)}});var xe=()=>useDispatch(),ee=e=>useSelector(e),yt=xe,ta=ee;var rn=20,El=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now()}),on=El("Slide 1"),tm={slides:[on],currentSlideId:on.id,history:{[on.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null},Bl=createSlice({name:"canvas",initialState:tm,reducers:{addSlide:e=>{if(e.slides.length>=rn)return;let o=El(`Slide ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{if(e.slides.length<=1)return;let t=e.slides.findIndex(a=>a.id===o.payload);if(t!==-1&&(e.slides.splice(t,1),delete e.history[o.payload],e.currentSlideId===o.payload)){let a=Math.max(0,t-1);e.currentSlideId=e.slides[a].id;}},duplicateSlide:(e,o)=>{if(e.slides.length>=rn)return;let t=e.slides.findIndex(s=>s.id===o.payload);if(t===-1)return;let a=e.slides[t],r={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[r]=e.slides.splice(t,1);e.slides.splice(a,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(r=>r.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload);if(a){let r={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(r),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,newTimestamp:s}=o.payload;switch(r){case "image":let n=t.images.find(g=>g.id===a);n&&(n.timestamp=s);break;case "video":let i=t.videos.find(g=>g.id===a);i&&(i.timestamp=s);break;case "shape":let u=t.shapes.find(g=>g.id===a);u&&(u.timestamp=s);break;case "text":let l=t.texts.find(g=>g.id===a);l&&(l.timestamp=s);break;case "flashcard":let c=t.flashcards.find(g=>g.id===a);c&&(c.timestamp=s);break;case "photoFrame":let d=t.photoFrames.find(g=>g.id===a);d&&(d.timestamp=s);break;case "mcq":let m=t.multipleChoices.find(g=>g.id===a);m&&(m.timestamp=s);break;case "trueFalse":let f=t.trueFalses.find(g=>g.id===a);f&&(f.timestamp=s);break;case "shortAnswer":let h=t.shortAnswers.find(g=>g.id===a);h&&(h.timestamp=s);break;case "longAnswer":let x=t.LongAnswer.find(g=>g.id===a);x&&(x.timestamp=s);break;case "fillInTheBlanks":let p=t.fillInTheBlanks.find(g=>g.id===a);p&&(p.timestamp=s);break;case "line":let v=t.lines.find(g=>g.id===a);v&&(v.timestamp=s);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);if(a){let r={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(r),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);if(a){let r={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(r),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(r),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let r=t.multipleChoices[t.multipleChoices.length-1];a.x=r.x+20,a.y=r.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(r=>r.id===o.payload);if(a){let r={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(r),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let r=t.trueFalses[t.trueFalses.length-1];a.x=r.x+20,a.y=r.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(r),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let r=t.shortAnswers[t.shortAnswers.length-1];a.x=r.x+20,a.y=r.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(r=>r.id===o.payload);if(a){let r={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(r),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let r=t.LongAnswer[t.LongAnswer.length-1];a.x=r.x+20,a.y=r.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload);if(a){let r={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(r),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let r=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=r.x+20,a.y=r.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(r=>r.id===o.payload);if(a){let r={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(r),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let s=t.images.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.images.splice(s,1);t.images.push(n);}}else if(r==="video"){let s=t.videos.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.videos.splice(s,1);t.videos.push(n);}}else if(r==="shape"){let s=t.shapes.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.shapes.splice(s,1);t.shapes.push(n);}}else if(r==="flashcard"){let s=t.flashcards.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.flashcards.splice(s,1);t.flashcards.push(n);}}else if(r==="photoFrame"){let s=t.photoFrames.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.photoFrames.splice(s,1);t.photoFrames.push(n);}}else if(r==="text"){let s=t.texts.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.texts.splice(s,1);t.texts.push(n);}}else if(r==="trueFalse"){let s=t.trueFalses.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.trueFalses.splice(s,1);t.trueFalses.push(n);}}else if(r==="shortAnswer"){let s=t.shortAnswers.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.shortAnswers.splice(s,1);t.shortAnswers.push(n);}}else if(r==="fillInTheBlanks"){let s=t.fillInTheBlanks.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.fillInTheBlanks.splice(s,1);t.fillInTheBlanks.push(n);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let s=t.images.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.images.splice(s,1);t.images.unshift(n);}}else if(r==="video"){let s=t.videos.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.videos.splice(s,1);t.videos.unshift(n);}}else if(r==="shape"){let s=t.shapes.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.shapes.splice(s,1);t.shapes.unshift(n);}}else if(r==="flashcard"){let s=t.flashcards.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.flashcards.splice(s,1);t.flashcards.unshift(n);}}else if(r==="photoFrame"){let s=t.photoFrames.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.photoFrames.splice(s,1);t.photoFrames.unshift(n);}}else if(r==="text"){let s=t.texts.findIndex(n=>n.id===a);if(s!==-1){let[n]=t.texts.splice(s,1);t.texts.unshift(n);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload,n=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,link:s}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="mcq"?t.multipleChoices:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.link=s,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,altText:s}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.altText=s,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,audioData:s}=o.payload,i=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(u=>u.id===a);i&&(i.audioData=s,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(r=>r.id===o.payload);if(a){let r={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(r),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a){let r={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(r),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let r=a.images.map((s,n)=>n).filter(s=>s!==a.currentIndex);if(r.length>0){let s=r[Math.floor(Math.random()*r.length)];a.navigationHistory.push(s),a.currentIndex=s;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);if(a){let r={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(r),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let r=o.past.pop();e.slides[t]=r;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let r=o.future.shift();e.slides[t]=r;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let r=JSON.parse(JSON.stringify(t));a.past.push(r),a.future=[],a.past.length>20&&a.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;}}}),{addSlide:sn,deleteSlide:nn,duplicateSlide:ln,setCurrentSlide:dn,updateSlideThumbnail:un,setBackgroundColor:cn,reorderSlides:am,loadSlides:ja,addLine:fn,removeLine:Hr,addImage:mn,updateImage:$a,deleteImage:pn,duplicateImage:Ur,addVideo:zr,updateVideo:Wr,deleteVideo:hn,duplicateVideo:Gr,toggleVideoPlaying:Fo,addShape:gn,updateShape:Xa,duplicateShape:Kr,deleteShape:xn,addText:bn,updateText:wt,deleteText:vn,duplicateText:_r,addFlashcard:yn,updateFlashcard:Ya,deleteFlashcard:wn,duplicateFlashcard:jr,editFlashcard:Eo,nextFlashcard:Ln,previousFlashcard:Sn,addPhotoFrame:In,updatePhotoFrame:Ta,deletePhotoFrame:Cn,duplicatePhotoFrame:$r,toggleImageDrawingMode:kn,addImageAnnotation:Mn,updateImageAnnotation:om,clearImageAnnotations:rm,togglePhotoFrameDrawingMode:Tn,addPhotoFrameAnnotation:An,updatePhotoFrameAnnotation:sm,clearPhotoFrameAnnotations:nm,addMultipleChoice:Pn,updateMultipleChoice:aa,editMultipleChoice:im,deleteMultipleChoice:Rn,duplicateMultipleChoice:Xr,addTrueFalse:Dn,updateTrueFalse:oa,deleteTrueFalse:Fn,duplicateTrueFalse:Yr,addShortAnswer:En,updateShortAnswer:Bo,deleteShortAnswer:Bn,duplicateShortAnswer:Jr,addLongAnswer:On,updateLongAnswer:Oo,deleteLongAnswer:Nn,duplicateLongAnswer:Zr,addFillInTheBlanks:Vn,updateFillInTheBlanks:No,deleteFillInTheBlanks:qn,duplicateFillInTheBlanks:Qr,setShowMcqForm:ra,setShowFlashcardForm:Aa,setActivityType:Hn,setEditingActivity:Vo,bringToFront:Un,sendToBack:zn,toggleLock:Wn,setLink:es,setAltText:ts,setAudioData:as,updateLastLine:lm,finalizeDrawing:Gn,setLines:dm,updateLinePosition:um,updateLineTransform:os,deleteLineById:Kn,duplicateLine:_n,updateElementOrder:qo,clearCanvas:jn,undo:$n,redo:Xn,saveToHistory:ue,toggleSketchMode:cm,setSketchMode:dt,setEditingTextId:Ho}=Bl.actions,Uo=e=>e.canvas.currentSlideId,ge=e=>{let o=e.canvas.currentSlideId,t=e.canvas.slides.findIndex(a=>a.id===o);return t>=0?e.canvas.slides[t]:void 0},zo=e=>e.canvas.slides,Yn=e=>e.canvas.slides.length<rn,fm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},Ol=Bl.reducer;var Vl=e=>{let o=xe(),t=useRef(null),a=useRef(false),r=ee(f=>f.toolbar.selectedTool),s=ee(f=>f.toolbar.penColor),n=ee(f=>f.toolbar.strokeWidth),i=ee(f=>f.canvas.isSketchMode),u=ee(f=>f.canvas.slides.find(x=>x.id===f.canvas.currentSlideId)?.lines||[]),l=useCallback(f=>{t.current=f;},[]),c=useCallback(f=>{r==="pen"&&t.current&&(o(ue()),t.current.startDrawing(f),a.current=true);},[r,o]),d=useCallback(f=>{!t.current||!a.current||t.current.draw(f);},[]),m=useCallback(()=>{if(!t.current||!a.current)return;let f=t.current.stopDrawing();a.current=false,f&&f.points.length>=4&&o(fn(f)),o(Gn()),e?.();},[o,e]);return {lines:u,tool:r,color:s,strokeWidth:n,isSketchMode:i,setCanvasRef:l,startDrawing:c,draw:d,stopDrawing:m}};var zl=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:s,style:n},i)=>{let u=useRef(null),l=useRef(false),c=useRef([]),d=useRef(null),m=useRef(t),f=useRef(a),h=useRef(r),x=useRef(s);useEffect(()=>{m.current=t,f.current=a,h.current=r,x.current=s;},[t,a,r,s]);let p=useCallback(()=>{let g=u.current;if(!g)return;let b=g.getContext("2d");b&&b.clearRect(0,0,g.width,g.height);},[]),v=useCallback(()=>{let g=u.current,b=c.current;if(!g||b.length<1)return;let y=g.getContext("2d");if(!y)return;if(y.clearRect(0,0,g.width,g.height),m.current==="eraser"?(y.globalCompositeOperation="destination-out",y.fillStyle="rgba(0,0,0,1)"):(y.globalCompositeOperation="source-over",y.fillStyle=f.current),b.length===1){y.beginPath(),y.arc(b[0].x,b[0].y,h.current/2,0,Math.PI*2),y.fill();return}let I=Ul(b,{size:h.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:C=>C,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(I.length<2)){y.beginPath(),y.moveTo(I[0][0],I[0][1]);for(let C=1;C<I.length;C++)y.lineTo(I[C][0],I[C][1]);y.closePath(),y.fill();}},[]);return useImperativeHandle(i,()=>({startDrawing:g=>{l.current=true,c.current=[{x:g.x,y:g.y}],d.current=g,v();},draw:g=>{if(!l.current||!d.current)return;let b=g.x-d.current.x,y=g.y-d.current.y;Math.sqrt(b*b+y*y)<2||(c.current.push({x:g.x,y:g.y}),d.current=g,v());},stopDrawing:()=>{if(!l.current)return null;if(l.current=false,c.current.length<2)return c.current=[],d.current=null,p(),null;let b=Ul(c.current,{size:h.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:S=>S,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(S=>[S[0],S[1]]),y={tool:m.current,points:b,color:f.current,strokeWidth:h.current,isSketch:true};return c.current=[],d.current=null,p(),y},clear:()=>{p(),c.current=[],d.current=null,l.current=false;},isDrawing:()=>l.current,getCanvasElement:()=>u.current}),[p,v]),useEffect(()=>{let g=u.current;g&&(g.width=e,g.height=o);},[e,o]),jsx("canvas",{ref:u,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});zl.displayName="DirectDrawingCanvas";var Wl=zl;var Kl=e=>{let o=xe(),a=ee(ge)?.images||[],r=useRef(new Map),s=useRef(new Map),n=useRef(new Set);useEffect(()=>{let c=new Set(a.map(d=>d.id));n.current.forEach(d=>{if(!c.has(d)){let m=s.current.get(d);m&&(m.src="",s.current.delete(d)),r.current.delete(d);}}),n.current=c;},[a]),useEffect(()=>()=>{s.current.forEach(c=>{c.src="";}),s.current.clear(),r.current.clear();},[]);let i=useCallback(c=>{if(s.current.has(c.id))return s.current.get(c.id);let d=new window.Image;return d.src=c.src,s.current.set(c.id,d),d},[]),u=useCallback((c,d)=>{let m=c.target,f=m.id();a.find(x=>x.id===f)&&(o($a({id:f,x:m.x(),y:m.y(),width:m.width(),height:m.height(),rotation:m.rotation()})),d?.());},[a,o]),l=useCallback((c,d)=>{let m=d.target,f=r.current.get(c);if(!f){console.error("\u274C Image node not found for id:",c);return}let h=m.scaleX(),x=m.scaleY(),p=m.rotation(),v=f.width(),g=f.height(),b=Math.max(5,v*h),y=Math.max(5,g*x);m.scaleX(1),m.scaleY(1),f.width(b),f.height(y),o($a({id:c,width:b,height:y,x:m.x(),y:m.y(),rotation:p})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:i,imageRefs:r,handleDragEnd:u,handleImageTransformEnd:l}};var _l=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),s=useCallback((i,u)=>{let l=u.target,c=l.scaleX(),d=l.scaleY(),m=l.rotation(),f=Math.max(5,l.width()*c),h=Math.max(5,l.height()*d);l.scaleX(1),l.scaleY(1),l.width(f),l.height(h),o(aa({id:i,width:f,height:h,x:l.x(),y:l.y(),rotation:m})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:s,mcqRefs:a,handleDragEnd:(i,u)=>{o(aa({id:u,x:i.target.x(),y:i.target.y()})),e?.();}}};var jl=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),s=useCallback((i,u)=>{let l=u.target,c=l.scaleX(),d=l.scaleY(),m=l.rotation(),f=Math.max(5,l.width()*c),h=Math.max(5,l.height()*d);l.scaleX(1),l.scaleY(1),l.width(f),l.height(h),o(oa({id:i,width:f,height:h,x:l.x(),y:l.y(),rotation:m})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:s,handleTrueFalseDragEnd:(i,u)=>{o(oa({id:u,x:i.target.x(),y:i.target.y()})),e?.();},trueFalseRefs:a}};var $l=e=>{let o=xe(),a=ee(ge)?.videos||[],r=useRef(new Map),s=useCallback(u=>{o(Fo(u));},[o]),n=useCallback((u,l)=>{let c=l.target;o(Wr({id:u,x:c.x(),y:c.y()})),e?.();},[o,e]),i=useCallback((u,l)=>{let c=l.target,d=c.scaleX(),m=c.scaleY(),f=c.rotation(),h=Math.max(5,c.width()*d),x=Math.max(5,c.height()*m);c.scaleX(1),c.scaleY(1),c.width(h),c.height(x),o(Wr({id:u,width:h,height:x,x:c.x(),y:c.y(),rotation:f})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:s,handleVideoDragEnd:n,handleVideoTransformEnd:i}};var Jl=e=>{let o=xe(),a=ee(ge)?.shapes||[],r=useRef(new Map),s=useRef(new Map),[n,i]=useState(false),u=useCallback((c,d)=>{let m=d.target;o(Xa({id:c,x:m.x(),y:m.y()})),e?.();},[o,e]),l=useCallback((c,d)=>{let m=d.target,f=a.find(b=>b.id===c);if(!f)return;let h=m.scaleX(),x=m.scaleY(),p=f.type?.toLowerCase();p==="arrow"||p==="line"||(m.scaleX(1),m.scaleY(1));let g={id:c,x:m.x(),y:m.y(),width:Math.max(5,m.width()*h),height:Math.max(5,m.height()*x),rotation:m.rotation()};switch(p){case "circle":g.radius=m.width()*h/2;break;case "star":g.innerRadius=m.width()*h/4,g.outerRadius=m.width()*h/2;break;case "triangle":g.radius=m.width()*h/2;break;case "ellipse":g.radiusX=m.width()*h/2,g.radiusY=m.height()*x/2;break;case "polygon":g.radius=m.width()*h/2;break;case "ring":let b=h;g.innerRadius=f.innerRadius&&f.innerRadius*b,g.outerRadius=f.outerRadius&&f.outerRadius*b;break;case "wedge":g.radius=f.radius&&f.radius*h;break;case "arc":g.innerRadius=f.innerRadius&&f.innerRadius*h,g.outerRadius=f.outerRadius&&f.outerRadius*h;break;case "arrow":case "line":{g.scaleX=h,g.scaleY=x,delete g.width,delete g.height;break}}o(Xa(g)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:n,loadedShapesRef:s,handleShapeDragEnd:u,handleShapeResizeEnd:l}};var Ql=(e,o)=>{let t=yt(),r=ee(ge)?.texts||[],s=useRef(new Map),[n,i]=useState(null),[u,l]=useState("");return {texts:r,textRefs:s,handleDragEnd:(p,v)=>{let g=p.target;t(ue()),t(wt({id:v,x:g.x(),y:g.y()})),e();},handleTransformEnd:p=>{let v=s.current.get(p);if(!v)return;let g=v.scaleX(),b=v.scaleY(),y=r.find(I=>I.id===p);if(!y)return;let S=(g+b)/2;v.scaleX(1),v.scaleY(1),t(ue()),t(wt({id:p,x:v.x(),y:v.y(),width:Math.max(5,(y.width||100)*g),height:Math.max(5,(y.height||50)*b),fontSize:Math.round(Math.max(8,y.fontSize*S)),rotation:v.rotation()})),e();},handleDoubleClick:p=>{let v=r.find(g=>g.id===p);v&&!v.locked&&(i(p),l(v.text));},startEditing:p=>{let v=r.find(g=>g.id===p);v&&!v.locked&&(i(p),l(v.text));},editingTextId:n,editingValue:u,handleEditingChange:p=>{l(p);},finishEditing:()=>{if(n){let p=s.current.get(n),v=r.find(b=>b.id===n);t(ue());let g={id:n,text:u};if(v&&(v.fontWeight!==void 0&&(g.fontWeight=v.fontWeight),v.fontStyle!==void 0&&(g.fontStyle=v.fontStyle),v.textDecoration!==void 0&&(g.textDecoration=v.textDecoration)),o?.current&&u.trim()){let b=o.current,y=b.offsetWidth,S=b.offsetHeight,I=1;if(p){let U=p.getStage();U&&(I=U.scaleX());}let C=14,L=(y-C)/I,P=(S-C)/I,A=u.split(`
3
+ `).length,F=r.find(U=>U.id===n)?.fontSize||24,D=A*F*1.2+10;g.width=Math.max(200,L),g.height=Math.max(50,P,D);}else if(p&&u.trim()){let b=p.text(),y=p.width();p.text(u),p.width(void 0);let S=p.width(),I=p.height();p.text(b),p.width(y),g.width=Math.max(200,S+20),g.height=Math.max(50,I+20);}t(wt(g)),i(null),l(""),t(Ho(null)),e();}}}};var ed=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),s=useCallback((n,i)=>{let u=n.target;o(Bo({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:s}};var td=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((s,n)=>{let i=s.target;o(Oo({id:n,x:i.x(),y:i.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var od=e=>{let o=xe(),a=ee(ge)?.flashcards||[],r=useRef(new Map),s=useRef(new Map),n=useCallback((d,m)=>{if(s.current.has(m))return s.current.get(m);let f=new window.Image;return f.src=d,s.current.set(m,f),f},[]),i=useCallback((d,m)=>{let f=d.target,h=f.id();a.find(p=>p.id===h)&&(o(Ya({id:h,x:f.x(),y:f.y()})),m?.());},[a,o]),u=useCallback((d,m)=>{let f=m.target,h=f.scaleX(),x=f.scaleY(),p=f.rotation(),v=Math.max(50,f.width()*h),g=Math.max(50,f.height()*x);f.scaleX(1),f.scaleY(1),f.width(v),f.height(g),o(Ya({id:d,width:v,height:g,x:f.x(),y:f.y(),rotation:p})),f.getLayer()?.batchDraw(),e?.();},[o,e]),l=useCallback(d=>{o(Ln(d)),e?.();},[o,e]),c=useCallback(d=>{o(Sn(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:r,handleDragEnd:i,handleFlashcardTransformEnd:u,handleNext:l,handlePrevious:c}};var nd=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],r=useRef(new Map),[s,n]=useState(new Map),i=useCallback((f,h)=>{console.log("handleDragEnd"),o(Ta({id:h,x:f.target.x(),y:f.target.y()})),e?.();},[o,e]),u=useCallback((f,h)=>{let x=h.target,p=x.scaleX(),v=x.scaleY(),g=x.rotation(),b=a.find(I=>I.id===f);if(!b)return;let y=Math.max(100,b.width*p),S=Math.max(100,b.height*v);x.scaleX(1),x.scaleY(1),o(Ta({id:f,width:y,height:S,x:x.x(),y:x.y(),rotation:g})),x.getLayer()?.batchDraw(),e?.();},[o,e,a]),l=useCallback(async f=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(x=>{let p=new Map(x);return p.set(f,h),p}),o(Ta({id:f,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),c=useCallback(f=>{let h=s.get(f);h&&(h.getTracks().forEach(x=>x.stop()),n(x=>{let p=new Map(x);return p.delete(f),p}),o(Ta({id:f,isCapturing:false})),e?.());},[s,o,e]),d=useCallback((f,h)=>{let x=document.createElement("canvas");x.width=h.videoWidth,x.height=h.videoHeight;let p=x.getContext("2d");if(p){p.drawImage(h,0,0,x.width,x.height);let v=x.toDataURL("image/jpeg",.8);return o(Ta({id:f,capturedImageUrl:v,isCapturing:false})),c(f),e?.(),v}return null},[o,c,e]),m=useRef(s);return useEffect(()=>{m.current=s;},[s]),useEffect(()=>()=>{m.current.forEach(f=>{f.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:i,handlePhotoFrameTransformEnd:u,startCamera:l,stopCamera:c,capturePhoto:d,cameraStreams:s}};var id=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((s,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((s,n,i,u,l,c,d=[])=>{if(e.current){if(s&&!d.find(h=>h.id===s)?.isPlaying){let h=n.get(s)||i.get(s)||u.get(s)||l.get(s)||c.get(s);if(h){e.current.boundBoxFunc(t),e.current.nodes([h]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var Hm=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},cd=(e,o)=>{let t=yt(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});t(un({id:a.current,thumbnail:n}));}catch(n){console.error("Error generating thumbnail:",n);}},[o,t]),s=Hm(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:s}};var zm=e=>e.flatMap(o=>[o[0],o[1]]),ss=(e,o)=>{let t=Ul(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return zm(t)};var fd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[s,n]=useState(null),i=ee(b=>b.toolbar.selectedTool),u=ee(b=>b.toolbar.penColor),l=ee(b=>b.toolbar.strokeWidth),c=ee(b=>b.canvas.isSketchMode),d=ee(b=>b.canvas.slides.find(S=>S.id===b.canvas.currentSlideId)?.images.find(S=>S.id===e)),m=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,x=d?.height||1,p=useCallback(b=>{if(i!=="pen"&&i!=="eraser")return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let y=b.x/h,S=b.y/x;n({tool:i,points:[y,S],color:u,strokeWidth:l/h,isSketch:c});},[i,u,l,c,h,x]),v=useCallback(b=>{if(!t.current||!s)return;a.current=true;let y=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-y.x,2)+Math.pow(b.y-y.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(c)I=ss(r.current,{size:l*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((L,P)=>P%2===0?L/h:L/x);else {let C=b.x/h,L=b.y/x;I=[...s.points,C,L];}n(C=>C?{...C,points:I}:null);},[c,l,s,h,x]),g=useCallback(()=>{t.current&&(s&&s.points.length>0&&o(Mn({imageId:e,line:s})),n(null),t.current=false,a.current=false,r.current=[]);},[o,e,s]);return {annotations:m,activeLine:s,isDrawingMode:f,startDrawing:p,draw:v,stopDrawing:g,tool:i}};var gd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n})=>{let{annotations:i,activeLine:u,stopDrawing:m,tool:f}=fd(e.id);useEffect(()=>{let g=t.current.get(e.id);g&&(g.width()!==e.width||g.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:g.width(),konvaHeight:g.height()}),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let h=false;useEffect(()=>{return;},[m,h]);let x=g=>{{s(e.id);return}},p=g=>{return;},v=g=>{};return jsxs(Group,{listening:f!=="pen"&&f!=="eraser",children:[jsx(Image$1,{id:e.id,ref:g=>{if(g){t.current.set(e.id,g),g.width(e.width),g.height(e.height),g.getLayer()?.batchDraw();let b=g.getStage()?.container();if(b){let y=S=>{let I=g.getStage()?.getPointerPosition();if(I){let C={x:e.x,y:e.y,width:e.width,height:e.height};I.x>=C.x&&I.x<=C.x+C.width&&I.y>=C.y&&I.y<=C.y+C.height&&n(S,e.id,"image");}};b.addEventListener("contextmenu",y),g._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",y);};}}else {let b=t.current.get(e.id);b?._contextMenuCleanup&&b._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:f!=="pen"&&f!=="eraser",onDragEnd:a,onTransformEnd:g=>r(e.id,g),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...f!=="pen"&&f!=="eraser"?{onClick:x,onTap:x,onMouseDown:x,onTouchStart:x,onMouseMove:p,onTouchMove:p,onMouseUp:v,onTouchEnd:v}:{}}),i?.map((g,b)=>{let y=g.points.map((I,C)=>C%2===0?I*e.width+e.x:I*e.height+e.y),S=g.strokeWidth*e.width;return jsx(Line,{points:y,stroke:g.tool==="eraser"?"white":g.color,strokeWidth:S,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:g.tool==="eraser"?"destination-out":"source-over",fill:g.isSketch?g.color:void 0,closed:g.isSketch,listening:false},b)}),u&&jsx(Line,{points:u.points.map((g,b)=>b%2===0?g*e.width+e.x:g*e.height+e.y),stroke:u.tool==="eraser"?"white":u.color,strokeWidth:u.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:u.tool==="eraser"?"destination-out":"source-over",fill:u.isSketch?u.color:void 0,closed:u.isSketch,listening:false},"active")]})});gd.displayName="ImageWithDrawing";var oi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>{let u=o(i);return u?jsx(gd,{img:i,loadedImage:u,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:s,onContextMenu:n},i.id):null})}));oi.displayName="ImageLayer";var Zm=({src:e,x:o,id:t,y:a,width:r,height:s,isSelected:n,rotation:i=0,onTransformEnd:u,onDragEnd:l})=>{let c=xe(),d=useRef(null),m=f=>{c(Fo(f));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:s,rotation:i,onDragEnd:l,onTransformEnd:u,children:[jsx(Rect,{width:r,height:s,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${s}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>m(t),onSeeking:f=>f.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},xd=Zm;var np=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,nodeRef:n})=>{let[i,u]=useState(null),l=useSelector(x=>x.toolbar.selectedTool),c=l==="pen"||l==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let x=new window.Image;x.src=e.thumbnailDataUrl,x.onload=()=>{u(x);};}},[e.thumbnailDataUrl]),!i)return null;let d=e.width/2,m=e.height/2,f=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(f,80));return jsxs(Group,{draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:a,onTransformEnd:r},ref:x=>{if(n(x),x){let p=x.getStage()?.container();if(p){let v=g=>{let b=x.getStage()?.getPointerPosition();if(b){let y={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=y.x&&b.x<=y.x+y.width&&b.y>=y.y&&b.y<=y.y+y.height&&s(g);}};p.addEventListener("contextmenu",v),x._contextMenuCleanup=()=>{p.removeEventListener("contextmenu",v);};}}},children:[jsx(Image$1,{image:i,width:e.width,height:e.height,listening:!c,...c?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:d,y:m,radius:h,fill:"white",listening:!c,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...c?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:m,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!c,...c?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:m,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!c,...c?{}:{onClick:t,onTap:t}})]})},vd=np;var ni=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:s,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>jsxs(be__default.Fragment,{children:[jsx(vd,{video:i,isSelected:!i.isPlaying&&o===i.id,onClick:()=>a(i.id),onDragEnd:u=>r(i.id,u),onTransformEnd:u=>s(i.id,u),onContextMenu:u=>n(u,i.id,"video"),nodeRef:u=>{u?t.current.set(i.id,u):t.current.delete(i.id);}}),i.isPlaying&&(()=>{let u=i.x,l=i.y;if(i.isRecorded){let c=typeof window<"u"?window.innerWidth:i.width,d=typeof window<"u"?window.innerHeight:i.height;u=(c-i.width)/2,l=(d-i.height)/2;}return jsx(xd,{id:i.id,src:i.objectUrl,x:u,y:l,width:i.width,height:i.height,isSelected:false,rotation:i.rotation,onTransformEnd:c=>s(i.id,c),onDragEnd:c=>r(i.id,c)})})()]},i.id))}));ni.displayName="VideoLayer";var ii=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:s,onContextMenu:n})=>{let i=useSelector(l=>l.toolbar.selectedTool),u=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map((l,c)=>{let d=l.id||c,m={id:l.id,x:l.x,y:l.y,rotation:l.rotation,draggable:!l.locked&&!u,listening:!u,fill:l.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(l.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},radius:l.radius||l.width/2,width:l.width,height:l.width},d);case "star":return jsx(Star,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},numPoints:5,innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},d);case "triangle":return jsx(RegularPolygon,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},sides:3,radius:l.radius||l.width/2},d);case "polygon":return jsx(RegularPolygon,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},sides:l.sides||6,radius:l.radius||l.width/2},d);case "ellipse":return jsx(Ellipse,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},radiusX:l.radiusX||l.width/2,radiusY:l.radiusY||l.height/2},d);case "ring":return jsx(Ring,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2},d);case "wedge":return jsx(Wedge,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},radius:l.radius||l.width/2,angle:l.angle||60},d);case "arrow":return jsx(Arrow,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},points:l.points||[0,0,l.width,0],pointerLength:l.pointerLength||10,pointerWidth:l.pointerWidth||10,stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},d);case "line":return jsx(Line,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,scaleX:l.scaleX||1,scaleY:l.scaleY||1,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},points:l.points||[0,0,l.width,0],stroke:"#000000",strokeWidth:l.strokeWidth||3,fill:"transparent"},d);case "arc":return jsx(Arc,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},innerRadius:l.innerRadius||l.width/4,outerRadius:l.outerRadius||l.width/2,angle:l.angle||90},d);case "rectangle":default:return jsx(Rect,{ref:f=>{f?o.current.set(l.id,f):o.current.delete(l.id);},...m,draggable:!l.locked&&!u,...u?{}:{onDragStart:f=>{s?.();},onDragEnd:f=>t(l.id,f),onTransformEnd:f=>a(l.id,f),onClick:()=>r(l.id),onContextMenu:f=>{f.evt.preventDefault(),n(f.evt,l.id,"shape");}},width:l.width,height:l.height,cornerRadius:l.type==="rounded-rectangle"?10:0},d)}})})});ii.displayName="ShapeLayer";var Ld=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:s,onDoubleClick:n,editingTextId:i})=>{let u=useSelector(c=>c.toolbar.selectedTool),l=u==="pen"||u==="eraser";return jsx(Fragment,{children:e.map(c=>{let d=c.id===i,m=c.fontWeight==="bold",f=m?Math.max(1,c.fontSize/25):0;return jsx(Text,{id:c.id,ref:h=>{h?o.current.set(c.id,h):o.current.delete(c.id);},text:c.text,x:c.x,y:c.y,width:c.width,height:c.height,rotation:c.rotation,draggable:!c.locked&&!d&&!l,listening:!l,fontSize:c.fontSize,fontFamily:c.fontFamily,fontStyle:c.fontStyle,fontWeight:c.fontWeight,textDecoration:c.textDecoration,fill:c.fill,stroke:m?c.fill:void 0,strokeWidth:f,align:c.align,wrap:"none",lineHeight:1.2,opacity:d?0:1,visible:!d,...l?{}:{onClick:()=>r(c.id),onTap:()=>r(c.id),onDblClick:()=>n(c.id),onDblTap:()=>n(c.id),onDragEnd:h=>t(h,c.id),onTransformEnd:()=>a(c.id),onContextMenu:h=>{h.evt.preventDefault();let x=h.evt;s(x,c.id,"text");}}},c.id)})})};var Rp=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,onNext:n,onPrevious:i,nodeRef:u})=>{let[l,c]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let p=new window.Image;p.src=e.images[e.currentIndex],p.onload=()=>{c(p);};}},[e.images,e.currentIndex]),!l||e.images.length===0)return null;let d=8,m=2,f=Math.min(e.width,e.height)*.08,h=Math.max(16,Math.min(f,32)),x=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,ref:p=>{if(u(p),p){let v=p.getStage()?.container();if(v){let g=b=>{let y=p.getStage()?.getPointerPosition();if(y){let S={x:e.x,y:e.y,width:e.width,height:e.height};y.x>=S.x&&y.x<=S.x+S.width&&y.y>=S.y&&y.y<=S.y+S.height&&s(b);}};v.addEventListener("contextmenu",g),p._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",g);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:d,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:d,stroke:"#E5E7EB",strokeWidth:m,listening:false}),jsx(Image$1,{x:m+4,y:m+4,image:l,width:e.width-(m+4)*2,height:e.height-(m+4)*2,cornerRadius:d-m,onClick:t,onTap:t}),jsx(Rect,{x:m,y:e.height-50,width:e.width-m*2,height:50,cornerRadius:[0,0,d-m,d-m],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:x+h,y:e.height/2,onClick:p=>{p.cancelBubble=true,i();},onTap:p=>{p.cancelBubble=true,i();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-x-h,y:e.height/2,onClick:p=>{p.cancelBubble=true,n();},onTap:p=>{p.cancelBubble=true,n();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Cd=Rp;var ui=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:s,onNext:n,onPrevious:i,onContextMenu:u})=>jsx(Fragment,{children:e.map(l=>jsx(Cd,{flashcard:l,isSelected:t===l.id,onClick:()=>s(l.id),onDragEnd:a,onTransformEnd:c=>r(l.id,c),onContextMenu:c=>u(c,l.id,"flashcard"),onNext:()=>n(l.id),onPrevious:()=>i(l.id),nodeRef:c=>{c?o.current.set(l.id,c):o.current.delete(l.id);}},l.id))}));ui.displayName="FlashcardLayer";var Md=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[s,n]=useState(null);ee(b=>b.toolbar.selectedTool);let u=ee(b=>b.toolbar.penColor),l=ee(b=>b.toolbar.strokeWidth),c=ee(b=>b.canvas.isSketchMode),d=ee(b=>b.canvas.slides.find(S=>S.id===b.canvas.currentSlideId)?.photoFrames.find(S=>S.id===e)),m=d?.annotations||[],f=d?.isDrawingMode||false,h=d?.width||1,x=d?.height||1,p=useCallback(b=>{if(!f)return;t.current=true,a.current=false,r.current=[{x:b.x,y:b.y}];let y=b.x/h,S=b.y/x;n({tool:"pen",points:[y,S],color:u,strokeWidth:l/h,isSketch:c});},[f,u,l,c,h,x]),v=useCallback(b=>{if(!t.current||!s)return;a.current=true;let y=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-y.x,2)+Math.pow(b.y-y.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(c)I=ss(r.current,{size:l*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((L,P)=>P%2===0?L/h:L/x);else {let C=b.x/h,L=b.y/x;I=[...s.points,C,L];}n(C=>C?{...C,points:I}:null);},[c,l,s,h,x]),g=useCallback(()=>{t.current&&(s&&s.points.length>0&&o(An({frameId:e,line:s})),n(null),t.current=false,a.current=false,r.current=[]);},[o,e,s]);return {annotations:m,activeLine:s,isDrawingMode:f,startDrawing:p,draw:v,stopDrawing:g}};var Hp=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:s,onStartCamera:n,onCapture:i,cameraStream:u,nodeRef:l})=>{let[c,d]=useState(null),[m,f]=useState(null),h=useRef(null),x=useRef(null),p=useRef(null),v=useRef(null),g=useRef(0),b=33,y=useSelector(R=>R.toolbar.selectedTool),S=y==="pen"||y==="eraser",{annotations:I,activeLine:C,isDrawingMode:L,startDrawing:P,draw:A,stopDrawing:H}=Md(e.id);useEffect(()=>{if(!L)return;let R=()=>{H();},z=()=>{H();};return window.addEventListener("mouseup",R),window.addEventListener("touchend",z),()=>{window.removeEventListener("mouseup",R),window.removeEventListener("touchend",z);}},[H,L]),useEffect(()=>{if(e.capturedImageUrl){let R=new window.Image;R.src=e.capturedImageUrl,R.onload=()=>{d(R);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&u){h.current||(h.current=document.createElement("video"),h.current.autoplay=true,h.current.playsInline=true),x.current||(x.current=document.createElement("canvas"));let R=h.current,z=x.current;R.srcObject=u;let X=()=>{z.width=R.videoWidth||640,z.height=R.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",z.width,z.height);let _=Y=>{if(Y-g.current<b){p.current=requestAnimationFrame(_);return}g.current=Y;let Z=z.getContext("2d");if(Z&&R.readyState===R.HAVE_ENOUGH_DATA){Z.drawImage(R,0,0,z.width,z.height);let Q=z.toDataURL("image/jpeg",.6),pe=new window.Image;pe.onload=()=>{f(pe);},pe.src=Q;}p.current=requestAnimationFrame(_);};p.current=requestAnimationFrame(_);};return R.onloadedmetadata=X,R.readyState>=R.HAVE_METADATA&&X(),R.play().catch(_=>console.error("Error playing video:",_)),()=>{p.current&&(cancelAnimationFrame(p.current),p.current=null);}}return ()=>{f(null),v.current&&(v.current.src="");}},[e.isCapturing,u]);let F=()=>{h.current&&e.isCapturing&&i(h.current);},E=R=>{if(e.capturedImageUrl){if(!L){t();return}let z=R.currentTarget,X=z.getAbsoluteTransform().copy(),Y=z.getStage()?.getPointerPosition();if(Y){X.invert();let Z=X.point(Y);P(Z);}R.cancelBubble=true;}else t();},D=R=>{if(!L||!e.capturedImageUrl)return;let z=R.currentTarget,X=z.getAbsoluteTransform().copy(),Y=z.getStage()?.getPointerPosition();if(Y){X.invert();let Z=X.point(Y);A(Z);}},U=()=>{!L||!e.capturedImageUrl||H();},N=e.isCapturing?m:c,te=Math.min(e.width,e.height)*.12,q=Math.max(25,Math.min(te,50)),G=e.width/2,oe=e.height/2;return jsxs(Group,{id:e.id,draggable:!L&&!S,listening:true,x:e.x,y:e.y,...S?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:R=>{if(l(R),R){let z=R.getStage()?.container();if(z){let X=_=>{let Y=R.getStage()?.getPointerPosition();if(Y){let Z={x:e.x,y:e.y,width:e.width,height:e.height};Y.x>=Z.x&&Y.x<=Z.x+Z.width&&Y.y>=Z.y&&Y.y<=Z.y+Z.height&&s(_);}};z.addEventListener("contextmenu",X),R._contextMenuCleanup=()=>{z.removeEventListener("contextmenu",X);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:N?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),N&&jsx(Image$1,{image:N,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:E,onTap:E,onMouseDown:E,onTouchStart:E,onMouseMove:D,onTouchMove:D,onMouseUp:U,onTouchEnd:U,...S?{}:{onDragEnd:a,onTransformEnd:r}}),I?.map((R,z)=>{let X=R.points.map((Y,Z)=>Z%2===0?Y*e.width:Y*e.height),_=R.strokeWidth*e.width;return jsx(Line,{points:X,stroke:R.tool==="eraser"?"white":R.color,strokeWidth:_,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:R.tool==="eraser"?"destination-out":"source-over",fill:R.isSketch?R.color:void 0,closed:R.isSketch,listening:false},z)}),C&&jsx(Line,{points:C.points.map((R,z)=>z%2===0?R*e.width:R*e.height),stroke:C.tool==="eraser"?"white":C.color,strokeWidth:C.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:C.tool==="eraser"?"destination-out":"source-over",fill:C.isSketch?C.color:void 0,closed:C.isSketch,listening:false},"active"),!N&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:oe-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:G-q+6,y:oe-60,width:q*1.6,height:q*1.6,radius:q,fill:"white",cornerRadius:8,listening:true,onClick:R=>{R.cancelBubble=true,e.isCapturing?F():n();},onTap:R=>{R.cancelBubble=true,e.isCapturing?F():n();}}),jsx(Html,{groupProps:{x:G-12,y:oe-40,width:q*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:R=>{R.stopPropagation(),e.isCapturing?F():n();}})})]}),jsx(Text,{x:0,y:oe,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:oe+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:G-24,y:oe+104,width:q*1.6,height:q*1.6,radius:q,fill:"#096B76",cornerRadius:q,listening:true,onClick:R=>{R.cancelBubble=true,e.isCapturing?F():n();},onTap:R=>{R.cancelBubble=true,e.isCapturing?F():n();}}),jsx(Html,{groupProps:{x:G-8,y:oe+120,width:q*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:R=>{R.stopPropagation(),e.isCapturing?F():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"})]})]})},Rd=Hp;var hi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:s,onStartCamera:n,onCapture:i,cameraStreams:u,onContextMenu:l})=>jsx(Fragment,{children:e.map(c=>jsx(Rd,{photoFrame:c,isSelected:t===c.id,onClick:()=>s(c.id),onDragEnd:d=>a(d,c.id),onTransformEnd:d=>r(c.id,d),onContextMenu:d=>l(d,c.id,"photoFrame"),onStartCamera:()=>n(c.id),onCapture:d=>i(c.id,d),cameraStream:u.get(c.id),nodeRef:d=>{d?o.current.set(c.id,d):o.current.delete(c.id);}},c.id))}));hi.displayName="PhotoFrameLayer";var Bd=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:s="",isDrawingMode:n,menuRef:i})=>{useEffect(()=>{let d=f=>{i?.current&&!i.current.contains(f.target)&&a();},m=f=>{f.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",m);}},[a]);let u=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(m=>!(m.showForTypes&&!m.showForTypes.includes(r)||m.hideForTypes&&m.hideForTypes.includes(r))),[r,n]),l=(d,m)=>{d==="order"||d==="lock"?t(d,m):(t(d),a());},c=jsx("div",{ref:i,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:u.map((d,m)=>jsxs("button",{onClick:f=>l(d.action,f),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},m))})});return createPortal(c,document.body)};var Od=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let s=n=>{r.current&&!r.current.contains(n.target)&&a();};return document.addEventListener("mousedown",s),()=>{document.removeEventListener("mousedown",s);}},[a]),jsx("div",{ref:r,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((s,n)=>jsx("button",{onClick:()=>{s.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:s.label})},n))})})};var Nd=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:s})=>{let[n,i]=useState(a),u=useRef(null);useEffect(()=>{u.current?.focus();},[]);let l=()=>{r(n),s();};return jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:s,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:u,type:"text",value:n,onChange:d=>i(d.target.value),onKeyDown:d=>{d.key==="Enter"?l():d.key==="Escape"&&s();},placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:s,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:l,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})})};var Vd=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),s=useRef(null);useEffect(()=>{let c=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]);let n=c=>{c.preventDefault(),o(a);},i=(c,d,m)=>{m/=100;let f=d*Math.min(m,1-m)/100,h=x=>{let p=(x+c/30)%12,v=m-f*Math.max(Math.min(p-3,9-p,1),-1);return Math.round(255*v).toString(16).padStart(2,"0")};return `#${h(0)}${h(8)}${h(4)}`},l=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:c=>c.stopPropagation(),onMouseUp:c=>c.stopPropagation(),onMouseMove:c=>c.stopPropagation(),onTouchStart:c=>c.stopPropagation(),onTouchMove:c=>c.stopPropagation(),onTouchEnd:c=>c.stopPropagation(),children:jsxs("div",{ref:s,className:"pointer-events-auto max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:c=>c.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Shape Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:n,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:c=>r(c.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:c=>r(c.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:c=>{let d=parseInt(c.target.value),m=i(d,100,50);r(m);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"].map(c=>jsx("button",{type:"button",onClick:()=>r(c),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===c.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:c},title:c},c))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(l,document.body)};var Sh=({imageSrc:e,onCrop:o})=>{let[t]=Ud(e),a=useRef(null),r=useRef(null),s=useRef(null),n=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),i=useMemo(()=>{let m=n.width*.5,f=n.height*.5,h=(n.width-m)/2,x=(n.height-f)/2;return {x:h,y:x,width:m,height:f}},[n]),[u,l]=useState(i);useEffect(()=>{l(i);},[i]),useEffect(()=>{s.current&&r.current&&(s.current.nodes([r.current]),s.current.getLayer()?.batchDraw());},[u]),useEffect(()=>{o(u.x,u.y,u.width,u.height);},[u,o]);let c=()=>{let m=r.current;if(!m)return;let f=m.scaleX(),h=m.scaleY();m.scaleX(1),m.scaleY(1),l({x:m.x(),y:m.y(),width:Math.max(20,m.width()*f),height:Math.max(20,m.height()*h)});},d=()=>{let m=r.current;m&&l({x:m.x(),y:m.y(),width:m.width(),height:m.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:u.x,y:u.y,width:u.width,height:u.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:u.x,y:u.y,width:u.width,height:u.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:c,dragBoundFunc:m=>{let f=Math.max(0,Math.min(m.x,n.width-u.width)),h=Math.max(0,Math.min(m.y,n.height-u.height));return {x:f,y:h}}}),jsx(Transformer,{ref:s,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(m,f)=>f.width<20||f.height<20||f.x<0||f.y<0||f.x+f.width>n.width||f.y+f.height>n.height?m:f})]})})},zd=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,s]=useState({x:0,y:0,width:0,height:0}),[n]=Ud(e);return useEffect(()=>{let c=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:c=>c.stopPropagation(),onMouseUp:c=>c.stopPropagation(),onMouseMove:c=>c.stopPropagation(),onTouchStart:c=>c.stopPropagation(),onTouchMove:c=>c.stopPropagation(),onTouchEnd:c=>c.stopPropagation(),children:jsxs("div",{ref:a,className:"pointer-events-auto max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:c=>c.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(Sh,{imageSrc:e,onCrop:(c,d,m,f)=>{s({x:c,y:d,width:m,height:f});}})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:()=>{if(!n)return;let m=Math.min(600/n.width,400/n.height),f=r.x/m,h=r.y/m,x=r.width/m,p=r.height/m,v=document.createElement("canvas");v.width=x,v.height=p;let g=v.getContext("2d");if(!g)return;g.drawImage(n,f,h,x,p,0,0,x,p);let b=v.toDataURL("image/png");o(b);},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),document.body)};var Yo=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,s]=useState(false),[n,i]=useState(null),[u,l]=useState(0),[c,d]=useState(true),m=useRef(null),f=useRef([]),h=useRef(null),x=useRef(null),p=useRef(null),v=useRef(null),g=useRef(null),b=useRef(null);useEffect(()=>()=>{p.current&&cancelAnimationFrame(p.current),h.current&&clearInterval(h.current),x.current&&x.current.getTracks().forEach(L=>L.stop());},[]);let y=async()=>{try{let L,P=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let D=o.current.getLayers();console.log("Konva layers:",D.length),D.forEach((z,X)=>{let _=z.getChildren();console.log(`Layer ${X} children count:`,_.length);});let U=document.createElement("canvas");U.width=o.current.width(),U.height=o.current.height();let N=U.getContext("2d",{willReadFrequently:!1});if(!N){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",U.width,"x",U.height),g.current=U;let te=()=>{if(N.clearRect(0,0,U.width,U.height),D.forEach(z=>{let X=z.getCanvas()._canvas;X&&N.drawImage(X,0,0);}),a?.current){let z=a.current;N.drawImage(z,0,0);}};b.current=te,o.current.draw(),te(),await new Promise(z=>setTimeout(z,100)),console.log("Creating captureStream..."),L=U.captureStream(30),console.log("Canvas stream created, tracks:",L.getTracks().length);let G=L.getVideoTracks()[0];G&&console.log("Video track:",G.label,"state:",G.readyState);let oe=0,R=()=>{te(),o?.current&&(o.current.getLayers().forEach(X=>{X.batchDraw();}),oe++,oe%60===0&&console.log("Drawing frame:",oe)),p.current=requestAnimationFrame(R);};R();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(c)try{P=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(D){console.warn("Microphone access denied:",D);}let A=[...L.getVideoTracks()];P&&A.push(...P.getAudioTracks());let H=new MediaStream(A);x.current=H;let F="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?F="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?F="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?F="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(F="video/webm;codecs=vp8"),console.log("Using mimeType:",F);let E=new MediaRecorder(H,{mimeType:F,videoBitsPerSecond:25e5});m.current=E,f.current=[],E.ondataavailable=D=>{console.log("Data available, size:",D.data.size),D.data.size>0&&f.current.push(D.data);},E.onstop=()=>{console.log("Recording stopped, chunks:",f.current.length);let D=new Blob(f.current,{type:F});console.log("Final blob size:",D.size),o?.current&&b.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(N=>{N.batchDraw();}),b.current(),v.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",v.current.length)),H.getTracks().forEach(U=>U.stop()),h.current&&clearInterval(h.current),p.current&&(cancelAnimationFrame(p.current),p.current=null),i(D);},E.onerror=D=>{console.error("MediaRecorder error:",D);},console.log("Starting recording..."),E.start(1e3),s(!0),l(0),h.current=setInterval(()=>{l(D=>D+1);},1e3);}catch(L){console.error("Error starting screen recording:",L),alert("Failed to start recording. Please ensure you granted permission.");}},S=()=>{m.current&&r&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),s(false));},I=()=>{if(n){let L=URL.createObjectURL(n),P=document.createElement("a");P.href=L,P.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(L);}},C=L=>{let P=Math.floor(L/60),A=L%60;return `${P.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:C(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:S,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!n&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>d(!c),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${c?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:c?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:y,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),n&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(n),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",C(u)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&n&&v.current&&(t(n,v.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{i(null),l(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})})};var Gd=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[s,n]=useState(false),[i,u]=useState(null),[l,c]=useState(false),[d,m]=useState(0),f=useRef(null),h=useRef([]),x=useRef(null),p=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(L=>L.blob()).then(L=>u(L)).catch(L=>console.error("Error loading audio:",L));},[o,i]);let v=async()=>{try{let L=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),P=new MediaRecorder(L);f.current=P,h.current=[],P.ondataavailable=A=>{A.data.size>0&&h.current.push(A.data);},P.onstop=()=>{let A=new Blob(h.current,{type:"audio/webm"});u(A),L.getTracks().forEach(H=>H.stop()),x.current&&clearInterval(x.current);},P.start(),n(!0),m(0),x.current=setInterval(()=>{m(A=>A+1);},1e3);}catch(L){console.error("Error starting audio recording:",L),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{f.current&&s&&(f.current.stop(),n(false));},b=()=>{if(i){let L=URL.createObjectURL(i),P=new Audio(L);p.current=P,P.onended=()=>{c(false),URL.revokeObjectURL(L);},P.play(),c(true);}},y=()=>{p.current&&(p.current.pause(),p.current.currentTime=0,c(false));},S=async()=>{if(i){let L=new FileReader;L.onloadend=()=>{let P=L.result;t(P),r();},L.readAsDataURL(i);}},I=()=>{u(null),a();},C=L=>{let P=Math.floor(L/60),A=L%60;return `${P.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`};return s?jsxs("div",{className:"fixed top-4 left-1/2 z-103 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:C(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-103 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:v,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:l?y:b,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),l?"Playing...":"Play Audio"]}),jsx("button",{onClick:I,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:S,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})})};var St=({audioData:e,x:o,y:t,width:a})=>{let[r,s]=useState(false),n=useRef(null);return jsx("button",{onClick:u=>{if(u.stopPropagation(),r&&n.current)n.current.pause(),n.current.currentTime=0,s(false);else {let l=new Audio(e);n.current=l,l.onended=()=>{s(false);},l.onerror=()=>{console.error("Error playing audio"),s(false);},l.play(),s(true);}},className:`absolute flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${r?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${o+a-35}px`,top:`${t+5}px`,width:"30px",height:"30px",zIndex:99},title:r?"Stop Audio":"Play Audio",children:r?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var jd=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=ee(ge),s=useMemo(()=>{if(!r)return [];let x=[];return r.images?.forEach(p=>{x.push({id:p.id,type:"image",name:"Image",timestamp:p.timestamp||0});}),r.videos?.forEach(p=>{x.push({id:p.id,type:"video",name:"Video",timestamp:p.timestamp||0});}),r.shapes?.forEach(p=>{x.push({id:p.id,type:"shape",name:`${p.type} Shape`,timestamp:p.timestamp||0});}),r.texts?.forEach(p=>{x.push({id:p.id,type:"text",name:p.text.substring(0,20)+(p.text.length>20?"...":""),timestamp:p.timestamp||0});}),r.flashcards?.forEach(p=>{x.push({id:p.id,type:"flashcard",name:`Flashcard (${p.images.length} images)`,timestamp:p.timestamp||0});}),r.photoFrames?.forEach(p=>{x.push({id:p.id,type:"photoFrame",name:"Photo Frame",timestamp:p.timestamp||0});}),r.multipleChoices?.forEach(p=>{x.push({id:p.id,type:"mcq",name:"Multiple Choice",timestamp:p.timestamp||0});}),r.trueFalses?.forEach(p=>{x.push({id:p.id,type:"trueFalse",name:"True/False",timestamp:p.timestamp||0});}),r.shortAnswers?.forEach(p=>{x.push({id:p.id,type:"shortAnswer",name:"Short Answer",timestamp:p.timestamp||0});}),r.LongAnswer?.forEach(p=>{x.push({id:p.id,type:"longAnswer",name:"Long Answer",timestamp:p.timestamp||0});}),r.fillInTheBlanks?.forEach(p=>{x.push({id:p.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:p.timestamp||0});}),r.lines?.forEach(p=>{p.id&&x.push({id:p.id,type:"line",name:"Drawn Line",timestamp:p.timestamp||0});}),x.sort((p,v)=>v.timestamp-p.timestamp)},[r]),[n,i]=useState(s),[u,l]=useState(false);useEffect(()=>{u||i(s);},[s]);let c=x=>{let p="h-5 w-5";switch(x){case "image":return jsx(Image$3,{className:p});case "video":return jsx(VideoCamera,{className:p});case "shape":return jsx(Shapes$1,{className:p});case "text":return jsx(TextT,{className:p});case "flashcard":return jsx(Cards$1,{className:p});case "photoFrame":return jsx(FrameCorners,{className:p});case "line":return jsx("span",{className:p,children:"\u270F\uFE0F"});default:return jsx(Question,{className:p})}},d=x=>{if(x===0)return;let p=n[x],v=n[x-1];a(qo({id:p.id,type:p.type,newTimestamp:v.timestamp+1}));},m=x=>{if(x===n.length-1)return;let p=n[x],v=n[x+1];a(qo({id:p.id,type:p.type,newTimestamp:v.timestamp-1}));},f=x=>{l(true),i(x);},h=()=>{l(false);let x=Date.now();n.forEach((p,v)=>{let g=x-v;a(qo({id:p.id,type:p.type,newTimestamp:g}));});};return jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-gray-200 bg-white shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 p-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Stack$1,{className:"h-5 w-5 text-gray-700",weight:"bold"}),jsx("h3",{className:"font-semibold text-gray-900",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto p-2",children:n.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:n,onReorder:f,className:"space-y-1",children:n.map((x,p)=>{let v=x.id===e;return jsxs(Reorder.Item,{value:x,onDragEnd:h,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${v?"border border-blue-200 bg-blue-50":"border border-transparent hover:bg-gray-50"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-4 w-4",weight:"bold"})}),jsxs("div",{onClick:()=>t(x.id,x.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${v?"text-blue-600":"text-gray-600"}`,children:c(x.type)}),jsx("span",{className:`text-sm ${v?"font-medium text-blue-900":"text-gray-700"}`,children:x.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:g=>{g.stopPropagation(),d(p);},disabled:p===0,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move up (forward)",children:jsx(ArrowUp,{className:"h-4 w-4"})}),jsx("button",{onClick:g=>{g.stopPropagation(),m(p);},disabled:p===n.length-1,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move down (backward)",children:jsx(ArrowDown,{className:"h-4 w-4"})})]})]},x.id)})})}),jsx("div",{className:"border-t border-gray-200 p-3 text-xs text-gray-500",children:jsx("p",{children:"Drag to reorder \u2022 Top layers appear above bottom layers"})})]})]})};var $d=memo(({multipleChoice:e,handleMcqTransform:o,mcqRefs:t,handleDragEnd:a,onContextMenu:r})=>{let s=useSelector(G=>G.toolbar.selectedTool),n=s==="pen"||s==="eraser",[i,u]=useState(new Set),[l,c]=useState(false),[d,m]=useState(null),f=useRef(null);useEffect(()=>{let G=f.current;if(G)return t.current.set(e.id,G),()=>{t.current.delete(e.id);}},[e.id]);let h=new Set(e.data.responseOptions.correctIndex),x=h.size>1,p=G=>{l||u(x?oe=>{let R=new Set(oe);return R.has(G)?R.delete(G):R.add(G),R}:new Set([G]));},v=()=>{i.size>0&&c(true);},g=()=>{c(false),u(new Set);},b=i.size===h.size&&Array.from(i).every(G=>h.has(G)),y=Array.from(i).filter(G=>h.has(G)),S=x&&y.length>0&&!b,I=()=>b?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${y.length}/${h.size})`:"\u2717 Try again!",C=()=>b?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},L=55,P=8,A=24,H=60,F=60,E=x&&!l?25:0,D=e.data.feedbackMode==="practice"?48:0,U=12,N=H+E+(l?F:0),te=e.data.responseOptions.options.length*(L+P),q=N+te+U+D+A;return jsxs(Group,{ref:f,name:"mcq-element",draggable:!n,listening:!n,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...n?{}:{onDragEnd:a,onContextMenu:G=>{let oe=f.current?.getStage()?.getPointerPosition();if(oe){let R={x:e.x,y:e.y,width:e.width,height:e.height};if(oe.x>=R.x&&oe.x<=R.x+R.width&&oe.y>=R.y&&oe.y<=R.y+R.height){let z=G.evt;r(z,e.id,"mcq");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:q,width:e.width,onTransformEnd:G=>o(e.id,G)}),jsx(Text,{x:A+8,y:A,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-A*2,listening:false}),x&&!l&&e.data.feedbackMode==="practice"?jsx(Text,{x:A,y:A+35,text:`Select ${h.size} answers (${i.size}/${h.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-A*2,listening:false}):null,l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:A+24,y:H+E,width:e.width-A*2-40,height:F-20,fill:C().bg,cornerRadius:8}),jsx(Text,{x:A,y:H+E,width:e.width-A*2,height:F-20,text:I(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,oe)=>{let R=h.has(oe),z=i.has(oe),X=N+oe*(L+P),_="#e5e7eb",Y="#ffffff",Z="#111827";return l&&R?(_="#22c55e",Y="#dcfce7",Z="#1B9D2C"):l&&z&&!R?(_="#ef4444",Y="#fee2e2",Z="#ef4444"):z&&(_="#096B76",Y="#ECFFF8",Z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:A+12,y:X+(L-20)/2,width:20,height:20,fill:z?"#096B76":"white",stroke:z?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:x?4:10,listening:false}),z&&jsx(Text,{x:A+12,y:X+(L-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:A+44,y:X,width:e.width-A*2-60,height:L,fill:Y,stroke:_,strokeWidth:2,cornerRadius:8,onClick:Q=>{Q.cancelBubble=true,p(oe);},onTap:Q=>{Q.cancelBubble=true,p(oe);}}),jsx(Text,{x:A+60,y:X,width:e.width-A*2-80,height:L,text:G,fontSize:16,fill:Z,verticalAlign:"middle",listening:false})]},oe)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:N+e.data.responseOptions.options.length*(L+P)+12,children:[jsxs(Group,{onMouseDown:G=>{G.cancelBubble=true,m("check");},onMouseUp:G=>{G.cancelBubble=true,m(null),v();},onMouseLeave:G=>{G.cancelBubble=true,m(null);},onTouchStart:G=>{G.cancelBubble=true,m("check");},onTouchEnd:G=>{G.cancelBubble=true,m(null),v();},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:A+14,width:(e.width-A*2-24)/(l?2:1),height:48,fill:i.size===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:A+14,width:(e.width-A*2-24)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-A*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),g();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),g();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:A,width:(e.width-A*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:A,width:(e.width-A*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});$d.displayName="MultipleChoice";var Xd=$d;var vi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t})=>{let a=useDispatch(),r=useSelector(R=>R.toolbar.selectedTool),s=r==="pen"||r==="eraser",[n,i]=useState(false),[u,l]=useState(new Set),[c,d]=useState(false),[m,f]=useState(false),[h,x]=useState(0),p=340,v=100,g=window.innerWidth*.4,b=window.innerHeight*.5,y=p+20,S=v+60,I=g-40,C=b-300,L=useRef(null),P=R=>{a(aa({id:e.id,x:R.target.x(),y:R.target.y()}));},A=R=>{let z=R.target,X=z.x(),_=z.y(),Y=window.innerWidth*.2,Q=X+Y>y&&X<y+I&&_+50>S&&_<S+C;i(Q);},H=(R,z)=>{let X=z.target,_=X.x(),Y=X.y(),Z=window.innerWidth*.2,pe=_+Z>y&&_<y+I&&Y+50>S&&Y<S+C;l(pe?we=>new Set(we).add(R):we=>{let Re=new Set(we);return Re.delete(R),Re}),i(false);},F=()=>{d(true);},E=()=>{d(false),l(new Set),x(R=>R+1);},D=new Set(e.data.responseOptions.correctIndex),U=u.size===D.size&&Array.from(u).every(R=>D.has(R)),N=Array.from(u).filter(R=>D.has(R)),te=N.length>0&&!U,q=()=>U?"\u2713 Correct! Great job!":te?`\u26A0 Partially correct (${N.length}/${D.size})`:"\u2717 Try again!",G=()=>U?{bg:"#dcfce7",text:"#166534"}:te?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},oe=()=>c?U?"#4CAF50":te?"#f59e0b":"#ef4444":n?"#4CAF50":"#075560";return jsxs(Group,{ref:L,name:"mcq-element",width:g,height:b,draggable:!s,listening:!s,...s?{}:{onContextMenu:R=>{R.evt.preventDefault(),o(R.evt,e.id,"mcq");}},children:[jsxs(Group,{x:p,y:v,rotation:e.rotation,onDragEnd:P,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?b-100:b-50,width:g,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:g-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:I,height:C,fill:"#EBF6F7",stroke:oe(),strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:C+18,width:I-5,height:60,fill:G().bg,cornerRadius:8}),jsx(Text,{x:20,y:C+20,width:I,height:60,text:q(),fontSize:18,fontStyle:"bold",fill:G().text,align:"center",verticalAlign:"middle"})]}),u.size===0&&!c&&jsx(Text,{x:20,y:60,width:I,height:C-60,text:D.size>1?`Drop ${D.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:c?b-200:b-160,children:[jsxs(Group,{onMouseDown:()=>{f(true),F();},onMouseUp:()=>f(false),onMouseLeave:()=>f(false),onTouchStart:()=>{f(true),F();},onTouchEnd:()=>f(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((R,z)=>{let X=z%2,_=Math.floor(z/2),Y=window.innerWidth*.2,Z=50,Q=10,pe=u.has(z),we=D.has(z),Re=c&&pe,Me="transparent";return Re?Me=we?"#4CAF50":"#ef4444":pe&&(Me="#4CAF50"),jsxs(Group,{x:340+X*(Y+Q),y:v+b-80+_*(Z+Q),draggable:!c,onDragMove:A,onDragEnd:He=>H(z,He),opacity:c&&!pe?.5:1,children:[jsx(Rect,{width:Y-20,height:Z,fill:"white",stroke:Me,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Y-20,height:Z,text:R,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${z}-${h}`)})]})};vi.displayName="MultipleChoiceDragAndDrop";var Yd=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Xd,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:i=>r(i,n.id),onContextMenu:s},n.id):jsx(vi,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:s},n.id))});var Jd=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(N=>N.toolbar.selectedTool),i=n==="pen"||n==="eraser",[u,l]=useState(null),[c,d]=useState(false),[m,f]=useState(null),h=useRef(null);useEffect(()=>{let N=h.current;if(N)return a.current.set(e.id,N),()=>{a.current.delete(e.id);}},[e.id]);let x=()=>{u!==null&&d(true);},p=()=>{d(false),l(null);},v=e.data.responseOptions.correctAnswer,g=u===v,b=N=>{c||l(N);},y=()=>g?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",S=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=70,C=12,L=24,P=60,A=60,H=e.data.feedbackMode==="practice"?48:0,F=12,E=P+(c?A:0),D=2*(I+C),U=E+D+F+H+L;return jsxs(Group,{ref:h,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:N=>s(N,e.id),onClick:N=>t(e.id),onTap:N=>t(e.id),onContextMenu:N=>{let te=h.current?.getStage()?.getPointerPosition();if(te){let q={x:e.x,y:e.y,width:e.width,height:e.height};if(te.x>=q.x&&te.x<=q.x+q.width&&te.y>=q.y&&te.y<=q.y+q.height){let G=N.evt;r(G,e.id,"trueFalse");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:U-20,width:e.width,onTransformEnd:N=>o(e.id,N)}),jsx(Text,{x:L,y:L,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),c&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:L,y:P,width:e.width-L*2,height:A-10,fill:S().bg,cornerRadius:8}),jsx(Text,{x:L,y:P,width:e.width-L*2,height:A-10,text:y(),fontSize:16,fontStyle:"bold",fill:S().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((N,te)=>{let q=v===N.value,G=u===N.value,oe=(e.width-L*3)/2,R=L+te*(oe+L),z=E,X=N.value===true,_=X?"#10b981":"#ef4444",Y="#ffffff",Z="#ffffff",Q="#e5e7eb";return c&&(q?(Z=X?"#f0fdf4":"#fef2f2",Q=X?"#86efac":"#fecaca"):G&&!q&&(Z="#fee2e2",Q="#ef4444")),G&&!c&&(Q="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:R,y:z,width:oe,height:I+50,fill:Z,stroke:Q,strokeWidth:2,cornerRadius:12,onClick:pe=>{pe.cancelBubble=true,b(N.value);},onTap:pe=>{pe.cancelBubble=true,b(N.value);}}),jsx(Circle,{x:R+oe/2,y:z+40,radius:28,fill:_,listening:false}),X?jsx(Text,{x:R+oe/2-14,y:z+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:R+oe/2-14,y:z+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:R,y:z+85,width:oe,height:30,text:N.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},N.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:E+2*(I+C),children:[jsxs(Group,{onMouseDown:N=>{N.cancelBubble=true,f("check");},onMouseUp:N=>{N.cancelBubble=true,f(null),x();},onMouseLeave:N=>{N.cancelBubble=true,f(null);},onTouchStart:N=>{N.cancelBubble=true,f("check");},onTouchEnd:N=>{N.cancelBubble=true,f(null),x();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(c?2:1),height:48,fill:u===null||c?"#9ca3af":"#096B76",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(c?2:1),height:48,text:c?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>f("reset"),onMouseUp:()=>{f(null),p();},onMouseLeave:()=>f(null),onTouchStart:()=>f("reset"),onTouchEnd:()=>{f(null),p();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Jd.displayName="TrueFalse";var Zd=Jd;var yg="#FFFFFF",Li=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(_=>_.toolbar.selectedTool),s=r==="pen"||r==="eraser",[n,i]=useState(false),[u,l]=useState(null),[c,d]=useState(false),[m,f]=useState(false),[h,x]=useState(0),[p,v]=useState(false),g=340,b=100,y=window.innerWidth*.4,S=window.innerHeight*.5,I=y-40,C=S-300,L=20,P=60,A=I,H=C,F=y*.2-40,E=50,D=useRef(null),U=_=>{a(oa({id:e.id,x:_.target.x(),y:_.target.y()}));},N=_=>{let Y=_.target,Z=Y.x(),Q=Y.y(),pe=Math.max(0,Math.min(Z+F,L+A)-Math.max(Z,L)),we=Math.max(0,Math.min(Q+E,P+H)-Math.max(Q,P)),Re=pe*we,Me=F*E;i(Re/Me>=.5);},te=(_,Y)=>{let Z=Y.target,Q=Z.x(),pe=Z.y(),we=Math.max(0,Math.min(Q+F,L+A)-Math.max(Q,L)),Re=Math.max(0,Math.min(pe+E,P+H)-Math.max(pe,P)),Me=we*Re,He=F*E;if(Me/He>=.5)l(_);else return;i(false);},q=()=>{d(true);},G=()=>{d(false),l(null),x(_=>_+1);},oe=e.data.responseOptions.correctAnswer,R=u===oe,z=()=>R?"\u2713 Correct! Great job!":"\u2717 Try again!",X=()=>R?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:D,name:"trueFalse-element",width:y,height:S,draggable:!s,listening:!s,...s?{}:{onContextMenu:_=>{_.evt.preventDefault(),o(_.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:g,y:b,rotation:e.rotation,onDragEnd:U,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:c?S:e.data.feedbackMode==="practice"?S-50:S-100,width:y,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:y-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:I,height:C,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:I,height:60,fill:X().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:I,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:X().text,align:"center",verticalAlign:"middle"})]}),u===null&&!c&&jsx(Text,{x:20,y:60,width:I,height:C-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:S-100,children:[jsxs(Group,{onMouseDown:()=>{u!==null&&(f(true),q());},onMouseUp:()=>f(false),onMouseLeave:()=>f(false),onTouchStart:()=>{u!==null&&(f(true),q());},onTouchEnd:()=>f(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:u===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:G,onTouchStart:G,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((_,Y)=>{let Z=window.innerWidth*.2,Q=50,pe=10,we=u===_.value,Re=oe===_.value,Me=c&&we,He="transparent";return Me?He=Re?"#4CAF50":"#ef4444":we&&(He="#4CAF50"),jsxs(Group,{x:16+Y*(Z+pe),y:b+S-300,draggable:!c,onDragMove:N,onDragEnd:re=>te(_.value,re),opacity:c&&!we?.5:1,children:[jsx(Rect,{width:Z-40,height:Q,fill:"#075560",stroke:He,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:Q,text:_.label,fontSize:18,fontStyle:"bold",fill:yg,align:"center",verticalAlign:"middle",listening:false})]},`${_.value}-${h}`)})]})})};Li.displayName="TrueFalseDragAndDrop";var Qd=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:s})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Zd,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r},n.id):jsx(Li,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s},n.id))});var la=new WeakMap,uo=new WeakMap,ar={current:[]},Ii=false,tr=0,er=new Set,gs=new Map;function eu(e){let o=Array.from(e).sort((t,a)=>t instanceof Ft&&t.options.deps.includes(a)?1:a instanceof Ft&&a.options.deps.includes(t)?-1:0);for(let t of o){if(ar.current.includes(t))continue;ar.current.push(t),t.recompute();let a=uo.get(t);if(a)for(let r of a){let s=la.get(r);s&&eu(s);}}}function Sg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Ig(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function xs(e){if(tr>0&&!gs.has(e)&&gs.set(e,e.prevState),er.add(e),!(tr>0)&&!Ii)try{for(Ii=!0;er.size>0;){let o=Array.from(er);er.clear();for(let t of o){let a=gs.get(t)??t.prevState;t.prevState=a,Sg(t);}for(let t of o){let a=la.get(t);a&&(ar.current.push(t),eu(a));}for(let t of o){let a=la.get(t);if(a)for(let r of a)Ig(r);}}}finally{Ii=false,ar.current=[],gs.clear();}}function ft(e){tr++;try{e();}finally{if(tr--,tr===0){let o=er.values().next().value;o&&xs(o);}}}function tu(e){return typeof e=="function"}var zt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,s;this.listeners.add(a);let n=(s=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:s.call(r,a,this);return ()=>{this.listeners.delete(a),n?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,r;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):tu(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),xs(this);}};var Ft=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let s=0;s<t;s++){let n=this.options.deps[s];a[s]=n.prevState,r[s]=n.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let s of this.options.deps)s instanceof e&&s.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let s=0;s<r.length;s++)if(r[s]!==a[s]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,r;this.listeners.add(t);let s=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),s?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof zt){let a=la.get(t);a||(a=new Set,la.set(t,a)),a.add(this);let r=uo.get(this);r||(r=new Set,uo.set(this,r)),r.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof zt){let a=la.get(t);a&&a.delete(this);let r=uo.get(this);r&&r.delete(t);}}};function Cg(e){return typeof e=="function"}function Ci(e,...o){return Cg(e)?e(...o):e}function au(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var da,rt,et,or,ua,Ea,jt,co,rr,bs,sr,fo,Ba=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Te(this,da,true);Te(this,rt);Te(this,et);Te(this,or);Te(this,ua);Te(this,Ea);Te(this,jt);Te(this,co);Te(this,rr,0);Te(this,bs,5);Te(this,sr,()=>{this.debugLog("Connected to event bus"),ke(this,Ea,true),this.debugLog("Emitting queued events",K(this,ua)),K(this,ua).forEach(o=>this.emitEventToBus(o)),ke(this,ua,[]),this.stopConnectLoop(),K(this,et).call(this).removeEventListener("tanstack-connect-success",K(this,sr));});Te(this,fo,()=>{if(K(this,et).call(this).addEventListener("tanstack-connect-success",K(this,sr)),K(this,rr)<K(this,bs)){Fl(this,rr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}K(this,et).call(this).removeEventListener("tanstack-connect",K(this,fo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});ke(this,rt,o),ke(this,da,a),ke(this,et,this.getGlobalTarget),ke(this,or,t),this.debugLog(" Initializing event subscription for plugin",K(this,rt)),ke(this,ua,[]),ke(this,Ea,false),ke(this,jt,null),ke(this,co,r);}startConnectLoop(){K(this,jt)!==null||K(this,Ea)||(this.debugLog(`Starting connect loop (every ${K(this,co)}ms)`),ke(this,jt,setInterval(K(this,fo),K(this,co))));}stopConnectLoop(){K(this,jt)!==null&&(clearInterval(K(this,jt)),ke(this,jt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){K(this,or)&&console.log(`\u{1F334} [tanstack-devtools:${K(this,rt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return K(this,rt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});K(this,et).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{K(this,et).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!K(this,da)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!K(this,Ea)){this.debugLog("Bus not available, will be pushed as soon as connected"),K(this,ua).push({type:`${K(this,rt)}:${o}`,payload:t,pluginId:K(this,rt)}),typeof CustomEvent<"u"&&(K(this,fo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${K(this,rt)}:${o}`,payload:t,pluginId:K(this,rt)})}on(o,t){let a=`${K(this,rt)}:${o}`;if(!K(this,da))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=s=>{this.debugLog("Received event from bus",s.detail),t(s.detail);};return K(this,et).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{K(this,et).call(this).removeEventListener(a,r);}}onAll(o){if(!K(this,da))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return K(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!K(this,da))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;K(this,rt)&&r.pluginId!==K(this,rt)||o(r);};return K(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}};da=new WeakMap,rt=new WeakMap,et=new WeakMap,or=new WeakMap,ua=new WeakMap,Ea=new WeakMap,jt=new WeakMap,co=new WeakMap,rr=new WeakMap,bs=new WeakMap,sr=new WeakMap,fo=new WeakMap;var ki=class extends Ba{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},ou=(e,o)=>{Mi.emit(e,o);},Mi=new ki;function ru(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var kg={enabled:true,leading:true,trailing:true,wait:0},ca,mt,Oa,Na,Va,mo,vs=class{constructor(o,t){Te(this,ca);Te(this,mt);Te(this,Oa);Te(this,Na);Te(this,Va);Te(this,mo);this.fn=o,this.store=new zt(ru()),this.setOptions=a=>{this.options={...this.options,...a},K(this,Oa).call(this)||this.cancel();},ke(this,mt,a=>{this.store.setState(r=>{let s={...r,...a},{isPending:n}=s;return {...s,status:K(this,Oa).call(this)?n?"pending":"idle":"disabled"}}),ou("Throttler",this);}),ke(this,Oa,()=>!!Ci(this.options.enabled,this)),ke(this,Na,()=>Ci(this.options.wait,this)),this.maybeExecute=(...a)=>{K(this,mt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),s=r-this.store.state.lastExecutionTime,n=K(this,Na).call(this);if(this.options.leading&&s>=n)K(this,Va).call(this,...a);else if(K(this,mt).call(this,{lastArgs:a}),!K(this,ca)&&this.options.trailing){let i=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,u=n-i;K(this,mt).call(this,{isPending:true}),ke(this,ca,setTimeout(()=>{let{lastArgs:l}=this.store.state;l!==void 0&&K(this,Va).call(this,...l);},u));}},ke(this,Va,(...a)=>{if(!K(this,Oa).call(this))return;this.fn(...a);let r=Date.now(),s=r+K(this,Na).call(this);K(this,mo).call(this),K(this,mt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:s,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||K(this,mt).call(this,{nextExecutionTime:void 0});},K(this,Na).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&K(this,Va).call(this,...this.store.state.lastArgs);},ke(this,mo,()=>{K(this,ca)&&(clearTimeout(K(this,ca)),ke(this,ca,void 0));}),this.cancel=()=>{K(this,mo).call(this),K(this,mt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{K(this,mt).call(this,ru());},this.key=au(t.key),this.options={...kg,...t},K(this,mt).call(this,this.options.initialState??{}),Mi.on("d-Throttler",a=>{a.payload.key===this.key&&(K(this,mt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ca=new WeakMap,mt=new WeakMap,Oa=new WeakMap,Na=new WeakMap,Va=new WeakMap,mo=new WeakMap;function Ti(e,o){return new vs(e,o).maybeExecute}function fa(e,o){return typeof e=="function"?e(o):e}function ma(e,o){return Ss(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function po(e,o,t){let a=Ss(o);function r(s){if(!a.length)return fa(t,s);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(s))return typeof s=="object"?(s===null&&(s={}),{...s,[n]:r(s[n])}):{[n]:r()};if(Array.isArray(s)&&typeof n=="number"){let i=s.slice(0,n);return [...i.length?i:new Array(n),r(s[n]),...s.slice(n+1)]}return [...new Array(n),r()]}return r(e)}function Pi(e,o){let t=Ss(o);function a(r){if(!r)return;if(t.length===1){let n=t[0];if(Array.isArray(r)&&typeof n=="number")return r.filter((l,c)=>c!==n);let{[n]:i,...u}=r;return u}let s=t.shift();if(typeof s=="string"&&typeof r=="object")return {...r,[s]:a(r[s])};if(typeof s=="number"&&Array.isArray(r)){if(s>=r.length)return r;let n=r.slice(0,s);return [...n.length?n:new Array(s),a(r[s]),...r.slice(s+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Mg=/^(\d+)$/gm,Tg=/\.(\d+)(?=\.)/gm,Ag=/^(\d+)\./gm,Pg=/\.(\d+$)/gm,Rg=/\.{2,}/gm,Ai="__int__",ys=`${Ai}$1`;function Ss(e){if(Array.isArray(e))return [...e];if(typeof e!="string")throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(Mg,ys).replace(Tg,`.${ys}.`).replace(Ag,`${ys}.`).replace(Pg,`.${ys}`).replace(Rg,".").split(".").map(o=>{if(o.startsWith(Ai)){let t=o.substring(Ai.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Ri(e){return !(Array.isArray(e)&&e.length===0)}function ho(e,o){let t=a=>a.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function go(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:s}=o.validators||{},n=t??0,i=u=>u.validators.filter(Boolean).map(l=>{let c=l?.cause||e,d=n;switch(c){case "change":d=r??n;break;case "blur":d=a??n;break;case "dynamic":d=s??n;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:c,validate:l.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:i})}var nr=e=>!!e&&typeof e=="object"&&"fields"in e;function pa(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,s]of e)if(!o.has(r)||!Object.is(s,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!pa(e[r],o[r]))return false;return true}var Is=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},Cs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Ge(e,o){return e==null?o:{...e,...o}}var qa=256,Ls=[],ws;for(;qa--;)Ls[qa]=(qa+256).toString(16).substring(1);function Di(){let e=0,o,t="";if(!ws||qa+16>256){for(ws=new Array(256),e=256;e--;)ws[e]=256*Math.random()|0;e=0,qa=0;}for(;e<16;e++)o=ws[qa+e],e===6?t+=Ls[o&15|64]:e===8?t+=Ls[o&63|128]:t+=Ls[o],e&1&&e>1&&e<11&&(t+="-");return qa++,t}var ha=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},s={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,s,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Dg(e,o){let t=new Map;for(let a of e){let r=a.path??[],s=o,n="";for(let i=0;i<r.length;i++){let u=r[i];if(u===void 0)continue;let l=typeof u=="object"?u.key:u,c=Number(l);Array.isArray(s)&&!Number.isNaN(c)?n+=`[${c}]`:n+=(i>0?".":"")+String(l),typeof s=="object"&&s!==null?s=s[l]:s=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var su=(e,o)=>{let t=Dg(e,o);return {form:t,fields:t}},ga={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:su(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:su(a.issues,e)}},ks=e=>!!e&&"~standard"in e;var xo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function ir(e){function o(d,m,f,h){let x=a(d,m,f,h);({insert:()=>i(x,d,m),remove:()=>u(x),swap:()=>h!==void 0&&c(x,d,m,h),move:()=>h!==void 0&&l(x,d,m,h)})[f]();}function t(d,m){return `${d}[${m}]`}function a(d,m,f,h){let x=[t(d,m)];if(f==="swap")x.push(t(d,h));else if(f==="move"){let[p,v]=[Math.min(m,h),Math.max(m,h)];for(let g=p;g<=v;g++)x.push(t(d,g));}else {let p=e.getFieldValue(d),v=Array.isArray(p)?p.length:0;for(let g=m+1;g<v;g++)x.push(t(d,g));}return Object.keys(e.fieldInfo).filter(p=>x.some(v=>p.startsWith(v)))}function r(d,m){return d.replace(/\[(\d+)\]/,(f,h)=>{let x=parseInt(h,10);return `[${m==="up"?x+1:Math.max(0,x-1)}]`})}function s(d,m){(m==="up"?d:[...d].reverse()).forEach(h=>{let x=r(h.toString(),m),p=e.getFieldMeta(x);p?e.setFieldMeta(h,p):e.setFieldMeta(h,n());});}let n=()=>xo,i=(d,m,f)=>{s(d,"down"),d.forEach(h=>{h.toString().startsWith(t(m,f))&&e.setFieldMeta(h,n());});},u=d=>{s(d,"up");},l=(d,m,f,h)=>{let x=new Map(Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,f))).map(p=>[p,e.getFieldMeta(p)]));s(d,f<h?"up":"down"),Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,h))).forEach(p=>{let v=p.replace(t(m,h),t(m,f)),g=x.get(v);g&&e.setFieldMeta(p,g);});},c=(d,m,f,h)=>{d.forEach(x=>{if(!x.toString().startsWith(t(m,f)))return;let p=x.toString().replace(t(m,f),t(m,h)),[v,g]=[e.getFieldMeta(x),e.getFieldMeta(p)];v&&e.setFieldMeta(p,v),g&&e.setFieldMeta(x,g);});};return {handleArrayFieldMetaShift:o}}var Fi=class extends Ba{constructor(){super({pluginId:"form-devtools"});}},pt=new Fi;function Ei(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var dr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),s=()=>{a(),r(),pt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),s},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let s=!!a.transform?.deps?.some((u,l)=>u!==this.prevTransformArray[l]),n=a.defaultValues&&!pa(a.defaultValues,r.defaultValues)&&!this.state.isTouched,i=!pa(a.defaultState,r.defaultState)&&!this.state.isTouched;!n&&!i&&!s||(ft(()=>{this.baseStore.setState(()=>Ei(Object.assign({},this.state,i?a.defaultState:{},n?{values:a.defaultValues}:{},s?{_force_re_eval:!this.state._force_re_eval}:{})));}),pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:s}=this.state,n=this.resetFieldMeta(s);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Ei({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let r=[];return ft(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let i=n.instance;r.push(Promise.resolve().then(()=>i.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(u=>({...u,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,s)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null,u=[`${a}[${r}]`];for(let m=r+1;m<=(i??0);m++)u.push(`${a}[${m}]`);let l=Object.keys(this.fieldInfo).filter(m=>u.some(f=>m.startsWith(f))),c=[];return ft(()=>{l.forEach(m=>{c.push(Promise.resolve().then(()=>this.validateField(m,s)));});}),(await Promise.all(c)).flat()},this.validateField=(a,r)=>{let s=this.fieldInfo[a]?.instance;return s?(s.state.meta.isTouched||s.setMeta(n=>({...n,isTouched:true})),s.validate(r)):[]},this.validateSync=a=>{let r=ho(a,{...this.options,form:this,validationLogic:this.options.validationLogic||ha}),s=false,n={};return ft(()=>{for(let l of r){if(!l.validate)continue;let c=this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:m}=Ms(c),f=lr(l.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let x=this.getFieldMeta(h);if(!x)continue;let{errorMap:p,errorSourceMap:v}=x,g=m?.[h],{newErrorValue:b,newSource:y}=Is({newFormValidatorError:g,isPreviousErrorFromFormValidator:v?.[f]==="form",previousErrorValue:p?.[f]});y==="form"&&(n[h]={...n[h],[f]:g}),p?.[f]!==b&&this.setFieldMeta(h,S=>({...S,errorMap:{...S.errorMap,[f]:b},errorSourceMap:{...S.errorSourceMap,[f]:y}}));}this.state.errorMap?.[f]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[f]:d}})),(d||m)&&(s=!0);}let i=lr("submit");this.state.errorMap?.[i]&&a!=="submit"&&!s&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[i]:void 0}}));let u=lr("server");this.state.errorMap?.[u]&&a!=="server"&&!s&&this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[u]:void 0}}));}),{hasErrored:s,fieldsErrorMap:n}},this.validateAsync=async a=>{let r=go(a,{...this.options,form:this,validationLogic:this.options.validationLogic||ha});this.state.isFormValidating||this.baseStore.setState(l=>({...l,isFormValidating:true}));let s=[],n;for(let l of r){if(!l.validate)continue;let c=lr(l.cause);this.state.validationMetaMap[c]?.lastAbortController.abort();let m=new AbortController;this.state.validationMetaMap[c]={lastAbortController:m},s.push(new Promise(async f=>{let h;try{h=await new Promise((g,b)=>{setTimeout(async()=>{if(m.signal.aborted)return g(void 0);try{g(await this.runValidator({validate:l.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:m.signal},type:"validateAsync"}));}catch(y){b(y);}},l.debounceMs);});}catch(g){h=g;}let{formError:x,fieldErrors:p}=Ms(h);p&&(n=n?{...n,...p}:p);let v=lr(l.cause);for(let g of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[g]===void 0)continue;let b=this.getFieldMeta(g);if(!b)continue;let{errorMap:y,errorSourceMap:S}=b,I=n?.[g],{newErrorValue:C,newSource:L}=Is({newFormValidatorError:I,isPreviousErrorFromFormValidator:S?.[v]==="form",previousErrorValue:y?.[v]});y?.[v]!==C&&this.setFieldMeta(g,P=>({...P,errorMap:{...P.errorMap,[v]:C},errorSourceMap:{...P.errorSourceMap,[v]:L}}));}this.baseStore.setState(g=>({...g,errorMap:{...g.errorMap,[v]:x}})),f(n?{fieldErrors:n,errorMapKey:v}:void 0);}));}let i=[],u={};if(s.length){i=await Promise.all(s);for(let l of i)if(l?.fieldErrors){let{errorMapKey:c}=l;for(let[d,m]of Object.entries(l.fieldErrors)){let h={...u[d]||{},[c]:m};u[d]=h;}}}return this.baseStore.setState(l=>({...l,isFormValidating:false})),u},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:s}=this.validateSync(a);return r&&!this.options.asyncAlways?s:this.validateAsync(a)},this.getFieldValue=a=>ma(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,r)=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:fa(r,s.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,s)=>{let n=s;return r[n]=xo,r},{}),this.setFieldValue=(a,r,s)=>{let n=s?.dontUpdateMeta??false,i=s?.dontRunListeners??false,u=s?.dontValidate??false;ft(()=>{n||this.setFieldMeta(a,l=>({...l,isTouched:!0,isDirty:!0,errorMap:{...l?.errorMap,onMount:void 0}})),this.baseStore.setState(l=>({...l,values:po(l.values,a,r)}));}),i||this.getFieldInfo(a).instance?.triggerOnChangeListener(),u||this.validateField(a,"change");},this.deleteField=a=>{let s=[...Object.keys(this.fieldInfo).filter(n=>{let i=a.toString();return n!==i&&n.startsWith(i)}),a];this.baseStore.setState(n=>{let i={...n};return s.forEach(u=>{i.values=Pi(i.values,u),delete this.fieldInfo[u],delete i.fieldMetaBase[u];}),i});},this.pushFieldValue=(a,r,s)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],r],s);},this.insertFieldValue=async(a,r,s,n)=>{this.setFieldValue(a,u=>[...u.slice(0,r),s,...u.slice(r)],Ge(n,{dontValidate:true}));let i=n?.dontValidate??false;i||await this.validateField(a,"change"),ir(this).handleArrayFieldMetaShift(a,r,"insert"),i||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,s,n)=>{this.setFieldValue(a,u=>u.map((l,c)=>c===r?s:l),Ge(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,s)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,l=>l.filter((c,d)=>d!==r),Ge(s,{dontValidate:true})),ir(this).handleArrayFieldMetaShift(a,r,"remove"),i!==null){let l=`${a}[${i}]`;this.deleteField(l);}(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,s,n)=>{this.setFieldValue(a,u=>{let l=u[r],c=u[s];return po(po(u,`${r}`,c),`${s}`,l)},Ge(n,{dontValidate:true})),ir(this).handleArrayFieldMetaShift(a,r,"swap",s),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${s}]`,"change"));},this.moveFieldValues=(a,r,s,n)=>{this.setFieldValue(a,u=>{let l=[...u];return l.splice(s,0,l.splice(r,1)[0]),l},Ge(n,{dontValidate:true})),ir(this).handleArrayFieldMetaShift(a,r,"move",s),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${s}]`,"change"));},this.clearFieldValues=(a,r)=>{let s=this.getFieldValue(a),n=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,[],Ge(r,{dontValidate:true})),n!==null)for(let u=0;u<=n;u++){let l=`${a}[${u}]`;this.deleteField(l);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:xo},values:this.options.defaultValues?po(r.values,a,ma(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,s])=>(Object.keys(s).length&&s.errors.length&&(a[r]={errors:s.errors,errorMap:s.errorMap}),a),{})}),this.parseValuesWithSchema=a=>ga.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ga.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Di(),this._devtoolsSubmissionOverride=false,this.baseStore=new zt(Ei({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Ft({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:s})=>{let n=s,i=a?.[0],u=r[0],l=0,c={};for(let d of Object.keys(u.fieldMetaBase)){let m=u.fieldMetaBase[d],f=i?.fieldMetaBase[d],h=n?.[d],x=ma(u.values,d),p=h?.errors;if(!f||m.errorMap!==f.errorMap){p=Object.values(m.errorMap??{}).filter(S=>S!==void 0);let y=this.getFieldInfo(d)?.instance;y&&!y.options.disableErrorFlat&&(p=p?.flat(1));}let v=!Ri(p??[]),g=!m.isDirty,b=pa(x,ma(this.options.defaultValues,d))||pa(x,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===g&&h.isValid===v&&h.isDefaultValue===b&&h.errors===p&&m===f){c[d]=h,l++;continue}c[d]={...m,errors:p,isPristine:g,isValid:v,isDefaultValue:b};}return Object.keys(u.fieldMetaBase).length&&n&&l===Object.keys(u.fieldMetaBase).length?n:c}}),this.store=new Ft({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:s})=>{let n=s,i=a?.[0],u=r[0],l=r[1],c=Object.values(l).filter(Boolean),d=c.some(D=>D.isValidating),m=c.every(D=>D.isValid),f=c.some(D=>D.isTouched),h=c.some(D=>D.isBlurred),x=c.every(D=>D.isDefaultValue),p=f&&u.errorMap?.onMount,v=c.some(D=>D.isDirty),g=!v,b=!!(u.errorMap?.onMount||c.some(D=>D?.errorMap?.onMount)),y=!!d,S=n?.errors??[];(!i||u.errorMap!==i.errorMap)&&(S=Object.values(u.errorMap).reduce((D,U)=>U===void 0?D:U&&nr(U)?(D.push(U.form),D):(D.push(U),D),[]));let I=S.length===0,C=m&&I,L=this.options.canSubmitWhenInvalid??false,P=u.submissionAttempts===0&&!f&&!b||!y&&!u.isSubmitting&&C||L,A=u.errorMap;if(p&&(S=S.filter(D=>D!==u.errorMap.onMount),A=Object.assign(A,{onMount:void 0})),n&&i&&n.errorMap===A&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===S&&n.isFieldsValidating===d&&n.isFieldsValid===m&&n.isFormValid===I&&n.isValid===C&&n.canSubmit===P&&n.isTouched===f&&n.isBlurred===h&&n.isPristine===g&&n.isDefaultValue===x&&n.isDirty===v&&pa(i,u))return n;let H={...u,errorMap:A,fieldMeta:this.fieldMetaDerived.state,errors:S,isFieldsValidating:d,isFieldsValid:m,isFormValid:I,isValid:C,canSubmit:P,isTouched:f,isBlurred:h,isPristine:g,isDefaultValue:x,isDirty:v},F=this.options.transform?.deps??[];if(F.length!==this.prevTransformArray.length||F.some((D,U)=>D!==this.prevTransformArray[U])){let D=Object.assign({},this,{state:H});this.options.transform?.fn(D),H=D.state,this.prevTransformArray=F;}return H}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Ti(a=>pt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),pt.on("request-form-state",a=>{a.payload.id===this._formId&&pt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),pt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),pt.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return ks(o.validate)?ga[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(r=>({...r,isSubmitted:false,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:false})),ft(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(s=>({...s,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ft(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ft(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(s=>({...s,isSubmitSuccessful:false})),pt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){ft(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(nr(a)){let{formError:s,fieldErrors:n}=Ms(a);for(let i of Object.keys(this.fieldInfo))this.getFieldMeta(i)&&this.setFieldMeta(i,l=>({...l,errorMap:{...l.errorMap,[r]:n?.[i]},errorSourceMap:{...l.errorSourceMap,[r]:"form"}}));this.baseStore.setState(i=>({...i,errorMap:{...i.errorMap,[r]:s}}));}else this.baseStore.setState(s=>({...s,errorMap:{...s.errorMap,[r]:a}}));});});}};function Ms(e){if(e){if(nr(e)){let o=Ms(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function lr(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}var ur=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let s=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});s&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:s},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=ma(t.form.options.defaultValues,t.name),s=t.defaultValue??r;a?this.setValue(n=>n||s,{dontUpdateMeta:true}):s!==void 0&&this.setValue(s,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Ge(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Ge(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let s of a){if(!s.instance)continue;let{onChangeListenTo:n,onBlurListenTo:i}=s.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&r.push(s.instance),t==="blur"&&i?.includes(this.name)&&r.push(s.instance);}return r},this.validateSync=(t,a)=>{let r=ho(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ha}),n=this.getLinkedFields(t).reduce((l,c)=>{let d=ho(t,{...c.options,form:c.form,validationLogic:c.form.options.validationLogic||ha});return d.forEach(m=>{m.field=c;}),l.concat(d)},[]),i=false;ft(()=>{let l=(c,d)=>{let m=Ts(d.cause),f=d.validate?nu(c.runValidator({validate:d.validate,value:{value:c.store.state.value,validationSource:"field",fieldApi:c},type:"validate"})):void 0,h=a[m],{newErrorValue:x,newSource:p}=Cs({formLevelError:h,fieldLevelError:f});c.state.meta.errorMap?.[m]!==x&&c.setMeta(v=>({...v,errorMap:{...v.errorMap,[m]:x},errorSourceMap:{...v.errorSourceMap,[m]:p}})),x&&(i=!0);};for(let c of r)l(this,c);for(let c of n)c.validate&&l(c.field,c);});let u=Ts("submit");return this.state.meta.errorMap?.[u]&&t!=="submit"&&!i&&this.setMeta(l=>({...l,errorMap:{...l.errorMap,[u]:void 0},errorSourceMap:{...l.errorSourceMap,[u]:void 0}})),{hasErrored:i}},this.validateAsync=async(t,a)=>{let r=go(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ha}),s=await a,n=this.getLinkedFields(t),i=n.reduce((m,f)=>{let h=go(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||ha});return h.forEach(x=>{x.field=f;}),m.concat(h)},[]);this.state.meta.isValidating||this.setMeta(m=>({...m,isValidating:true}));for(let m of n)m.setMeta(f=>({...f,isValidating:true}));let u=[],l=[],c=(m,f,h)=>{let x=Ts(f.cause);m.getInfo().validationMetaMap[x]?.lastAbortController.abort();let v=new AbortController;this.getInfo().validationMetaMap[x]={lastAbortController:v},h.push(new Promise(async g=>{let b;try{b=await new Promise((L,P)=>{this.timeoutIds.validations[f.cause]&&clearTimeout(this.timeoutIds.validations[f.cause]),this.timeoutIds.validations[f.cause]=setTimeout(async()=>{if(v.signal.aborted)return L(void 0);try{L(await this.runValidator({validate:f.validate,value:{value:m.store.state.value,fieldApi:m,signal:v.signal,validationSource:"field"},type:"validateAsync"}));}catch(A){P(A);}},f.debounceMs);});}catch(L){b=L;}if(v.signal.aborted)return g(void 0);let y=nu(b),S=s[this.name]?.[x],{newErrorValue:I,newSource:C}=Cs({formLevelError:S,fieldLevelError:y});m.setMeta(L=>({...L,errorMap:{...L?.errorMap,[x]:I},errorSourceMap:{...L.errorSourceMap,[x]:C}})),g(I);}));};for(let m of r)m.validate&&c(this,m,u);for(let m of i)m.validate&&c(m.field,m,l);let d=[];(u.length||l.length)&&(d=await Promise.all(u),await Promise.all(l)),this.setMeta(m=>({...m,isValidating:false}));for(let m of n)m.setMeta(f=>({...f,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:s}=this.validateSync(t,r[this.name]??{});if(s&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Ts(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>ga.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ga.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Ft({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...xo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return ks(o.validate)?ga[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function nu(e){if(e)return e}function Ts(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function As(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Eg)}function Eg(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,r]of e)if(!o.has(a)||!Object.is(r,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=iu(e);if(t.length!==iu(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function iu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var bo=typeof window<"u"?useLayoutEffect:useEffect;function Ug(e){let[o]=useState(()=>{let a=new ur({...e,form:e.form,name:e.name});return a.Field=Bi,a});return bo(o.mount,[o]),bo(()=>{o.update(e);}),As(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Bi=(({children:e,...o})=>{let t=Ug(o),a=useMemo(()=>fa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Gg({form:e,selector:o,children:t}){let a=As(e.store,o);return fa(t,a)}function Oi(e){let o=useId(),[t]=useState(()=>{let a=new dr({...e,formId:o}),r=a;return r.Field=function(n){return jsx(Bi,{...n,form:a})},r.Subscribe=function(n){return jsx(Gg,{form:a,selector:n.selector,children:n.children})},r});return bo(t.mount,[]),bo(()=>{t.update(e);}),t}function Ni({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var ex=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),r=!!e,s=e?.data.questionType||t?.activityType||"multiple-choice",[n,i]=useState(s),u=Oi({defaultValues:{questionType:s,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:d})=>{if(d.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctAnswer:d.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?oa(m):Dn(m));}else if(d.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctIndex:d.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?aa(m):Pn(m));}else if(d.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Bo(m):En(m));}else if(d.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?No(m):Vn(m));}else if(d.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctLongAnswer:d.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Oo(m):On(m));}o(ra(false));}}),l=()=>{o(ra(false));},c=jsx("div",{className:"fixed inset-0 z-106 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-6 shadow-lg",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-240px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-100px)] w-full flex-col gap-1 rounded-lg bg-white p-4",onSubmit:d=>{d.preventDefault(),d.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-4",children:[jsxs("div",{className:"flex flex-col gap-1",children:[jsx("h2",{className:"text-2xl font-bold text-[#000000CC]",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"font-semibold text-[#00000099]",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-8 w-8 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600",onClick:()=>{l();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(u.Field,{name:"questionType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:m=>{d.handleChange(m.target.value),i(m.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 font-semibold text-[#000000CC] ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Question type cannot be changed when editing"}),jsx(Ni,{field:d})]})}),n&&!["short-answer","fill-in-the-blank","long-answer"].includes(n)&&jsx(u.Field,{name:"responseType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:m=>d.handleChange(m.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-4 py-3 pr-10 font-semibold text-[#000000CC]",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Ni,{field:d})]})})]}),jsx(u.Field,{name:"feedbackMode",children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-2 rounded-lg bg-gray-100 p-1.5 ${n==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:n==="long-answer",onClick:()=>d.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",size:16}),"Practice Mode"]}),jsxs("button",{type:"button",disabled:n==="long-answer",onClick:()=>d.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",size:16}),"Assessment Mode"]})]}),n==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(Ni,{field:d})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:d})=>d?void 0:"A question is required"},children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-4 py-3 text-gray-900",value:d.state.value,onChange:m=>d.handleChange(m.target.value),onBlur:d.handleBlur,placeholder:"Enter Your Question"})}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),n==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:d=>{let m=d.state.value;return jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{className:"text-base font-semibold text-[#00000066] uppercase",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-4",children:[jsxs("button",{type:"button",onClick:()=>d.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"True"}),m===true&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>d.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"False"}),m===false&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]})]}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Select the correct answer for this true/false question"})]})}}),n==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:d})=>{if(d.options.filter(f=>!f.trim()).length>0)return "All options must have text";if(!d.correctIndex||d.correctIndex.length===0)return "Please select at least one correct answer"}},children:d=>{let m=(p,v)=>{let g=[...d.state.value.options];g[p]=v,d.handleChange({...d.state.value,options:g});},f=()=>{if(d.state.value.options.length>=6){alert("Maximum 6 options allowed");return}d.handleChange({...d.state.value,options:[...d.state.value.options,""]});},h=p=>{if(d.state.value.options.length<=2){alert("Minimum 2 options required");return}let v=d.state.value.options.filter((b,y)=>y!==p),g=d.state.value.correctIndex?.filter(b=>b!==p).map(b=>b>p?b-1:b);d.handleChange({...d.state.value,options:v,correctIndex:g});},x=p=>{let v=d.state.value.correctIndex||[];if(v.includes(p))d.handleChange({...d.state.value,correctIndex:v.filter(b=>b!==p)});else {if(v.length>=6){alert("Maximum 6 correct answers allowed");return}d.handleChange({...d.state.value,correctIndex:[...v,p]});}};return jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:d.name,className:"mb-2 text-base font-semibold text-gray-900",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-4 flex flex-col gap-3",children:d.state.value.options.map((p,v)=>{let g=!p.trim(),b=d.state.value.correctIndex?.includes(v),y=d.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>x(v),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${b?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:b&&jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-4 py-3 transition-colors ${y?"border-red-500 bg-red-50":b?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${v+1}`,value:p,onChange:S=>m(v,S.target.value),onBlur:d.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),d.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>h(v),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},v)})}),jsx("button",{type:"button",onClick:f,disabled:d.state.value.options.length>=6,className:"mx-2 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-3 text-lg font-semibold text-[#00000066] disabled:cursor-not-allowed",children:"+ Add Option"}),d.state.value.correctIndex.length===0||d.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:d.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill"}),jsx("p",{className:"",children:"Correct answer selected"})]})]})}}),(n==="short-answer"||n==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:d.state.value,onChange:m=>{d.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Learners must write this answer exactly (case-insensitive)."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),n==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-gray-900",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:d.state.value,onChange:m=>{d.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"This will be used as a reference answer for manual grading."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:d=>[d.canSubmit,d.isSubmitting],children:([d,m])=>jsx("button",{type:"submit",disabled:!d,className:"mt-2 mb-4 w-full rounded-lg bg-[#096B76] px-6 py-3 font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50",children:m?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(c,document.body)},uu=ex;var cu=({text:e,position:o})=>{let t=xe(),a=l=>{t(ue()),t(wt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+l))}));},r=l=>{t(ue()),t(wt({id:e.id,fill:l}));},s=()=>{t(ue()),t(wt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ue()),t(wt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},i=()=>{t(ue()),t(wt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},u=l=>{t(ue()),t(wt({id:e.id,fontFamily:l}));};return jsxs("div",{className:"fixed z-1001 flex items-center gap-1 rounded-lg border border-gray-200 bg-white p-2 shadow-2xl",style:{left:`${o.x}px`,top:`${o.y-60}px`,transform:"translateX(-50%)"},onClick:l=>l.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:l=>u(l.target.value),className:"rounded border border-gray-300 bg-white px-2 py-1 text-xs hover:bg-gray-50",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-8 text-center text-xs font-medium",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:s,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:jsx(TextB,{size:16,weight:"bold"})}),jsx("button",{onClick:n,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:jsx(TextItalic,{size:16,weight:"bold"})}),jsx("button",{onClick:i,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:jsx(TextUnderline,{size:16,weight:"bold"})})]}),jsx("div",{className:"ml-1 border-l border-gray-200 pl-1",children:jsx("div",{className:"relative",children:jsx("input",{type:"color",value:e.fill,onChange:l=>r(l.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var mu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:s,textareaRef:n})=>{let i=useRef(null),u=useMemo(()=>({fontSize:`${e.fontSize*s}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,s]),l=useCallback(c=>{c.style.height="auto",c.style.height=`${c.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(c).font,d.style.fontSize=c.style.fontSize,d.style.fontFamily=c.style.fontFamily,d.style.fontWeight=c.style.fontWeight,d.style.fontStyle=c.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let m=c.value.split(`
4
+ `),f=0;document.body.appendChild(d);for(let x of m){d.textContent=x||" ";let p=d.offsetWidth;p>f&&(f=p);}document.body.removeChild(d);let h=10;c.style.width=`${Math.max(200,f+h+20)}px`;},[]);return useEffect(()=>{let c=i.current;c&&(c.style.fontSize=`${e.fontSize*s}px`,c.style.fontFamily=e.fontFamily,c.style.fontStyle=e.fontStyle,c.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",c.style.textDecoration=e.textDecoration,c.style.color=e.fill,l(c));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,s,l]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:c=>{if(i.current=c,n.current=c,c){c.focus();let d=c.value.length;c.setSelectionRange(d,d),l(c);}},value:o,onChange:c=>{t(c.target.value);},onKeyDown:c=>{c.key==="Escape"&&a();},style:u},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var pu=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(E=>E.toolbar.selectedTool),i=n==="pen"||n==="eraser",u=useRef(null),[l,c]=useState(""),[d,m]=useState(false),[f,h]=useState(null);useEffect(()=>{let E=u.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id,a]);let x=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=d&&l.trim().toLowerCase()===x,v=()=>{m(false),c("");},g=()=>p?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",b=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},y=24,S=60,I=d?50:0,C=50,L=12,P=e.data.feedbackMode==="practice"?48:0,A=12,H=30,F=S+I+H+C+L+A+P+y;return jsxs(Group,{ref:u,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"sa-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let D=u.current?.getStage()?.getPointerPosition();if(!D)return;let U={x:e.x,y:e.y,width:e.width,height:e.height};D.x>=U.x&&D.x<=U.x+U.width&&D.y>=U.y&&D.y<=U.y+U.height&&r(E.evt,e.id,"shortAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:F,onTransformEnd:E=>t(e.id,E)}),jsx(Text,{text:e.data.question,x:y,y,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:y,y:S,width:e.width-y*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:I,text:g(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer:",x:y,y:S+I+L,fontSize:14,fill:"#6b7280",width:e.width-y*2,listening:false}),jsx(Rect,{x:y,y:S+I+H,width:e.width-y*2,height:C,fill:"#ffffff",stroke:p?"#22c55e":d?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${S+I+H}px`,left:`${y}px`,width:`${e.width-y*2}px`,height:`${C}px`,pointerEvents:d?"none":"auto"}},children:jsx("input",{type:"text",value:l,onChange:E=>c(E.target.value),disabled:d,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:d?"none":"auto"}})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:S+I+H+C+L+A,children:[!d&&jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,h("check");},onMouseUp:E=>{E.cancelBubble=true,h(null),l.length>0&&m(true);},onMouseLeave:E=>{E.cancelBubble=true,h(null);},onTouchStart:E=>{E.cancelBubble=true,h("check");},onTouchEnd:E=>{E.cancelBubble=true,h(null),l.length>0&&m(true);},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:l.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});pu.displayName="ShortAnswer";var hu=pu;var xu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(hu,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var bu=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),s=useCallback((n,i)=>{let u=n.target;o(No({id:i,x:u.x(),y:u.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:s}};var vu=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r})=>{let s=useSelector(F=>F.toolbar.selectedTool),n=s==="pen"||s==="eraser",i=useRef(null),[u,l]=useState(""),[c,d]=useState(false),[m,f]=useState(null);useEffect(()=>{if(i.current)return ()=>{}},[e.id]);let h=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=c&&u.trim().toLowerCase()===h,p=()=>{d(false),l("");},v=()=>x?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",g=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=24,y=80,S=c?50:0,I=45,C=8,L=20,P=e.data.feedbackMode==="practice"?48:0,A=12,H=y+S+C+L+C+A+P+b;return jsxs(Group,{ref:i,draggable:!n,listening:!n,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...n?{}:{onDragEnd:F=>a(F,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:F=>{let E=i.current?.getStage()?.getPointerPosition();if(!E||!r)return;let D={x:e.x,y:e.y,width:e.width,height:e.height};E.x>=D.x&&E.x<=D.x+D.width&&E.y>=D.y&&E.y<=D.y+D.height&&r(F.evt,e.id,"fillInTheBlanks");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:H,onTransformEnd:F=>t(e.id,F)}),jsx(Text,{text:e.data.question,x:b,y:b,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2-200,listening:false}),jsx(Rect,{x:e.width-b-180,y:b+10,width:180,height:I,fill:"#ffffff",stroke:x?"#22c55e":c?"#ef4444":"#096B76",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${b+10}px`,left:`${e.width-b-180}px`,width:"180px",height:`${I}px`,pointerEvents:c?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:F=>l(F.target.value),disabled:c,placeholder:"__________",className:"h-full w-full border-0 bg-white px-2 text-center text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:c?"none":"auto"}})}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:b,y,width:e.width-b*2,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:b,y,width:e.width-b*2,height:S,text:v(),fontSize:16,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"\u26A0\uFE0F Answer is case sensitive",x:b,y:y+S+C,fontSize:10,fontStyle:"italic",fill:"#6b7280",width:e.width-b*2,listening:false}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:y+S+C+L+C+A,children:[!c&&jsxs(Group,{onMouseDown:F=>{F.cancelBubble=true,f("check");},onMouseUp:F=>{F.cancelBubble=true,f(null),u.length>0&&d(true);},onMouseLeave:F=>{F.cancelBubble=true,f(null);},onTouchStart:F=>{F.cancelBubble=true,f("check");},onTouchEnd:F=>{F.cancelBubble=true,f(null),u.length>0&&d(true);},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:u.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{onMouseDown:()=>f("reset"),onMouseUp:()=>{f(null),p();},onMouseLeave:()=>f(null),onTouchStart:()=>f("reset"),onTouchEnd:()=>{f(null),p();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:F=>F.cancelBubble=true,onTap:F=>F.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});vu.displayName="FillInTheBlanks";var yu=vu;var Lu=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r})=>jsx(Fragment,{children:e.map(s=>jsx(yu,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r},s.id))});var Wi=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>{let n=useSelector(E=>E.toolbar.selectedTool),i=n==="pen"||n==="eraser",u=useRef(null),[l,c]=useState(""),[d,m]=useState(false),[f,h]=useState(null);useEffect(()=>{let E=u.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id,a]);let x=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",p=d&&l.trim().toLowerCase()===x,v=()=>{m(false),c("");},g=()=>p?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",b=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},y=24,S=60,I=d?60:0,C=120,L=12,P=48,A=12,H=30,F=S+I+H+C+L+A+P+y;return jsxs(Group,{ref:u,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...i?{}:{onDragEnd:s,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let D=u.current?.getStage()?.getPointerPosition();if(!D||!r)return;let U={x:e.x,y:e.y,width:e.width,height:e.height};D.x>=U.x&&D.x<=U.x+U.width&&D.y>=U.y&&D.y<=U.y+U.height&&r(E.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:F,onTransformEnd:E=>t(e.id,E)}),jsx(Text,{text:e.data.question,x:y,y,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:y,y:S,width:e.width-y*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:I,text:g(),fontSize:14,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:y,y:S+I+L,fontSize:14,fill:"#6b7280",width:e.width-y*2,listening:false}),jsx(Rect,{x:y,y:S+I+H,width:e.width-y*2,height:C,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${S+I+H}px`,left:`${y}px`,width:`${e.width-y*2}px`,height:`${C}px`,pointerEvents:d?"none":"auto"}},children:jsx("textarea",{value:l,onChange:E=>c(E.target.value),disabled:d,placeholder:`Type your extended answer here...\r
5
5
  \r
6
- This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:d?"none":"auto"}})}),jsx(Group,{y:S+I+U+C+L+A,children:d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Wi.displayName="LongAnswer";var Iu=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(Wi,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>n(i,s.id)},s.id))});var Ex=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r,className:n,style:s}={})=>{let i=qt(),u=ee(w=>w.toolbar.selectedTool),l=ee(ge),c=ee(Uo),d=l?.editingActivity,p=l?.showMcqForm,f=l?.lines||[],h=useRef(null),x=useRef(null),[m,v]=useState(null),[g,b]=useState(""),[y,S]=useState({width:1280,height:1200}),[I,C]=useState("bottom"),L=useRef(null),[P,A]=useState(null),[U,F]=useState(null),[E,D]=useState(null),[H,N]=useState(null),[te,q]=useState(null),[G,oe]=useState(null),[R,z]=useState(null),[X,_]=useState(false),[Y,Z]=useState(null),[Q,pe]=useState(false),we=useRef(null),Re=useRef(null),Me=useRef(null),{debouncedGenerateThumbnail:Ue}=cd(c,h);useEffect(()=>{let w=()=>{if(x.current){let T=x.current.getBoundingClientRect();S({width:T.width,height:T.height});}};w();let M=new ResizeObserver(w);return x.current&&M.observe(x.current),window.addEventListener("resize",w),()=>{M.disconnect(),window.removeEventListener("resize",w);}},[]),useEffect(()=>{if(h.current){let w=h.current.container();w&&(w.style.cursor="");}},[u]);let re=useCallback(()=>{h.current&&requestAnimationFrame(()=>{if(!h.current)return;h.current.getLayers().forEach(O=>O.batchDraw());let M=1/6,T=h.current.toDataURL({pixelRatio:M});b(T),Ue();});},[Ue]),kr=useRef(c);useEffect(()=>{kr.current!==c&&(kr.current=c,re());},[c,re]);let Mr=useRef(null),Tr=useRef(true);useEffect(()=>{if(!l)return;let w=(l.lines?.length||0)+(l.images?.length||0)+(l.videos?.length||0)+(l.shapes?.length||0)+(l.texts?.length||0)+(l.flashcards?.length||0)+(l.photoFrames?.length||0)+(l.multipleChoices?.length||0)+(l.trueFalses?.length||0)+(l.shortAnswers?.length||0)+(l.LongAnswer?.length||0)+(l.fillInTheBlanks?.length||0),M=Mr.current?.count!==w;!Tr.current&&M&&setTimeout(()=>{re();},100),Mr.current={slideId:c,count:w},Tr.current=false;},[l,c,re]),useEffect(()=>{h.current&&e&&e(h);},[e]),useEffect(()=>{Me.current&&a&&a(Me);},[a]);let{startDrawing:Ar,draw:Ca,stopDrawing:Pr,setCanvasRef:Xn,tool:Yn,color:Rr,strokeWidth:Jn,isSketchMode:Zn}=Vl(re),ka=useRef(new Map),{images:Qn,getLoadedImage:es,imageRefs:B,handleDragEnd:se,handleImageTransformEnd:Ie}=Kl(re),{videos:me,videoRefs:ne,handleVideoClick:ie,handleVideoDragEnd:Ve,handleVideoTransformEnd:Vt}=$l(re),{multipleChoice:Kt,handleMcqTransform:_e,mcqRefs:Ce,handleDragEnd:Je}=_l(re),{trueFalse:_t,handleTrueFalseTransform:Ma,trueFalseRefs:Ta,handleTrueFalseDragEnd:$a}=jl(re),{shortAnswers:Dr,saRefs:Ze,handleShortAnswerDragEnd:ea}=ed(re),{longAnswers:Aa,handleLongAnswerDragEnd:yf}=td(re),{fillInTheBlanks:wf,handleFillInTheBlanksDragEnd:Lf}=bu(re),{transformerRef:de,boundBoxFunc:gt}=id(),{shapes:Sf,shapeRefs:Fr,isDragging:Sl,handleShapeDragEnd:If,handleShapeResizeEnd:Cf}=Jl(re),{texts:Ro,textRefs:ta,handleDragEnd:kf,handleTransformEnd:Mf,handleDoubleClick:Tf,startEditing:Er,editingTextId:he,editingValue:Il,handleEditingChange:Cl,finishEditing:ts}=Ql(re,we);useEffect(()=>{t&&t(Er);},[t,Er]);let Br=ee(w=>w.canvas.editingTextId);useEffect(()=>{Br&&Br!==he&&Er(Br);},[Br,he,Er]);let{flashcards:Af,flashcardRefs:Or,handleDragEnd:Pf,handleFlashcardTransformEnd:Rf,handleNext:Df,handlePrevious:Ff}=od(re),{photoFrames:kl,photoFrameRefs:Nr,handleDragEnd:Ef,handlePhotoFrameTransformEnd:Bf,startCamera:Of,capturePhoto:Nf,cameraStreams:Vf}=sd(re);useEffect(()=>{if(de.current){if(he){de.current.nodes([]),de.current.getLayer()?.batchDraw();return}if(m&&!me.find(T=>T.id===m)?.isPlaying){let T=ka.current.get(m)||B.current.get(m)||ne.current.get(m)||Fr.current.get(m)||ta.current.get(m)||Ce.current.get(m)||Or.current.get(m)||Nr.current.get(m);if(T){let O=T.attrs?.locked;if(T.visible()&&O!==true){de.current.nodes([T]),de.current.getLayer()?.batchDraw();return}}}de.current.nodes([]),de.current.getLayer()?.batchDraw();}},[m,he,me,ka,B,ne,Fr,ta,Or,Nr,kl,Ce,de]);let He=useCallback(w=>{v(w),o?.(w);},[o]),Vr=useCallback(()=>{v(null),o?.(null),de.current&&(de.current.nodes([]),de.current.getLayer()?.batchDraw());},[de,o]);useEffect(()=>{let w=de.current;return ()=>{w&&w.nodes([]);}},[c]),useEffect(()=>{let w=M=>{he&&M.target.tagName!=="TEXTAREA"&&ts();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[he,ts]),useEffect(()=>{let w=he||m;if(!w||m&&he){F(null);return}let M=ta.current.get(w),T=h.current;if(!M||!T){F(null);return}let O=T.container().getBoundingClientRect(),De=M.absolutePosition(),Le=T.scaleX();F({x:O.left+(De.x+M.width()*Le/2)*Le,y:O.top+De.y*Le});},[m,he,Ro,ta]),useEffect(()=>{if(!he){D(null);return}let w=ta.current.get(he),M=h.current;if(!w||!M){D(null);return}let T=M.container().getBoundingClientRect(),O=w.absolutePosition(),De=M.scaleX();D({top:T.top+O.y*De,left:T.left+O.x*De,scale:De});},[he,Ro,ta]);let Ml=useCallback(w=>{let M=w.target.getClassName(),T=w.target===w.target.getStage(),O=M==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",De=M==="Image",Le=M==="Text",ae=M==="Group"||w.target.getParent()?.getClassName()==="Group",Pt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&w.target.attrs.id,bt=M==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:M,clickedOnImage:De,clickedOnGroup:ae,tool:u,targetId:w.target.attrs?.id}),T&&!O&&!De&&!Le&&!ae&&!Pt&&!bt&&Vr(),!(u==="pen"||u==="eraser")&&(De||Le||O||ae||Pt||bt))return;let je=w.target.getStage()?.getPointerPosition();if(!je)return;["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)||Ar(je);},[u,Ar,Vr]),Tl=useCallback(w=>{if(Sl)return;let M=w.target.getStage()?.getPointerPosition();M&&Ca(M);},[Ca,Sl]),Al=useCallback(()=>{Pr();},[Pr]),qf=useCallback(w=>{se(w,re);},[se,re]),Uf=useCallback(w=>{ie(w),He(w);},[ie,He]),xt=useCallback((w,M,T)=>{w.preventDefault();let O=w.clientX,De=w.clientY,Le=L.current?.offsetHeight||450,ae=L.current?.offsetWidth||450,Pt=window.innerHeight,bt=window.innerWidth,tt=O,je=De;De+Le>Pt&&(je=De-Le),O+ae>bt&&(tt=O-ae),A({x:tt,y:je,elementId:M,elementType:T}),He(M);},[He]),Pl=useCallback(w=>{i(No(w)),i(na(true));},[i]),Hf=useCallback(w=>{i(Fo(w)),i(Ra(true));},[i]),zf=useCallback((w,M)=>{if(!P)return;let{elementId:T,elementType:O}=P;switch(w){case "order":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"order"});}break;case "lock":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"lock"});}break;case "link":if(A(null),O==="line")break;let De=l?O==="image"?l.images.find(k=>k.id===T):l.videos.find(k=>k.id===T):null;q({type:"link",defaultValue:De?.link||""});break;case "voice":if(A(null),O==="line")break;let Le=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="text"?l.texts.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):O==="mcq"?l.multipleChoices.find(k=>k.id===T):O==="fillInTheBlanks"?l.fillInTheBlanks.find(k=>k.id===T):O==="longAnswer"?l.LongAnswer.find(k=>k.id===T):O==="shortAnswer"?l.shortAnswers.find(k=>k.id===T):O==="trueFalse"?l.trueFalses.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;Z({elementId:T,elementType:O,existingAudio:Le?.audioData});break;case "edit":A(null);let ae=null;O==="mcq"?ae=l?.multipleChoices.find(k=>k.id===T):O==="trueFalse"?ae=l?.trueFalses.find(k=>k.id===T):O==="shortAnswer"?ae=l?.shortAnswers.find(k=>k.id===T):O==="longAnswer"?ae=l?.LongAnswer.find(k=>k.id===T):O==="fillInTheBlanks"&&(ae=l?.fillInTheBlanks.find(k=>k.id===T)),ae&&Pl(ae);break;case "editFlashcard":A(null);let Pt=l?.flashcards.find(k=>k.id===T);Pt&&Hf(Pt);break;case "color":A(null);let bt=l?.shapes.find(k=>k.id===T);oe({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(A(null),O==="image"){let k=l?.images.find(Xf=>Xf.id===T);k&&z({elementId:T,imageSrc:k.src});}break;case "draw":A(null),O==="image"?i(ks(T)):O==="photoFrame"&&i(Ts(T));break;case "duplicate":i(ue()),O==="line"?i(_s(T)):O==="image"?i(Ur(T)):O==="video"?i(Wr(T)):O==="shape"?i(Gr(T)):O==="text"?i(Kr(T)):O==="flashcard"?i(_r(T)):O==="photoFrame"?i(jr(T)):O==="mcq"?i($r(T)):O==="trueFalse"?i(Xr(T)):O==="shortAnswer"?i(Yr(T)):O==="fillInTheBlanks"?i(Zr(T)):O==="longAnswer"&&i(Jr(T)),re();break;case "infinite-clone":i(ue());let tt=5;for(let k=0;k<tt;k++)O==="image"?i(Ur(T)):O==="video"?i(Wr(T)):O==="shape"?i(Gr(T)):O==="text"?i(Kr(T)):O==="flashcard"?i(_r(T)):O==="photoFrame"?i(jr(T)):O==="mcq"?i($r(T)):O==="trueFalse"?i(Xr(T)):O==="shortAnswer"?i(Yr(T)):O==="fillInTheBlanks"?i(Zr(T)):O==="longAnswer"&&i(Jr(T));re();break;case "make-response":if(A(null),O==="line")break;let je=`#response-${T}`;i(ue()),i(Qr({id:T,type:O,link:je})),(l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):l.multipleChoices.find(k=>k.id===T):null)?.altText||i(en({id:T,type:O,altText:"Interactive response area"})),re(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(A(null),O==="line")break;let V=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;q({type:"altText",defaultValue:V?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),A(null),pe(true),console.log("showLayersPanel state set to:",true);break;case "delete":i(ue()),O==="line"?i(Ks(T)):O==="image"?i(ps(T)):O==="video"?i(hs(T)):O==="shape"?i(xs(T)):O==="text"?i(vs(T)):O==="flashcard"?i(ws(T)):O==="photoFrame"?i(Cs(T)):O==="mcq"?i(Rs(T)):O==="trueFalse"?i(Fs(T)):O==="shortAnswer"?i(Bs(T)):O==="longAnswer"?i(Ns(T)):O==="fillInTheBlanks"&&i(qs(T)),Vr(),re();break}},[P,i,re,Vr,l,Pl]),Wf=useCallback(()=>{A(null),N(null);},[]),as=useCallback(w=>{if(!P)return;let{elementId:M,elementType:T}=P;switch(i(ue()),w){case "bring-to-front":T!=="line"&&i(Hs({id:M,type:T}));break;case "send-to-back":T!=="line"&&i(zs({id:M,type:T}));break;case "lock":case "unlock":T!=="line"&&i(Ws({id:M,type:T}));break}re(),A(null),N(null);},[P,i,re]),Gf=useCallback(w=>{if(!P||!te)return;let{elementId:M,elementType:T}=P;i(ue()),te.type==="link"&&T!=="line"?i(Qr({id:M,type:T,link:w})):te.type==="altText"&&T!=="line"&&i(en({id:M,type:T,altText:w})),re(),q(null);},[P,te,i,re]),Kf=useCallback(w=>{if(!Y)return;let{elementId:M,elementType:T}=Y;i(ue()),i(tn({id:M,type:T,audioData:w})),re(),Z(null);},[Y,i,re]),_f=useCallback(()=>{if(!Y)return;let{elementId:w,elementType:M}=Y;i(ue()),i(tn({id:w,type:M,audioData:""})),re();},[Y,i,re]),jf=useCallback(w=>{if(!G)return;let{elementId:M}=G;i(ue()),i(Ya({id:M,color:w})),re(),oe(null);},[G,i,re]),$f=useCallback(w=>{if(!R)return;let{elementId:M}=R;i(ue()),i(Xa({id:M,src:w})),re(),z(null);},[R,i,re]);return jsxs("div",{ref:x,className:n||"fixed top-[90px] right-80 bottom-0 left-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default",...s},children:[u==="pen"&&jsx(Wl,{ref:w=>{if(Re.current=w,Xn(w),w){let M=w.getCanvasElement();M&&(Me.current=M,a&&a(Me));}},width:y.width,height:y.height,tool:Yn,color:Rr,strokeWidth:Jn,isSketchMode:Zn}),jsxs(Stage,{ref:h,width:y.width,height:y.height,onMouseDown:Ml,onMouseMove:Tl,onMouseUp:Al,onTouchStart:Ml,onTouchMove:Tl,onTouchEnd:Al,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:y.width,height:y.height,fill:l?.backgroundColor||"white"})}),jsx(Layer,{children:(()=>{let w=[];return f.forEach((M,T)=>{w.push({type:"line",timestamp:M.timestamp||T,element:{...M,id:M.id??`line-${T}`},index:T});}),Sf.forEach(M=>{w.push({type:"shape",timestamp:M.timestamp||0,element:M});}),Qn.forEach(M=>{w.push({type:"image",timestamp:M.timestamp||0,element:M});}),me.forEach(M=>{w.push({type:"video",timestamp:M.timestamp||0,element:M});}),Ro.forEach(M=>{w.push({type:"text",timestamp:M.timestamp||0,element:M});}),Af.forEach(M=>{w.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),kl.forEach(M=>{w.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),Kt.forEach(M=>{w.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),_t.forEach(M=>{w.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Dr.forEach(M=>{w.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),Aa.forEach(M=>{w.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),wf.forEach(M=>{w.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),w.sort((M,T)=>M.timestamp-T.timestamp),w.map((M,T)=>{let O=`${M.type}-${"id"in M.element&&M.element.id||M.index||T}`,De="id"in M.element?M.element.id:void 0,Le=De&&m===De;switch(M.type){case "line":let ae=M.element,Pt=M.index||0,bt=ae.tool==="eraser",tt=ae.isSketch&&ae.tool==="pen",je=ae.isSketch&&bt,vt=ae.id||`line-${Pt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{i(ue()),i(qr(Pt));},onTap:()=>{i(ue()),i(qr(Pt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:V=>{let k=V.target.getStage();k&&(k.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:V=>{let k=V.target.getStage();k&&(k.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:V=>{V?ka.current.set(vt,V):ka.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",vt),He(vt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",vt),He(vt));},onDragEnd:V=>{i(ue()),i(an({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onTransformEnd:V=>{i(ue()),i(an({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onMouseEnter:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="move");}},onMouseLeave:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="default");}},onContextMenu:V=>{let k=V.evt;k.preventDefault(),xt(k,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=ka.current.get(m);console.log("Line Transformer - selectedId:",m,"node found:",!!k),k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shape":return jsxs(be__default.Fragment,{children:[jsx(ii,{onSelect:He,shapes:[M.element],shapeRefs:Fr,handleShapeDragEnd:If,handleShapeResizeEnd:Cf,onContextMenu:xt}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Fr.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "image":return jsxs(be__default.Fragment,{children:[jsx(oi,{images:[M.element],getLoadedImage:es,imageRefs:B,onDragEnd:qf,onTransform:Ie,onSelect:He,onContextMenu:xt}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=B.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "video":return jsxs(be__default.Fragment,{children:[jsx(si,{videos:[M.element],selectedId:m,videoRefs:ne,onVideoClick:Uf,onDragEnd:Ve,onTransformEnd:Vt,onContextMenu:xt}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=ne.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "text":return jsxs(be__default.Fragment,{children:[jsx(Ld,{texts:[M.element],textRefs:ta,onDragEnd:kf,onTransformEnd:Mf,onSelect:He,onContextMenu:xt,onDoubleClick:Tf,editingTextId:he,editingValue:Il,onEditingChange:Cl}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=ta.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(ui,{flashcards:[M.element],flashcardRefs:Or,selectedId:m,onDragEnd:Pf,onTransform:Rf,onSelect:He,onNext:Df,onPrevious:Ff,onContextMenu:xt}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Or.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(hi,{photoFrames:[M.element],photoFrameRefs:Nr,selectedId:m,onDragEnd:Ef,onTransform:Bf,onSelect:He,onStartCamera:Of,onCapture:Nf,cameraStreams:Vf,onContextMenu:xt}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Nr.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Yd,{handleMcqTransform:_e,multipleChoice:[M.element],handleSelect:He,mcqRefs:Ce,handleDragEnd:Je,onContextMenu:xt}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ce.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Qd,{trueFalses:[M.element],handleTrueFalseTransform:Ma,handleSelect:He,trueFalseRefs:Ta,onContextMenu:xt,handleDragEnd:$a}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ta.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(xu,{shortAnswers:[M.element],handleSelect:He,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:ea}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Iu,{longAnswer:[M.element],handleSelect:He,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:yf}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Lu,{fillInTheBlanks:[M.element],handleSelect:He,handleTransform:_e,onContextMenu:xt,handleDragEnd:Lf}),Le&&!he&&m&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(m);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);default:return null}})})()})]}),P&&r?.enabled!==false&&jsx(Bd,{menuRef:L,x:P.x,y:P.y,type:P.elementType,elementId:P.elementId,onAction:zf,onClose:Wf,isDrawingMode:P.elementType==="image"?l?.images.find(w=>w.id===P.elementId)?.isDrawingMode:P.elementType==="photoFrame"?l?.photoFrames.find(w=>w.id===P.elementId)?.isDrawingMode:false}),H&&P&&jsx(Od,{x:H.x,y:H.y,items:H.type==="order"?[{label:"Bring to Front",onClick:()=>as("bring-to-front")},{label:"Send to Back",onClick:()=>as("send-to-back")}]:[{label:l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"Unlock":"Lock",onClick:()=>as(l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"unlock":"lock")}],onClose:()=>N(null)}),te&&jsx(Nd,{title:te.type==="link"?"Add Link":"Add Alt Text",label:te.type==="link"?"URL":"Alternative Text",placeholder:te.type==="link"?"https://example.com":"Describe this image/video",defaultValue:te.defaultValue,onSave:Gf,onClose:()=>q(null)}),G&&jsx(Vd,{defaultColor:G.defaultColor,onConfirm:jf,onCancel:()=>oe(null)}),R&&jsx(zd,{imageSrc:R.imageSrc,onConfirm:$f,onCancel:()=>z(null)}),X&&jsx(Xo,{onClose:()=>_(false),stageRef:h}),Y&&jsx(Gd,{elementId:Y.elementId,elementType:Y.elementType,existingAudio:Y.existingAudio,onSave:Kf,onDelete:_f,onClose:()=>Z(null)}),Q&&jsx(jd,{selectedElementId:m||void 0,onClose:()=>pe(false),onSelectElement:w=>{He(w),pe(false);}}),l?.images.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.videos.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shapes?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.texts?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.flashcards?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(Lt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),p&&jsx(uu,{editElement:d}),U&&(()=>{let w=he||m;if(!w)return null;let M=Ro.find(T=>T.id===w);return M?jsx(cu,{text:M,position:U}):null})(),E&&he&&(()=>{let w=Ro.find(M=>M.id===he);return w?jsx(mu,{text:w,editingValue:Il,onEditingChange:Cl,onFinish:ts,position:{top:E.top,left:E.left},scale:E.scale,textareaRef:we},he):null})()]})},Bx=Ex;var Ox="SchooplaVideoStorage";var ba="videos",Gi=()=>new Promise((e,o)=>{let t=indexedDB.open(Ox,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ba)||r.createObjectStore(ba,{keyPath:"id"});};}),xr=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Gi(),n=a.transaction([ba],"readwrite").objectStore(ba),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,u)=>{let l=n.put(s);l.onsuccess=()=>i(!0),l.onerror=()=>u(l.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var Tu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Gi(),t=e.transaction([ba],"readonly").objectStore(ba);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,i=new Map;s.forEach(u=>{i.set(u.id,{blob:u.blob,thumbnailDataUrl:u.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${i.size} video blobs from IndexedDB`),a(i);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Ki=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Gi(),a=o.transaction([ba],"readwrite").objectStore(ba);await new Promise((r,n)=>{let s=a.delete(e);s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}};var Au=e=>URL.createObjectURL(e);function va(e,o=[]){let t=[];function a(n,s){let i=be.createContext(s),u=t.length;t=[...t,s];let l=d=>{let{scope:p,children:f,...h}=d,x=p?.[e]?.[u]||i,m=be.useMemo(()=>h,Object.values(h));return jsx(x.Provider,{value:m,children:f})};l.displayName=n+"Provider";function c(d,p){let f=p?.[e]?.[u]||i,h=be.useContext(f);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${n}\``)}return [l,c]}let r=()=>{let n=t.map(s=>be.createContext(s));return function(i){let u=i?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:u}}),[i,u])}};return r.scopeName=e,[a,Vx(r,...o)]}function Vx(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let s=a.reduce((i,{useScope:u,scopeName:l})=>{let d=u(n)[`__scope${l}`];return {...i,...d}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function Pu(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function br(...e){return o=>{let t=false,a=e.map(r=>{let n=Pu(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():Pu(e[r],null);}}}}function Tt(...e){return be.useCallback(br(...e),e)}function Fu(e){let o=qx(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,i=be.Children.toArray(n),u=i.find(Hx);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...s,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function qx(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=Wx(r),i=zx(n,r.props);return r.type!==be.Fragment&&(i.ref=a?br(a,s):s),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Ux=Symbol("radix.slottable");function Hx(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ux}function zx(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...i)=>{let u=n(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function Wx(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var _x=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=_x.reduce((e,o)=>{let t=Fu(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:s,...i}=r,u=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(u,{...i,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function Xe(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function _i(e){let o=jx(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,i=be.Children.toArray(n),u=i.find(Xx);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...s,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function jx(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=Jx(r),i=Yx(n,r.props);return r.type!==be.Fragment&&(i.ref=a?br(a,s):s),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var $x=Symbol("radix.slottable");function Xx(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$x}function Yx(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...i)=>{let u=n(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function Jx(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function Bn(e){let o=e+"CollectionProvider",[t,a]=va(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=x=>{let{scope:m,children:v}=x,g=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(r,{scope:m,itemMap:b,collectionRef:g,children:v})};s.displayName=o;let i=e+"CollectionSlot",u=_i(i),l=be__default.forwardRef((x,m)=>{let{scope:v,children:g}=x,b=n(i,v),y=Tt(m,b.collectionRef);return jsx(u,{ref:y,children:g})});l.displayName=i;let c=e+"CollectionItemSlot",d="data-radix-collection-item",p=_i(c),f=be__default.forwardRef((x,m)=>{let{scope:v,children:g,...b}=x,y=be__default.useRef(null),S=Tt(m,y),I=n(c,v);return be__default.useEffect(()=>(I.itemMap.set(y,{ref:y,...b}),()=>void I.itemMap.delete(y))),jsx(p,{[d]:"",ref:S,children:g})});f.displayName=c;function h(x){let m=n(e+"CollectionConsumer",x);return be__default.useCallback(()=>{let g=m.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(m.itemMap.values()).sort((I,C)=>b.indexOf(I.ref.current)-b.indexOf(C.ref.current))},[m.collectionRef,m.itemMap])}return [{Provider:s,Slot:l,ItemSlot:f},h,a]}var yo=globalThis?.document?be.useLayoutEffect:()=>{};var Zx=be[" useId ".trim().toString()]||(()=>{}),Qx=0;function Nu(e){let[o,t]=be.useState(Zx());return yo(()=>{t(a=>a??String(Qx++));},[e]),(o?`radix-${o}`:"")}function Vu(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var eb=be[" useInsertionEffect ".trim().toString()]||yo;function Xt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=tb({defaultProp:o,onChange:t}),i=e!==void 0,u=i?e:r;{let c=be.useRef(e!==void 0);be.useEffect(()=>{let d=c.current;d!==i&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${i?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),c.current=i;},[i,a]);}let l=be.useCallback(c=>{if(i){let d=ab(c)?c(e):c;d!==e&&s.current?.(d);}else n(c);},[i,e,n,s]);return [u,l]}function tb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return eb(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function ab(e){return typeof e=="function"}var ob=be.createContext(void 0);function Lo(e){let o=be.useContext(ob);return e||o||"ltr"}var Xi="rovingFocusGroup.onEntryFocus",rb={bubbles:false,cancelable:true},vr="RovingFocusGroup",[Yi,qu,nb]=Bn(vr),[sb,Ji]=va(vr,[nb]),[ib,lb]=sb(vr),Uu=be.forwardRef((e,o)=>jsx(Yi.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Yi.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(db,{...e,ref:o})})}));Uu.displayName=vr;var db=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:u,onEntryFocus:l,preventScrollOnEntryFocus:c=false,...d}=e,p=be.useRef(null),f=Tt(o,p),h=Lo(n),[x,m]=Xt({prop:s,defaultProp:i??null,onChange:u,caller:vr}),[v,g]=be.useState(false),b=Vu(l),y=qu(t),S=be.useRef(false),[I,C]=be.useState(0);return be.useEffect(()=>{let L=p.current;if(L)return L.addEventListener(Xi,b),()=>L.removeEventListener(Xi,b)},[b]),jsx(ib,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:x,onItemFocus:be.useCallback(L=>m(L),[m]),onItemShiftTab:be.useCallback(()=>g(true),[]),onFocusableItemAdd:be.useCallback(()=>C(L=>L+1),[]),onFocusableItemRemove:be.useCallback(()=>C(L=>L-1),[]),children:jsx(it.div,{tabIndex:v||I===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:Xe(e.onMouseDown,()=>{S.current=true;}),onFocus:Xe(e.onFocus,L=>{let P=!S.current;if(L.target===L.currentTarget&&P&&!v){let A=new CustomEvent(Xi,rb);if(L.currentTarget.dispatchEvent(A),!A.defaultPrevented){let U=y().filter(N=>N.focusable),F=U.find(N=>N.active),E=U.find(N=>N.id===x),H=[F,E,...U].filter(Boolean).map(N=>N.ref.current);Wu(H,c);}}S.current=false;}),onBlur:Xe(e.onBlur,()=>g(false))})})}),Hu="RovingFocusGroupItem",zu=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...i}=e,u=Nu(),l=n||u,c=lb(Hu,t),d=c.currentTabStopId===l,p=qu(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:x}=c;return be.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Yi.ItemSlot,{scope:t,id:l,focusable:a,active:r,children:jsx(it.span,{tabIndex:d?0:-1,"data-orientation":c.orientation,...i,ref:o,onMouseDown:Xe(e.onMouseDown,m=>{a?c.onItemFocus(l):m.preventDefault();}),onFocus:Xe(e.onFocus,()=>c.onItemFocus(l)),onKeyDown:Xe(e.onKeyDown,m=>{if(m.key==="Tab"&&m.shiftKey){c.onItemShiftTab();return}if(m.target!==m.currentTarget)return;let v=fb(m,c.orientation,c.dir);if(v!==void 0){if(m.metaKey||m.ctrlKey||m.altKey||m.shiftKey)return;m.preventDefault();let b=p().filter(y=>y.focusable).map(y=>y.ref.current);if(v==="last")b.reverse();else if(v==="prev"||v==="next"){v==="prev"&&b.reverse();let y=b.indexOf(m.currentTarget);b=c.loop?mb(b,y+1):b.slice(y+1);}setTimeout(()=>Wu(b));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:x!=null}):s})})});zu.displayName=Hu;var ub={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cb(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function fb(e,o,t){let a=cb(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return ub[a]}function Wu(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function mb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Gu=Uu,Ku=zu;var ju="Toggle",Zi=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,i]=Xt({prop:t,onChange:r,defaultProp:a??false,caller:ju});return jsx(it.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:Xe(e.onClick,()=>{e.disabled||i(!s);})})});Zi.displayName=ju;var ya="ToggleGroup",[Xu]=va(ya,[Ji]),Yu=Ji(),Qi=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(gb,{...a,ref:o});if(t==="multiple")return jsx(xb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${ya}\``)});Qi.displayName=ya;var[Ju,Zu]=Xu(ya),gb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,i]=Xt({prop:t,defaultProp:a??"",onChange:r,caller:ya});return jsx(Ju,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(Qu,{...n,ref:o})})}),xb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,i]=Xt({prop:t,defaultProp:a??[],onChange:r,caller:ya}),u=be__default.useCallback(c=>i((d=[])=>[...d,c]),[i]),l=be__default.useCallback(c=>i((d=[])=>d.filter(p=>p!==c)),[i]);return jsx(Ju,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:u,onItemDeactivate:l,children:jsx(Qu,{...n,ref:o})})});Qi.displayName=ya;var[bb,vb]=Xu(ya),Qu=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:i=true,...u}=e,l=Yu(t),c=Lo(s),d={role:"group",dir:c,...u};return jsx(bb,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(Gu,{asChild:true,...l,orientation:n,dir:c,loop:i,children:jsx(it.div,{...d,ref:o})}):jsx(it.div,{...d,ref:o})})}),Vn="ToggleGroupItem",yb=be__default.forwardRef((e,o)=>{let t=Zu(Vn,e.__scopeToggleGroup),a=vb(Vn,e.__scopeToggleGroup),r=Yu(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,i={...e,pressed:n,disabled:s},u=be__default.useRef(null);return a.rovingFocus?jsx(Ku,{asChild:true,...r,focusable:!s,active:n,ref:u,children:jsx($u,{...i,ref:o})}):jsx($u,{...i,ref:o})});yb.displayName=Vn;var $u=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=Zu(Vn,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=n.type==="single"?s:void 0;return jsx(Zi,{...i,...r,ref:o,onPressedChange:u=>{u?n.onItemActivate(a):n.onItemDeactivate(a);}})}),ec=Qi;function tc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=tc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function qn(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=tc(e))&&(a&&(a+=" "),a+=o);return a}var Lb=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},Sb=(e,o)=>({classGroupId:e,validator:o}),sc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var ac=[],Ib="arbitrary..",Cb=e=>{let o=Mb(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return kb(s);let i=s.split("-"),u=i[0]===""&&i.length>1?1:0;return ic(i,u,o)},getConflictingClassGroupIds:(s,i)=>{if(i){let u=a[s],l=t[s];return u?l?Lb(l,u):u:l||ac}return t[s]||ac}}},ic=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let l=ic(e,o+1,n);if(l)return l}let s=t.validators;if(s===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),u=s.length;for(let l=0;l<u;l++){let c=s[l];if(c.validator(i))return c.classGroupId}},kb=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?Ib+a:void 0})(),Mb=e=>{let{theme:o,classGroups:t}=e;return Tb(t,o)},Tb=(e,o)=>{let t=sc();for(let a in e){let r=e[a];al(r,t,a,o);}return t},al=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];Ab(s,o,t,a);}},Ab=(e,o,t,a)=>{if(typeof e=="string"){Pb(e,o,t);return}if(typeof e=="function"){Rb(e,o,t,a);return}Db(e,o,t,a);},Pb=(e,o,t)=>{let a=e===""?o:lc(o,e);a.classGroupId=t;},Rb=(e,o,t,a)=>{if(Fb(e)){al(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Sb(t,e));},Db=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[i,u]=r[s];al(u,lc(o,i),t,a);}},lc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let s=a[n],i=t.nextPart.get(s);i||(i=sc(),t.nextPart.set(s,i)),t=i;}return t},Fb=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Eb=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,s)=>{t[n]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let s=t[n];if(s!==void 0)return s;if((s=a[n])!==void 0)return r(n,s),s},set(n,s){n in t?t[n]=s:r(n,s);}}};var Bb=[],oc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),Ob=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,i=0,u=0,l,c=r.length;for(let x=0;x<c;x++){let m=r[x];if(s===0&&i===0){if(m===":"){n.push(r.slice(u,x)),u=x+1;continue}if(m==="/"){l=x;continue}}m==="["?s++:m==="]"?s--:m==="("?i++:m===")"&&i--;}let d=n.length===0?r:r.slice(u),p=d,f=false;d.endsWith("!")?(p=d.slice(0,-1),f=true):d.startsWith("!")&&(p=d.slice(1),f=true);let h=l&&l>u?l-u:void 0;return oc(n,f,p,h)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):oc(Bb,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},Nb=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let s=t[n],i=s[0]==="[",u=o.has(s);i||u?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(s)):r.push(s);}return r.length>0&&(r.sort(),a.push(...r)),a}},Vb=e=>({cache:Eb(e.cacheSize),parseClassName:Ob(e),sortModifiers:Nb(e),...Cb(e)}),qb=/\s+/,Ub=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],i=e.trim().split(qb),u="";for(let l=i.length-1;l>=0;l-=1){let c=i[l],{isExternal:d,modifiers:p,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:x}=t(c);if(d){u=c+(u.length>0?" "+u:u);continue}let m=!!x,v=a(m?h.substring(0,x):h);if(!v){if(!m){u=c+(u.length>0?" "+u:u);continue}if(v=a(h),!v){u=c+(u.length>0?" "+u:u);continue}m=false;}let g=p.length===0?"":p.length===1?p[0]:n(p).join(":"),b=f?g+"!":g,y=b+v;if(s.indexOf(y)>-1)continue;s.push(y);let S=r(v,m);for(let I=0;I<S.length;++I){let C=S[I];s.push(b+C);}u=c+(u.length>0?" "+u:u);}return u},Hb=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=dc(t))&&(r&&(r+=" "),r+=a);return r},dc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=dc(e[a]))&&(t&&(t+=" "),t+=o);return t},zb=(e,...o)=>{let t,a,r,n,s=u=>{let l=o.reduce((c,d)=>d(c),e());return t=Vb(l),a=t.cache.get,r=t.cache.set,n=i,i(u)},i=u=>{let l=a(u);if(l)return l;let c=Ub(u,t);return r(u,c),c};return n=s,(...u)=>n(Hb(...u))},Wb=[],Ne=e=>{let o=t=>t[e]||Wb;return o.isThemeGetter=true,o},uc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,cc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Gb=/^\d+\/\d+$/,Kb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,_b=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,jb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$b=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Xb=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,So=e=>Gb.test(e),le=e=>!!e&&!Number.isNaN(Number(e)),wa=e=>!!e&&Number.isInteger(Number(e)),el=e=>e.endsWith("%")&&le(e.slice(0,-1)),Yt=e=>Kb.test(e),Yb=()=>true,Jb=e=>_b.test(e)&&!jb.test(e),fc=()=>false,Zb=e=>$b.test(e),Qb=e=>Xb.test(e),ev=e=>!j(e)&&!$(e),tv=e=>Io(e,hc,fc),j=e=>uc.test(e),Ga=e=>Io(e,gc,Jb),tl=e=>Io(e,sv,le),rc=e=>Io(e,mc,fc),av=e=>Io(e,pc,Qb),Un=e=>Io(e,xc,Zb),$=e=>cc.test(e),yr=e=>Co(e,gc),ov=e=>Co(e,iv),nc=e=>Co(e,mc),rv=e=>Co(e,hc),nv=e=>Co(e,pc),Hn=e=>Co(e,xc,true),Io=(e,o,t)=>{let a=uc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Co=(e,o,t=false)=>{let a=cc.exec(e);return a?a[1]?o(a[1]):t:false},mc=e=>e==="position"||e==="percentage",pc=e=>e==="image"||e==="url",hc=e=>e==="length"||e==="size"||e==="bg-size",gc=e=>e==="length",sv=e=>e==="number",iv=e=>e==="family-name",xc=e=>e==="shadow";var lv=()=>{let e=Ne("color"),o=Ne("font"),t=Ne("text"),a=Ne("font-weight"),r=Ne("tracking"),n=Ne("leading"),s=Ne("breakpoint"),i=Ne("container"),u=Ne("spacing"),l=Ne("radius"),c=Ne("shadow"),d=Ne("inset-shadow"),p=Ne("text-shadow"),f=Ne("drop-shadow"),h=Ne("blur"),x=Ne("perspective"),m=Ne("aspect"),v=Ne("ease"),g=Ne("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],y=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],S=()=>[...y(),$,j],I=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],L=()=>[$,j,u],P=()=>[So,"full","auto",...L()],A=()=>[wa,"none","subgrid",$,j],U=()=>["auto",{span:["full",wa,$,j]},wa,$,j],F=()=>[wa,"auto",$,j],E=()=>["auto","min","max","fr",$,j],D=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],H=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...L()],te=()=>[So,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...L()],q=()=>[e,$,j],G=()=>[...y(),nc,rc,{position:[$,j]}],oe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],R=()=>["auto","cover","contain",rv,tv,{size:[$,j]}],z=()=>[el,yr,Ga],X=()=>["","none","full",l,$,j],_=()=>["",le,yr,Ga],Y=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[le,el,nc,rc],pe=()=>["","none",h,$,j],we=()=>["none",le,$,j],Re=()=>["none",le,$,j],Me=()=>[le,$,j],Ue=()=>[So,"full",...L()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Yt],breakpoint:[Yt],color:[Yb],container:[Yt],"drop-shadow":[Yt],ease:["in","out","in-out"],font:[ev],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Yt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Yt],shadow:[Yt],spacing:["px",le],text:[Yt],"text-shadow":[Yt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",So,j,$,m]}],container:["container"],columns:[{columns:[le,j,$,i]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:S()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:P()}],"inset-x":[{"inset-x":P()}],"inset-y":[{"inset-y":P()}],start:[{start:P()}],end:[{end:P()}],top:[{top:P()}],right:[{right:P()}],bottom:[{bottom:P()}],left:[{left:P()}],visibility:["visible","invisible","collapse"],z:[{z:[wa,"auto",$,j]}],basis:[{basis:[So,"full","auto",i,...L()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[le,So,"auto","initial","none",j]}],grow:[{grow:["",le,$,j]}],shrink:[{shrink:["",le,$,j]}],order:[{order:[wa,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":A()}],"col-start-end":[{col:U()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":A()}],"row-start-end":[{row:U()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":E()}],"auto-rows":[{"auto-rows":E()}],gap:[{gap:L()}],"gap-x":[{"gap-x":L()}],"gap-y":[{"gap-y":L()}],"justify-content":[{justify:[...D(),"normal"]}],"justify-items":[{"justify-items":[...H(),"normal"]}],"justify-self":[{"justify-self":["auto",...H()]}],"align-content":[{content:["normal",...D()]}],"align-items":[{items:[...H(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...H(),{baseline:["","last"]}]}],"place-content":[{"place-content":D()}],"place-items":[{"place-items":[...H(),"baseline"]}],"place-self":[{"place-self":["auto",...H()]}],p:[{p:L()}],px:[{px:L()}],py:[{py:L()}],ps:[{ps:L()}],pe:[{pe:L()}],pt:[{pt:L()}],pr:[{pr:L()}],pb:[{pb:L()}],pl:[{pl:L()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":L()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":L()}],"space-y-reverse":["space-y-reverse"],size:[{size:te()}],w:[{w:[i,"screen",...te()]}],"min-w":[{"min-w":[i,"screen","none",...te()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[s]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",t,yr,Ga]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,tl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",el,j]}],"font-family":[{font:[ov,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,j]}],"line-clamp":[{"line-clamp":[le,"none",$,tl]}],leading:[{leading:[n,...L()]}],"list-image":[{"list-image":["none",$,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:q()}],"text-color":[{text:q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[le,"from-font","auto",$,Ga]}],"text-decoration-color":[{decoration:q()}],"underline-offset":[{"underline-offset":[le,"auto",$,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:L()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:G()}],"bg-repeat":[{bg:oe()}],"bg-size":[{bg:R()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},wa,$,j],radial:["",$,j],conic:[wa,$,j]},nv,av]}],"bg-color":[{bg:q()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:q()}],"gradient-via":[{via:q()}],"gradient-to":[{to:q()}],rounded:[{rounded:X()}],"rounded-s":[{"rounded-s":X()}],"rounded-e":[{"rounded-e":X()}],"rounded-t":[{"rounded-t":X()}],"rounded-r":[{"rounded-r":X()}],"rounded-b":[{"rounded-b":X()}],"rounded-l":[{"rounded-l":X()}],"rounded-ss":[{"rounded-ss":X()}],"rounded-se":[{"rounded-se":X()}],"rounded-ee":[{"rounded-ee":X()}],"rounded-es":[{"rounded-es":X()}],"rounded-tl":[{"rounded-tl":X()}],"rounded-tr":[{"rounded-tr":X()}],"rounded-br":[{"rounded-br":X()}],"rounded-bl":[{"rounded-bl":X()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"hidden","none"]}],"border-color":[{border:q()}],"border-color-x":[{"border-x":q()}],"border-color-y":[{"border-y":q()}],"border-color-s":[{"border-s":q()}],"border-color-e":[{"border-e":q()}],"border-color-t":[{"border-t":q()}],"border-color-r":[{"border-r":q()}],"border-color-b":[{"border-b":q()}],"border-color-l":[{"border-l":q()}],"divide-color":[{divide:q()}],"outline-style":[{outline:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[le,$,j]}],"outline-w":[{outline:["",le,yr,Ga]}],"outline-color":[{outline:q()}],shadow:[{shadow:["","none",c,Hn,Un]}],"shadow-color":[{shadow:q()}],"inset-shadow":[{"inset-shadow":["none",d,Hn,Un]}],"inset-shadow-color":[{"inset-shadow":q()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:q()}],"ring-offset-w":[{"ring-offset":[le,Ga]}],"ring-offset-color":[{"ring-offset":q()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":q()}],"text-shadow":[{"text-shadow":["none",p,Hn,Un]}],"text-shadow-color":[{"text-shadow":q()}],opacity:[{opacity:[le,$,j]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[le]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":q()}],"mask-image-linear-to-color":[{"mask-linear-to":q()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":q()}],"mask-image-t-to-color":[{"mask-t-to":q()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":q()}],"mask-image-r-to-color":[{"mask-r-to":q()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":q()}],"mask-image-b-to-color":[{"mask-b-to":q()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":q()}],"mask-image-l-to-color":[{"mask-l-to":q()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":q()}],"mask-image-x-to-color":[{"mask-x-to":q()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":q()}],"mask-image-y-to-color":[{"mask-y-to":q()}],"mask-image-radial":[{"mask-radial":[$,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":q()}],"mask-image-radial-to-color":[{"mask-radial-to":q()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":y()}],"mask-image-conic-pos":[{"mask-conic":[le]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":q()}],"mask-image-conic-to-color":[{"mask-conic-to":q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:G()}],"mask-repeat":[{mask:oe()}],"mask-size":[{mask:R()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:pe()}],brightness:[{brightness:[le,$,j]}],contrast:[{contrast:[le,$,j]}],"drop-shadow":[{"drop-shadow":["","none",f,Hn,Un]}],"drop-shadow-color":[{"drop-shadow":q()}],grayscale:[{grayscale:["",le,$,j]}],"hue-rotate":[{"hue-rotate":[le,$,j]}],invert:[{invert:["",le,$,j]}],saturate:[{saturate:[le,$,j]}],sepia:[{sepia:["",le,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[le,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[le,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",le,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[le,$,j]}],"backdrop-invert":[{"backdrop-invert":["",le,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[le,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[le,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",le,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":L()}],"border-spacing-x":[{"border-spacing-x":L()}],"border-spacing-y":[{"border-spacing-y":L()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[le,"initial",$,j]}],ease:[{ease:["linear","initial",v,$,j]}],delay:[{delay:[le,$,j]}],animate:[{animate:["none",g,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[x,$,j]}],"perspective-origin":[{"perspective-origin":S()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:Re()}],"scale-x":[{"scale-x":Re()}],"scale-y":[{"scale-y":Re()}],"scale-z":[{"scale-z":Re()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:S()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ue()}],"translate-x":[{"translate-x":Ue()}],"translate-y":[{"translate-y":Ue()}],"translate-z":[{"translate-z":Ue()}],"translate-none":["translate-none"],accent:[{accent:q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:q()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,j]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":L()}],"scroll-mx":[{"scroll-mx":L()}],"scroll-my":[{"scroll-my":L()}],"scroll-ms":[{"scroll-ms":L()}],"scroll-me":[{"scroll-me":L()}],"scroll-mt":[{"scroll-mt":L()}],"scroll-mr":[{"scroll-mr":L()}],"scroll-mb":[{"scroll-mb":L()}],"scroll-ml":[{"scroll-ml":L()}],"scroll-p":[{"scroll-p":L()}],"scroll-px":[{"scroll-px":L()}],"scroll-py":[{"scroll-py":L()}],"scroll-ps":[{"scroll-ps":L()}],"scroll-pe":[{"scroll-pe":L()}],"scroll-pt":[{"scroll-pt":L()}],"scroll-pr":[{"scroll-pr":L()}],"scroll-pb":[{"scroll-pb":L()}],"scroll-pl":[{"scroll-pl":L()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,j]}],fill:[{fill:["none",...q()]}],"stroke-w":[{stroke:[le,yr,Ga,tl]}],stroke:[{stroke:["none",...q()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var bc=zb(lv);function La(...e){return bc(qn(e))}var uv=be.createContext({size:"default",variant:"default",spacing:0});function Sa({className:e,variant:o,size:t,spacing:a=2,children:r,...n}){return jsx(ec,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:La("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(uv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var fv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Sc=createSlice({name:"toolbar",initialState:fv,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:Bt,setPenColor:zn,setStrokeWidth:rl,setFontSize:SA,setFontFamily:IA,setFontStyle:CA,setFontWeight:kA,setTextDecoration:MA,setTextColor:TA}=Sc.actions,Ic=Sc.reducer;var Cc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,n]=useState(null),[s,i]=useState(0),[u,l]=useState(null),[c,d]=useState(false),p=useRef(null),f=useRef([]),h=useRef(null),x=useRef(null),m=useRef(null);useEffect(()=>((async()=>{try{let C=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});l(C),d(!0),m.current&&(m.current.srcObject=C);}catch(C){console.error("Error accessing camera:",C),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),u&&u.getTracks().forEach(C=>C.stop());}),[]);let v=()=>{u&&(u.getTracks().forEach(I=>I.stop()),l(null),d(false));},g=async()=>{try{let I=null,C=null;try{I=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(F){console.error("Error accessing camera for recording:",F),alert("Failed to access camera for recording.");return}try{C=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let L=[...I.getVideoTracks()];C&&L.push(...C.getAudioTracks());let P=new MediaStream(L),A="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?A="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?A="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?A="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(A="video/webm;codecs=vp8");let U=new MediaRecorder(P,{mimeType:A,videoBitsPerSecond:25e5});p.current=U,f.current=[],U.ondataavailable=F=>{F.data.size>0&&f.current.push(F.data);},U.onstop=()=>{let F=new Blob(f.current,{type:A}),E=document.createElement("video");E.src=URL.createObjectURL(F),E.muted=!0,E.currentTime=.1,E.onseeked=()=>{let D=document.createElement("canvas");D.width=E.videoWidth,D.height=E.videoHeight;let H=D.getContext("2d");H&&(H.drawImage(E,0,0),x.current=D.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(E.src);},P.getTracks().forEach(D=>D.stop()),I&&I.getTracks().forEach(D=>D.stop()),C&&C.getTracks().forEach(D=>D.stop()),h.current&&clearInterval(h.current),n(F),v();},U.onerror=F=>{console.error("MediaRecorder error:",F);},U.start(1e3),a(!0),i(0),h.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(I){console.error("Error starting camera recording:",I),alert("Failed to start recording. Please check permissions.");}},b=()=>{p.current&&t&&(p.current.state!=="inactive"&&(p.current.requestData(),setTimeout(()=>{p.current&&p.current.state!=="inactive"&&p.current.stop();},100)),a(false));},y=()=>{if(r){let I=URL.createObjectURL(r),C=document.createElement("a");C.href=I,C.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(I);}},S=I=>{let C=Math.floor(I/60),L=I%60;return `${C.toString().padStart(2,"0")}:${L.toString().padStart(2,"0")}`};return jsx("div",{className:"fixed inset-0 flex items-center justify-center",children:jsxs("div",{className:"relative w-full max-w-2xl overflow-hidden rounded-2xl shadow-2xl",children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:m,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!t&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,disabled:!c,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!c&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),t&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:b,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:S(s)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",S(s)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:y,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&x.current&&(o(r,x.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})})};var Jt=40,Mc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[i,u]=useState(false),l=useRef(null),c=useRef(null);useEffect(()=>{let g=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let d=g=>{let b=g.target.files;if(!b||b.length===0)return;let y=Jt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Jt} images`);return}let S=Array.from(b).slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Jt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=U=>{U.target?.result?L(U.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]),c.current&&(c.current.value="");});},p=g=>{g.preventDefault(),u(false);let b=Array.from(g.dataTransfer.files).filter(C=>C.type.startsWith("image/"));if(b.length===0)return;let y=Jt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Jt} images`);return}let S=b.slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Jt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=U=>{U.target?.result?L(U.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]);});},f=g=>{g.preventDefault(),u(true);},h=()=>{u(false);},x=g=>{r(b=>b.filter((y,S)=>S!==g));},v=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:l,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);},className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=Jt?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",Jt," images"]}):jsxs("span",{children:[a.length,"/",Jt," images"]})})]}),jsx("input",{ref:c,type:"file",accept:"image/*",multiple:true,onChange:d,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:p,onDragOver:f,onDragLeave:h,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${i?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp$1,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:i?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>x(b),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:b+1})]},b))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(v,document.body)};var Wn={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},Mv={enabled:true};function il(e){return e?{tools:{...Wn.tools,...e.tools},actions:{...Wn.actions,...e.actions}}:Wn}var Tv={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Av={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var ay=({isOpen:e,onClose:o,onScreenRecord:t,stageRef:a,onTextAdded:r,showToggleButton:n=true,config:s}={})=>{let i=xe(),u=ee(B=>B.canvas.slides.find(se=>se.id===B.canvas.currentSlideId)),l=u?.videos||[],c=u?.editingFlashcard,d=ee(B=>B.toolbar.selectedTool),p=ee(B=>B.toolbar.penColor),f=u?.showMcqForm,h=u?.showFlashcardForm,x=useMemo(()=>il(s),[s]),{tools:m,actions:v}=x,g=l.some(B=>B.isRecorded&&B.isPlaying),b=ee(B=>B.toolbar.fontSize),y=ee(B=>B.toolbar.fontFamily),S=ee(B=>B.toolbar.fontStyle),I=ee(B=>B.toolbar.fontWeight),C=ee(B=>B.toolbar.textDecoration),L=ee(B=>B.toolbar.textColor),[P,A]=useState(false),[U,F]=useState(false),[E,D]=useState(false),[H,N]=useState(false),[te,q]=useState(false),[G,oe]=useState(true),z=useRef(null),X=useRef(null),Y=[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],Z=useMemo(()=>Y.filter(B=>{let se=m[B.configKey];return typeof se=="boolean"?se:Array.isArray(se)?se.length>0:true}),[m]),Q=[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],pe=useMemo(()=>{let B=m.shapes;return B===false?[]:B===true?Q:Array.isArray(B)?Q.filter(se=>B.includes(se.name)):Q},[m.shapes]),we=[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],Re=useMemo(()=>{let B=m.activities;return B===false?[]:B===true?we:Array.isArray(B)?we.filter(se=>B.includes(se.name)):we},[m.activities]),Me=useMemo(()=>{let B=m.media;return B===false?{photoFrame:false,image:false,video:false}:B===true?{photoFrame:true,image:true,video:true}:Array.isArray(B)?{photoFrame:B.includes("photo-frame"),image:B.includes("image"),video:B.includes("video")}:{photoFrame:true,image:true,video:true}},[m.media]),Ue=useMemo(()=>{let B=m.activities;return B===false?false:B===true?true:Array.isArray(B)?B.includes("flashcard"):true},[m.activities]),re=B=>{let se=B.target.files;!se||se.length===0||(i(Bt("select")),i(dt(false)),N(false),Array.from(se).forEach(Ie=>{let me=new FileReader;me.onload=ne=>{let ie=new window.Image;ie.src=ne.target?.result,ie.onload=()=>{let Ve=ie.width/ie.height,Vt=300,Kt=300,_e=ie.width,Ce=ie.height;_e>Vt&&(_e=Vt,Ce=_e/Ve),Ce>Kt&&(Ce=Kt,_e=Ce*Ve),i(ue());let Je=(window.innerWidth-_e)/2,_t=(window.innerHeight-Ce)/2;i(ms({id:v4(),src:ie.src,x:Je,y:_t,width:_e,height:Ce,draggable:true,rotation:0}));};},me.readAsDataURL(Ie);}),B.target.value="");},kr=async B=>{let se=B.target.files;if(!(!se||se.length===0)){console.log("files",B),i(Bt("select")),i(dt(false)),N(false);for(let Ie of Array.from(se))try{let me=URL.createObjectURL(Ie),ne=document.createElement("video");console.log("video",ne),ne.src=me,ne.muted=!0,ne.playsInline=!0,ne.preload="auto",ne.load(),await new Promise((Ze,ea)=>{let Aa=setTimeout(()=>ea(new Error("Metadata load timeout")),1e4);ne.onloadedmetadata=()=>{clearTimeout(Aa),Ze();},ne.onerror=()=>{clearTimeout(Aa),ea(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ne.duration,width:ne.videoWidth,height:ne.videoHeight}),await new Promise((Ze,ea)=>{let Aa=setTimeout(()=>ea(new Error("Video load timeout")),1e4);ne.readyState>=2?(clearTimeout(Aa),Ze()):ne.onloadeddata=()=>{clearTimeout(Aa),Ze();};});let ie=Math.min(.8,ne.duration/2);console.log("Seeking to:",ie),ne.currentTime=ie,await new Promise(Ze=>{let ea=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);ne.onseeked=()=>{clearTimeout(ea),console.log("Seek completed"),Ze();};});let Ve=document.createElement("canvas"),Vt=ne.videoWidth/ne.videoHeight,Kt=400,_e=400,Ce=ne.videoWidth,Je=ne.videoHeight;Ce>Kt&&(Ce=Kt,Je=Ce/Vt),Je>_e&&(Je=_e,Ce=Je*Vt),Ve.width=Ce,Ve.height=Je;let _t=Ve.getContext("2d",{willReadFrequently:!1});if(!_t)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),ne.videoWidth===0||ne.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ce,height:Je}),_t.drawImage(ne,0,0,Ce,Je);let Ma=Ve.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ma.length),i(ue());let Ta=(window.innerWidth-Ce)/2,$a=(window.innerHeight-Je)/2,Dr=v4();await xr(Dr,Ie,Ma),i(Hr({id:Dr,objectUrl:me,thumbnailDataUrl:Ma,videoBlob:Ie,x:Ta,y:$a,width:Ce,height:Je,draggable:!0,isPlaying:!1,rotation:0})),ne.src="",ne.load(),console.log(`Video uploaded: ${Ie.name}`);}catch(me){console.error("Error processing video:",me),alert(`Failed to process video: ${Ie.name}`);}B.target.value="";}},Mr=(B,se,Ie)=>{i(ue()),i(Bt("select")),i(dt(false));let me=300,ne=300,ie=(window.innerWidth-me)/2,Ve=(window.innerHeight-ne)/2;i(Ie?Ja({id:Ie,images:B,order:se,x:ie,y:Ve,width:me,height:ne,rotation:0,draggable:true}):ys({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:B,currentIndex:0,order:se,x:ie,y:Ve,width:me,height:ne,rotation:0,draggable:true})),i(Ra(false));},Tr=()=>{i(ue()),i(Bt("select")),i(dt(false));let B=400,se=300,Ie=(window.innerWidth-B)/2,me=(window.innerHeight-se)/2;i(Is({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ie,y:me,width:B,height:se,rotation:0,draggable:true,isCapturing:false})),q(false);},Ar=B=>{let me=(window.innerWidth-100)/2,ne=(window.innerHeight-100)/2,ie={};switch(B.name){case "circle":case "ring":case "wedge":case "arc":ie.radius=50,(B.name==="ring"||B.name==="arc")&&(ie.innerRadius=25,ie.outerRadius=50),(B.name==="wedge"||B.name==="arc")&&(ie.angle=B.name==="wedge"?60:90);break;case "ellipse":ie.radiusX=60,ie.radiusY=40;break;case "triangle":ie.radius=50,ie.sides=3;break;case "polygon":ie.radius=50,ie.sides=6;break;case "star":ie.innerRadius=25,ie.outerRadius=50,ie.numPoints=5;break;case "arrow":case "line":ie.points=[0,0,100,0],B.name==="arrow"&&(ie.pointerLength=10,ie.pointerWidth=10);break}let Ve={id:`shape-${Date.now()}`,type:B.name,x:me,y:ne,width:100,height:100,rotation:0,color:p,...ie};i(ue()),i(dt(false)),i(Bt(B.name)),i(gs(Ve));},Ca=B=>{if(i(Bt(B)),B==="select")i(dt(false));else if(B==="text"){i(dt(false)),i(ue());let se=200,Ie=50,me=(window.innerWidth-se)/2,ne=(window.innerHeight-Ie)/2,ie=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;i(bs({id:ie,text:"",x:me,y:ne,width:se,height:Ie,rotation:0,draggable:true,fontSize:b,fontFamily:y,fontStyle:S,fontWeight:I,textDecoration:C,fill:L,align:"left"})),setTimeout(()=>{i(qo(ie));},100),r&&r(ie);}else i(dt(true));},Pr=()=>{i(js()),i(Bt("select")),i(dt(false));},Xn=()=>{t?t():a?A(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Yn=()=>{F(true);},Rr=async(B,se)=>{try{i(Bt("select")),i(dt(!1));let Ie=URL.createObjectURL(B),me=document.createElement("video");me.src=Ie,me.muted=!0,me.playsInline=!0,me.preload="auto",await new Promise((Ma,Ta)=>{let $a=setTimeout(()=>Ta(new Error("Metadata load timeout")),1e4);me.onloadedmetadata=()=>{clearTimeout($a),Ma();},me.onerror=()=>{clearTimeout($a),Ta(new Error("Failed to load video"));};});let ne=640,ie=me.videoWidth/me.videoHeight,Ve=ne,Vt=Ve/ie,Kt=window.innerWidth,_e=window.innerHeight;i(ue());let Ce=(Kt-Ve)/2,Je=(_e-Vt)/2,_t=v4();await xr(_t,B,se),i(Hr({id:_t,objectUrl:Ie,thumbnailDataUrl:se,videoBlob:B,x:Ce,y:Je,width:Ve,height:Vt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),A(!1),F(!1);}catch(Ie){console.error("Error adding recorded video to canvas:",Ie),alert("Failed to add video to canvas. Please try again.");}},Jn=B=>{i(Bt("select")),i(dt(false)),i(No(null)),B&&i(Us(B)),i(na(!f));},Zn=()=>{i(Fo(null)),i(Ra(true)),q(false);},ka=()=>{D(!E);},Qn=()=>{N(!H);},es=()=>{q(!te);};return g?null:jsx("div",{className:"konva-editor-root",children:jsxs("div",{className:"fixed top-1/2 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(Sa,{type:"single",className:"flex flex-col gap-1 border bg-white p-1 shadow-xl",children:Z.map((B,se)=>jsx("div",{title:B.label,className:`hover:bg-primary/10 mb-1 cursor-pointer rounded-md px-4 py-3 ${B.name===d?"bg-primary/10":""}`,onClick:()=>{if(B.name==="image"){Qn(),D(false),q(false),Ca(B.name);return}else if(B.name==="shapes"){ka(),N(false),q(false),Ca(B.name);return}else if(B.name==="activities"){Ca(B.name),es(),D(false),N(false);return}Ca(B.name),D(false),N(false),q(false);},children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},se))}),E&&jsx(Sa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:pe.map((B,se)=>jsx("div",{title:B.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",onClick:()=>Ar(B),children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},se))}),H&&jsxs(Sa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Tr,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Me.image&&jsx("div",{onClick:()=>z.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Image$2,{weight:"fill",size:24,className:"text-primary"})}),Me.video&&jsx("div",{onClick:()=>X.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(MonitorPlay,{weight:"fill",size:24,className:"text-primary"})})]}),te&&jsxs(Sa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Ue&&jsx("div",{title:"Flashcard",onClick:()=>Zn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Cards,{weight:"fill",size:24,className:"text-primary"})}),Re.map((B,se)=>jsx("div",{title:B.label,onClick:()=>Jn(B.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},se))]})]}),jsx("input",{ref:z,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:re}),jsx("input",{ref:X,type:"file",accept:"video/*",className:"hidden",onChange:kr}),!t&&P&&a&&jsx(Xo,{onClose:()=>A(false),stageRef:a,onRecordingComplete:Rr}),U&&jsx(Cc,{onClose:()=>F(false),onRecordingComplete:Rr}),h&&jsx(Mc,{editingFlashcard:c,onConfirm:Mr,onCancel:()=>i(Ra(false))}),(v.undo||v.redo||v.screenRecord||v.cameraRecord||v.clear)&&jsxs(Sa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[v.undo&&jsx("button",{value:"undo",onClick:()=>i($s()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{size:24,weight:"bold"})}),v.redo&&jsx("button",{value:"redo",onClick:()=>i(Xs()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{size:24,weight:"bold"})}),v.screenRecord&&jsx("button",{value:"screen-record",onClick:Xn,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#2260DD]",title:"Screen Record",children:jsx(Record,{size:24,weight:"bold"})}),v.cameraRecord&&jsx("button",{value:"camera-record",onClick:Yn,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#804FF2]",title:"Camera Record",children:jsx(Camera,{size:24,weight:"fill"})}),v.clear&&jsx("button",{value:"clear",onClick:()=>Pr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{size:24,weight:"bold"})})]})]})})},oy=ay;var cl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=aa(Ho),s=(aa(h=>h.canvas.slides.find(x=>x.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),[i,u]=useState(false),[l,c]=useState(null),[d,p]=useState(null),f=async()=>{if(a.length===0){p({type:"error",message:"No slides to publish"});return}if(!e){p({type:"error",message:"No publish handler provided"});return}u(true),p(null);try{let h=await e(a,x=>{c(x);});h.success?p({type:"success",message:h.message}):p({type:"error",message:h.message});}catch(h){p({type:"error",message:h instanceof Error?h.message:"An unexpected error occurred"});}finally{u(false),setTimeout(()=>{c(null),p(null);},3e3);}};return s?null:jsxs("button",{onClick:f,disabled:i||a.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-3 px-4 py-3 font-medium text-white transition-colors",children:[jsx(Export,{size:24,color:"#fff"})," Publish"]})};var dy=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,showPublishButton:r=true,showBackButton:n=true,className:s="",rightContent:i,leftContent:u})=>jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-6 shadow-sm ${s}`,children:[u||jsxs("div",{className:"flex items-center gap-6 px-2",children:[n&&jsx("button",{onClick:t,className:"h-10 w-10 rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A]",children:jsx(CaretLeft,{size:24,color:"#64758B",weight:"bold"})}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"text-2xl font-medium text-[#000000CC]",children:e}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(CloudArrowUp,{weight:"fill",color:"#63748A",size:20}),jsx("span",{className:"text-base font-medium text-[#63748A]",children:o})]})]})]}),i||r&&a&&jsx(cl,{onPublish:a})]});function fl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Pc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Dc(e){let[o,t]=be.useState(void 0);return yo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],s,i;if("borderBoxSize"in n){let u=n.borderBoxSize,l=Array.isArray(u)?u[0]:u;s=l.inlineSize,i=l.blockSize;}else s=e.offsetWidth,i=e.offsetHeight;t({width:s,height:i});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var Fc=["PageUp","PageDown"],Ec=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Bc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Ao="Slider",[ml,cy,fy]=Bn(Ao),[Oc]=va(Ao,[fy]),[my,_n]=Oc(Ao),Nc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:i=false,minStepsBetweenThumbs:u=0,defaultValue:l=[a],value:c,onValueChange:d=()=>{},onValueCommit:p=()=>{},inverted:f=false,form:h,...x}=e,m=be.useRef(new Set),v=be.useRef(0),b=s==="horizontal"?py:hy,[y=[],S]=Xt({prop:c,defaultProp:l,onChange:U=>{[...m.current][v.current]?.focus(),d(U);}}),I=be.useRef(y);function C(U){let F=yy(y,U);A(U,F);}function L(U){A(U,v.current);}function P(){let U=I.current[v.current];y[v.current]!==U&&p(y);}function A(U,F,{commit:E}={commit:false}){let D=Iy(n),H=Cy(Math.round((U-a)/n)*n+a,D),N=fl(H,[a,r]);S((te=[])=>{let q=by(te,N,F);if(Sy(q,u*n)){v.current=q.indexOf(N);let G=String(q)!==String(te);return G&&E&&p(q),G?q:te}else return te});}return jsx(my,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:r,valueIndexToChangeRef:v,thumbs:m.current,values:y,orientation:s,form:h,children:jsx(ml.Provider,{scope:e.__scopeSlider,children:jsx(ml.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":i,"data-disabled":i?"":void 0,...x,ref:o,onPointerDown:Xe(x.onPointerDown,()=>{i||(I.current=y);}),min:a,max:r,inverted:f,onSlideStart:i?void 0:C,onSlideMove:i?void 0:L,onSlideEnd:i?void 0:P,onHomeKeyDown:()=>!i&&A(a,0,{commit:true}),onEndKeyDown:()=>!i&&A(r,y.length-1,{commit:true}),onStepKeyDown:({event:U,direction:F})=>{if(!i){let H=Fc.includes(U.key)||U.shiftKey&&Ec.includes(U.key)?10:1,N=v.current,te=y[N],q=n*H*F;A(te+q,N,{commit:true});}}})})})})});Nc.displayName=Ao;var[Vc,qc]=Oc(Ao,{startEdge:"left",endEdge:"right",size:"width",direction:1}),py=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:i,onSlideEnd:u,onStepKeyDown:l,...c}=e,[d,p]=be.useState(null),f=Tt(o,b=>p(b)),h=be.useRef(void 0),x=Lo(r),m=x==="ltr",v=m&&!n||!m&&n;function g(b){let y=h.current||d.getBoundingClientRect(),S=[0,y.width],C=gl(S,v?[t,a]:[a,t]);return h.current=y,C(b-y.left)}return jsx(Vc,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:jsx(Uc,{dir:x,"data-orientation":"horizontal",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let y=g(b.clientX);s?.(y);},onSlideMove:b=>{let y=g(b.clientX);i?.(y);},onSlideEnd:()=>{h.current=void 0,u?.();},onStepKeyDown:b=>{let S=Bc[v?"from-left":"from-right"].includes(b.key);l?.({event:b,direction:S?-1:1});}})})}),hy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:i,onStepKeyDown:u,...l}=e,c=be.useRef(null),d=Tt(o,c),p=be.useRef(void 0),f=!r;function h(x){let m=p.current||c.current.getBoundingClientRect(),v=[0,m.height],b=gl(v,f?[a,t]:[t,a]);return p.current=m,b(x-m.top)}return jsx(Vc,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(Uc,{"data-orientation":"vertical",...l,ref:d,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{let m=h(x.clientY);n?.(m);},onSlideMove:x=>{let m=h(x.clientY);s?.(m);},onSlideEnd:()=>{p.current=void 0,i?.();},onStepKeyDown:x=>{let v=Bc[f?"from-bottom":"from-top"].includes(x.key);u?.({event:x,direction:v?-1:1});}})})}),Uc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:i,onStepKeyDown:u,...l}=e,c=_n(Ao,t);return jsx(it.span,{...l,ref:o,onKeyDown:Xe(e.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(i(d),d.preventDefault()):Fc.concat(Ec).includes(d.key)&&(u(d),d.preventDefault());}),onPointerDown:Xe(e.onPointerDown,d=>{let p=d.target;p.setPointerCapture(d.pointerId),d.preventDefault(),c.thumbs.has(p)?p.focus():a(d);}),onPointerMove:Xe(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:Xe(e.onPointerUp,d=>{let p=d.target;p.hasPointerCapture(d.pointerId)&&(p.releasePointerCapture(d.pointerId),n(d));})})}),Hc="SliderTrack",zc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=_n(Hc,t);return jsx(it.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});zc.displayName=Hc;var pl="SliderRange",Wc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=_n(pl,t),n=qc(pl,t),s=be.useRef(null),i=Tt(o,s),u=r.values.length,l=r.values.map(p=>_c(p,r.min,r.max)),c=u>1?Math.min(...l):0,d=100-Math.max(...l);return jsx(it.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:i,style:{...e.style,[n.startEdge]:c+"%",[n.endEdge]:d+"%"}})});Wc.displayName=pl;var hl="SliderThumb",Gc=be.forwardRef((e,o)=>{let t=cy(e.__scopeSlider),[a,r]=be.useState(null),n=Tt(o,i=>r(i)),s=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx(gy,{...e,ref:n,index:s})}),gy=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=_n(hl,t),i=qc(hl,t),[u,l]=be.useState(null),c=Tt(o,g=>l(g)),d=u?s.form||!!u.closest("form"):true,p=Dc(u),f=s.values[a],h=f===void 0?0:_c(f,s.min,s.max),x=vy(a,s.values.length),m=p?.[i.size],v=m?wy(m,h,i.direction):0;return be.useEffect(()=>{if(u)return s.thumbs.add(u),()=>{s.thumbs.delete(u);}},[u,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${h}% + ${v}px)`},children:[jsx(ml.ItemSlot,{scope:e.__scopeSlider,children:jsx(it.span,{role:"slider","aria-label":e["aria-label"]||x,"aria-valuemin":s.min,"aria-valuenow":f,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...n,ref:c,style:f===void 0?{display:"none"}:e.style,onFocus:Xe(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),d&&jsx(Kc,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:f},a)]})});Gc.displayName=hl;var xy="RadioBubbleInput",Kc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=Tt(r,a),s=Pc(o);return be.useEffect(()=>{let i=r.current;if(!i)return;let u=window.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==o&&c){let d=new Event("input",{bubbles:true});c.call(i,o),i.dispatchEvent(d);}},[s,o]),jsx(it.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});Kc.displayName=xy;function by(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function _c(e,o,t){let n=100/(t-o)*(e-o);return fl(n,[0,100])}function vy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function yy(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function wy(e,o,t){let a=e/2,n=gl([0,50],[0,a]);return (a-n(o)*t)*t}function Ly(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Sy(e,o){if(o>0){let t=Ly(e);return Math.min(...t)>=o}return true}function gl(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function Iy(e){return (String(e).split(".")[1]||"").length}function Cy(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var jc=Nc,$c=zc,Xc=Wc,Yc=Gc;function Zc({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:i,...u}){let l=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(jc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:La("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...u,children:[jsx($c,{"data-slot":"slider-track",className:La("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",s),children:jsx(Xc,{"data-slot":"slider-range",className:La("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:l.length},(c,d)=>jsx(Yc,{"data-slot":"slider-thumb",className:La("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",i)},d))]})}var Ty=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Ay=({colors:e=Ty,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let n=ee(i=>i.toolbar.penColor),s=xe();return jsxs("div",{className:`fixed bottom-6 left-1/2 z-50 flex h-fit w-full max-w-3xl -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-6 shadow-2xl xl:max-w-4xl ${r}`,style:{marginLeft:"-160px"},children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex w-full flex-col px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex w-full items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(Zc,{defaultValue:[12],max:28,min:6,step:1,className:"w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:i=>s(rl(i[0]))}),jsx("div",{className:"h-8 w-8 rounded-full bg-black"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(Sa,{type:"single",className:"flex w-full px-6",children:[e.map(i=>jsx("button",{value:i.value,className:`h-12 w-12 rounded-full border hover:cursor-pointer ${n===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>s(zn(i.value))},i.value)),jsxs("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>s(zn(i.target.value))}),"+"]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center",children:jsx("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>s(us(i.target.value))})})})]})};function Py({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var ef=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Dy=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),bl=e=>{let o=Dy(e);return o.charAt(0).toUpperCase()+o.slice(1)},jn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),tf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var af={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var rf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:s,...i},u)=>createElement("svg",{ref:u,...af,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:jn("lucide",r),...!n&&!tf(i)&&{"aria-hidden":"true"},...i},[...s.map(([l,c])=>createElement(l,c)),...Array.isArray(n)?n:[n]]));var $n=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(rf,{ref:n,iconNode:o,className:jn(`lucide-${ef(bl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=bl(e),t};var Oy=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Ir=$n("copy",Oy);var Ny=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Cr=$n("trash-2",Ny);var sf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"shadow-lg":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:r,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:i=>{i.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Ir,{size:14})}),!a&&jsx("button",{onClick:i=>{i.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Cr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Slide ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var Hy=()=>{let e=qt(),o=aa(Ho),t=aa(Uo),a=aa(Ys),[r,n]=useState(true),u=(aa(f=>f.canvas.slides.find(h=>h.id===f.canvas.currentSlideId))?.videos||[]).some(f=>f.isRecorded&&f.isPlaying),l=()=>{a&&e(ns());},c=f=>{e(ls(f));},d=f=>{e(is(f));},p=f=>{o.length>1&&e(ss(f));};return u?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-100 flex items-start",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Slides"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[o.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:o.map((f,h)=>jsx(sf,{slide:f,index:h,isSelected:f.id===t,isSingleSlide:o.length===1,onSelect:()=>c(f.id),onDuplicate:()=>d(f.id),onDelete:()=>p(f.id)},f.id))}),jsxs("button",{onClick:l,disabled:!a,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${a?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Slide"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var zy="SchooplaEditorDB",Wy=1,Po="slides",uf="schoopla_current_slide_id",cf=()=>new Promise((e,o)=>{let t=indexedDB.open(zy,Wy);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Po)||r.createObjectStore(Po,{keyPath:"id"});};}),vl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await cf(),a=o.transaction([Po],"readwrite").objectStore(Po);await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);});for(let r of e)await new Promise((n,s)=>{let i=a.add(r);i.onsuccess=()=>n(!0),i.onerror=()=>s(i.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},ff=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await cf(),t=e.transaction([Po],"readonly").objectStore(Po);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(i=>({id:i.id,width:i.width,height:i.height,x:i.x,y:i.y}))),a(s.length>0?s:null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var yl=e=>{try{localStorage.setItem(uf,e);}catch(o){console.error("Error saving current slide ID:",o);}},mf=()=>{try{return localStorage.getItem(uf)}catch(e){return console.error("Error loading current slide ID:",e),null}},pf=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}};var Gy=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/setCurrentSlide","canvas/updateSlideThumbnail","canvas/reorderSlides"],Ky=["canvas/clearCanvas"],_y=pf((e,o)=>{vl(e),yl(o);},500),jy=(e,o)=>{vl(e),yl(o);},wl=false,hf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Ki(r).catch(n=>{console.error("Error deleting video blob:",n);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,s=e.getState().canvas.slides.find(i=>i.id===r);s&&s.videos&&s.videos.length>0&&s.videos.forEach(i=>{Ki(i.id).catch(u=>{console.error("Error deleting video blob:",u);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),i=n.canvas.slides.find(u=>u.id===n.canvas.currentSlideId)?.videos.find(u=>u.id===r);i&&i.videoBlob&&setTimeout(()=>{let u=e.getState(),c=u.canvas.slides.find(d=>d.id===u.canvas.currentSlideId)?.videos.find(d=>d.id!==r&&d.x===i.x+20&&d.y===i.y+20);c&&i.videoBlob&&xr(c.id,i.videoBlob,c.thumbnailDataUrl).catch(d=>{console.error("Error saving duplicated video blob:",d);});},0);}let a=o(t);if(t.type&&Ky.includes(t.type)){if(!wl){wl=true;try{let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;jy(n,s);}finally{setTimeout(()=>{wl=false;},0);}}}else if(t.type&&Gy.includes(t.type)){let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;_y(n,s);}return a});new QueryClient;var Yy=configureStore({reducer:{toolbar:Ic,canvas:Ol},middleware:e=>e({serializableCheck:false}).concat(hf)});var Jy=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:s,quality:a,pixelRatio:r}),u=document.createElement("a");u.download=`${n}.${t}`,u.href=i,document.body.appendChild(u),u.click(),document.body.removeChild(u);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},Zy=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,s)=>{try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:r});fetch(u).then(l=>l.blob()).then(l=>n(l)).catch(l=>s(l));}catch(i){s(i);}})},Qy=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var ew=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),i=o.x+s*a,u=o.y+s*r;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-u,2))},Ll=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let s=1;s<e.length-1;s++){let i=ew(e[s],r,n);i>t&&(t=i,a=s);}if(t>o){let s=Ll(e.slice(0,a+1),o),i=Ll(e.slice(a),o);return [...s.slice(0,-1),...i]}return [r,n]},tw=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},aw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},gf=(e,o=1.5)=>{if(e.length<=4)return e;let t=tw(e),a=Ll(t,o);return aw(a)},xf=(e,o=1.5)=>({...e,points:gf(e.points,o)}),ow=(e,o=1.5)=>e.map(t=>xf(t,o)),rw=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var nw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var bf=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,s)=>{let i=new Image;i.onload=()=>{let{width:u,height:l}=i;if(u>t||l>a){let h=u/l;u>l?(u=Math.min(u,t),l=u/h):(l=Math.min(l,a),u=l*h);}let c=document.createElement("canvas");c.width=u,c.height=l;let d=c.getContext("2d");if(!d){s(new Error("Failed to get canvas context"));return}d.drawImage(i,0,0,u,l);let p=nw(e),f=c.toDataURL(p,r);n(f);},i.onerror=s,i.src=e;})};var Qt=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},Ia=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",ja=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",sw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85,fullSizeThumbnails:s}=o,i=[],u=0;for(let l of e){let c=[],d=[],p=[];for(let m of l.images){let v=m.src;if(t&&v.startsWith("data:"))try{v=await bf(v,{maxWidth:a,maxHeight:r,quality:n});}catch(g){console.warn("Failed to optimize image, using original:",g);}if(v.startsWith("data:")){let g=Qt(v),b=Ia(v);u+=g.byteLength;let y={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,buffer:g,mimeType:b};if(m.audioData&&m.audioData.startsWith("data:")){let S=Qt(m.audioData),I=Ia(m.audioData);u+=S.byteLength,y.audioBuffer=S,y.audioMimeType=I;}c.push(y);}}for(let m of l.videos){let v,g;if(m.videoBlob)v=await m.videoBlob.arrayBuffer(),g=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))v=Qt(m.videoData),g=Ia(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}u+=v.byteLength;let b={id:m.id,thumbnailDataUrl:m.thumbnailDataUrl,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,isPlaying:m.isPlaying,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isRecorded:m.isRecorded,buffer:v,mimeType:g};if(m.audioData&&m.audioData.startsWith("data:")){let y=Qt(m.audioData),S=Ia(m.audioData);u+=y.byteLength,b.audioBuffer=y,b.audioMimeType=S;}d.push(b);}for(let m of l.photoFrames){let v={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:m.draggable,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isCapturing:m.isCapturing};if(m.capturedImageUrl&&m.capturedImageUrl.startsWith("data:")){let g=Qt(m.capturedImageUrl),b=Ia(m.capturedImageUrl);u+=g.byteLength,v.buffer=g,v.mimeType=b;}if(m.audioData&&m.audioData.startsWith("data:")){let g=Qt(m.audioData),b=Ia(m.audioData);u+=g.byteLength,v.audioBuffer=g,v.audioMimeType=b;}p.push(v);}let f,h,x=s?.get(l.id);x&&x.startsWith("data:")?(f=Qt(x),h=Ia(x),u+=f.byteLength):l.thumbnail&&l.thumbnail.startsWith("data:")&&(f=Qt(l.thumbnail),h=Ia(l.thumbnail),u+=f.byteLength),i.push({...l,images:c,videos:d,photoFrames:p,thumbnailBuffer:f,thumbnailMimeType:h});}return {slides:i,totalSize:u}},iw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},lw=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnailFileKey:`slide_${r}_thumbnail`,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${s}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${s}`,thumbnailFileKey:`slide_${r}_video_${s}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${s}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${s}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{if(a.images.forEach((n,s)=>{let i=new Blob([n.buffer],{type:n.mimeType}),u=`${n.id}.${ja(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,i,u),n.audioBuffer&&n.audioMimeType){let l=new Blob([n.audioBuffer],{type:n.audioMimeType}),c=`${n.id}_audio.${ja(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,l,c);}}),a.videos.forEach((n,s)=>{let i=new Blob([n.buffer],{type:n.mimeType}),u=`${n.id}.${ja(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,i,u),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let l=Qt(n.thumbnailDataUrl),c=new Blob([l],{type:"image/jpeg"}),d=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,c,d);}if(n.audioBuffer&&n.audioMimeType){let l=new Blob([n.audioBuffer],{type:n.audioMimeType}),c=`${n.id}_audio.${ja(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,l,c);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let i=new Blob([n.buffer],{type:n.mimeType}),u=`${n.id}.${ja(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,i,u);}if(n.audioBuffer&&n.audioMimeType){let i=new Blob([n.audioBuffer],{type:n.audioMimeType}),u=`${n.id}_audio.${ja(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,i,u);}}),a.thumbnailBuffer&&a.thumbnailMimeType){let n=new Blob([a.thumbnailBuffer],{type:a.thumbnailMimeType}),s=`slide_${r}_thumbnail.${ja(a.thumbnailMimeType)}`;o.append(`slide_${r}_thumbnail`,n,s);}}),o},vf=(e,o={})=>{if(!e.current)return null;let{pixelRatio:t=1,mimeType:a="image/jpeg",quality:r=.9}=o;try{return e.current.toDataURL({pixelRatio:t,mimeType:a,quality:r})}catch(n){return console.error("Error generating full-size thumbnail:",n),null}},dw=async(e,o,t)=>{let a=new Map;for(let r of e){await t(r.id),await new Promise(s=>setTimeout(s,100));let n=vf(o);n&&a.set(r.id,n);}return a};var cw=()=>{let e=qt();useEffect(()=>{(async()=>{try{let t=await ff(),a=mf();if(t&&t.length>0){let r=await Tu(),n=t.map(i=>{if(i.videos&&i.videos.length>0){let u=i.videos.map(l=>{let c=r.get(l.id);if(c){let d=Au(c.blob);return {...l,objectUrl:d,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return l});return {...i,videos:u}}return i}),s=a&&n.find(i=>i.id===a)?a:n[0].id;e(cs({slides:n,currentSlideId:s}));}}catch(t){console.error("Error loading persisted slides:",t);}})();},[e]);};/*! Bundled license information:
6
+ This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:d?"none":"auto"}})}),jsx(Group,{y:S+I+H+C+L+A,children:d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),v();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:y,width:e.width-y*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:y,width:e.width-y*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Wi.displayName="LongAnswer";var Iu=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:s})=>jsx(Fragment,{children:e.map(n=>jsx(Wi,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>s(i,n.id)},n.id))});var Ox=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r,className:s,style:n}={})=>{let i=yt(),u=ee(w=>w.toolbar.selectedTool),l=ee(ge),c=ee(Uo),d=l?.editingActivity,m=l?.showMcqForm,f=l?.lines||[],h=useRef(null),x=useRef(null),[p,v]=useState(null),[g,b]=useState(""),[y,S]=useState({width:1280,height:1200}),[I,C]=useState("bottom"),L=useRef(null),[P,A]=useState(null),[H,F]=useState(null),[E,D]=useState(null),[U,N]=useState(null),[te,q]=useState(null),[G,oe]=useState(null),[R,z]=useState(null),[X,_]=useState(false),[Y,Z]=useState(null),[Q,pe]=useState(false),we=useRef(null),Re=useRef(null),Me=useRef(null),{debouncedGenerateThumbnail:He}=cd(c,h);useEffect(()=>{let w=()=>{if(x.current){let T=x.current.getBoundingClientRect();S({width:T.width,height:T.height});}};w();let M=new ResizeObserver(w);return x.current&&M.observe(x.current),window.addEventListener("resize",w),()=>{M.disconnect(),window.removeEventListener("resize",w);}},[]),useEffect(()=>{if(h.current){let w=h.current.container();w&&(w.style.cursor="");}},[u]);let re=useCallback(()=>{h.current&&requestAnimationFrame(()=>{if(!h.current)return;h.current.getLayers().forEach(O=>O.batchDraw());let M=1/6,T=h.current.toDataURL({pixelRatio:M});b(T),He();});},[He]),Mr=useRef(c);useEffect(()=>{Mr.current!==c&&(Mr.current=c,re());},[c,re]);let Tr=useRef(null),Ar=useRef(true);useEffect(()=>{if(!l)return;let w=(l.lines?.length||0)+(l.images?.length||0)+(l.videos?.length||0)+(l.shapes?.length||0)+(l.texts?.length||0)+(l.flashcards?.length||0)+(l.photoFrames?.length||0)+(l.multipleChoices?.length||0)+(l.trueFalses?.length||0)+(l.shortAnswers?.length||0)+(l.LongAnswer?.length||0)+(l.fillInTheBlanks?.length||0),M=Tr.current?.count!==w;!Ar.current&&M&&setTimeout(()=>{re();},100),Tr.current={slideId:c,count:w},Ar.current=false;},[l,c,re]),useEffect(()=>{h.current&&e&&e(h);},[e]),useEffect(()=>{Me.current&&a&&a(Me);},[a]);let{startDrawing:Pr,draw:Sa,stopDrawing:Rr,setCanvasRef:Xs,tool:Ys,color:Dr,strokeWidth:Js,isSketchMode:Zs}=Vl(re),Ia=useRef(new Map),{images:Qs,getLoadedImage:en,imageRefs:B,handleDragEnd:ne,handleImageTransformEnd:Ie}=Kl(re),{videos:me,videoRefs:se,handleVideoClick:ie,handleVideoDragEnd:Ve,handleVideoTransformEnd:qt}=$l(re),{multipleChoice:Kt,handleMcqTransform:_e,mcqRefs:Ce,handleDragEnd:Je}=_l(re),{trueFalse:_t,handleTrueFalseTransform:Ca,trueFalseRefs:ka,handleTrueFalseDragEnd:_a}=jl(re),{shortAnswers:Fr,saRefs:Ze,handleShortAnswerDragEnd:Qt}=ed(re),{longAnswers:Ma,handleLongAnswerDragEnd:Lf}=td(re),{fillInTheBlanks:Sf,handleFillInTheBlanksDragEnd:If}=bu(re),{transformerRef:de,boundBoxFunc:gt}=id(),{shapes:Cf,shapeRefs:Er,isDragging:Sl,handleShapeDragEnd:kf,handleShapeResizeEnd:Mf}=Jl(re),{texts:Do,textRefs:ea,handleDragEnd:Tf,handleTransformEnd:Af,handleDoubleClick:Pf,startEditing:Br,editingTextId:he,editingValue:Il,handleEditingChange:Cl,finishEditing:tn}=Ql(re,we);useEffect(()=>{t&&t(Br);},[t,Br]);let Or=ee(w=>w.canvas.editingTextId);useEffect(()=>{Or&&Or!==he&&Br(Or);},[Or,he,Br]);let{flashcards:Rf,flashcardRefs:Nr,handleDragEnd:Df,handleFlashcardTransformEnd:Ff,handleNext:Ef,handlePrevious:Bf}=od(re),{photoFrames:kl,photoFrameRefs:Vr,handleDragEnd:Of,handlePhotoFrameTransformEnd:Nf,startCamera:Vf,capturePhoto:qf,cameraStreams:Hf}=nd(re);useEffect(()=>{if(de.current){if(he){de.current.nodes([]),de.current.getLayer()?.batchDraw();return}if(p&&!me.find(T=>T.id===p)?.isPlaying){let T=Ia.current.get(p)||B.current.get(p)||se.current.get(p)||Er.current.get(p)||ea.current.get(p)||Ce.current.get(p)||Nr.current.get(p)||Vr.current.get(p);if(T){let O=T.attrs?.locked;if(T.visible()&&O!==true){de.current.nodes([T]),de.current.getLayer()?.batchDraw();return}}}de.current.nodes([]),de.current.getLayer()?.batchDraw();}},[p,he,me,Ia,B,se,Er,ea,Nr,Vr,kl,Ce,de]);let Ue=useCallback(w=>{v(w),o?.(w);},[o]),qr=useCallback(()=>{v(null),o?.(null),de.current&&(de.current.nodes([]),de.current.getLayer()?.batchDraw());},[de,o]);useEffect(()=>{let w=de.current;return ()=>{w&&w.nodes([]);}},[c]),useEffect(()=>{let w=M=>{he&&M.target.tagName!=="TEXTAREA"&&tn();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[he,tn]),useEffect(()=>{let w=he||p;if(!w||p&&he){F(null);return}let M=ea.current.get(w),T=h.current;if(!M||!T){F(null);return}let O=T.container().getBoundingClientRect(),De=M.absolutePosition(),Le=T.scaleX();F({x:O.left+(De.x+M.width()*Le/2)*Le,y:O.top+De.y*Le});},[p,he,Do,ea]),useEffect(()=>{if(!he){D(null);return}let w=ea.current.get(he),M=h.current;if(!w||!M){D(null);return}let T=M.container().getBoundingClientRect(),O=w.absolutePosition(),De=M.scaleX();D({top:T.top+O.y*De,left:T.left+O.x*De,scale:De});},[he,Do,ea]);let Ml=useCallback(w=>{let M=w.target.getClassName(),T=w.target===w.target.getStage(),O=M==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",De=M==="Image",Le=M==="Text",ae=M==="Group"||w.target.getParent()?.getClassName()==="Group",Rt=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&w.target.attrs.id,bt=M==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:M,clickedOnImage:De,clickedOnGroup:ae,tool:u,targetId:w.target.attrs?.id}),T&&!O&&!De&&!Le&&!ae&&!Rt&&!bt&&qr(),!(u==="pen"||u==="eraser")&&(De||Le||O||ae||Rt||bt))return;let je=w.target.getStage()?.getPointerPosition();if(!je)return;["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(u)||Pr(je);},[u,Pr,qr]),Tl=useCallback(w=>{if(Sl)return;let M=w.target.getStage()?.getPointerPosition();M&&Sa(M);},[Sa,Sl]),Al=useCallback(()=>{Rr();},[Rr]),Uf=useCallback(w=>{ne(w,re);},[ne,re]),zf=useCallback(w=>{ie(w),Ue(w);},[ie,Ue]),xt=useCallback((w,M,T)=>{w.preventDefault();let O=w.clientX,De=w.clientY,Le=L.current?.offsetHeight||450,ae=L.current?.offsetWidth||450,Rt=window.innerHeight,bt=window.innerWidth,tt=O,je=De;De+Le>Rt&&(je=De-Le),O+ae>bt&&(tt=O-ae),A({x:tt,y:je,elementId:M,elementType:T}),Ue(M);},[Ue]),Pl=useCallback(w=>{i(Vo(w)),i(ra(true));},[i]),Wf=useCallback(w=>{i(Eo(w)),i(Aa(true));},[i]),Gf=useCallback((w,M)=>{if(!P)return;let{elementId:T,elementType:O}=P;switch(w){case "order":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"order"});}break;case "lock":if(M){let k=M.target.getBoundingClientRect();N({x:k.right+5,y:k.top,type:"lock"});}break;case "link":if(A(null),O==="line")break;let De=l?O==="image"?l.images.find(k=>k.id===T):l.videos.find(k=>k.id===T):null;q({type:"link",defaultValue:De?.link||""});break;case "voice":if(A(null),O==="line")break;let Le=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="text"?l.texts.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):O==="mcq"?l.multipleChoices.find(k=>k.id===T):O==="fillInTheBlanks"?l.fillInTheBlanks.find(k=>k.id===T):O==="longAnswer"?l.LongAnswer.find(k=>k.id===T):O==="shortAnswer"?l.shortAnswers.find(k=>k.id===T):O==="trueFalse"?l.trueFalses.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;Z({elementId:T,elementType:O,existingAudio:Le?.audioData});break;case "edit":A(null);let ae=null;O==="mcq"?ae=l?.multipleChoices.find(k=>k.id===T):O==="trueFalse"?ae=l?.trueFalses.find(k=>k.id===T):O==="shortAnswer"?ae=l?.shortAnswers.find(k=>k.id===T):O==="longAnswer"?ae=l?.LongAnswer.find(k=>k.id===T):O==="fillInTheBlanks"&&(ae=l?.fillInTheBlanks.find(k=>k.id===T)),ae&&Pl(ae);break;case "editFlashcard":A(null);let Rt=l?.flashcards.find(k=>k.id===T);Rt&&Wf(Rt);break;case "color":A(null);let bt=l?.shapes.find(k=>k.id===T);oe({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(A(null),O==="image"){let k=l?.images.find(Jf=>Jf.id===T);k&&z({elementId:T,imageSrc:k.src});}break;case "draw":A(null),O==="image"?i(kn(T)):O==="photoFrame"&&i(Tn(T));break;case "duplicate":i(ue()),O==="line"?i(_n(T)):O==="image"?i(Ur(T)):O==="video"?i(Gr(T)):O==="shape"?i(Kr(T)):O==="text"?i(_r(T)):O==="flashcard"?i(jr(T)):O==="photoFrame"?i($r(T)):O==="mcq"?i(Xr(T)):O==="trueFalse"?i(Yr(T)):O==="shortAnswer"?i(Jr(T)):O==="fillInTheBlanks"?i(Qr(T)):O==="longAnswer"&&i(Zr(T)),re();break;case "infinite-clone":i(ue());let tt=5;for(let k=0;k<tt;k++)O==="image"?i(Ur(T)):O==="video"?i(Gr(T)):O==="shape"?i(Kr(T)):O==="text"?i(_r(T)):O==="flashcard"?i(jr(T)):O==="photoFrame"?i($r(T)):O==="mcq"?i(Xr(T)):O==="trueFalse"?i(Yr(T)):O==="shortAnswer"?i(Jr(T)):O==="fillInTheBlanks"?i(Qr(T)):O==="longAnswer"&&i(Zr(T));re();break;case "make-response":if(A(null),O==="line")break;let je=`#response-${T}`;i(ue()),i(es({id:T,type:O,link:je})),(l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):O==="flashcard"?l.flashcards.find(k=>k.id===T):O==="photoFrame"?l.photoFrames.find(k=>k.id===T):l.multipleChoices.find(k=>k.id===T):null)?.altText||i(ts({id:T,type:O,altText:"Interactive response area"})),re(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(A(null),O==="line")break;let V=l?O==="image"?l.images.find(k=>k.id===T):O==="video"?l.videos.find(k=>k.id===T):O==="shape"?l.shapes.find(k=>k.id===T):null:null;q({type:"altText",defaultValue:V?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),A(null),pe(true),console.log("showLayersPanel state set to:",true);break;case "delete":i(ue()),O==="line"?i(Kn(T)):O==="image"?i(pn(T)):O==="video"?i(hn(T)):O==="shape"?i(xn(T)):O==="text"?i(vn(T)):O==="flashcard"?i(wn(T)):O==="photoFrame"?i(Cn(T)):O==="mcq"?i(Rn(T)):O==="trueFalse"?i(Fn(T)):O==="shortAnswer"?i(Bn(T)):O==="longAnswer"?i(Nn(T)):O==="fillInTheBlanks"&&i(qn(T)),qr(),re();break}},[P,i,re,qr,l,Pl]),Kf=useCallback(()=>{A(null),N(null);},[]),an=useCallback(w=>{if(!P)return;let{elementId:M,elementType:T}=P;switch(i(ue()),w){case "bring-to-front":T!=="line"&&i(Un({id:M,type:T}));break;case "send-to-back":T!=="line"&&i(zn({id:M,type:T}));break;case "lock":case "unlock":T!=="line"&&i(Wn({id:M,type:T}));break}re(),A(null),N(null);},[P,i,re]),_f=useCallback(w=>{if(!P||!te)return;let{elementId:M,elementType:T}=P;i(ue()),te.type==="link"&&T!=="line"?i(es({id:M,type:T,link:w})):te.type==="altText"&&T!=="line"&&i(ts({id:M,type:T,altText:w})),re(),q(null);},[P,te,i,re]),jf=useCallback(w=>{if(!Y)return;let{elementId:M,elementType:T}=Y;i(ue()),i(as({id:M,type:T,audioData:w})),re(),Z(null);},[Y,i,re]),$f=useCallback(()=>{if(!Y)return;let{elementId:w,elementType:M}=Y;i(ue()),i(as({id:w,type:M,audioData:""})),re();},[Y,i,re]),Xf=useCallback(w=>{if(!G)return;let{elementId:M}=G;i(ue()),i(Xa({id:M,color:w})),re(),oe(null);},[G,i,re]),Yf=useCallback(w=>{if(!R)return;let{elementId:M}=R;i(ue()),i($a({id:M,src:w})),re(),z(null);},[R,i,re]);return jsxs("div",{ref:x,className:s||"fixed top-[90px] right-80 bottom-0 left-0",style:{cursor:u==="pen"?"crosshair":u==="eraser"?"":"default",...n},children:[u==="pen"&&jsx(Wl,{ref:w=>{if(Re.current=w,Xs(w),w){let M=w.getCanvasElement();M&&(Me.current=M,a&&a(Me));}},width:y.width,height:y.height,tool:Ys,color:Dr,strokeWidth:Js,isSketchMode:Zs}),jsxs(Stage,{ref:h,width:y.width,height:y.height,onMouseDown:Ml,onMouseMove:Tl,onMouseUp:Al,onTouchStart:Ml,onTouchMove:Tl,onTouchEnd:Al,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:y.width,height:y.height,fill:l?.backgroundColor||"white"})}),jsx(Layer,{children:(()=>{let w=[];return f.forEach((M,T)=>{w.push({type:"line",timestamp:M.timestamp||T,element:{...M,id:M.id??`line-${T}`},index:T});}),Cf.forEach(M=>{w.push({type:"shape",timestamp:M.timestamp||0,element:M});}),Qs.forEach(M=>{w.push({type:"image",timestamp:M.timestamp||0,element:M});}),me.forEach(M=>{w.push({type:"video",timestamp:M.timestamp||0,element:M});}),Do.forEach(M=>{w.push({type:"text",timestamp:M.timestamp||0,element:M});}),Rf.forEach(M=>{w.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),kl.forEach(M=>{w.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),Kt.forEach(M=>{w.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),_t.forEach(M=>{w.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Fr.forEach(M=>{w.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),Ma.forEach(M=>{w.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),Sf.forEach(M=>{w.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),w.sort((M,T)=>M.timestamp-T.timestamp),w.map((M,T)=>{let O=`${M.type}-${"id"in M.element&&M.element.id||M.index||T}`,De="id"in M.element?M.element.id:void 0,Le=De&&p===De;switch(M.type){case "line":let ae=M.element,Rt=M.index||0,bt=ae.tool==="eraser",tt=ae.isSketch&&ae.tool==="pen",je=ae.isSketch&&bt,vt=ae.id||`line-${Rt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),u==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{i(ue()),i(Hr(Rt));},onTap:()=>{i(ue()),i(Hr(Rt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:V=>{let k=V.target.getStage();k&&(k.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:V=>{let k=V.target.getStage();k&&(k.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:V=>{V?Ia.current.set(vt,V):Ia.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:u==="select",listening:u==="select",onClick:()=>{u==="select"&&(console.log("Line clicked:",vt),Ue(vt));},onTap:()=>{u==="select"&&(console.log("Line tapped:",vt),Ue(vt));},onDragEnd:V=>{i(ue()),i(os({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onTransformEnd:V=>{i(ue()),i(os({id:vt,x:V.target.x(),y:V.target.y(),scaleX:V.target.scaleX(),scaleY:V.target.scaleY(),rotation:V.target.rotation()})),re();},onMouseEnter:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="move");}},onMouseLeave:V=>{if(u==="select"){let k=V.target.getStage();k&&(k.container().style.cursor="default");}},onContextMenu:V=>{let k=V.evt;k.preventDefault(),xt(k,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:tt||je?void 0:ae.color,strokeWidth:tt||je?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||je?bt?"black":ae.color:void 0,closed:tt||je,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ia.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!k),k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shape":return jsxs(be__default.Fragment,{children:[jsx(ii,{onSelect:Ue,shapes:[M.element],shapeRefs:Er,handleShapeDragEnd:kf,handleShapeResizeEnd:Mf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Er.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "image":return jsxs(be__default.Fragment,{children:[jsx(oi,{images:[M.element],getLoadedImage:en,imageRefs:B,onDragEnd:Uf,onTransform:Ie,onSelect:Ue,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=B.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "video":return jsxs(be__default.Fragment,{children:[jsx(ni,{videos:[M.element],selectedId:p,videoRefs:se,onVideoClick:zf,onDragEnd:Ve,onTransformEnd:qt,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=se.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "text":return jsxs(be__default.Fragment,{children:[jsx(Ld,{texts:[M.element],textRefs:ea,onDragEnd:Tf,onTransformEnd:Af,onSelect:Ue,onContextMenu:xt,onDoubleClick:Pf,editingTextId:he,editingValue:Il,onEditingChange:Cl}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=ea.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(ui,{flashcards:[M.element],flashcardRefs:Nr,selectedId:p,onDragEnd:Df,onTransform:Ff,onSelect:Ue,onNext:Ef,onPrevious:Bf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Nr.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(hi,{photoFrames:[M.element],photoFrameRefs:Vr,selectedId:p,onDragEnd:Of,onTransform:Nf,onSelect:Ue,onStartCamera:Vf,onCapture:qf,cameraStreams:Hf,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Vr.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Yd,{handleMcqTransform:_e,multipleChoice:[M.element],handleSelect:Ue,mcqRefs:Ce,handleDragEnd:Je,onContextMenu:xt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ce.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Qd,{trueFalses:[M.element],handleTrueFalseTransform:Ca,handleSelect:Ue,trueFalseRefs:ka,onContextMenu:xt,handleDragEnd:_a}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=ka.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(xu,{shortAnswers:[M.element],handleSelect:Ue,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:Qt}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Iu,{longAnswer:[M.element],handleSelect:Ue,handleTransform:_e,saRefs:Ze,onContextMenu:xt,handleDragEnd:Lf}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Lu,{fillInTheBlanks:[M.element],handleSelect:Ue,handleTransform:_e,onContextMenu:xt,handleDragEnd:If}),Le&&!he&&p&&jsx(Transformer,{ref:V=>{if(V&&de.current!==V){de.current=V;let k=Ze.current.get(p);k&&k.visible()&&(V.nodes([k]),V.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);default:return null}})})()})]}),P&&r?.enabled!==false&&jsx(Bd,{menuRef:L,x:P.x,y:P.y,type:P.elementType,elementId:P.elementId,onAction:Gf,onClose:Kf,isDrawingMode:P.elementType==="image"?l?.images.find(w=>w.id===P.elementId)?.isDrawingMode:P.elementType==="photoFrame"?l?.photoFrames.find(w=>w.id===P.elementId)?.isDrawingMode:false}),U&&P&&jsx(Od,{x:U.x,y:U.y,items:U.type==="order"?[{label:"Bring to Front",onClick:()=>an("bring-to-front")},{label:"Send to Back",onClick:()=>an("send-to-back")}]:[{label:l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"Unlock":"Lock",onClick:()=>an(l&&(P.elementType==="image"?l.images.find(w=>w.id===P.elementId)?.locked:l.videos.find(w=>w.id===P.elementId)?.locked)?"unlock":"lock")}],onClose:()=>N(null)}),te&&jsx(Nd,{title:te.type==="link"?"Add Link":"Add Alt Text",label:te.type==="link"?"URL":"Alternative Text",placeholder:te.type==="link"?"https://example.com":"Describe this image/video",defaultValue:te.defaultValue,onSave:_f,onClose:()=>q(null)}),G&&jsx(Vd,{defaultColor:G.defaultColor,onConfirm:Xf,onCancel:()=>oe(null)}),R&&jsx(zd,{imageSrc:R.imageSrc,onConfirm:Yf,onCancel:()=>z(null)}),X&&jsx(Yo,{onClose:()=>_(false),stageRef:h}),Y&&jsx(Gd,{elementId:Y.elementId,elementType:Y.elementType,existingAudio:Y.existingAudio,onSave:jf,onDelete:$f,onClose:()=>Z(null)}),Q&&jsx(jd,{selectedElementId:p||void 0,onClose:()=>pe(false),onSelectElement:w=>{Ue(w),pe(false);}}),l?.images.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.videos.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shapes?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.texts?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.flashcards?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),l?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(St,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),m&&jsx(uu,{editElement:d}),H&&(()=>{let w=he||p;if(!w)return null;let M=Do.find(T=>T.id===w);return M?jsx(cu,{text:M,position:H}):null})(),E&&he&&(()=>{let w=Do.find(M=>M.id===he);return w?jsx(mu,{text:w,editingValue:Il,onEditingChange:Cl,onFinish:tn,position:{top:E.top,left:E.left},scale:E.scale,textareaRef:we},he):null})()]})},Nx=Ox;var Vx="SchooplaVideoStorage";var xa="videos",Gi=()=>new Promise((e,o)=>{let t=indexedDB.open(Vx,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(xa)||r.createObjectStore(xa,{keyPath:"id"});};}),br=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Gi(),s=a.transaction([xa],"readwrite").objectStore(xa),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,u)=>{let l=s.put(n);l.onsuccess=()=>i(!0),l.onerror=()=>u(l.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var Tu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Gi(),t=e.transaction([xa],"readonly").objectStore(xa);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result,i=new Map;n.forEach(u=>{i.set(u.id,{blob:u.blob,thumbnailDataUrl:u.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${i.size} video blobs from IndexedDB`),a(i);},s.onerror=()=>{e.close(),r(s.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Ki=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Gi(),a=o.transaction([xa],"readwrite").objectStore(xa);await new Promise((r,s)=>{let n=a.delete(e);n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}};var Au=e=>URL.createObjectURL(e);function ba(e,o=[]){let t=[];function a(s,n){let i=be.createContext(n),u=t.length;t=[...t,n];let l=d=>{let{scope:m,children:f,...h}=d,x=m?.[e]?.[u]||i,p=be.useMemo(()=>h,Object.values(h));return jsx(x.Provider,{value:p,children:f})};l.displayName=s+"Provider";function c(d,m){let f=m?.[e]?.[u]||i,h=be.useContext(f);if(h)return h;if(n!==void 0)return n;throw new Error(`\`${d}\` must be used within \`${s}\``)}return [l,c]}let r=()=>{let s=t.map(n=>be.createContext(n));return function(i){let u=i?.[e]||s;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:u}}),[i,u])}};return r.scopeName=e,[a,Hx(r,...o)]}function Hx(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(s){let n=a.reduce((i,{useScope:u,scopeName:l})=>{let d=u(s)[`__scope${l}`];return {...i,...d}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}function Pu(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function vr(...e){return o=>{let t=false,a=e.map(r=>{let s=Pu(r,o);return !t&&typeof s=="function"&&(t=true),s});if(t)return ()=>{for(let r=0;r<a.length;r++){let s=a[r];typeof s=="function"?s():Pu(e[r],null);}}}}function At(...e){return be.useCallback(vr(...e),e)}function Fu(e){let o=Ux(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),u=i.find(Wx);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...n,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Ux(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=Kx(r),i=Gx(s,r.props);return r.type!==be.Fragment&&(i.ref=a?vr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var zx=Symbol("radix.slottable");function Wx(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zx}function Gx(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let u=s(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function Kx(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var $x=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=$x.reduce((e,o)=>{let t=Fu(`Primitive.${o}`),a=be.forwardRef((r,s)=>{let{asChild:n,...i}=r,u=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(u,{...i,ref:s})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function Xe(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function _i(e){let o=Xx(e),t=be.forwardRef((a,r)=>{let{children:s,...n}=a,i=be.Children.toArray(s),u=i.find(Jx);if(u){let l=u.props.children,c=i.map(d=>d===u?be.Children.count(l)>1?be.Children.only(null):be.isValidElement(l)?l.props.children:null:d);return jsx(o,{...n,ref:r,children:be.isValidElement(l)?be.cloneElement(l,void 0,c):null})}return jsx(o,{...n,ref:r,children:s})});return t.displayName=`${e}.Slot`,t}function Xx(e){let o=be.forwardRef((t,a)=>{let{children:r,...s}=t;if(be.isValidElement(r)){let n=Qx(r),i=Zx(s,r.props);return r.type!==be.Fragment&&(i.ref=a?vr(a,n):n),be.cloneElement(r,i)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Yx=Symbol("radix.slottable");function Jx(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Yx}function Zx(e,o){let t={...o};for(let a in o){let r=e[a],s=o[a];/^on[A-Z]/.test(a)?r&&s?t[a]=(...i)=>{let u=s(...i);return r(...i),u}:r&&(t[a]=r):a==="style"?t[a]={...r,...s}:a==="className"&&(t[a]=[r,s].filter(Boolean).join(" "));}return {...e,...t}}function Qx(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function Bs(e){let o=e+"CollectionProvider",[t,a]=ba(o),[r,s]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=x=>{let{scope:p,children:v}=x,g=be__default.useRef(null),b=be__default.useRef(new Map).current;return jsx(r,{scope:p,itemMap:b,collectionRef:g,children:v})};n.displayName=o;let i=e+"CollectionSlot",u=_i(i),l=be__default.forwardRef((x,p)=>{let{scope:v,children:g}=x,b=s(i,v),y=At(p,b.collectionRef);return jsx(u,{ref:y,children:g})});l.displayName=i;let c=e+"CollectionItemSlot",d="data-radix-collection-item",m=_i(c),f=be__default.forwardRef((x,p)=>{let{scope:v,children:g,...b}=x,y=be__default.useRef(null),S=At(p,y),I=s(c,v);return be__default.useEffect(()=>(I.itemMap.set(y,{ref:y,...b}),()=>void I.itemMap.delete(y))),jsx(m,{[d]:"",ref:S,children:g})});f.displayName=c;function h(x){let p=s(e+"CollectionConsumer",x);return be__default.useCallback(()=>{let g=p.collectionRef.current;if(!g)return [];let b=Array.from(g.querySelectorAll(`[${d}]`));return Array.from(p.itemMap.values()).sort((I,C)=>b.indexOf(I.ref.current)-b.indexOf(C.ref.current))},[p.collectionRef,p.itemMap])}return [{Provider:n,Slot:l,ItemSlot:f},h,a]}var vo=globalThis?.document?be.useLayoutEffect:()=>{};var eb=be[" useId ".trim().toString()]||(()=>{}),tb=0;function Nu(e){let[o,t]=be.useState(eb());return vo(()=>{t(a=>a??String(tb++));},[e]),(o?`radix-${o}`:"")}function Vu(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var ab=be[" useInsertionEffect ".trim().toString()]||vo;function Xt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,s,n]=ob({defaultProp:o,onChange:t}),i=e!==void 0,u=i?e:r;{let c=be.useRef(e!==void 0);be.useEffect(()=>{let d=c.current;d!==i&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${i?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),c.current=i;},[i,a]);}let l=be.useCallback(c=>{if(i){let d=rb(c)?c(e):c;d!==e&&n.current?.(d);}else s(c);},[i,e,s,n]);return [u,l]}function ob({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),s=be.useRef(o);return ab(()=>{s.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(s.current?.(t),r.current=t);},[t,r]),[t,a,s]}function rb(e){return typeof e=="function"}var sb=be.createContext(void 0);function wo(e){let o=be.useContext(sb);return e||o||"ltr"}var Xi="rovingFocusGroup.onEntryFocus",nb={bubbles:false,cancelable:true},yr="RovingFocusGroup",[Yi,qu,ib]=Bs(yr),[lb,Ji]=ba(yr,[ib]),[db,ub]=lb(yr),Hu=be.forwardRef((e,o)=>jsx(Yi.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Yi.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(cb,{...e,ref:o})})}));Hu.displayName=yr;var cb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:s,currentTabStopId:n,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:u,onEntryFocus:l,preventScrollOnEntryFocus:c=false,...d}=e,m=be.useRef(null),f=At(o,m),h=wo(s),[x,p]=Xt({prop:n,defaultProp:i??null,onChange:u,caller:yr}),[v,g]=be.useState(false),b=Vu(l),y=qu(t),S=be.useRef(false),[I,C]=be.useState(0);return be.useEffect(()=>{let L=m.current;if(L)return L.addEventListener(Xi,b),()=>L.removeEventListener(Xi,b)},[b]),jsx(db,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:x,onItemFocus:be.useCallback(L=>p(L),[p]),onItemShiftTab:be.useCallback(()=>g(true),[]),onFocusableItemAdd:be.useCallback(()=>C(L=>L+1),[]),onFocusableItemRemove:be.useCallback(()=>C(L=>L-1),[]),children:jsx(it.div,{tabIndex:v||I===0?-1:0,"data-orientation":a,...d,ref:f,style:{outline:"none",...e.style},onMouseDown:Xe(e.onMouseDown,()=>{S.current=true;}),onFocus:Xe(e.onFocus,L=>{let P=!S.current;if(L.target===L.currentTarget&&P&&!v){let A=new CustomEvent(Xi,nb);if(L.currentTarget.dispatchEvent(A),!A.defaultPrevented){let H=y().filter(N=>N.focusable),F=H.find(N=>N.active),E=H.find(N=>N.id===x),U=[F,E,...H].filter(Boolean).map(N=>N.ref.current);Wu(U,c);}}S.current=false;}),onBlur:Xe(e.onBlur,()=>g(false))})})}),Uu="RovingFocusGroupItem",zu=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:s,children:n,...i}=e,u=Nu(),l=s||u,c=ub(Uu,t),d=c.currentTabStopId===l,m=qu(t),{onFocusableItemAdd:f,onFocusableItemRemove:h,currentTabStopId:x}=c;return be.useEffect(()=>{if(a)return f(),()=>h()},[a,f,h]),jsx(Yi.ItemSlot,{scope:t,id:l,focusable:a,active:r,children:jsx(it.span,{tabIndex:d?0:-1,"data-orientation":c.orientation,...i,ref:o,onMouseDown:Xe(e.onMouseDown,p=>{a?c.onItemFocus(l):p.preventDefault();}),onFocus:Xe(e.onFocus,()=>c.onItemFocus(l)),onKeyDown:Xe(e.onKeyDown,p=>{if(p.key==="Tab"&&p.shiftKey){c.onItemShiftTab();return}if(p.target!==p.currentTarget)return;let v=pb(p,c.orientation,c.dir);if(v!==void 0){if(p.metaKey||p.ctrlKey||p.altKey||p.shiftKey)return;p.preventDefault();let b=m().filter(y=>y.focusable).map(y=>y.ref.current);if(v==="last")b.reverse();else if(v==="prev"||v==="next"){v==="prev"&&b.reverse();let y=b.indexOf(p.currentTarget);b=c.loop?hb(b,y+1):b.slice(y+1);}setTimeout(()=>Wu(b));}}),children:typeof n=="function"?n({isCurrentTabStop:d,hasTabStop:x!=null}):n})})});zu.displayName=Uu;var fb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function mb(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function pb(e,o,t){let a=mb(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return fb[a]}function Wu(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function hb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Gu=Hu,Ku=zu;var ju="Toggle",Zi=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...s}=e,[n,i]=Xt({prop:t,onChange:r,defaultProp:a??false,caller:ju});return jsx(it.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:o,onClick:Xe(e.onClick,()=>{e.disabled||i(!n);})})});Zi.displayName=ju;var va="ToggleGroup",[Xu]=ba(va,[Ji]),Yu=Ji(),Qi=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(bb,{...a,ref:o});if(t==="multiple")return jsx(vb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${va}\``)});Qi.displayName=va;var[Ju,Zu]=Xu(va),bb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Xt({prop:t,defaultProp:a??"",onChange:r,caller:va});return jsx(Ju,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(Qu,{...s,ref:o})})}),vb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...s}=e,[n,i]=Xt({prop:t,defaultProp:a??[],onChange:r,caller:va}),u=be__default.useCallback(c=>i((d=[])=>[...d,c]),[i]),l=be__default.useCallback(c=>i((d=[])=>d.filter(m=>m!==c)),[i]);return jsx(Ju,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:u,onItemDeactivate:l,children:jsx(Qu,{...s,ref:o})})});Qi.displayName=va;var[yb,wb]=Xu(va),Qu=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:s,dir:n,loop:i=true,...u}=e,l=Yu(t),c=wo(n),d={role:"group",dir:c,...u};return jsx(yb,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(Gu,{asChild:true,...l,orientation:s,dir:c,loop:i,children:jsx(it.div,{...d,ref:o})}):jsx(it.div,{...d,ref:o})})}),Vs="ToggleGroupItem",Lb=be__default.forwardRef((e,o)=>{let t=Zu(Vs,e.__scopeToggleGroup),a=wb(Vs,e.__scopeToggleGroup),r=Yu(e.__scopeToggleGroup),s=t.value.includes(e.value),n=a.disabled||e.disabled,i={...e,pressed:s,disabled:n},u=be__default.useRef(null);return a.rovingFocus?jsx(Ku,{asChild:true,...r,focusable:!n,active:s,ref:u,children:jsx($u,{...i,ref:o})}):jsx($u,{...i,ref:o})});Lb.displayName=Vs;var $u=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,s=Zu(Vs,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=s.type==="single"?n:void 0;return jsx(Zi,{...i,...r,ref:o,onPressedChange:u=>{u?s.onItemActivate(a):s.onItemDeactivate(a);}})}),ec=Qi;function tc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=tc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function qs(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=tc(e))&&(a&&(a+=" "),a+=o);return a}var Ib=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},Cb=(e,o)=>({classGroupId:e,validator:o}),nc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var ac=[],kb="arbitrary..",Mb=e=>{let o=Ab(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Tb(n);let i=n.split("-"),u=i[0]===""&&i.length>1?1:0;return ic(i,u,o)},getConflictingClassGroupIds:(n,i)=>{if(i){let u=a[n],l=t[n];return u?l?Ib(l,u):u:l||ac}return t[n]||ac}}},ic=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],s=t.nextPart.get(r);if(s){let l=ic(e,o+1,s);if(l)return l}let n=t.validators;if(n===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),u=n.length;for(let l=0;l<u;l++){let c=n[l];if(c.validator(i))return c.classGroupId}},Tb=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?kb+a:void 0})(),Ab=e=>{let{theme:o,classGroups:t}=e;return Pb(t,o)},Pb=(e,o)=>{let t=nc();for(let a in e){let r=e[a];al(r,t,a,o);}return t},al=(e,o,t,a)=>{let r=e.length;for(let s=0;s<r;s++){let n=e[s];Rb(n,o,t,a);}},Rb=(e,o,t,a)=>{if(typeof e=="string"){Db(e,o,t);return}if(typeof e=="function"){Fb(e,o,t,a);return}Eb(e,o,t,a);},Db=(e,o,t)=>{let a=e===""?o:lc(o,e);a.classGroupId=t;},Fb=(e,o,t,a)=>{if(Bb(e)){al(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Cb(t,e));},Eb=(e,o,t,a)=>{let r=Object.entries(e),s=r.length;for(let n=0;n<s;n++){let[i,u]=r[n];al(u,lc(o,i),t,a);}},lc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let s=0;s<r;s++){let n=a[s],i=t.nextPart.get(n);i||(i=nc(),t.nextPart.set(n,i)),t=i;}return t},Bb=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Ob=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(s,n)=>{t[s]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(s){let n=t[s];if(n!==void 0)return n;if((n=a[s])!==void 0)return r(s,n),n},set(s,n){s in t?t[s]=n:r(s,n);}}};var Nb=[],oc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),Vb=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let s=[],n=0,i=0,u=0,l,c=r.length;for(let x=0;x<c;x++){let p=r[x];if(n===0&&i===0){if(p===":"){s.push(r.slice(u,x)),u=x+1;continue}if(p==="/"){l=x;continue}}p==="["?n++:p==="]"?n--:p==="("?i++:p===")"&&i--;}let d=s.length===0?r:r.slice(u),m=d,f=false;d.endsWith("!")?(m=d.slice(0,-1),f=true):d.startsWith("!")&&(m=d.slice(1),f=true);let h=l&&l>u?l-u:void 0;return oc(s,f,m,h)};if(o){let r=o+":",s=a;a=n=>n.startsWith(r)?s(n.slice(r.length)):oc(Nb,false,n,void 0,true);}if(t){let r=a;a=s=>t({className:s,parseClassName:r});}return a},qb=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],i=n[0]==="[",u=o.has(n);i||u?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(n)):r.push(n);}return r.length>0&&(r.sort(),a.push(...r)),a}},Hb=e=>({cache:Ob(e.cacheSize),parseClassName:Vb(e),sortModifiers:qb(e),...Mb(e)}),Ub=/\s+/,zb=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:s}=o,n=[],i=e.trim().split(Ub),u="";for(let l=i.length-1;l>=0;l-=1){let c=i[l],{isExternal:d,modifiers:m,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:x}=t(c);if(d){u=c+(u.length>0?" "+u:u);continue}let p=!!x,v=a(p?h.substring(0,x):h);if(!v){if(!p){u=c+(u.length>0?" "+u:u);continue}if(v=a(h),!v){u=c+(u.length>0?" "+u:u);continue}p=false;}let g=m.length===0?"":m.length===1?m[0]:s(m).join(":"),b=f?g+"!":g,y=b+v;if(n.indexOf(y)>-1)continue;n.push(y);let S=r(v,p);for(let I=0;I<S.length;++I){let C=S[I];n.push(b+C);}u=c+(u.length>0?" "+u:u);}return u},Wb=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=dc(t))&&(r&&(r+=" "),r+=a);return r},dc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=dc(e[a]))&&(t&&(t+=" "),t+=o);return t},Gb=(e,...o)=>{let t,a,r,s,n=u=>{let l=o.reduce((c,d)=>d(c),e());return t=Hb(l),a=t.cache.get,r=t.cache.set,s=i,i(u)},i=u=>{let l=a(u);if(l)return l;let c=zb(u,t);return r(u,c),c};return s=n,(...u)=>s(Wb(...u))},Kb=[],Ne=e=>{let o=t=>t[e]||Kb;return o.isThemeGetter=true,o},uc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,cc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,_b=/^\d+\/\d+$/,jb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,$b=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Xb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Yb=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Jb=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Lo=e=>_b.test(e),le=e=>!!e&&!Number.isNaN(Number(e)),ya=e=>!!e&&Number.isInteger(Number(e)),el=e=>e.endsWith("%")&&le(e.slice(0,-1)),Yt=e=>jb.test(e),Zb=()=>true,Qb=e=>$b.test(e)&&!Xb.test(e),fc=()=>false,ev=e=>Yb.test(e),tv=e=>Jb.test(e),av=e=>!j(e)&&!$(e),ov=e=>So(e,hc,fc),j=e=>uc.test(e),za=e=>So(e,gc,Qb),tl=e=>So(e,lv,le),rc=e=>So(e,mc,fc),rv=e=>So(e,pc,tv),Hs=e=>So(e,xc,ev),$=e=>cc.test(e),wr=e=>Io(e,gc),sv=e=>Io(e,dv),sc=e=>Io(e,mc),nv=e=>Io(e,hc),iv=e=>Io(e,pc),Us=e=>Io(e,xc,true),So=(e,o,t)=>{let a=uc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Io=(e,o,t=false)=>{let a=cc.exec(e);return a?a[1]?o(a[1]):t:false},mc=e=>e==="position"||e==="percentage",pc=e=>e==="image"||e==="url",hc=e=>e==="length"||e==="size"||e==="bg-size",gc=e=>e==="length",lv=e=>e==="number",dv=e=>e==="family-name",xc=e=>e==="shadow";var uv=()=>{let e=Ne("color"),o=Ne("font"),t=Ne("text"),a=Ne("font-weight"),r=Ne("tracking"),s=Ne("leading"),n=Ne("breakpoint"),i=Ne("container"),u=Ne("spacing"),l=Ne("radius"),c=Ne("shadow"),d=Ne("inset-shadow"),m=Ne("text-shadow"),f=Ne("drop-shadow"),h=Ne("blur"),x=Ne("perspective"),p=Ne("aspect"),v=Ne("ease"),g=Ne("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],y=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],S=()=>[...y(),$,j],I=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],L=()=>[$,j,u],P=()=>[Lo,"full","auto",...L()],A=()=>[ya,"none","subgrid",$,j],H=()=>["auto",{span:["full",ya,$,j]},ya,$,j],F=()=>[ya,"auto",$,j],E=()=>["auto","min","max","fr",$,j],D=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...L()],te=()=>[Lo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...L()],q=()=>[e,$,j],G=()=>[...y(),sc,rc,{position:[$,j]}],oe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],R=()=>["auto","cover","contain",nv,ov,{size:[$,j]}],z=()=>[el,wr,za],X=()=>["","none","full",l,$,j],_=()=>["",le,wr,za],Y=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[le,el,sc,rc],pe=()=>["","none",h,$,j],we=()=>["none",le,$,j],Re=()=>["none",le,$,j],Me=()=>[le,$,j],He=()=>[Lo,"full",...L()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Yt],breakpoint:[Yt],color:[Zb],container:[Yt],"drop-shadow":[Yt],ease:["in","out","in-out"],font:[av],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Yt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Yt],shadow:[Yt],spacing:["px",le],text:[Yt],"text-shadow":[Yt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Lo,j,$,p]}],container:["container"],columns:[{columns:[le,j,$,i]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:S()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:P()}],"inset-x":[{"inset-x":P()}],"inset-y":[{"inset-y":P()}],start:[{start:P()}],end:[{end:P()}],top:[{top:P()}],right:[{right:P()}],bottom:[{bottom:P()}],left:[{left:P()}],visibility:["visible","invisible","collapse"],z:[{z:[ya,"auto",$,j]}],basis:[{basis:[Lo,"full","auto",i,...L()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[le,Lo,"auto","initial","none",j]}],grow:[{grow:["",le,$,j]}],shrink:[{shrink:["",le,$,j]}],order:[{order:[ya,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":A()}],"col-start-end":[{col:H()}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":A()}],"row-start-end":[{row:H()}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":E()}],"auto-rows":[{"auto-rows":E()}],gap:[{gap:L()}],"gap-x":[{"gap-x":L()}],"gap-y":[{"gap-y":L()}],"justify-content":[{justify:[...D(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...D()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":D()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:L()}],px:[{px:L()}],py:[{py:L()}],ps:[{ps:L()}],pe:[{pe:L()}],pt:[{pt:L()}],pr:[{pr:L()}],pb:[{pb:L()}],pl:[{pl:L()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":L()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":L()}],"space-y-reverse":["space-y-reverse"],size:[{size:te()}],w:[{w:[i,"screen",...te()]}],"min-w":[{"min-w":[i,"screen","none",...te()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[n]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",t,wr,za]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,tl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",el,j]}],"font-family":[{font:[sv,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,j]}],"line-clamp":[{"line-clamp":[le,"none",$,tl]}],leading:[{leading:[s,...L()]}],"list-image":[{"list-image":["none",$,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:q()}],"text-color":[{text:q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[le,"from-font","auto",$,za]}],"text-decoration-color":[{decoration:q()}],"underline-offset":[{"underline-offset":[le,"auto",$,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:L()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:G()}],"bg-repeat":[{bg:oe()}],"bg-size":[{bg:R()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ya,$,j],radial:["",$,j],conic:[ya,$,j]},iv,rv]}],"bg-color":[{bg:q()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:q()}],"gradient-via":[{via:q()}],"gradient-to":[{to:q()}],rounded:[{rounded:X()}],"rounded-s":[{"rounded-s":X()}],"rounded-e":[{"rounded-e":X()}],"rounded-t":[{"rounded-t":X()}],"rounded-r":[{"rounded-r":X()}],"rounded-b":[{"rounded-b":X()}],"rounded-l":[{"rounded-l":X()}],"rounded-ss":[{"rounded-ss":X()}],"rounded-se":[{"rounded-se":X()}],"rounded-ee":[{"rounded-ee":X()}],"rounded-es":[{"rounded-es":X()}],"rounded-tl":[{"rounded-tl":X()}],"rounded-tr":[{"rounded-tr":X()}],"rounded-br":[{"rounded-br":X()}],"rounded-bl":[{"rounded-bl":X()}],"border-w":[{border:_()}],"border-w-x":[{"border-x":_()}],"border-w-y":[{"border-y":_()}],"border-w-s":[{"border-s":_()}],"border-w-e":[{"border-e":_()}],"border-w-t":[{"border-t":_()}],"border-w-r":[{"border-r":_()}],"border-w-b":[{"border-b":_()}],"border-w-l":[{"border-l":_()}],"divide-x":[{"divide-x":_()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":_()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"hidden","none"]}],"border-color":[{border:q()}],"border-color-x":[{"border-x":q()}],"border-color-y":[{"border-y":q()}],"border-color-s":[{"border-s":q()}],"border-color-e":[{"border-e":q()}],"border-color-t":[{"border-t":q()}],"border-color-r":[{"border-r":q()}],"border-color-b":[{"border-b":q()}],"border-color-l":[{"border-l":q()}],"divide-color":[{divide:q()}],"outline-style":[{outline:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[le,$,j]}],"outline-w":[{outline:["",le,wr,za]}],"outline-color":[{outline:q()}],shadow:[{shadow:["","none",c,Us,Hs]}],"shadow-color":[{shadow:q()}],"inset-shadow":[{"inset-shadow":["none",d,Us,Hs]}],"inset-shadow-color":[{"inset-shadow":q()}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:q()}],"ring-offset-w":[{"ring-offset":[le,za]}],"ring-offset-color":[{"ring-offset":q()}],"inset-ring-w":[{"inset-ring":_()}],"inset-ring-color":[{"inset-ring":q()}],"text-shadow":[{"text-shadow":["none",m,Us,Hs]}],"text-shadow-color":[{"text-shadow":q()}],opacity:[{opacity:[le,$,j]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[le]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":q()}],"mask-image-linear-to-color":[{"mask-linear-to":q()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":q()}],"mask-image-t-to-color":[{"mask-t-to":q()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":q()}],"mask-image-r-to-color":[{"mask-r-to":q()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":q()}],"mask-image-b-to-color":[{"mask-b-to":q()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":q()}],"mask-image-l-to-color":[{"mask-l-to":q()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":q()}],"mask-image-x-to-color":[{"mask-x-to":q()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":q()}],"mask-image-y-to-color":[{"mask-y-to":q()}],"mask-image-radial":[{"mask-radial":[$,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":q()}],"mask-image-radial-to-color":[{"mask-radial-to":q()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":y()}],"mask-image-conic-pos":[{"mask-conic":[le]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":q()}],"mask-image-conic-to-color":[{"mask-conic-to":q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:G()}],"mask-repeat":[{mask:oe()}],"mask-size":[{mask:R()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:pe()}],brightness:[{brightness:[le,$,j]}],contrast:[{contrast:[le,$,j]}],"drop-shadow":[{"drop-shadow":["","none",f,Us,Hs]}],"drop-shadow-color":[{"drop-shadow":q()}],grayscale:[{grayscale:["",le,$,j]}],"hue-rotate":[{"hue-rotate":[le,$,j]}],invert:[{invert:["",le,$,j]}],saturate:[{saturate:[le,$,j]}],sepia:[{sepia:["",le,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":pe()}],"backdrop-brightness":[{"backdrop-brightness":[le,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[le,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",le,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[le,$,j]}],"backdrop-invert":[{"backdrop-invert":["",le,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[le,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[le,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",le,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":L()}],"border-spacing-x":[{"border-spacing-x":L()}],"border-spacing-y":[{"border-spacing-y":L()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[le,"initial",$,j]}],ease:[{ease:["linear","initial",v,$,j]}],delay:[{delay:[le,$,j]}],animate:[{animate:["none",g,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[x,$,j]}],"perspective-origin":[{"perspective-origin":S()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:Re()}],"scale-x":[{"scale-x":Re()}],"scale-y":[{"scale-y":Re()}],"scale-z":[{"scale-z":Re()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:S()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:He()}],"translate-x":[{"translate-x":He()}],"translate-y":[{"translate-y":He()}],"translate-z":[{"translate-z":He()}],"translate-none":["translate-none"],accent:[{accent:q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:q()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,j]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":L()}],"scroll-mx":[{"scroll-mx":L()}],"scroll-my":[{"scroll-my":L()}],"scroll-ms":[{"scroll-ms":L()}],"scroll-me":[{"scroll-me":L()}],"scroll-mt":[{"scroll-mt":L()}],"scroll-mr":[{"scroll-mr":L()}],"scroll-mb":[{"scroll-mb":L()}],"scroll-ml":[{"scroll-ml":L()}],"scroll-p":[{"scroll-p":L()}],"scroll-px":[{"scroll-px":L()}],"scroll-py":[{"scroll-py":L()}],"scroll-ps":[{"scroll-ps":L()}],"scroll-pe":[{"scroll-pe":L()}],"scroll-pt":[{"scroll-pt":L()}],"scroll-pr":[{"scroll-pr":L()}],"scroll-pb":[{"scroll-pb":L()}],"scroll-pl":[{"scroll-pl":L()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,j]}],fill:[{fill:["none",...q()]}],"stroke-w":[{stroke:[le,wr,za,tl]}],stroke:[{stroke:["none",...q()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var bc=Gb(uv);function wa(...e){return bc(qs(e))}var fv=be.createContext({size:"default",variant:"default",spacing:0});function La({className:e,variant:o,size:t,spacing:a=2,children:r,...s}){return jsx(ec,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:wa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...s,children:jsx(fv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var pv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Sc=createSlice({name:"toolbar",initialState:pv,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:Ot,setPenColor:zs,setStrokeWidth:rl,setFontSize:CA,setFontFamily:kA,setFontStyle:MA,setFontWeight:TA,setTextDecoration:AA,setTextColor:PA}=Sc.actions,Ic=Sc.reducer;var Cc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,s]=useState(null),[n,i]=useState(0),[u,l]=useState(null),[c,d]=useState(false),m=useRef(null),f=useRef([]),h=useRef(null),x=useRef(null),p=useRef(null);useEffect(()=>((async()=>{try{let C=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});l(C),d(!0),p.current&&(p.current.srcObject=C);}catch(C){console.error("Error accessing camera:",C),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),u&&u.getTracks().forEach(C=>C.stop());}),[]);let v=()=>{u&&(u.getTracks().forEach(I=>I.stop()),l(null),d(false));},g=async()=>{try{let I=null,C=null;try{I=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(F){console.error("Error accessing camera for recording:",F),alert("Failed to access camera for recording.");return}try{C=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(F){console.warn("Microphone access denied:",F);}let L=[...I.getVideoTracks()];C&&L.push(...C.getAudioTracks());let P=new MediaStream(L),A="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?A="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?A="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?A="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(A="video/webm;codecs=vp8");let H=new MediaRecorder(P,{mimeType:A,videoBitsPerSecond:25e5});m.current=H,f.current=[],H.ondataavailable=F=>{F.data.size>0&&f.current.push(F.data);},H.onstop=()=>{let F=new Blob(f.current,{type:A}),E=document.createElement("video");E.src=URL.createObjectURL(F),E.muted=!0,E.currentTime=.1,E.onseeked=()=>{let D=document.createElement("canvas");D.width=E.videoWidth,D.height=E.videoHeight;let U=D.getContext("2d");U&&(U.drawImage(E,0,0),x.current=D.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(E.src);},P.getTracks().forEach(D=>D.stop()),I&&I.getTracks().forEach(D=>D.stop()),C&&C.getTracks().forEach(D=>D.stop()),h.current&&clearInterval(h.current),s(F),v();},H.onerror=F=>{console.error("MediaRecorder error:",F);},H.start(1e3),a(!0),i(0),h.current=setInterval(()=>{i(F=>F+1);},1e3);}catch(I){console.error("Error starting camera recording:",I),alert("Failed to start recording. Please check permissions.");}},b=()=>{m.current&&t&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),a(false));},y=()=>{if(r){let I=URL.createObjectURL(r),C=document.createElement("a");C.href=I,C.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(I);}},S=I=>{let C=Math.floor(I/60),L=I%60;return `${C.toString().padStart(2,"0")}:${L.toString().padStart(2,"0")}`};return jsx("div",{className:"fixed inset-0 flex items-center justify-center",children:jsxs("div",{className:"relative w-full max-w-2xl overflow-hidden rounded-2xl shadow-2xl",children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:p,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!t&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,disabled:!c,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!c&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),t&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:b,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:S(n)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",S(n)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{s(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:y,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&x.current&&(o(r,x.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})})};var Jt=40,Mc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[s,n]=useState(t?.order||"sequential"),[i,u]=useState(false),l=useRef(null),c=useRef(null);useEffect(()=>{let g=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let d=g=>{let b=g.target.files;if(!b||b.length===0)return;let y=Jt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Jt} images`);return}let S=Array.from(b).slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Jt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=H=>{H.target?.result?L(H.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]),c.current&&(c.current.value="");});},m=g=>{g.preventDefault(),u(false);let b=Array.from(g.dataTransfer.files).filter(C=>C.type.startsWith("image/"));if(b.length===0)return;let y=Jt-a.length;if(y<=0){alert(`You can only upload a maximum of ${Jt} images`);return}let S=b.slice(0,y);S.length<b.length&&alert(`Only ${y} more images can be added (max ${Jt} total)`);let I=S.map(C=>new Promise((L,P)=>{let A=new FileReader;A.onload=H=>{H.target?.result?L(H.target.result):P(new Error("Failed to read file"));},A.onerror=P,A.readAsDataURL(C);}));Promise.all(I).then(C=>{r(L=>[...L,...C]);});},f=g=>{g.preventDefault(),u(true);},h=()=>{u(false);},x=g=>{r(b=>b.filter((y,S)=>S!==g));},v=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:l,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,s,t?.id);},className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=Jt?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",Jt," images"]}):jsxs("span",{children:[a.length,"/",Jt," images"]})})]}),jsx("input",{ref:c,type:"file",accept:"image/*",multiple:true,onChange:d,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:f,onDragLeave:h,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${i?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp$1,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:i?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${s==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${s==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${s==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>x(b),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:b+1})]},b))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(v,document.body)};var Ws={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},Av={enabled:true};function il(e){return e?{tools:{...Ws.tools,...e.tools},actions:{...Ws.actions,...e.actions}}:Ws}var Pv={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},Rv={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var ry=({isOpen:e,onClose:o,onScreenRecord:t,stageRef:a,onTextAdded:r,showToggleButton:s=true,config:n}={})=>{let i=xe(),u=ee(B=>B.canvas.slides.find(ne=>ne.id===B.canvas.currentSlideId)),l=u?.videos||[],c=u?.editingFlashcard,d=ee(B=>B.toolbar.selectedTool),m=ee(B=>B.toolbar.penColor),f=u?.showMcqForm,h=u?.showFlashcardForm,x=useMemo(()=>il(n),[n]),{tools:p,actions:v}=x,g=l.some(B=>B.isRecorded&&B.isPlaying),b=ee(B=>B.toolbar.fontSize),y=ee(B=>B.toolbar.fontFamily),S=ee(B=>B.toolbar.fontStyle),I=ee(B=>B.toolbar.fontWeight),C=ee(B=>B.toolbar.textDecoration),L=ee(B=>B.toolbar.textColor),[P,A]=useState(false),[H,F]=useState(false),[E,D]=useState(false),[U,N]=useState(false),[te,q]=useState(false),[G,oe]=useState(true),z=useRef(null),X=useRef(null),Y=[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],Z=useMemo(()=>Y.filter(B=>{let ne=p[B.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[p]),Q=[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],pe=useMemo(()=>{let B=p.shapes;return B===false?[]:B===true?Q:Array.isArray(B)?Q.filter(ne=>B.includes(ne.name)):Q},[p.shapes]),we=[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],Re=useMemo(()=>{let B=p.activities;return B===false?[]:B===true?we:Array.isArray(B)?we.filter(ne=>B.includes(ne.name)):we},[p.activities]),Me=useMemo(()=>{let B=p.media;return B===false?{photoFrame:false,image:false,video:false}:B===true?{photoFrame:true,image:true,video:true}:Array.isArray(B)?{photoFrame:B.includes("photo-frame"),image:B.includes("image"),video:B.includes("video")}:{photoFrame:true,image:true,video:true}},[p.media]),He=useMemo(()=>{let B=p.activities;return B===false?false:B===true?true:Array.isArray(B)?B.includes("flashcard"):true},[p.activities]),re=B=>{let ne=B.target.files;!ne||ne.length===0||(i(Ot("select")),i(dt(false)),N(false),Array.from(ne).forEach(Ie=>{let me=new FileReader;me.onload=se=>{let ie=new window.Image;ie.src=se.target?.result,ie.onload=()=>{let Ve=ie.width/ie.height,qt=300,Kt=300,_e=ie.width,Ce=ie.height;_e>qt&&(_e=qt,Ce=_e/Ve),Ce>Kt&&(Ce=Kt,_e=Ce*Ve),i(ue());let Je=(window.innerWidth-_e)/2,_t=(window.innerHeight-Ce)/2;i(mn({id:v4(),src:ie.src,x:Je,y:_t,width:_e,height:Ce,draggable:true,rotation:0}));};},me.readAsDataURL(Ie);}),B.target.value="");},Mr=async B=>{let ne=B.target.files;if(!(!ne||ne.length===0)){console.log("files",B),i(Ot("select")),i(dt(false)),N(false);for(let Ie of Array.from(ne))try{let me=URL.createObjectURL(Ie),se=document.createElement("video");console.log("video",se),se.src=me,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Ze,Qt)=>{let Ma=setTimeout(()=>Qt(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ma),Ze();},se.onerror=()=>{clearTimeout(Ma),Qt(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Ze,Qt)=>{let Ma=setTimeout(()=>Qt(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ma),Ze()):se.onloadeddata=()=>{clearTimeout(Ma),Ze();};});let ie=Math.min(.8,se.duration/2);console.log("Seeking to:",ie),se.currentTime=ie,await new Promise(Ze=>{let Qt=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);se.onseeked=()=>{clearTimeout(Qt),console.log("Seek completed"),Ze();};});let Ve=document.createElement("canvas"),qt=se.videoWidth/se.videoHeight,Kt=400,_e=400,Ce=se.videoWidth,Je=se.videoHeight;Ce>Kt&&(Ce=Kt,Je=Ce/qt),Je>_e&&(Je=_e,Ce=Je*qt),Ve.width=Ce,Ve.height=Je;let _t=Ve.getContext("2d",{willReadFrequently:!1});if(!_t)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ce,height:Je}),_t.drawImage(se,0,0,Ce,Je);let Ca=Ve.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ca.length),i(ue());let ka=(window.innerWidth-Ce)/2,_a=(window.innerHeight-Je)/2,Fr=v4();await br(Fr,Ie,Ca),i(zr({id:Fr,objectUrl:me,thumbnailDataUrl:Ca,videoBlob:Ie,x:ka,y:_a,width:Ce,height:Je,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${Ie.name}`);}catch(me){console.error("Error processing video:",me),alert(`Failed to process video: ${Ie.name}`);}B.target.value="";}},Tr=(B,ne,Ie)=>{i(ue()),i(Ot("select")),i(dt(false));let me=300,se=300,ie=(window.innerWidth-me)/2,Ve=(window.innerHeight-se)/2;i(Ie?Ya({id:Ie,images:B,order:ne,x:ie,y:Ve,width:me,height:se,rotation:0,draggable:true}):yn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:B,currentIndex:0,order:ne,x:ie,y:Ve,width:me,height:se,rotation:0,draggable:true})),i(Aa(false));},Ar=()=>{i(ue()),i(Ot("select")),i(dt(false));let B=400,ne=300,Ie=(window.innerWidth-B)/2,me=(window.innerHeight-ne)/2;i(In({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ie,y:me,width:B,height:ne,rotation:0,draggable:true,isCapturing:false})),q(false);},Pr=B=>{let me=(window.innerWidth-100)/2,se=(window.innerHeight-100)/2,ie={};switch(B.name){case "circle":case "ring":case "wedge":case "arc":ie.radius=50,(B.name==="ring"||B.name==="arc")&&(ie.innerRadius=25,ie.outerRadius=50),(B.name==="wedge"||B.name==="arc")&&(ie.angle=B.name==="wedge"?60:90);break;case "ellipse":ie.radiusX=60,ie.radiusY=40;break;case "triangle":ie.radius=50,ie.sides=3;break;case "polygon":ie.radius=50,ie.sides=6;break;case "star":ie.innerRadius=25,ie.outerRadius=50,ie.numPoints=5;break;case "arrow":case "line":ie.points=[0,0,100,0],B.name==="arrow"&&(ie.pointerLength=10,ie.pointerWidth=10);break}let Ve={id:`shape-${Date.now()}`,type:B.name,x:me,y:se,width:100,height:100,rotation:0,color:m,...ie};i(ue()),i(dt(false)),i(Ot(B.name)),i(gn(Ve));},Sa=B=>{if(i(Ot(B)),B==="select")i(dt(false));else if(B==="text"){i(dt(false)),i(ue());let ne=200,Ie=50,me=(window.innerWidth-ne)/2,se=(window.innerHeight-Ie)/2,ie=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;i(bn({id:ie,text:"",x:me,y:se,width:ne,height:Ie,rotation:0,draggable:true,fontSize:b,fontFamily:y,fontStyle:S,fontWeight:I,textDecoration:C,fill:L,align:"left"})),setTimeout(()=>{i(Ho(ie));},100),r&&r(ie);}else i(dt(true));},Rr=()=>{i(jn()),i(Ot("select")),i(dt(false));},Xs=()=>{t?t():a?A(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Ys=()=>{F(true);},Dr=async(B,ne)=>{try{i(Ot("select")),i(dt(!1));let Ie=URL.createObjectURL(B),me=document.createElement("video");me.src=Ie,me.muted=!0,me.playsInline=!0,me.preload="auto",await new Promise((Ca,ka)=>{let _a=setTimeout(()=>ka(new Error("Metadata load timeout")),1e4);me.onloadedmetadata=()=>{clearTimeout(_a),Ca();},me.onerror=()=>{clearTimeout(_a),ka(new Error("Failed to load video"));};});let se=640,ie=me.videoWidth/me.videoHeight,Ve=se,qt=Ve/ie,Kt=window.innerWidth,_e=window.innerHeight;i(ue());let Ce=(Kt-Ve)/2,Je=(_e-qt)/2,_t=v4();await br(_t,B,ne),i(zr({id:_t,objectUrl:Ie,thumbnailDataUrl:ne,videoBlob:B,x:Ce,y:Je,width:Ve,height:qt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),A(!1),F(!1);}catch(Ie){console.error("Error adding recorded video to canvas:",Ie),alert("Failed to add video to canvas. Please try again.");}},Js=B=>{i(Ot("select")),i(dt(false)),i(Vo(null)),B&&i(Hn(B)),i(ra(!f));},Zs=()=>{i(Eo(null)),i(Aa(true)),q(false);},Ia=()=>{D(!E);},Qs=()=>{N(!U);},en=()=>{q(!te);};return g?null:jsx("div",{className:"konva-editor-root",children:jsxs("div",{className:"fixed top-1/2 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4",children:[jsxs("div",{className:"flex items-center",children:[jsx(La,{type:"single",className:"flex flex-col gap-1 border bg-white p-1 shadow-xl",children:Z.map((B,ne)=>jsx("div",{title:B.label,className:`hover:bg-primary/10 mb-1 cursor-pointer rounded-md px-4 py-3 ${B.name===d?"bg-primary/10":""}`,onClick:()=>{if(B.name==="image"){Qs(),D(false),q(false),Sa(B.name);return}else if(B.name==="shapes"){Ia(),N(false),q(false),Sa(B.name);return}else if(B.name==="activities"){Sa(B.name),en(),D(false),N(false);return}Sa(B.name),D(false),N(false),q(false);},children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))}),E&&jsx(La,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:pe.map((B,ne)=>jsx("div",{title:B.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",onClick:()=>Pr(B),children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))}),U&&jsxs(La,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Ar,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Me.image&&jsx("div",{onClick:()=>z.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Image$2,{weight:"fill",size:24,className:"text-primary"})}),Me.video&&jsx("div",{onClick:()=>X.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(MonitorPlay,{weight:"fill",size:24,className:"text-primary"})})]}),te&&jsxs(La,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[He&&jsx("div",{title:"Flashcard",onClick:()=>Zs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(Cards,{weight:"fill",size:24,className:"text-primary"})}),Re.map((B,ne)=>jsx("div",{title:B.label,onClick:()=>Js(B.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(B.icon,{weight:"fill",size:24,className:"text-primary"})},ne))]})]}),jsx("input",{ref:z,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:re}),jsx("input",{ref:X,type:"file",accept:"video/*",className:"hidden",onChange:Mr}),!t&&P&&a&&jsx(Yo,{onClose:()=>A(false),stageRef:a,onRecordingComplete:Dr}),H&&jsx(Cc,{onClose:()=>F(false),onRecordingComplete:Dr}),h&&jsx(Mc,{editingFlashcard:c,onConfirm:Tr,onCancel:()=>i(Aa(false))}),(v.undo||v.redo||v.screenRecord||v.cameraRecord||v.clear)&&jsxs(La,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[v.undo&&jsx("button",{value:"undo",onClick:()=>i($n()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{size:24,weight:"bold"})}),v.redo&&jsx("button",{value:"redo",onClick:()=>i(Xn()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{size:24,weight:"bold"})}),v.screenRecord&&jsx("button",{value:"screen-record",onClick:Xs,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#2260DD]",title:"Screen Record",children:jsx(Record,{size:24,weight:"bold"})}),v.cameraRecord&&jsx("button",{value:"camera-record",onClick:Ys,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#804FF2]",title:"Camera Record",children:jsx(Camera,{size:24,weight:"fill"})}),v.clear&&jsx("button",{value:"clear",onClick:()=>Rr(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{size:24,weight:"bold"})})]})]})})},sy=ry;var cl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=ta(zo),n=(ta(h=>h.canvas.slides.find(x=>x.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),[i,u]=useState(false),[l,c]=useState(null),[d,m]=useState(null),f=async()=>{if(a.length===0){m({type:"error",message:"No slides to publish"});return}if(!e){m({type:"error",message:"No publish handler provided"});return}u(true),m(null);try{let h=await e(a,x=>{c(x);});h.success?m({type:"success",message:h.message}):m({type:"error",message:h.message});}catch(h){m({type:"error",message:h instanceof Error?h.message:"An unexpected error occurred"});}finally{u(false),setTimeout(()=>{c(null),m(null);},3e3);}};return n?null:jsxs("button",{onClick:f,disabled:i||a.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-3 px-4 py-3 font-medium text-white transition-colors",children:[jsx(Export,{size:24,color:"#fff"})," Publish"]})};var cy=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,showPublishButton:r=true,showBackButton:s=true,className:n="",rightContent:i,leftContent:u})=>jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-6 shadow-sm ${n}`,children:[u||jsxs("div",{className:"flex items-center gap-6 px-2",children:[s&&jsx("button",{onClick:t,className:"h-10 w-10 rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A]",children:jsx(CaretLeft,{size:24,color:"#64758B",weight:"bold"})}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"text-2xl font-medium text-[#000000CC]",children:e}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(CloudArrowUp,{weight:"fill",color:"#63748A",size:20}),jsx("span",{className:"text-base font-medium text-[#63748A]",children:o})]})]})]}),i||r&&a&&jsx(cl,{onPublish:a})]});function fl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Pc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Dc(e){let[o,t]=be.useState(void 0);return vo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let s=r[0],n,i;if("borderBoxSize"in s){let u=s.borderBoxSize,l=Array.isArray(u)?u[0]:u;n=l.inlineSize,i=l.blockSize;}else n=e.offsetWidth,i=e.offsetHeight;t({width:n,height:i});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var Fc=["PageUp","PageDown"],Ec=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Bc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},To="Slider",[ml,my,py]=Bs(To),[Oc]=ba(To,[py]),[hy,_s]=Oc(To),Nc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:s=1,orientation:n="horizontal",disabled:i=false,minStepsBetweenThumbs:u=0,defaultValue:l=[a],value:c,onValueChange:d=()=>{},onValueCommit:m=()=>{},inverted:f=false,form:h,...x}=e,p=be.useRef(new Set),v=be.useRef(0),b=n==="horizontal"?gy:xy,[y=[],S]=Xt({prop:c,defaultProp:l,onChange:H=>{[...p.current][v.current]?.focus(),d(H);}}),I=be.useRef(y);function C(H){let F=Ly(y,H);A(H,F);}function L(H){A(H,v.current);}function P(){let H=I.current[v.current];y[v.current]!==H&&m(y);}function A(H,F,{commit:E}={commit:false}){let D=ky(s),U=My(Math.round((H-a)/s)*s+a,D),N=fl(U,[a,r]);S((te=[])=>{let q=yy(te,N,F);if(Cy(q,u*s)){v.current=q.indexOf(N);let G=String(q)!==String(te);return G&&E&&m(q),G?q:te}else return te});}return jsx(hy,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:r,valueIndexToChangeRef:v,thumbs:p.current,values:y,orientation:n,form:h,children:jsx(ml.Provider,{scope:e.__scopeSlider,children:jsx(ml.Slot,{scope:e.__scopeSlider,children:jsx(b,{"aria-disabled":i,"data-disabled":i?"":void 0,...x,ref:o,onPointerDown:Xe(x.onPointerDown,()=>{i||(I.current=y);}),min:a,max:r,inverted:f,onSlideStart:i?void 0:C,onSlideMove:i?void 0:L,onSlideEnd:i?void 0:P,onHomeKeyDown:()=>!i&&A(a,0,{commit:true}),onEndKeyDown:()=>!i&&A(r,y.length-1,{commit:true}),onStepKeyDown:({event:H,direction:F})=>{if(!i){let U=Fc.includes(H.key)||H.shiftKey&&Ec.includes(H.key)?10:1,N=v.current,te=y[N],q=s*U*F;A(te+q,N,{commit:true});}}})})})})});Nc.displayName=To;var[Vc,qc]=Oc(To,{startEdge:"left",endEdge:"right",size:"width",direction:1}),gy=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:s,onSlideStart:n,onSlideMove:i,onSlideEnd:u,onStepKeyDown:l,...c}=e,[d,m]=be.useState(null),f=At(o,b=>m(b)),h=be.useRef(void 0),x=wo(r),p=x==="ltr",v=p&&!s||!p&&s;function g(b){let y=h.current||d.getBoundingClientRect(),S=[0,y.width],C=gl(S,v?[t,a]:[a,t]);return h.current=y,C(b-y.left)}return jsx(Vc,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:jsx(Hc,{dir:x,"data-orientation":"horizontal",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{let y=g(b.clientX);n?.(y);},onSlideMove:b=>{let y=g(b.clientX);i?.(y);},onSlideEnd:()=>{h.current=void 0,u?.();},onStepKeyDown:b=>{let S=Bc[v?"from-left":"from-right"].includes(b.key);l?.({event:b,direction:S?-1:1});}})})}),xy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:s,onSlideMove:n,onSlideEnd:i,onStepKeyDown:u,...l}=e,c=be.useRef(null),d=At(o,c),m=be.useRef(void 0),f=!r;function h(x){let p=m.current||c.current.getBoundingClientRect(),v=[0,p.height],b=gl(v,f?[a,t]:[t,a]);return m.current=p,b(x-p.top)}return jsx(Vc,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:jsx(Hc,{"data-orientation":"vertical",...l,ref:d,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{let p=h(x.clientY);s?.(p);},onSlideMove:x=>{let p=h(x.clientY);n?.(p);},onSlideEnd:()=>{m.current=void 0,i?.();},onStepKeyDown:x=>{let v=Bc[f?"from-bottom":"from-top"].includes(x.key);u?.({event:x,direction:v?-1:1});}})})}),Hc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:s,onHomeKeyDown:n,onEndKeyDown:i,onStepKeyDown:u,...l}=e,c=_s(To,t);return jsx(it.span,{...l,ref:o,onKeyDown:Xe(e.onKeyDown,d=>{d.key==="Home"?(n(d),d.preventDefault()):d.key==="End"?(i(d),d.preventDefault()):Fc.concat(Ec).includes(d.key)&&(u(d),d.preventDefault());}),onPointerDown:Xe(e.onPointerDown,d=>{let m=d.target;m.setPointerCapture(d.pointerId),d.preventDefault(),c.thumbs.has(m)?m.focus():a(d);}),onPointerMove:Xe(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:Xe(e.onPointerUp,d=>{let m=d.target;m.hasPointerCapture(d.pointerId)&&(m.releasePointerCapture(d.pointerId),s(d));})})}),Uc="SliderTrack",zc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=_s(Uc,t);return jsx(it.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});zc.displayName=Uc;var pl="SliderRange",Wc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=_s(pl,t),s=qc(pl,t),n=be.useRef(null),i=At(o,n),u=r.values.length,l=r.values.map(m=>_c(m,r.min,r.max)),c=u>1?Math.min(...l):0,d=100-Math.max(...l);return jsx(it.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:i,style:{...e.style,[s.startEdge]:c+"%",[s.endEdge]:d+"%"}})});Wc.displayName=pl;var hl="SliderThumb",Gc=be.forwardRef((e,o)=>{let t=my(e.__scopeSlider),[a,r]=be.useState(null),s=At(o,i=>r(i)),n=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx(by,{...e,ref:s,index:n})}),by=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...s}=e,n=_s(hl,t),i=qc(hl,t),[u,l]=be.useState(null),c=At(o,g=>l(g)),d=u?n.form||!!u.closest("form"):true,m=Dc(u),f=n.values[a],h=f===void 0?0:_c(f,n.min,n.max),x=wy(a,n.values.length),p=m?.[i.size],v=p?Sy(p,h,i.direction):0;return be.useEffect(()=>{if(u)return n.thumbs.add(u),()=>{n.thumbs.delete(u);}},[u,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${h}% + ${v}px)`},children:[jsx(ml.ItemSlot,{scope:e.__scopeSlider,children:jsx(it.span,{role:"slider","aria-label":e["aria-label"]||x,"aria-valuemin":n.min,"aria-valuenow":f,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...s,ref:c,style:f===void 0?{display:"none"}:e.style,onFocus:Xe(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),d&&jsx(Kc,{name:r??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:f},a)]})});Gc.displayName=hl;var vy="RadioBubbleInput",Kc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),s=At(r,a),n=Pc(o);return be.useEffect(()=>{let i=r.current;if(!i)return;let u=window.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(u,"value").set;if(n!==o&&c){let d=new Event("input",{bubbles:true});c.call(i,o),i.dispatchEvent(d);}},[n,o]),jsx(it.input,{style:{display:"none"},...t,ref:s,defaultValue:o})});Kc.displayName=vy;function yy(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,s)=>r-s)}function _c(e,o,t){let s=100/(t-o)*(e-o);return fl(s,[0,100])}function wy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Ly(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function Sy(e,o,t){let a=e/2,s=gl([0,50],[0,a]);return (a-s(o)*t)*t}function Iy(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Cy(e,o){if(o>0){let t=Iy(e);return Math.min(...t)>=o}return true}function gl(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function ky(e){return (String(e).split(".")[1]||"").length}function My(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var jc=Nc,$c=zc,Xc=Wc,Yc=Gc;function Zc({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:s,trackClassName:n,thumbClassName:i,...u}){let l=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(jc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:wa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...u,children:[jsx($c,{"data-slot":"slider-track",className:wa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(Xc,{"data-slot":"slider-range",className:wa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",s)})}),Array.from({length:l.length},(c,d)=>jsx(Yc,{"data-slot":"slider-thumb",className:wa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",i)},d))]})}var Py=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Ry=({colors:e=Py,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let s=ee(i=>i.toolbar.penColor),n=xe();return jsxs("div",{className:`fixed bottom-6 left-1/2 z-50 flex h-fit w-full max-w-3xl -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-6 shadow-2xl xl:max-w-4xl ${r}`,style:{marginLeft:"-160px"},children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex w-full flex-col px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex w-full items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(Zc,{defaultValue:[12],max:28,min:6,step:1,className:"w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:i=>n(rl(i[0]))}),jsx("div",{className:"h-8 w-8 rounded-full bg-black"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(La,{type:"single",className:"flex w-full px-6",children:[e.map(i=>jsx("button",{value:i.value,className:`h-12 w-12 rounded-full border hover:cursor-pointer ${s===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>n(zs(i.value))},i.value)),jsxs("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>n(zs(i.target.value))}),"+"]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center",children:jsx("label",{className:"relative flex h-12 w-12 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033]",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>n(cn(i.target.value))})})})]})};function Dy({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var ef=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ey=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),bl=e=>{let o=Ey(e);return o.charAt(0).toUpperCase()+o.slice(1)},js=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),tf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var af={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var rf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:s,iconNode:n,...i},u)=>createElement("svg",{ref:u,...af,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:js("lucide",r),...!s&&!tf(i)&&{"aria-hidden":"true"},...i},[...n.map(([l,c])=>createElement(l,c)),...Array.isArray(s)?s:[s]]));var $s=(e,o)=>{let t=forwardRef(({className:a,...r},s)=>createElement(rf,{ref:s,iconNode:o,className:js(`lucide-${ef(bl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=bl(e),t};var Vy=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Cr=$s("copy",Vy);var qy=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],kr=$s("trash-2",qy);var nf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:s,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"shadow-lg":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:r,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:i=>{i.stopPropagation(),s();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Cr,{size:14})}),!a&&jsx("button",{onClick:i=>{i.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(kr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Slide ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var Wy=()=>{let e=yt(),o=ta(zo),t=ta(Uo),a=ta(Yn),[r,s]=useState(true),u=(ta(f=>f.canvas.slides.find(h=>h.id===f.canvas.currentSlideId))?.videos||[]).some(f=>f.isRecorded&&f.isPlaying),l=()=>{a&&e(sn());},c=f=>{e(dn(f));},d=f=>{e(ln(f));},m=f=>{o.length>1&&e(nn(f));};return u?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-100 flex items-start",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>s(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Slides"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[o.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:o.map((f,h)=>jsx(nf,{slide:f,index:h,isSelected:f.id===t,isSingleSlide:o.length===1,onSelect:()=>c(f.id),onDuplicate:()=>d(f.id),onDelete:()=>m(f.id)},f.id))}),jsxs("button",{onClick:l,disabled:!a,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${a?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Slide"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>s(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var Gy="SchooplaEditorDB",Ky=1,Ao="slides",uf="schoopla_current_slide_id",cf=()=>new Promise((e,o)=>{let t=indexedDB.open(Gy,Ky);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Ao)||r.createObjectStore(Ao,{keyPath:"id"});};}),vl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await cf(),a=o.transaction([Ao],"readwrite").objectStore(Ao);await new Promise((r,s)=>{let n=a.clear();n.onsuccess=()=>r(!0),n.onerror=()=>s(n.error);});for(let r of e)await new Promise((s,n)=>{let i=a.add(r);i.onsuccess=()=>s(!0),i.onerror=()=>n(i.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},ff=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await cf(),t=e.transaction([Ao],"readonly").objectStore(Ao);return new Promise((a,r)=>{let s=t.getAll();s.onsuccess=()=>{e.close();let n=s.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(i=>({id:i.id,width:i.width,height:i.height,x:i.x,y:i.y}))),a(n.length>0?n:null);},s.onerror=()=>{e.close(),r(s.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var yl=e=>{try{localStorage.setItem(uf,e);}catch(o){console.error("Error saving current slide ID:",o);}},mf=()=>{try{return localStorage.getItem(uf)}catch(e){return console.error("Error loading current slide ID:",e),null}},pf=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}};var _y=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/setCurrentSlide","canvas/updateSlideThumbnail","canvas/reorderSlides"],jy=["canvas/clearCanvas"],$y=pf((e,o)=>{vl(e),yl(o);},500),Xy=(e,o)=>{vl(e),yl(o);},wl=false,hf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Ki(r).catch(s=>{console.error("Error deleting video blob:",s);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,n=e.getState().canvas.slides.find(i=>i.id===r);n&&n.videos&&n.videos.length>0&&n.videos.forEach(i=>{Ki(i.id).catch(u=>{console.error("Error deleting video blob:",u);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,s=e.getState(),i=s.canvas.slides.find(u=>u.id===s.canvas.currentSlideId)?.videos.find(u=>u.id===r);i&&i.videoBlob&&setTimeout(()=>{let u=e.getState(),c=u.canvas.slides.find(d=>d.id===u.canvas.currentSlideId)?.videos.find(d=>d.id!==r&&d.x===i.x+20&&d.y===i.y+20);c&&i.videoBlob&&br(c.id,i.videoBlob,c.thumbnailDataUrl).catch(d=>{console.error("Error saving duplicated video blob:",d);});},0);}let a=o(t);if(t.type&&jy.includes(t.type)){if(!wl){wl=true;try{let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;Xy(s,n);}finally{setTimeout(()=>{wl=false;},0);}}}else if(t.type&&_y.includes(t.type)){let r=e.getState(),{slides:s,currentSlideId:n}=r.canvas;$y(s,n);}return a});new QueryClient;var Zy=configureStore({reducer:{toolbar:Ic,canvas:Ol},middleware:e=>e({serializableCheck:false}).concat(hf)});var Qy=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:s=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:n,quality:a,pixelRatio:r}),u=document.createElement("a");u.download=`${s}.${t}`,u.href=i,document.body.appendChild(u),u.click(),document.body.removeChild(u);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},ew=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((s,n)=>{try{let i=t==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:i,quality:a,pixelRatio:r});fetch(u).then(l=>l.blob()).then(l=>s(l)).catch(l=>n(l));}catch(i){n(i);}})},tw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,s=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:s,quality:a,pixelRatio:r})};var aw=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let s=a*a+r*r,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/s)),i=o.x+n*a,u=o.y+n*r;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-u,2))},Ll=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],s=e[e.length-1];for(let n=1;n<e.length-1;n++){let i=aw(e[n],r,s);i>t&&(t=i,a=n);}if(t>o){let n=Ll(e.slice(0,a+1),o),i=Ll(e.slice(a),o);return [...n.slice(0,-1),...i]}return [r,s]},ow=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},rw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},gf=(e,o=1.5)=>{if(e.length<=4)return e;let t=ow(e),a=Ll(t,o);return rw(a)},xf=(e,o=1.5)=>({...e,points:gf(e.points,o)}),sw=(e,o=1.5)=>e.map(t=>xf(t,o)),nw=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var iw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var bf=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((s,n)=>{let i=new Image;i.onload=()=>{let{width:u,height:l}=i;if(u>t||l>a){let h=u/l;u>l?(u=Math.min(u,t),l=u/h):(l=Math.min(l,a),u=l*h);}let c=document.createElement("canvas");c.width=u,c.height=l;let d=c.getContext("2d");if(!d){n(new Error("Failed to get canvas context"));return}d.drawImage(i,0,0,u,l);let m=iw(e),f=c.toDataURL(m,r);s(f);},i.onerror=n,i.src=e;})};var Ka=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},Po=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Ro=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",lw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:s=.85}=o,n=[],i=0;for(let u of e){let l=[],c=[],d=[];for(let m of u.images){let f=m.src;if(t&&f.startsWith("data:"))try{f=await bf(f,{maxWidth:a,maxHeight:r,quality:s});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(f.startsWith("data:")){let h=Ka(f),x=Po(f);i+=h.byteLength;let p={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,buffer:h,mimeType:x};if(m.audioData&&m.audioData.startsWith("data:")){let v=Ka(m.audioData),g=Po(m.audioData);i+=v.byteLength,p.audioBuffer=v,p.audioMimeType=g;}l.push(p);}}for(let m of u.videos){let f,h;if(m.videoBlob)f=await m.videoBlob.arrayBuffer(),h=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))f=Ka(m.videoData),h=Po(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}i+=f.byteLength;let x={id:m.id,thumbnailDataUrl:m.thumbnailDataUrl,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,isPlaying:m.isPlaying,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isRecorded:m.isRecorded,buffer:f,mimeType:h};if(m.audioData&&m.audioData.startsWith("data:")){let p=Ka(m.audioData),v=Po(m.audioData);i+=p.byteLength,x.audioBuffer=p,x.audioMimeType=v;}c.push(x);}for(let m of u.photoFrames){let f={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:m.draggable,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isCapturing:m.isCapturing};if(m.capturedImageUrl&&m.capturedImageUrl.startsWith("data:")){let h=Ka(m.capturedImageUrl),x=Po(m.capturedImageUrl);i+=h.byteLength,f.buffer=h,f.mimeType=x;}if(m.audioData&&m.audioData.startsWith("data:")){let h=Ka(m.audioData),x=Po(m.audioData);i+=h.byteLength,f.audioBuffer=h,f.audioMimeType=x;}d.push(f);}n.push({...u,images:l,videos:c,photoFrames:d});}return {slides:n,totalSize:i}},dw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},uw=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,mimeType:s.mimeType,fileKey:`slide_${r}_image_${n}`,audioFileKey:s.audioBuffer?`slide_${r}_image_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),videos:a.videos.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,draggable:s.draggable,isPlaying:s.isPlaying,rotation:s.rotation,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isRecorded:s.isRecorded,mimeType:s.mimeType,fileKey:`slide_${r}_video_${n}`,thumbnailFileKey:`slide_${r}_video_${n}_thumbnail`,audioFileKey:s.audioBuffer?`slide_${r}_video_${n}_audio`:void 0,audioMimeType:s.audioMimeType})),photoFrames:a.photoFrames.map((s,n)=>({id:s.id,x:s.x,y:s.y,width:s.width,height:s.height,rotation:s.rotation,draggable:s.draggable,locked:s.locked,link:s.link,altText:s.altText,zIndex:s.zIndex,isCapturing:s.isCapturing,mimeType:s.mimeType,fileKey:s.buffer?`slide_${r}_photoframe_${n}`:void 0,audioFileKey:s.audioBuffer?`slide_${r}_photoframe_${n}_audio`:void 0,audioMimeType:s.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;if(o.append(`slide_${r}_image_${n}`,i,u),s.audioBuffer&&s.audioMimeType){let l=new Blob([s.audioBuffer],{type:s.audioMimeType}),c=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_image_${n}_audio`,l,c);}}),a.videos.forEach((s,n)=>{let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;if(o.append(`slide_${r}_video_${n}`,i,u),s.thumbnailDataUrl&&s.thumbnailDataUrl.startsWith("data:")){let l=Ka(s.thumbnailDataUrl),c=new Blob([l],{type:"image/jpeg"}),d=`${s.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${n}_thumbnail`,c,d);}if(s.audioBuffer&&s.audioMimeType){let l=new Blob([s.audioBuffer],{type:s.audioMimeType}),c=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_video_${n}_audio`,l,c);}}),a.photoFrames.forEach((s,n)=>{if(s.buffer&&s.mimeType){let i=new Blob([s.buffer],{type:s.mimeType}),u=`${s.id}.${Ro(s.mimeType)}`;o.append(`slide_${r}_photoframe_${n}`,i,u);}if(s.audioBuffer&&s.audioMimeType){let i=new Blob([s.audioBuffer],{type:s.audioMimeType}),u=`${s.id}_audio.${Ro(s.audioMimeType)}`;o.append(`slide_${r}_photoframe_${n}_audio`,i,u);}});}),o};var fw=()=>{let e=yt();useEffect(()=>{(async()=>{try{let t=await ff(),a=mf();if(t&&t.length>0){let r=await Tu(),s=t.map(i=>{if(i.videos&&i.videos.length>0){let u=i.videos.map(l=>{let c=r.get(l.id);if(c){let d=Au(c.blob);return {...l,objectUrl:d,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return l});return {...i,videos:u}}return i}),n=a&&s.find(i=>i.id===a)?a:s[0].id;e(ja({slides:s,currentSlideId:n}));}}catch(t){console.error("Error loading persisted slides:",t);}})();},[e]);};var yf=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),wf=new WeakSet,mw=()=>{let e=yt(),o=useCallback(a=>{if(!a.slides||a.slides.length===0||wf.has(a))return;wf.add(a);let{slides:r,currentSlideId:s}=a,n=s&&r.find(u=>u.id===s)?s:r[0].id,i=yf(r);e(ja({slides:i,currentSlideId:n}));},[e]),t=useCallback(a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:s}=a,n=s&&r.find(u=>u.id===s)?s:r[0].id,i=yf(r);e(ja({slides:i,currentSlideId:n}));},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
7
7
 
8
8
  lucide-react/dist/esm/shared/src/utils.js:
9
9
  lucide-react/dist/esm/defaultAttributes.js:
@@ -18,5 +18,5 @@ lucide-react/dist/esm/lucide-react.js:
18
18
  * This source code is licensed under the ISC license.
19
19
  * See the LICENSE file in the root directory of this source tree.
20
20
  *)
21
- */export{Av as BASIC_EDITOR_TOOLBAR_CONFIG,Ay as BottomToolbar,Bx as Canvas,Mv as DEFAULT_CONTEXT_MENU_CONFIG,Wn as DEFAULT_TOOLBAR_CONFIG,Py as EditorRoot,cl as PublishButton,Xo as ScreenRecorder,Hy as SlideNavigation,oy as Toolbar,dy as TopNavBar,Tv as VIEWER_TOOLBAR_CONFIG,Vs as addFillInTheBlanks,ys as addFlashcard,ms as addImage,Ms as addImageAnnotation,fs as addLine,Os as addLongAnswer,Ps as addMultipleChoice,Is as addPhotoFrame,As as addPhotoFrameAnnotation,gs as addShape,Es as addShortAnswer,ns as addSlide,bs as addText,Ds as addTrueFalse,Hr as addVideo,iw as arrayBufferToBase64,Hs as bringToFront,js as clearCanvas,am as clearImageAnnotations,rm as clearPhotoFrameAnnotations,qs as deleteFillInTheBlanks,ws as deleteFlashcard,ps as deleteImage,Ks as deleteLineById,Ns as deleteLongAnswer,Rs as deleteMultipleChoice,Cs as deletePhotoFrame,xs as deleteShape,Bs as deleteShortAnswer,ss as deleteSlide,vs as deleteText,Fs as deleteTrueFalse,hs as deleteVideo,Zr as duplicateFillInTheBlanks,_r as duplicateFlashcard,Ur as duplicateImage,_s as duplicateLine,Jr as duplicateLongAnswer,$r as duplicateMultipleChoice,jr as duplicatePhotoFrame,Gr as duplicateShape,Yr as duplicateShortAnswer,is as duplicateSlide,Kr as duplicateText,Xr as duplicateTrueFalse,Wr as duplicateVideo,Fo as editFlashcard,nm as editMultipleChoice,Zy as exportSlideAsBlob,Jy as exportSlideAsImage,Gs as finalizeDrawing,dw as generateAllFullSizeThumbnails,vf as generateFullSizeThumbnail,rw as getCompressionStats,Qy as getSlideDataURL,cs as loadSlides,il as mergeToolbarConfig,Ls as nextFlashcard,lw as prepareFormData,sw as prepareSlidesForPublishing,Ss as previousFlashcard,Xs as redo,qr as removeLine,em as reorderSlides,ue as saveToHistory,Ho as selectAllSlides,Ys as selectCanAddSlide,ge as selectCurrentSlide,Uo as selectCurrentSlideId,um as selectSlideById,zs as sendToBack,Us as setActivityType,en as setAltText,tn as setAudioData,us as setBackgroundColor,ls as setCurrentSlide,No as setEditingActivity,qo as setEditingTextId,im as setLines,Qr as setLink,zn as setPenColor,Ra as setShowFlashcardForm,na as setShowMcqForm,dt as setSketchMode,rl as setStrokeWidth,Bt as setTool,gf as simplifyFlatPoints,xf as simplifyLine,ow as simplifyLines,Yy as store,ks as toggleImageDrawingMode,Ws as toggleLock,Ts as togglePhotoFrameDrawingMode,dm as toggleSketchMode,Do as toggleVideoPlaying,$s as undo,Vo as updateElementOrder,Oo as updateFillInTheBlanks,Ja as updateFlashcard,Xa as updateImage,tm as updateImageAnnotation,sm as updateLastLine,lm as updateLinePosition,an as updateLineTransform,Bo as updateLongAnswer,oa as updateMultipleChoice,Pa as updatePhotoFrame,om as updatePhotoFrameAnnotation,Ya as updateShape,Eo as updateShortAnswer,ds as updateSlideThumbnail,yt as updateText,ra as updateTrueFalse,zr as updateVideo,xe as useDispatch,ee as useSelector,cw as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
+ */export{Rv as BASIC_EDITOR_TOOLBAR_CONFIG,Ry as BottomToolbar,Nx as Canvas,Av as DEFAULT_CONTEXT_MENU_CONFIG,Ws as DEFAULT_TOOLBAR_CONFIG,Dy as EditorRoot,cl as PublishButton,Yo as ScreenRecorder,Wy as SlideNavigation,sy as Toolbar,cy as TopNavBar,Pv as VIEWER_TOOLBAR_CONFIG,Vn as addFillInTheBlanks,yn as addFlashcard,mn as addImage,Mn as addImageAnnotation,fn as addLine,On as addLongAnswer,Pn as addMultipleChoice,In as addPhotoFrame,An as addPhotoFrameAnnotation,gn as addShape,En as addShortAnswer,sn as addSlide,bn as addText,Dn as addTrueFalse,zr as addVideo,dw as arrayBufferToBase64,Un as bringToFront,jn as clearCanvas,rm as clearImageAnnotations,nm as clearPhotoFrameAnnotations,qn as deleteFillInTheBlanks,wn as deleteFlashcard,pn as deleteImage,Kn as deleteLineById,Nn as deleteLongAnswer,Rn as deleteMultipleChoice,Cn as deletePhotoFrame,xn as deleteShape,Bn as deleteShortAnswer,nn as deleteSlide,vn as deleteText,Fn as deleteTrueFalse,hn as deleteVideo,Qr as duplicateFillInTheBlanks,jr as duplicateFlashcard,Ur as duplicateImage,_n as duplicateLine,Zr as duplicateLongAnswer,Xr as duplicateMultipleChoice,$r as duplicatePhotoFrame,Kr as duplicateShape,Jr as duplicateShortAnswer,ln as duplicateSlide,_r as duplicateText,Yr as duplicateTrueFalse,Gr as duplicateVideo,Eo as editFlashcard,im as editMultipleChoice,ew as exportSlideAsBlob,Qy as exportSlideAsImage,Gn as finalizeDrawing,nw as getCompressionStats,tw as getSlideDataURL,ja as loadSlides,il as mergeToolbarConfig,Ln as nextFlashcard,uw as prepareFormData,lw as prepareSlidesForPublishing,Sn as previousFlashcard,Xn as redo,Hr as removeLine,am as reorderSlides,ue as saveToHistory,zo as selectAllSlides,Yn as selectCanAddSlide,ge as selectCurrentSlide,Uo as selectCurrentSlideId,fm as selectSlideById,zn as sendToBack,Hn as setActivityType,ts as setAltText,as as setAudioData,cn as setBackgroundColor,dn as setCurrentSlide,Vo as setEditingActivity,Ho as setEditingTextId,dm as setLines,es as setLink,zs as setPenColor,Aa as setShowFlashcardForm,ra as setShowMcqForm,dt as setSketchMode,rl as setStrokeWidth,Ot as setTool,gf as simplifyFlatPoints,xf as simplifyLine,sw as simplifyLines,Zy as store,kn as toggleImageDrawingMode,Wn as toggleLock,Tn as togglePhotoFrameDrawingMode,cm as toggleSketchMode,Fo as toggleVideoPlaying,$n as undo,qo as updateElementOrder,No as updateFillInTheBlanks,Ya as updateFlashcard,$a as updateImage,om as updateImageAnnotation,lm as updateLastLine,um as updateLinePosition,os as updateLineTransform,Oo as updateLongAnswer,aa as updateMultipleChoice,Ta as updatePhotoFrame,sm as updatePhotoFrameAnnotation,Xa as updateShape,Bo as updateShortAnswer,un as updateSlideThumbnail,wt as updateText,oa as updateTrueFalse,Wr as updateVideo,xe as useDispatch,mw as useInitialSlides,ee as useSelector,fw as useSlidesPersistence};//# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map