@turnix-co/konva-editor 3.0.7 → 3.0.9

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,useMemo,createElement,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 ld from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X as X$1,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,CaretLeft,Plus,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {EyeIcon,Stack as Stack$1,X as X$2,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 lu 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 Ql=e=>{throw TypeError(e)};var ed=(e,o,t)=>o.has(e)||Ql("Cannot "+t);var _=(e,o,t)=>(ed(e,o,"read from private field"),t?t.call(e):o.get(e)),Te=(e,o,t)=>o.has(e)?Ql("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),ke=(e,o,t,a)=>(ed(e,o,"write to private field"),o.set(e,t),t);var td=(e,o,t,a)=>({set _(r){ke(e,o,r);},get _(){return _(e,o,a)}});var xe=()=>useDispatch(),te=e=>useSelector(e),et=xe,It=te;var Cs=20,ks=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()}),Ss=ks("Slide 1"),Mm={slides:[Ss],currentSlideId:Ss.id,history:{[Ss.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false},ad=createSlice({name:"canvas",initialState:Mm,reducers:{addSlide:e=>{if(e.slides.length>=Cs)return;let o=ks(`Page ${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>=Cs)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(b=>b.id===a);s&&(s.timestamp=n);break;case "video":let i=t.videos.find(b=>b.id===a);i&&(i.timestamp=n);break;case "shape":let l=t.shapes.find(b=>b.id===a);l&&(l.timestamp=n);break;case "text":let d=t.texts.find(b=>b.id===a);d&&(d.timestamp=n);break;case "flashcard":let m=t.flashcards.find(b=>b.id===a);m&&(m.timestamp=n);break;case "photoFrame":let u=t.photoFrames.find(b=>b.id===a);u&&(u.timestamp=n);break;case "mcq":let f=t.multipleChoices.find(b=>b.id===a);f&&(f.timestamp=n);break;case "trueFalse":let c=t.trueFalses.find(b=>b.id===a);c&&(c.timestamp=n);break;case "shortAnswer":let p=t.shortAnswers.find(b=>b.id===a);p&&(p.timestamp=n);break;case "longAnswer":let g=t.LongAnswer.find(b=>b.id===a);g&&(g.timestamp=n);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(b=>b.id===a);h&&(h.timestamp=n);break;case "line":let w=t.lines.find(b=>b.id===a);w&&(w.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(l=>l.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(l=>l.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(l=>l.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.backgroundColor="#fff",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;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;}}}),{addSlide:Ms,deleteSlide:Ts,duplicateSlide:As,setCurrentSlide:Ps,updateSlideThumbnail:Ds,setBackgroundColor:Rs,reorderSlides:Tm,loadSlides:to,addLine:Es,removeLine:Gr,addImage:Fs,updateImage:ao,deleteImage:Kr,duplicateImage:_r,addVideo:jr,updateVideo:$r,deleteVideo:Xr,duplicateVideo:Yr,toggleVideoPlaying:Uo,addShape:Bs,updateShape:oo,duplicateShape:Jr,deleteShape:Zr,addText:Os,updateText:St,deleteText:Qr,duplicateText:en,addFlashcard:Ns,updateFlashcard:ro,deleteFlashcard:tn,duplicateFlashcard:an,editFlashcard:Wo,nextFlashcard:Vs,previousFlashcard:qs,addPhotoFrame:Hs,updatePhotoFrame:Aa,deletePhotoFrame:on,duplicatePhotoFrame:rn,toggleImageDrawingMode:Us,addImageAnnotation:Ws,updateImageAnnotation:Am,clearImageAnnotations:Pm,togglePhotoFrameDrawingMode:zs,addPhotoFrameAnnotation:Gs,updatePhotoFrameAnnotation:Dm,clearPhotoFrameAnnotations:Rm,addMultipleChoice:Ks,updateMultipleChoice:ia,editMultipleChoice:Em,deleteMultipleChoice:nn,duplicateMultipleChoice:sn,addTrueFalse:_s,updateTrueFalse:la,deleteTrueFalse:ln,duplicateTrueFalse:dn,addShortAnswer:js,updateShortAnswer:zo,deleteShortAnswer:un,duplicateShortAnswer:cn,addLongAnswer:$s,updateLongAnswer:Go,deleteLongAnswer:fn,duplicateLongAnswer:mn,addFillInTheBlanks:Xs,updateFillInTheBlanks:Ko,deleteFillInTheBlanks:pn,duplicateFillInTheBlanks:hn,setShowMcqForm:da,setShowFlashcardForm:Pa,setActivityType:Ys,setEditingActivity:_o,bringToFront:Js,sendToBack:Zs,toggleLock:Qs,setLink:gn,setAltText:xn,setAudioData:bn,updateLastLine:Fm,finalizeDrawing:ei,setLines:Bm,updateLinePosition:Om,updateLineTransform:vn,deleteLineById:yn,duplicateLine:ti,updateElementOrder:jo,clearCanvas:ai,undo:oi,redo:ri,saveToHistory:de,toggleSketchMode:Nm,setSketchMode:ut,setEditingTextId:$o,setPresentationTitle:ni,setPresentationDescription:si,loadPresentationMetadata:ii,setMetadataLoaded:wn}=ad.actions;var Xo=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},Yo=e=>e.canvas.slides,li=e=>e.canvas.slides.length<Cs,Vm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},Jo=e=>e.canvas.presentationMetadata,di=e=>e.canvas.metadataLoaded,od=ad.reducer;var nd=e=>{let o=xe(),t=useRef(null),a=useRef(false),r=te(c=>c.toolbar.selectedTool),n=te(c=>c.toolbar.penColor),s=te(c=>c.toolbar.strokeWidth),i=te(c=>c.canvas.isSketchMode),l=te(c=>c.canvas.slides.find(g=>g.id===c.canvas.currentSlideId)?.lines||[]),d=useCallback(c=>{t.current=c;},[]),m=useCallback(c=>{r==="pen"&&t.current&&(o(de()),t.current.startDrawing(c),a.current=true);},[r,o]),u=useCallback(c=>{!t.current||!a.current||t.current.draw(c);},[]),f=useCallback(()=>{if(!t.current||!a.current)return;let c=t.current.stopDrawing();a.current=false,c&&c.points.length>=4&&o(Es(c)),o(ei()),e?.();},[o,e]);return {lines:l,tool:r,color:n,strokeWidth:s,isSketchMode:i,setCanvasRef:d,startDrawing:m,draw:u,stopDrawing:f}};var dd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:n,style:s,xOffset:i=0,yOffset:l=0},d)=>{let m=useRef(null),u=useRef(false),f=useRef([]),c=useRef([]),p=useRef(null),g=useRef(t),h=useRef(a),w=useRef(r),b=useRef(n),v=useRef(i),L=useRef(l);useEffect(()=>{g.current=t,h.current=a,w.current=r,b.current=n,v.current=i,L.current=l;},[t,a,r,n,i,l]);let k=useCallback(()=>{let I=m.current;if(!I)return;let x=I.getContext("2d");x&&x.clearRect(0,0,I.width,I.height);},[]),S=useCallback(()=>{let I=m.current,x=c.current;if(!I||x.length<1)return;let A=I.getContext("2d");if(!A)return;if(A.clearRect(0,0,I.width,I.height),g.current==="eraser"?(A.globalCompositeOperation="destination-out",A.fillStyle="rgba(0,0,0,1)"):(A.globalCompositeOperation="source-over",A.fillStyle=h.current),x.length===1){A.beginPath(),A.arc(x[0].x,x[0].y,w.current/2,0,Math.PI*2),A.fill();return}let D=ld(x,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:q=>q,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(D.length<2)){A.beginPath(),A.moveTo(D[0][0],D[0][1]);for(let q=1;q<D.length;q++)A.lineTo(D[q][0],D[q][1]);A.closePath(),A.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:I=>{u.current=true;let x={x:I.x-v.current,y:I.y-L.current};f.current=[{x:I.x,y:I.y}],c.current=[x],p.current=I,S();},draw:I=>{if(!u.current||!p.current)return;let x=I.x-p.current.x,A=I.y-p.current.y;if(Math.sqrt(x*x+A*A)<2)return;let D={x:I.x-v.current,y:I.y-L.current};f.current.push({x:I.x,y:I.y}),c.current.push(D),p.current=I,S();},stopDrawing:()=>{if(!u.current)return null;if(u.current=false,f.current.length<2)return f.current=[],c.current=[],p.current=null,k(),null;let x=ld(f.current,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:V=>V,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(V=>[V[0],V[1]]),A={tool:g.current,points:x,color:h.current,strokeWidth:w.current,isSketch:true};return f.current=[],c.current=[],p.current=null,k(),A},clear:()=>{k(),f.current=[],c.current=[],p.current=null,u.current=false;},isDrawing:()=>u.current,getCanvasElement:()=>m.current}),[k,S]),useEffect(()=>{let I=m.current;I&&(I.width=e,I.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});dd.displayName="DirectDrawingCanvas";var ud=dd;var fd=e=>{let o=xe(),a=te(ge)?.images||[],r=useRef(new Map),n=useRef(new Map),s=useRef(new Set);useEffect(()=>{let m=new Set(a.map(u=>u.id));s.current.forEach(u=>{if(!m.has(u)){let f=n.current.get(u);f&&(f.src="",n.current.delete(u)),r.current.delete(u);}}),s.current=m;},[a]),useEffect(()=>()=>{n.current.forEach(m=>{m.src="";}),n.current.clear(),r.current.clear();},[]);let i=useCallback(m=>{if(n.current.has(m.id))return n.current.get(m.id);let u=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(u.crossOrigin="anonymous"),u.src=m.src,n.current.set(m.id,u),u},[]),l=useCallback((m,u)=>{let f=m.target,c=f.id();a.find(g=>g.id===c)&&(o(ao({id:c,x:f.x(),y:f.y(),width:f.width(),height:f.height(),rotation:f.rotation()})),u?.());},[a,o]),d=useCallback((m,u)=>{let f=u.target,c=r.current.get(m);if(!c){console.error("\u274C Image node not found for id:",m);return}let p=f.scaleX(),g=f.scaleY(),h=f.rotation(),w=c.width(),b=c.height(),v=Math.max(5,w*p),L=Math.max(5,b*g);f.scaleX(1),f.scaleY(1),c.width(v),c.height(L),o(ao({id:m,width:v,height:L,x:f.x(),y:f.y(),rotation:h})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:i,imageRefs:r,handleDragEnd:l,handleImageTransformEnd:d}};var md=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),n=useCallback((i,l)=>{let d=l.target,m=d.scaleX(),u=d.scaleY(),f=d.rotation(),c=Math.max(5,d.width()*m),p=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(c),d.height(p),o(ia({id:i,width:c,height:p,x:d.x(),y:d.y(),rotation:f})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:n,mcqRefs:a,handleDragEnd:(i,l)=>{o(ia({id:l,x:i.target.x(),y:i.target.y()})),e?.();}}};var pd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),n=useCallback((i,l)=>{let d=l.target,m=d.scaleX(),u=d.scaleY(),f=d.rotation(),c=Math.max(5,d.width()*m),p=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(c),d.height(p),o(la({id:i,width:c,height:p,x:d.x(),y:d.y(),rotation:f})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:n,handleTrueFalseDragEnd:(i,l)=>{o(la({id:l,x:i.target.x(),y:i.target.y()})),e?.();},trueFalseRefs:a}};var hd=e=>{let o=xe(),a=te(ge)?.videos||[],r=useRef(new Map),n=useCallback(l=>{o(Uo(l));},[o]),s=useCallback((l,d)=>{let m=d.target;o($r({id:l,x:m.x(),y:m.y()})),e?.();},[o,e]),i=useCallback((l,d)=>{let m=d.target,u=m.scaleX(),f=m.scaleY(),c=m.rotation(),p=Math.max(5,m.width()*u),g=Math.max(5,m.height()*f);m.scaleX(1),m.scaleY(1),m.width(p),m.height(g),o($r({id:l,width:p,height:g,x:m.x(),y:m.y(),rotation:c})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:n,handleVideoDragEnd:s,handleVideoTransformEnd:i}};var bd=e=>{let o=xe(),a=te(ge)?.shapes||[],r=useRef(new Map),n=useRef(new Map),[s,i]=useState(false),l=useCallback((m,u)=>{let f=u.target;o(oo({id:m,x:f.x(),y:f.y()})),e?.();},[o,e]),d=useCallback((m,u)=>{let f=u.target,c=a.find(v=>v.id===m);if(!c)return;let p=f.scaleX(),g=f.scaleY(),h=c.type?.toLowerCase();h==="arrow"||h==="line"||(f.scaleX(1),f.scaleY(1));let b={id:m,x:f.x(),y:f.y(),width:Math.max(5,f.width()*p),height:Math.max(5,f.height()*g),rotation:f.rotation()};switch(h){case "circle":b.radius=f.width()*p/2;break;case "star":b.innerRadius=f.width()*p/4,b.outerRadius=f.width()*p/2;break;case "triangle":b.radius=f.width()*p/2;break;case "ellipse":b.radiusX=f.width()*p/2,b.radiusY=f.height()*g/2;break;case "polygon":b.radius=f.width()*p/2;break;case "ring":let v=p;b.innerRadius=c.innerRadius&&c.innerRadius*v,b.outerRadius=c.outerRadius&&c.outerRadius*v;break;case "wedge":b.radius=c.radius&&c.radius*p;break;case "arc":b.innerRadius=c.innerRadius&&c.innerRadius*p,b.outerRadius=c.outerRadius&&c.outerRadius*p;break;case "arrow":case "line":{b.scaleX=p,b.scaleY=g,delete b.width,delete b.height;break}}o(oo(b)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:s,loadedShapesRef:n,handleShapeDragEnd:l,handleShapeResizeEnd:d}};var yd=(e,o)=>{let t=et(),r=te(ge)?.texts||[],n=useRef(new Map),[s,i]=useState(null),[l,d]=useState("");return {texts:r,textRefs:n,handleDragEnd:(h,w)=>{let b=h.target;t(de()),t(St({id:w,x:b.x(),y:b.y()})),e();},handleTransformEnd:h=>{let w=n.current.get(h);if(!w)return;let b=w.scaleX(),v=w.scaleY(),L=r.find(S=>S.id===h);if(!L)return;let k=(b+v)/2;w.scaleX(1),w.scaleY(1),t(de()),t(St({id:h,x:w.x(),y:w.y(),width:Math.max(5,(L.width||100)*b),height:Math.max(5,(L.height||50)*v),fontSize:Math.round(Math.max(8,L.fontSize*k)),rotation:w.rotation()})),e();},handleDoubleClick:h=>{let w=r.find(b=>b.id===h);w&&!w.locked&&(i(h),d(w.text));},startEditing:h=>{let w=r.find(b=>b.id===h);w&&!w.locked&&(i(h),d(w.text));},editingTextId:s,editingValue:l,handleEditingChange:h=>{d(h);},finishEditing:()=>{if(s){let h=n.current.get(s),w=r.find(v=>v.id===s);t(de());let b={id:s,text:l};if(w&&(w.fontWeight!==void 0&&(b.fontWeight=w.fontWeight),w.fontStyle!==void 0&&(b.fontStyle=w.fontStyle),w.textDecoration!==void 0&&(b.textDecoration=w.textDecoration)),o?.current&&l.trim()){let v=o.current,L=v.offsetWidth,k=v.offsetHeight,S=1;if(h){let W=h.getStage();W&&(S=W.scaleX());}let I=14,x=(L-I)/S,A=(k-I)/S,V=l.split(`
3
- `).length,q=r.find(W=>W.id===s)?.fontSize||24,T=V*q*1.2+10;b.width=Math.max(200,x),b.height=Math.max(50,A,T);}else if(h&&l.trim()){let v=h.text(),L=h.width();h.text(l),h.width(void 0);let k=h.width(),S=h.height();h.text(v),h.width(L),b.width=Math.max(200,k+20),b.height=Math.max(50,S+20);}t(St(b)),i(null),d(""),t($o(null)),e();}}}};var wd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),n=useCallback((s,i)=>{let l=s.target;o(zo({id:i,x:l.x(),y:l.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var Ld=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,s)=>{let i=n.target;o(Go({id:s,x:i.x(),y:i.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var Sd=e=>{let o=xe(),a=te(ge)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),s=useCallback((u,f)=>{if(n.current.has(f))return n.current.get(f);let c=new window.Image;return c.src=u,n.current.set(f,c),c},[]),i=useCallback((u,f)=>{let c=u.target,p=c.id();a.find(h=>h.id===p)&&(o(ro({id:p,x:c.x(),y:c.y()})),f?.());},[a,o]),l=useCallback((u,f)=>{let c=f.target,p=c.scaleX(),g=c.scaleY(),h=c.rotation(),w=Math.max(50,c.width()*p),b=Math.max(50,c.height()*g);c.scaleX(1),c.scaleY(1),c.width(w),c.height(b),o(ro({id:u,width:w,height:b,x:c.x(),y:c.y(),rotation:h})),c.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(u=>{o(Vs(u)),e?.();},[o,e]),m=useCallback(u=>{o(qs(u)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:r,handleDragEnd:i,handleFlashcardTransformEnd:l,handleNext:d,handlePrevious:m}};var Md=e=>{let o=xe(),a=te(ge)?.photoFrames||[],r=useRef(new Map),[n,s]=useState(new Map),i=useCallback((c,p)=>{console.log("handleDragEnd"),o(Aa({id:p,x:c.target.x(),y:c.target.y()})),e?.();},[o,e]),l=useCallback((c,p)=>{let g=p.target,h=g.scaleX(),w=g.scaleY(),b=g.rotation(),v=a.find(S=>S.id===c);if(!v)return;let L=Math.max(100,v.width*h),k=Math.max(100,v.height*w);g.scaleX(1),g.scaleY(1),o(Aa({id:c,width:L,height:k,x:g.x(),y:g.y(),rotation:b})),g.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async c=>{try{let p=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(g=>{let h=new Map(g);return h.set(c,p),h}),o(Aa({id:c,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),m=useCallback(c=>{let p=n.get(c);p&&(p.getTracks().forEach(g=>g.stop()),s(g=>{let h=new Map(g);return h.delete(c),h}),o(Aa({id:c,isCapturing:false})),e?.());},[n,o,e]),u=useCallback((c,p)=>{let g=document.createElement("canvas");g.width=p.videoWidth,g.height=p.videoHeight;let h=g.getContext("2d");if(h){h.drawImage(p,0,0,g.width,g.height);let w=g.toDataURL("image/jpeg",.8);return o(Aa({id:c,capturedImageUrl:w,isCapturing:false})),m(c),e?.(),w}return null},[o,m,e]),f=useRef(n);return useEffect(()=>{f.current=n;},[n]),useEffect(()=>()=>{f.current.forEach(c=>{c.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:i,handlePhotoFrameTransformEnd:l,startCamera:d,stopCamera:m,capturePhoto:u,cameraStreams:n}};var Td=()=>{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,l,d,m,u,f=[])=>{if(e.current){if(n&&!f.find(g=>g.id===n)?.isPlaying){let g=s.get(n)||i.get(n)||l.get(n)||d.get(n)||m.get(n)||(u?u.get(n):null);if(g){e.current.boundBoxFunc(t),e.current.nodes([g]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var fp=(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])},Rd=(e,o)=>{let t=et(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let s=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});s&&s.startsWith("data:")&&t(Ds({id:a.current,thumbnail:s}));}catch(s){console.warn("Could not generate thumbnail (likely CORS issue with images):",s);}},[o,t]),n=fp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var pp=e=>e.flatMap(o=>[o[0],o[1]]),In=(e,o)=>{let t=ld(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 pp(t)};var Ed=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null),i=te(v=>v.toolbar.selectedTool),l=te(v=>v.toolbar.penColor),d=te(v=>v.toolbar.strokeWidth),m=te(v=>v.canvas.isSketchMode),u=te(v=>v.canvas.slides.find(k=>k.id===v.canvas.currentSlideId)?.images.find(k=>k.id===e)),f=u?.annotations||[],c=u?.isDrawingMode||false,p=u?.width||1,g=u?.height||1,h=useCallback(v=>{if(i!=="pen"&&i!=="eraser")return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/p,k=v.y/g;s({tool:i,points:[L,k],color:l,strokeWidth:d/p,isSketch:m});},[i,l,d,m,p,g]),w=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let S;if(m)S=In(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,A)=>A%2===0?x/p:x/g);else {let I=v.x/p,x=v.y/g;S=[...n.points,I,x];}s(I=>I?{...I,points:S}:null);},[m,d,n,p,g]),b=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Ws({imageId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:f,activeLine:n,isDrawingMode:c,startDrawing:h,draw:w,stopDrawing:b,tool:i}};var Nd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>{let{annotations:i,activeLine:l,stopDrawing:f,tool:c}=Ed(e.id);useEffect(()=>{let b=t.current.get(e.id);b&&(b.width()!==e.width||b.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:b.width(),konvaHeight:b.height()}),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[f,p]);let g=b=>{{n(e.id);return}},h=b=>{return;},w=b=>{};return jsxs(Group,{listening:c!=="pen"&&c!=="eraser",children:[jsx(Image$1,{id:e.id,ref:b=>{if(b){t.current.set(e.id,b),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw();let v=b.getStage()?.container();if(v){let L=k=>{let S=b.getStage()?.getPointerPosition();if(S){let I={x:e.x,y:e.y,width:e.width,height:e.height};S.x>=I.x&&S.x<=I.x+I.width&&S.y>=I.y&&S.y<=I.y+I.height&&s(k,e.id,"image");}};v.addEventListener("contextmenu",L),b._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",L);};}}else {let v=t.current.get(e.id);v?._contextMenuCleanup&&v._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:c!=="pen"&&c!=="eraser",onDragEnd:a,onTransformEnd:b=>r(e.id,b),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...c!=="pen"&&c!=="eraser"?{onClick:g,onTap:g,onMouseDown:g,onTouchStart:g,onMouseMove:h,onTouchMove:h,onMouseUp:w,onTouchEnd:w}:{}}),i?.map((b,v)=>{let L=b.points.map((S,I)=>I%2===0?S*e.width+e.x:S*e.height+e.y),k=b.strokeWidth*e.width;return jsx(Line,{points:L,stroke:b.tool==="eraser"?"white":b.color,strokeWidth:k,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},v)}),l&&jsx(Line,{points:l.points.map((b,v)=>v%2===0?b*e.width+e.x:b*e.height+e.y),stroke:l.tool==="eraser"?"white":l.color,strokeWidth:l.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:l.tool==="eraser"?"destination-out":"source-over",fill:l.isSketch?l.color:void 0,closed:l.isSketch,listening:false},"active")]})});Nd.displayName="ImageWithDrawing";var gi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(i=>{let l=o(i);return l?jsx(Nd,{img:i,loadedImage:l,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s},i.id):null})}));gi.displayName="ImageLayer";var Sp=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:s,rotation:i=0,onTransformEnd:l,onDragEnd:d})=>{let m=xe(),u=useRef(null),f=c=>{m(Uo(c));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:i,onDragEnd:d,onTransformEnd:l,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:u,src:e,controls:true,autoPlay:true,onClick:()=>f(t),onSeeking:c=>c.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Vd=Sp;var Rp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:s})=>{let[i,l]=useState(null),d=useSelector(g=>g.toolbar.selectedTool),m=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let g=new window.Image;g.src=e.thumbnailDataUrl,g.onload=()=>{l(g);};}},[e.thumbnailDataUrl]),!i)return null;let u=e.width/2,f=e.height/2,c=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(c,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:r},ref:g=>{if(s(g),g){let h=g.getStage()?.container();if(h){let w=b=>{let v=g.getStage()?.getPointerPosition();if(v){let L={x:e.x,y:e.y,width:e.width,height:e.height};v.x>=L.x&&v.x<=L.x+L.width&&v.y>=L.y&&v.y<=L.y+L.height&&n(b);}};h.addEventListener("contextmenu",w),g._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",w);};}}},children:[jsx(Image$1,{image:i,width:e.width,height:e.height,listening:!m,...m?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:u,y:f,radius:p,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:u,y:f,radius:p*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:u+p*.1,y:f,sides:3,radius:p*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},Hd=Rp;var vi=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(Hd,{video:i,isSelected:!i.isPlaying&&o===i.id,onClick:()=>a(i.id),onDragEnd:l=>r(i.id,l),onTransformEnd:l=>n(i.id,l),onContextMenu:l=>s(l,i.id,"video"),nodeRef:l=>{l?t.current.set(i.id,l):t.current.delete(i.id);}}),i.isPlaying&&(()=>{let l=i.x,d=i.y;if(i.isRecorded){let m=typeof window<"u"?window.innerWidth:i.width,u=typeof window<"u"?window.innerHeight:i.height;l=(m-i.width)/2,d=(u-i.height)/2;}return jsx(Vd,{id:i.id,src:i.objectUrl,x:l,y:d,width:i.width,height:i.height,isSelected:false,rotation:i.rotation,onTransformEnd:m=>n(i.id,m),onDragEnd:m=>r(i.id,m)})})()]},i.id))}));vi.displayName="VideoLayer";var yi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:s})=>{let i=useSelector(d=>d.toolbar.selectedTool),l=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map((d,m)=>{let u=d.id||m,f={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!l,listening:!l,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},u);case "star":return jsx(Star,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "triangle":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},u);case "polygon":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},u);case "ellipse":return jsx(Ellipse,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},u);case "ring":return jsx(Ring,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "wedge":return jsx(Wedge,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},u);case "arrow":return jsx(Arrow,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "line":return jsx(Line,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "arc":return jsx(Arc,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},u);case "rectangle":default:return jsx(Rect,{ref:c=>{c?o.current.set(d.id,c):o.current.delete(d.id);},...f,draggable:!d.locked&&!l,...l?{}:{onDragStart:c=>{n?.();},onDragEnd:c=>t(d.id,c),onTransformEnd:c=>a(d.id,c),onClick:()=>r(d.id),onContextMenu:c=>{c.evt.preventDefault(),s(c.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},u)}})})});yi.displayName="ShapeLayer";var zd=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:s,editingTextId:i})=>{let l=useSelector(m=>m.toolbar.selectedTool),d=l==="pen"||l==="eraser";return jsx(Fragment,{children:e.map(m=>{let u=m.id===i,f=m.fontWeight==="bold",c=f?Math.max(1,m.fontSize/25):0;return jsx(Text,{id:m.id,ref:p=>{p?o.current.set(m.id,p):o.current.delete(m.id);},text:m.text,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:!m.locked&&!u&&!d,listening:!d,fontSize:m.fontSize,fontFamily:m.fontFamily,fontStyle:m.fontStyle,fontWeight:m.fontWeight,textDecoration:m.textDecoration,fill:m.fill,stroke:f?m.fill:void 0,strokeWidth:c,align:m.align,wrap:"none",lineHeight:1.2,opacity:u?0:1,visible:!u,...d?{}:{onClick:()=>r(m.id),onTap:()=>r(m.id),onDblClick:()=>s(m.id),onDblTap:()=>s(m.id),onDragEnd:p=>t(p,m.id),onTransformEnd:()=>a(m.id),onContextMenu:p=>{p.evt.preventDefault();let g=p.evt;n(g,m.id,"text");}}},m.id)})})};var oh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:s,onPrevious:i,nodeRef:l})=>{let[d,m]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{m(h);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let u=8,f=2,c=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(c,32)),g=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:h=>{if(l(h),h){let w=h.getStage()?.container();if(w){let b=v=>{let L=h.getStage()?.getPointerPosition();if(L){let k={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=k.x&&L.x<=k.x+k.width&&L.y>=k.y&&L.y<=k.y+k.height&&n(v);}};w.addEventListener("contextmenu",b),h._contextMenuCleanup=()=>{w.removeEventListener("contextmenu",b);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:u,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:u,stroke:"#E5E7EB",strokeWidth:f,listening:false}),jsx(Image$1,{x:f+4,y:f+4,image:d,width:e.width-(f+4)*2,height:e.height-(f+4)*2,cornerRadius:u-f,onClick:t,onTap:t}),jsx(Rect,{x:f,y:e.height-50,width:e.width-f*2,height:50,cornerRadius:[0,0,u-f,u-f],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:g+p,y:e.height/2,onClick:h=>{h.cancelBubble=true,i();},onTap:h=>{h.cancelBubble=true,i();},children:[jsx(Circle,{radius:p,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-g-p,y:e.height/2,onClick:h=>{h.cancelBubble=true,s();},onTap:h=>{h.cancelBubble=true,s();},children:[jsx(Circle,{radius:p,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"})]})},_d=oh;var Ii=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:s,onPrevious:i,onContextMenu:l})=>jsx(Fragment,{children:e.map(d=>jsx(_d,{flashcard:d,isSelected:t===d.id,onClick:()=>n(d.id),onDragEnd:a,onTransformEnd:m=>r(d.id,m),onContextMenu:m=>l(m,d.id,"flashcard"),onNext:()=>s(d.id),onPrevious:()=>i(d.id),nodeRef:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);}},d.id))}));Ii.displayName="FlashcardLayer";var $d=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null);te(v=>v.toolbar.selectedTool);let l=te(v=>v.toolbar.penColor),d=te(v=>v.toolbar.strokeWidth),m=te(v=>v.canvas.isSketchMode),u=te(v=>v.canvas.slides.find(k=>k.id===v.canvas.currentSlideId)?.photoFrames.find(k=>k.id===e)),f=u?.annotations||[],c=u?.isDrawingMode||false,p=u?.width||1,g=u?.height||1,h=useCallback(v=>{if(!c)return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/p,k=v.y/g;s({tool:"pen",points:[L,k],color:l,strokeWidth:d/p,isSketch:m});},[c,l,d,m,p,g]),w=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let S;if(m)S=In(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((x,A)=>A%2===0?x/p:x/g);else {let I=v.x/p,x=v.y/g;S=[...n.points,I,x];}s(I=>I?{...I,points:S}:null);},[m,d,n,p,g]),b=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Gs({frameId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:f,activeLine:n,isDrawingMode:c,startDrawing:h,draw:w,stopDrawing:b}};var fh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:s,onCapture:i,cameraStream:l,nodeRef:d})=>{let[m,u]=useState(null),[f,c]=useState(null),p=useRef(null),g=useRef(null),h=useRef(null),w=useRef(null),b=useRef(0),v=33,L=useSelector(N=>N.toolbar.selectedTool),k=L==="pen"||L==="eraser",{annotations:S,activeLine:I,isDrawingMode:x,startDrawing:A,draw:V,stopDrawing:D}=$d(e.id);useEffect(()=>{if(!x)return;let N=()=>{D();},j=()=>{D();};return window.addEventListener("mouseup",N),window.addEventListener("touchend",j),()=>{window.removeEventListener("mouseup",N),window.removeEventListener("touchend",j);}},[D,x]),useEffect(()=>{if(e.capturedImageUrl){let N=new window.Image;N.src=e.capturedImageUrl,N.onload=()=>{u(N);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&l){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),g.current||(g.current=document.createElement("canvas"));let N=p.current,j=g.current;N.srcObject=l;let H=()=>{j.width=N.videoWidth||640,j.height=N.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",j.width,j.height);let K=J=>{if(J-b.current<v){h.current=requestAnimationFrame(K);return}b.current=J;let ee=j.getContext("2d");if(ee&&N.readyState===N.HAVE_ENOUGH_DATA){ee.drawImage(N,0,0,j.width,j.height);let Z=j.toDataURL("image/jpeg",.6),ne=new window.Image;ne.onload=()=>{c(ne);},ne.src=Z;}h.current=requestAnimationFrame(K);};h.current=requestAnimationFrame(K);};return N.onloadedmetadata=H,N.readyState>=N.HAVE_METADATA&&H(),N.play().catch(K=>console.error("Error playing video:",K)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{c(null),w.current&&(w.current.src="");}},[e.isCapturing,l]);let q=()=>{p.current&&e.isCapturing&&i(p.current);},U=N=>{if(e.capturedImageUrl){if(!x){t();return}let j=N.currentTarget,H=j.getAbsoluteTransform().copy(),J=j.getStage()?.getPointerPosition();if(J){H.invert();let ee=H.point(J);A(ee);}N.cancelBubble=true;}else t();},T=N=>{if(!x||!e.capturedImageUrl)return;let j=N.currentTarget,H=j.getAbsoluteTransform().copy(),J=j.getStage()?.getPointerPosition();if(J){H.invert();let ee=H.point(J);V(ee);}},W=()=>{!x||!e.capturedImageUrl||D();},R=e.isCapturing?f:m,oe=Math.min(e.width,e.height)*.12,O=Math.max(25,Math.min(oe,50)),fe=e.width/2,z=e.height/2;return jsxs(Group,{id:e.id,draggable:!x&&!k,listening:true,x:e.x,y:e.y,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:N=>{if(d(N),N){let j=N.getStage()?.container();if(j){let H=K=>{let J=N.getStage()?.getPointerPosition();if(J){let ee={x:e.x,y:e.y,width:e.width,height:e.height};J.x>=ee.x&&J.x<=ee.x+ee.width&&J.y>=ee.y&&J.y<=ee.y+ee.height&&n(K);}};j.addEventListener("contextmenu",H),N._contextMenuCleanup=()=>{j.removeEventListener("contextmenu",H);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:R?"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}}),R&&jsx(Image$1,{image:R,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:U,onTap:U,onMouseDown:U,onTouchStart:U,onMouseMove:T,onTouchMove:T,onMouseUp:W,onTouchEnd:W,...k?{}:{onDragEnd:a,onTransformEnd:r}}),S?.map((N,j)=>{let H=N.points.map((J,ee)=>ee%2===0?J*e.width:J*e.height),K=N.strokeWidth*e.width;return jsx(Line,{points:H,stroke:N.tool==="eraser"?"white":N.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:N.tool==="eraser"?"destination-out":"source-over",fill:N.isSketch?N.color:void 0,closed:N.isSketch,listening:false},j)}),I&&jsx(Line,{points:I.points.map((N,j)=>j%2===0?N*e.width:N*e.height),stroke:I.tool==="eraser"?"white":I.color,strokeWidth:I.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:I.tool==="eraser"?"destination-out":"source-over",fill:I.isSketch?I.color:void 0,closed:I.isSketch,listening:false},"active"),!R&&!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:z-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:fe-O+6,y:z-60,width:O*1.6,height:O*1.6,radius:O,fill:"white",cornerRadius:8,listening:true,onClick:N=>{N.cancelBubble=true,e.isCapturing?q():s();},onTap:N=>{N.cancelBubble=true,e.isCapturing?q():s();}}),jsx(Html,{groupProps:{x:fe-12,y:z-40,width:O*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:N=>{N.stopPropagation(),e.isCapturing?q():s();}})})]}),jsx(Text,{x:0,y:z,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:z+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:fe-24,y:z+104,width:O*1.6,height:O*1.6,radius:O,fill:"#096B76",cornerRadius:O,listening:true,onClick:N=>{N.cancelBubble=true,e.isCapturing?q():s();},onTap:N=>{N.cancelBubble=true,e.isCapturing?q():s();}}),jsx(Html,{groupProps:{x:fe-8,y:z+120,width:O*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:N=>{N.stopPropagation(),e.isCapturing?q():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"})]})]})},Zd=fh;var Ti=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:s,onCapture:i,cameraStreams:l,onContextMenu:d})=>jsx(Fragment,{children:e.map(m=>jsx(Zd,{photoFrame:m,isSelected:t===m.id,onClick:()=>n(m.id),onDragEnd:u=>a(u,m.id),onTransformEnd:u=>r(m.id,u),onContextMenu:u=>d(u,m.id,"photoFrame"),onStartCamera:()=>s(m.id),onCapture:u=>i(m.id,u),cameraStream:l.get(m.id),nodeRef:u=>{u?o.current.set(m.id,u):o.current.delete(m.id);}},m.id))}));Ti.displayName="PhotoFrameLayer";var au=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:s,menuRef:i})=>{useEffect(()=>{let u=c=>{i?.current&&!i.current.contains(c.target)&&a();},f=c=>{c.key==="Escape"&&a();};return document.addEventListener("mousedown",u),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",f);}},[a]);let l=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(f=>!(f.showForTypes&&!f.showForTypes.includes(r)||f.hideForTypes&&f.hideForTypes.includes(r))),[r,s]),d=(u,f)=>{u==="order"||u==="lock"?t(u,f):(t(u),a());},m=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:l.map((u,f)=>jsxs("button",{onClick:c=>d(u.action,c),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] ${u.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[u.icon,jsx("span",{className:`font-medium ${u.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:u.label})]}),u.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"})})]},f))})});return createPortal(m,document.body)};var ou=({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 ru=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[s,i]=useState(a),l=useRef(null);useEffect(()=>{l.current?.focus();},[]);let d=()=>{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$1,{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:l,type:"text",value:s,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"?d():u.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:d,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 nu=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null);useEffect(()=>{let m=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[t]);let s=m=>{m.preventDefault(),o(a);},i=(m,u,f)=>{f/=100;let c=u*Math.min(f,1-f)/100,p=g=>{let h=(g+m/30)%12,w=f-c*Math.max(Math.min(h-3,9-h,1),-1);return Math.round(255*w).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},d=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:m=>m.stopPropagation(),onMouseUp:m=>m.stopPropagation(),onMouseMove:m=>m.stopPropagation(),onTouchStart:m=>m.stopPropagation(),onTouchMove:m=>m.stopPropagation(),onTouchEnd:m=>m.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:m=>m.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$1,{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:m=>r(m.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:m=>r(m.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:m=>{let u=parseInt(m.target.value),f=i(u,100,50);r(f);},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(m=>jsx("button",{type:"button",onClick:()=>r(m),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===m.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:m},title:m},m))})]})]}),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(d,document.body)};var Xh=({imageSrc:e,onCrop:o})=>{let[t]=lu(e),a=useRef(null),r=useRef(null),n=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let p=Math.min(600/t.width,400/t.height);return {width:t.width*p,height:t.height*p}},[t]),i=useMemo(()=>{let f=s.width*.5,c=s.height*.5,p=(s.width-f)/2,g=(s.height-c)/2;return {x:p,y:g,width:f,height:c}},[s]),[l,d]=useState(i);useEffect(()=>{d(i);},[i]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[l]),useEffect(()=>{o(l.x,l.y,l.width,l.height);},[l,o]);let m=()=>{let f=r.current;if(!f)return;let c=f.scaleX(),p=f.scaleY();f.scaleX(1),f.scaleY(1),d({x:f.x(),y:f.y(),width:Math.max(20,f.width()*c),height:Math.max(20,f.height()*p)});},u=()=>{let f=r.current;f&&d({x:f.x(),y:f.y(),width:f.width(),height:f.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:l.x,y:l.y,width:l.width,height:l.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:l.x,y:l.y,width:l.width,height:l.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:u,onTransformEnd:m,dragBoundFunc:f=>{let c=Math.max(0,Math.min(f.x,s.width-l.width)),p=Math.max(0,Math.min(f.y,s.height-l.height));return {x:c,y:p}}}),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:(f,c)=>c.width<20||c.height<20||c.x<0||c.y<0||c.x+c.width>s.width||c.y+c.height>s.height?f:c})]})})},du=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[s]=lu(e);return useEffect(()=>{let m=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:m=>m.stopPropagation(),onMouseUp:m=>m.stopPropagation(),onMouseMove:m=>m.stopPropagation(),onTouchStart:m=>m.stopPropagation(),onTouchMove:m=>m.stopPropagation(),onTouchEnd:m=>m.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:m=>m.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$1,{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(Xh,{imageSrc:e,onCrop:(m,u,f,c)=>{n({x:m,y:u,width:f,height:c});}})}),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 f=Math.min(600/s.width,400/s.height),c=r.x/f,p=r.y/f,g=r.width/f,h=r.height/f,w=document.createElement("canvas");w.width=g,w.height=h;let b=w.getContext("2d");if(!b)return;b.drawImage(s,c,p,g,h,0,0,g,h);let v=w.toDataURL("image/png");o(v);},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 nr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,n]=useState(false),[s,i]=useState(null),[l,d]=useState(0),[m,u]=useState(true),f=useRef(null),c=useRef([]),p=useRef(null),g=useRef(null),h=useRef(null),w=useRef(null),b=useRef(null),v=useRef(null);useEffect(()=>()=>{h.current&&cancelAnimationFrame(h.current),p.current&&clearInterval(p.current),g.current&&g.current.getTracks().forEach(x=>x.stop());},[]);let L=async()=>{try{let x,A=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let T=o.current.getLayers();console.log("Konva layers:",T.length),T.forEach((j,H)=>{let K=j.getChildren();console.log(`Layer ${H} children count:`,K.length);});let W=document.createElement("canvas");W.width=o.current.width(),W.height=o.current.height();let R=W.getContext("2d",{willReadFrequently:!1});if(!R){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",W.width,"x",W.height),b.current=W;let oe=()=>{if(R.clearRect(0,0,W.width,W.height),T.forEach(j=>{let H=j.getCanvas()._canvas;H&&R.drawImage(H,0,0);}),a?.current){let j=a.current;R.drawImage(j,0,0);}};v.current=oe,o.current.draw(),oe(),await new Promise(j=>setTimeout(j,100)),console.log("Creating captureStream..."),x=W.captureStream(30),console.log("Canvas stream created, tracks:",x.getTracks().length);let fe=x.getVideoTracks()[0];fe&&console.log("Video track:",fe.label,"state:",fe.readyState);let z=0,N=()=>{oe(),o?.current&&(o.current.getLayers().forEach(H=>{H.batchDraw();}),z++,z%60===0&&console.log("Drawing frame:",z)),h.current=requestAnimationFrame(N);};N();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(m)try{A=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(T){console.warn("Microphone access denied:",T);}let V=[...x.getVideoTracks()];A&&V.push(...A.getAudioTracks());let D=new MediaStream(V);g.current=D;let q="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?q="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?q="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?q="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(q="video/webm;codecs=vp8"),console.log("Using mimeType:",q);let U=new MediaRecorder(D,{mimeType:q,videoBitsPerSecond:25e5});f.current=U,c.current=[],U.ondataavailable=T=>{console.log("Data available, size:",T.data.size),T.data.size>0&&c.current.push(T.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",c.current.length);let T=new Blob(c.current,{type:q});console.log("Final blob size:",T.size),o?.current&&v.current&&b.current&&(o.current.draw(),o.current.getLayers().forEach(R=>{R.batchDraw();}),v.current(),w.current=b.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",w.current.length)),D.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),h.current&&(cancelAnimationFrame(h.current),h.current=null),i(T);},U.onerror=T=>{console.error("MediaRecorder error:",T);},console.log("Starting recording..."),U.start(1e3),n(!0),d(0),p.current=setInterval(()=>{d(T=>T+1);},1e3);}catch(x){console.error("Error starting screen recording:",x),alert("Failed to start recording. Please ensure you granted permission.");}},k=()=>{f.current&&r&&(console.log("Stopping recording, state:",f.current.state),f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),n(false));},S=()=>{if(s){let x=URL.createObjectURL(s),A=document.createElement("a");A.href=x,A.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(x);}},I=x=>{let A=Math.floor(x/60),V=x%60;return `${A.toString().padStart(2,"0")}:${V.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:I(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:k,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$1,{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:()=>u(!m),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${m?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:m?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:L,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: ",I(l)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&s&&w.current&&(t(s,w.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:S,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),d(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 cu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[n,s]=useState(false),[i,l]=useState(null),[d,m]=useState(false),[u,f]=useState(0),c=useRef(null),p=useRef([]),g=useRef(null),h=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(x=>x.blob()).then(x=>l(x)).catch(x=>console.error("Error loading audio:",x));},[o,i]);let w=async()=>{try{let x=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),A=new MediaRecorder(x);c.current=A,p.current=[],A.ondataavailable=V=>{V.data.size>0&&p.current.push(V.data);},A.onstop=()=>{let V=new Blob(p.current,{type:"audio/webm"});l(V),x.getTracks().forEach(D=>D.stop()),g.current&&clearInterval(g.current);},A.start(),s(!0),f(0),g.current=setInterval(()=>{f(V=>V+1);},1e3);}catch(x){console.error("Error starting audio recording:",x),alert("Failed to start recording. Please allow microphone access.");}},b=()=>{c.current&&n&&(c.current.stop(),s(false));},v=()=>{if(i){let x=URL.createObjectURL(i),A=new Audio(x);h.current=A,A.onended=()=>{m(false),URL.revokeObjectURL(x);},A.play(),m(true);}},L=()=>{h.current&&(h.current.pause(),h.current.currentTime=0,m(false));},k=async()=>{if(i){let x=new FileReader;x.onloadend=()=>{let A=x.result;t(A),r();},x.readAsDataURL(i);}},S=()=>{l(null),a();},I=x=>{let A=Math.floor(x/60),V=x%60;return `${A.toString().padStart(2,"0")}:${V.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:I(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:b,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:w,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:d?L:v,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"}),d?"Playing...":"Play Audio"]}),jsx("button",{onClick:S,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:k,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 kt=({audioData:e,x:o,y:t,width:a})=>{let[r,n]=useState(false),s=useRef(null);return jsx("button",{onClick:l=>{if(l.stopPropagation(),r&&s.current)s.current.pause(),s.current.currentTime=0,n(false);else {let d=new Audio(e);s.current=d,d.onended=()=>{n(false);},d.onerror=()=>{console.error("Error playing audio"),n(false);},d.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 pu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=te(ge),n=useMemo(()=>{if(!r)return [];let g=[];return r.images?.forEach(h=>{g.push({id:h.id,type:"image",name:"Image",timestamp:h.timestamp||0});}),r.videos?.forEach(h=>{g.push({id:h.id,type:"video",name:"Video",timestamp:h.timestamp||0});}),r.shapes?.forEach(h=>{g.push({id:h.id,type:"shape",name:`${h.type} Shape`,timestamp:h.timestamp||0});}),r.texts?.forEach(h=>{g.push({id:h.id,type:"text",name:h.text.substring(0,20)+(h.text.length>20?"...":""),timestamp:h.timestamp||0});}),r.flashcards?.forEach(h=>{g.push({id:h.id,type:"flashcard",name:`Flashcard (${h.images.length} images)`,timestamp:h.timestamp||0});}),r.photoFrames?.forEach(h=>{g.push({id:h.id,type:"photoFrame",name:"Photo Frame",timestamp:h.timestamp||0});}),r.multipleChoices?.forEach(h=>{g.push({id:h.id,type:"mcq",name:"Multiple Choice",timestamp:h.timestamp||0});}),r.trueFalses?.forEach(h=>{g.push({id:h.id,type:"trueFalse",name:"True/False",timestamp:h.timestamp||0});}),r.shortAnswers?.forEach(h=>{g.push({id:h.id,type:"shortAnswer",name:"Short Answer",timestamp:h.timestamp||0});}),r.LongAnswer?.forEach(h=>{g.push({id:h.id,type:"longAnswer",name:"Long Answer",timestamp:h.timestamp||0});}),r.fillInTheBlanks?.forEach(h=>{g.push({id:h.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:h.timestamp||0});}),r.lines?.forEach(h=>{h.id&&g.push({id:h.id,type:"line",name:"Drawn Line",timestamp:h.timestamp||0});}),g.sort((h,w)=>w.timestamp-h.timestamp)},[r]),[s,i]=useState(n),[l,d]=useState(false);useEffect(()=>{l||i(n);},[n]);let m=g=>{let h="h-5 w-5";switch(g){case "image":return jsx(Image$3,{className:h});case "video":return jsx(VideoCamera,{className:h});case "shape":return jsx(Shapes$1,{className:h});case "text":return jsx(TextT,{className:h});case "flashcard":return jsx(Cards$1,{className:h});case "photoFrame":return jsx(FrameCorners,{className:h});case "line":return jsx("span",{className:h,children:"\u270F\uFE0F"});default:return jsx(Question,{className:h})}},u=g=>{if(g===0)return;let h=s[g],w=s[g-1];a(jo({id:h.id,type:h.type,newTimestamp:w.timestamp+1}));},f=g=>{if(g===s.length-1)return;let h=s[g],w=s[g+1];a(jo({id:h.id,type:h.type,newTimestamp:w.timestamp-1}));},c=g=>{d(true),i(g);},p=()=>{d(false);let g=Date.now();s.forEach((h,w)=>{let b=g-w;a(jo({id:h.id,type:h.type,newTimestamp:b}));});};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$2,{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:c,className:"space-y-1",children:s.map((g,h)=>{let w=g.id===e;return jsxs(Reorder.Item,{value:g,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${w?"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(g.id,g.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${w?"text-blue-600":"text-gray-600"}`,children:m(g.type)}),jsx("span",{className:`text-sm ${w?"font-medium text-blue-900":"text-gray-700"}`,children:g.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:b=>{b.stopPropagation(),u(h);},disabled:h===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:b=>{b.stopPropagation(),f(h);},disabled:h===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"})})]})]},g.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 hu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>{let s=useSelector(z=>z.toolbar.selectedTool),i=s==="pen"||s==="eraser",[l,d]=useState(new Set),[m,u]=useState(false),[f,c]=useState(null),p=useRef(null);useEffect(()=>{let z=p.current;if(z)return a.current.set(e.id,z),()=>{a.current.delete(e.id);}},[e.id]);let g=new Set(e.data.responseOptions.correctIndex),h=g.size>1,w=z=>{m||d(h?N=>{let j=new Set(N);return j.has(z)?j.delete(z):j.add(z),j}:new Set([z]));},b=()=>{l.size>0&&u(true);},v=()=>{u(false),d(new Set);},L=l.size===g.size&&Array.from(l).every(z=>g.has(z)),k=Array.from(l).filter(z=>g.has(z)),S=h&&k.length>0&&!L,I=()=>L?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${k.length}/${g.size})`:"\u2717 Try again!",x=()=>L?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},A=55,V=8,D=24,q=60,U=60,T=h&&!m?25:0,W=e.data.feedbackMode==="practice"?48:0,R=12,oe=q+T+(m?U:0),O=e.data.responseOptions.options.length*(A+V),fe=oe+O+R+W+D;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:r,onClick:z=>t(e.id),onTap:z=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:fe,width:e.width,onTransformEnd:z=>o(e.id,z),onContextMenu:z=>{z.cancelBubble=true,n(z.evt,e.id,"mcq");}}),jsx(Text,{x:D+8,y:D,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-D*2,listening:false}),h&&!m&&e.data.feedbackMode==="practice"?jsx(Text,{x:D,y:D+35,text:`Select ${g.size} answers (${l.size}/${g.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-D*2,listening:false}):null,m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:D+24,y:q+T,width:e.width-D*2-40,height:U-20,fill:x().bg,cornerRadius:8}),jsx(Text,{x:D,y:q+T,width:e.width-D*2,height:U-20,text:I(),fontSize:16,fontStyle:"bold",fill:x().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((z,N)=>{let j=g.has(N),H=l.has(N),K=oe+N*(A+V),J="#e5e7eb",ee="#ffffff",Z="#111827";return m&&j?(J="#22c55e",ee="#dcfce7",Z="#1B9D2C"):m&&H&&!j?(J="#ef4444",ee="#fee2e2",Z="#ef4444"):H&&(J="#096B76",ee="#ECFFF8",Z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:D+12,y:K+(A-20)/2,width:20,height:20,fill:H?"#096B76":"white",stroke:H?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:ne=>{ne.cancelBubble=true,w(N);},onTap:ne=>{ne.cancelBubble=true,w(N);}}),H&&jsx(Text,{x:D+12,y:K+(A-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:D+44,y:K,width:e.width-D*2-60,height:A,fill:ee,stroke:J,strokeWidth:2,cornerRadius:8,onClick:ne=>{ne.cancelBubble=true,w(N);},onTap:ne=>{ne.cancelBubble=true,w(N);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:A,text:z,fontSize:16,fill:Z,verticalAlign:"middle",listening:false})]},N)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:oe+e.data.responseOptions.options.length*(A+V)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,c("check");},onMouseUp:z=>{z.cancelBubble=true,c(null),b();},onMouseLeave:z=>{z.cancelBubble=true,c(null);},onTouchStart:z=>{z.cancelBubble=true,c("check");},onTouchEnd:z=>{z.cancelBubble=true,c(null),b();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:D+14,width:(e.width-D*2-24)/(m?2:1),height:48,fill:l.size===0||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:D+14,width:(e.width-D*2-24)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-D*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),v();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),v();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:D,width:(e.width-D*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:D,width:(e.width-D*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});hu.displayName="MultipleChoice";var gu=hu;var Ri=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r})=>{let n=useDispatch(),s=useSelector(H=>H.toolbar.selectedTool),i=s==="pen"||s==="eraser",[l,d]=useState(false),[m,u]=useState(new Set),[f,c]=useState(false),[p,g]=useState(false),[h,w]=useState(0),b=340,v=100,L=window.innerWidth*.4,k=window.innerHeight*.5,S=b+20,I=v+60,x=L-40,A=k-300,V=useRef(null);useEffect(()=>{let H=V.current;if(H)return r.current.set(e.id,H),()=>{r.current.delete(e.id);}},[e.id]);let D=H=>{n(ia({id:e.id,x:H.target.x(),y:H.target.y()}));},q=H=>{let K=H.target,J=K.x(),ee=K.y(),Z=window.innerWidth*.2,Ie=J+Z>S&&J<S+x&&ee+50>I&&ee<I+A;d(Ie);},U=(H,K)=>{let J=K.target,ee=J.x(),Z=J.y(),ne=window.innerWidth*.2,Y=ee+ne>S&&ee<S+x&&Z+50>I&&Z<I+A;u(Y?De=>new Set(De).add(H):De=>{let Se=new Set(De);return Se.delete(H),Se}),d(false);},T=()=>{c(true);},W=()=>{c(false),u(new Set),w(H=>H+1);},R=new Set(e.data.responseOptions.correctIndex),oe=m.size===R.size&&Array.from(m).every(H=>R.has(H)),O=Array.from(m).filter(H=>R.has(H)),fe=O.length>0&&!oe,z=()=>oe?"\u2713 Correct! Great job!":fe?`\u26A0 Partially correct (${O.length}/${R.size})`:"\u2717 Try again!",N=()=>oe?{bg:"#dcfce7",text:"#166534"}:fe?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},j=()=>f?oe?"#4CAF50":fe?"#f59e0b":"#ef4444":l?"#4CAF50":"#075560";return jsxs(Group,{ref:V,name:"mcq-element",width:L,height:k,draggable:!i,listening:!i,...i?{}:{onClick:H=>a(e.id),onTap:H=>a(e.id),onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b,y:v,rotation:e.rotation,onDragEnd:D,children:[jsx(Rect,{fill:"white",stroke:l?"#4CAF50":"#e5e7eb",strokeWidth:l?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?k-100:k-50,width:L,shadowColor:l?"#4CAF50":"transparent",shadowBlur:l?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:x,height:A,fill:"#EBF6F7",stroke:j(),strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:A+18,width:x-5,height:60,fill:N().bg,cornerRadius:8}),jsx(Text,{x:20,y:A+20,width:x,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:N().text,align:"center",verticalAlign:"middle"})]}),m.size===0&&!f&&jsx(Text,{x:20,y:60,width:x,height:A-60,text:R.size>1?`Drop ${R.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:f?k-200:k-160,children:[jsxs(Group,{onMouseDown:()=>{g(true),T();},onMouseUp:()=>g(false),onMouseLeave:()=>g(false),onTouchStart:()=>{g(true),T();},onTouchEnd:()=>g(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:x}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:x,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:x}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:x,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((H,K)=>{let J=K%2,ee=Math.floor(K/2),Z=window.innerWidth*.2,ne=50,Ie=10,Y=m.has(K),De=R.has(K),Se=f&&Y,Ft="transparent";return Se?Ft=De?"#4CAF50":"#ef4444":Y&&(Ft="#4CAF50"),jsxs(Group,{x:340+J*(Z+Ie),y:v+k-80+ee*(ne+Ie),draggable:!f,onDragMove:q,onDragEnd:Ja=>U(K,Ja),opacity:f&&!Y?.5:1,children:[jsx(Rect,{width:Z-20,height:ne,fill:"white",stroke:Ft,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Z-20,height:ne,text:H,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${h}`)})]})};Ri.displayName="MultipleChoiceDragAndDrop";var xu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(gu,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:i=>r(i,s.id),onContextMenu:n},s.id):jsx(Ri,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:n},s.id))});var bu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(R=>R.toolbar.selectedTool),i=s==="pen"||s==="eraser",[l,d]=useState(null),[m,u]=useState(false),[f,c]=useState(null),p=useRef(null);useEffect(()=>{let R=p.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{l!==null&&u(true);},h=()=>{u(false),d(null);},w=e.data.responseOptions.correctAnswer,b=l===w,v=R=>{m||d(R);},L=()=>b?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",k=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=70,I=12,x=24,A=60,V=60,D=e.data.feedbackMode==="practice"?48:0,q=12,U=A+(m?V:0),T=2*(S+I),W=U+T+q+D+x;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:R=>n(R,e.id),onClick:R=>t(e.id),onTap:R=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:W-20,width:e.width,onTransformEnd:R=>o(e.id,R),onContextMenu:R=>{R.cancelBubble=true,r(R.evt,e.id,"trueFalse");}}),jsx(Text,{x,y:x,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-x*2,listening:false}),m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x,y:A,width:e.width-x*2,height:V-10,fill:k().bg,cornerRadius:8}),jsx(Text,{x,y:A,width:e.width-x*2,height:V-10,text:L(),fontSize:16,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((R,oe)=>{let O=w===R.value,fe=l===R.value,z=(e.width-x*3)/2,N=x+oe*(z+x),j=U,H=R.value===true,K=H?"#10b981":"#ef4444",J="#ffffff",ee="#ffffff",Z="#e5e7eb";return m&&(O?(ee=H?"#f0fdf4":"#fef2f2",Z=H?"#86efac":"#fecaca"):fe&&!O&&(ee="#fee2e2",Z="#ef4444")),fe&&!m&&(Z="#096B76",ee="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:N,y:j,width:z,height:S+50,fill:ee,stroke:Z,strokeWidth:2,cornerRadius:12,onClick:ne=>{ne.cancelBubble=true,v(R.value);},onTap:ne=>{ne.cancelBubble=true,v(R.value);}}),jsx(Circle,{x:N+z/2,y:j+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:N+z/2-14,y:j+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:J,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:N+z/2-14,y:j+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:J,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:N,y:j+85,width:z,height:30,text:R.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},R.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:U+2*(S+I),children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,c("check");},onMouseUp:R=>{R.cancelBubble=true,c(null),g();},onMouseLeave:R=>{R.cancelBubble=true,c(null);},onTouchStart:R=>{R.cancelBubble=true,c("check");},onTouchEnd:R=>{R.cancelBubble=true,c(null),g();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x,width:(e.width-x*2-8)/(m?2:1),height:48,fill:l===null||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x,width:(e.width-x*2-8)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-x*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),h();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),h();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x,width:(e.width-x*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x,width:(e.width-x*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});bu.displayName="TrueFalse";var vu=bu;var jg="#FFFFFF",Bi=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(K=>K.toolbar.selectedTool),n=r==="pen"||r==="eraser",[s,i]=useState(false),[l,d]=useState(null),[m,u]=useState(false),[f,c]=useState(false),[p,g]=useState(0),[h,w]=useState(false),b=340,v=100,L=window.innerWidth*.4,k=window.innerHeight*.5,S=L-40,I=k-300,x=20,A=60,V=S,D=I,q=L*.2-40,U=50,T=useRef(null),W=K=>{a(la({id:e.id,x:K.target.x(),y:K.target.y()}));},R=K=>{let J=K.target,ee=J.x(),Z=J.y(),ne=Math.max(0,Math.min(ee+q,x+V)-Math.max(ee,x)),Ie=Math.max(0,Math.min(Z+U,A+D)-Math.max(Z,A)),Y=ne*Ie,De=q*U;i(Y/De>=.5);},oe=(K,J)=>{let ee=J.target,Z=ee.x(),ne=ee.y(),Ie=Math.max(0,Math.min(Z+q,x+V)-Math.max(Z,x)),Y=Math.max(0,Math.min(ne+U,A+D)-Math.max(ne,A)),De=Ie*Y,Se=q*U;if(De/Se>=.5)d(K);else return;i(false);},O=()=>{u(true);},fe=()=>{u(false),d(null),g(K=>K+1);},z=e.data.responseOptions.correctAnswer,N=l===z,j=()=>N?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>N?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:T,name:"trueFalse-element",width:L,height:k,draggable:!n,listening:!n,...n?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:v,rotation:e.rotation,onDragEnd:W,children:[jsx(Rect,{fill:"white",stroke:s?"#4CAF50":"#e5e7eb",strokeWidth:s?4:2,cornerRadius:12,height:m?k:e.data.feedbackMode==="practice"?k-50:k-100,width:L,shadowColor:s?"#4CAF50":"transparent",shadowBlur:s?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:S,height:I,fill:"transparent",stroke:s?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:S,height:60,fill:H().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:S,height:60,text:j(),fontSize:18,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle"})]}),l===null&&!m&&jsx(Text,{x:20,y:60,width:S,height:I-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:k-100,children:[jsxs(Group,{onMouseDown:()=>{l!==null&&(c(true),O());},onMouseUp:()=>c(false),onMouseLeave:()=>c(false),onTouchStart:()=>{l!==null&&(c(true),O());},onTouchEnd:()=>c(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:l===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:fe,onTouchStart:fe,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,J)=>{let ee=window.innerWidth*.2,Z=50,ne=10,Ie=l===K.value,Y=z===K.value,De=m&&Ie,Se="transparent";return De?Se=Y?"#4CAF50":"#ef4444":Ie&&(Se="#4CAF50"),jsxs(Group,{x:16+J*(ee+ne),y:v+k-300,draggable:!m,onDragMove:R,onDragEnd:Ft=>oe(K.value,Ft),opacity:m&&!Ie?.5:1,children:[jsx(Rect,{width:ee-40,height:Z,fill:"#075560",stroke:Se,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:ee-40,height:Z,text:K.label,fontSize:18,fontStyle:"bold",fill:jg,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${p}`)})]})})};Bi.displayName="TrueFalseDragAndDrop";var yu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(vu,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r},s.id):jsx(Bi,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n},s.id))});var fa=new WeakMap,bo=new WeakMap,cr={current:[]},Ni=false,ur=0,dr=new Set,Fn=new Map;function wu(e){let o=Array.from(e).sort((t,a)=>t instanceof Vt&&t.options.deps.includes(a)?1:a instanceof Vt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(cr.current.includes(t))continue;cr.current.push(t),t.recompute();let a=bo.get(t);if(a)for(let r of a){let n=fa.get(r);n&&wu(n);}}}function Yg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Jg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Bn(e){if(ur>0&&!Fn.has(e)&&Fn.set(e,e.prevState),dr.add(e),!(ur>0)&&!Ni)try{for(Ni=!0;dr.size>0;){let o=Array.from(dr);dr.clear();for(let t of o){let a=Fn.get(t)??t.prevState;t.prevState=a,Yg(t);}for(let t of o){let a=fa.get(t);a&&(cr.current.push(t),wu(a));}for(let t of o){let a=fa.get(t);if(a)for(let r of a)Jg(r);}}}finally{Ni=false,cr.current=[],Fn.clear();}}function mt(e){ur++;try{e();}finally{if(ur--,ur===0){let o=dr.values().next().value;o&&Bn(o);}}}function Lu(e){return typeof e=="function"}var $t=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):Lu(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),Bn(this);}};var Vt=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 $t){let a=fa.get(t);a||(a=new Set,fa.set(t,a)),a.add(this);let r=bo.get(this);r||(r=new Set,bo.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 $t){let a=fa.get(t);a&&a.delete(this);let r=bo.get(this);r&&r.delete(t);}}};function Zg(e){return typeof e=="function"}function Vi(e,...o){return Zg(e)?e(...o):e}function Iu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ma,ot,Je,fr,pa,Ba,Zt,vo,mr,On,pr,yo,Oa=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Te(this,ma,true);Te(this,ot);Te(this,Je);Te(this,fr);Te(this,pa);Te(this,Ba);Te(this,Zt);Te(this,vo);Te(this,mr,0);Te(this,On,5);Te(this,pr,()=>{this.debugLog("Connected to event bus"),ke(this,Ba,true),this.debugLog("Emitting queued events",_(this,pa)),_(this,pa).forEach(o=>this.emitEventToBus(o)),ke(this,pa,[]),this.stopConnectLoop(),_(this,Je).call(this).removeEventListener("tanstack-connect-success",_(this,pr));});Te(this,yo,()=>{if(_(this,Je).call(this).addEventListener("tanstack-connect-success",_(this,pr)),_(this,mr)<_(this,On)){td(this,mr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,Je).call(this).removeEventListener("tanstack-connect",_(this,yo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});ke(this,ot,o),ke(this,ma,a),ke(this,Je,this.getGlobalTarget),ke(this,fr,t),this.debugLog(" Initializing event subscription for plugin",_(this,ot)),ke(this,pa,[]),ke(this,Ba,false),ke(this,Zt,null),ke(this,vo,r);}startConnectLoop(){_(this,Zt)!==null||_(this,Ba)||(this.debugLog(`Starting connect loop (every ${_(this,vo)}ms)`),ke(this,Zt,setInterval(_(this,yo),_(this,vo))));}stopConnectLoop(){_(this,Zt)!==null&&(clearInterval(_(this,Zt)),ke(this,Zt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,fr)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,ot)}-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 _(this,ot)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,Je).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,Je).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(!_(this,ma)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!_(this,Ba)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,pa).push({type:`${_(this,ot)}:${o}`,payload:t,pluginId:_(this,ot)}),typeof CustomEvent<"u"&&(_(this,yo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,ot)}:${o}`,payload:t,pluginId:_(this,ot)})}on(o,t){let a=`${_(this,ot)}:${o}`;if(!_(this,ma))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 _(this,Je).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{_(this,Je).call(this).removeEventListener(a,r);}}onAll(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;_(this,ot)&&r.pluginId!==_(this,ot)||o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}};ma=new WeakMap,ot=new WeakMap,Je=new WeakMap,fr=new WeakMap,pa=new WeakMap,Ba=new WeakMap,Zt=new WeakMap,vo=new WeakMap,mr=new WeakMap,On=new WeakMap,pr=new WeakMap,yo=new WeakMap;var qi=class extends Oa{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Su=(e,o)=>{Hi.emit(e,o);},Hi=new qi;function Cu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Qg={enabled:true,leading:true,trailing:true,wait:0},ha,pt,Na,Va,qa,wo,Nn=class{constructor(o,t){Te(this,ha);Te(this,pt);Te(this,Na);Te(this,Va);Te(this,qa);Te(this,wo);this.fn=o,this.store=new $t(Cu()),this.setOptions=a=>{this.options={...this.options,...a},_(this,Na).call(this)||this.cancel();},ke(this,pt,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:s}=n;return {...n,status:_(this,Na).call(this)?s?"pending":"idle":"disabled"}}),Su("Throttler",this);}),ke(this,Na,()=>!!Vi(this.options.enabled,this)),ke(this,Va,()=>Vi(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,pt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,s=_(this,Va).call(this);if(this.options.leading&&n>=s)_(this,qa).call(this,...a);else if(_(this,pt).call(this,{lastArgs:a}),!_(this,ha)&&this.options.trailing){let i=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,l=s-i;_(this,pt).call(this,{isPending:true}),ke(this,ha,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&_(this,qa).call(this,...d);},l));}},ke(this,qa,(...a)=>{if(!_(this,Na).call(this))return;this.fn(...a);let r=Date.now(),n=r+_(this,Va).call(this);_(this,wo).call(this),_(this,pt).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||_(this,pt).call(this,{nextExecutionTime:void 0});},_(this,Va).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,qa).call(this,...this.store.state.lastArgs);},ke(this,wo,()=>{_(this,ha)&&(clearTimeout(_(this,ha)),ke(this,ha,void 0));}),this.cancel=()=>{_(this,wo).call(this),_(this,pt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,pt).call(this,Cu());},this.key=Iu(t.key),this.options={...Qg,...t},_(this,pt).call(this,this.options.initialState??{}),Hi.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,pt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ha=new WeakMap,pt=new WeakMap,Na=new WeakMap,Va=new WeakMap,qa=new WeakMap,wo=new WeakMap;function Ui(e,o){return new Nn(e,o).maybeExecute}function ga(e,o){return typeof e=="function"?e(o):e}function xa(e,o){return Un(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Lo(e,o,t){let a=Un(o);function r(n){if(!a.length)return ga(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 zi(e,o){let t=Un(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((d,m)=>m!==s);let{[s]:i,...l}=r;return l}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 ex=/^(\d+)$/gm,tx=/\.(\d+)(?=\.)/gm,ax=/^(\d+)\./gm,ox=/\.(\d+$)/gm,rx=/\.{2,}/gm,Wi="__int__",Vn=`${Wi}$1`;function Un(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(ex,Vn).replace(tx,`.${Vn}.`).replace(ax,`${Vn}.`).replace(ox,`.${Vn}`).replace(rx,".").split(".").map(o=>{if(o.startsWith(Wi)){let t=o.substring(Wi.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Gi(e){return !(Array.isArray(e)&&e.length===0)}function Io(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 So(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},s=t??0,i=l=>l.validators.filter(Boolean).map(d=>{let m=d?.cause||e,u=s;switch(m){case "change":u=r??s;break;case "blur":u=a??s;break;case "dynamic":u=n??s;break;case "submit":u=0;break}return e==="submit"&&(u=0),{cause:m,validate:d.fn,debounceMs:u}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:i})}var hr=e=>!!e&&typeof e=="object"&&"fields"in e;function ba(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)||!ba(e[r],o[r]))return false;return true}var Wn=({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},zn=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function ze(e,o){return e==null?o:{...e,...o}}var Ha=256,Hn=[],qn;for(;Ha--;)Hn[Ha]=(Ha+256).toString(16).substring(1);function Ki(){let e=0,o,t="";if(!qn||Ha+16>256){for(qn=new Array(256),e=256;e--;)qn[e]=256*Math.random()|0;e=0,Ha=0;}for(;e<16;e++)o=qn[Ha+e],e===6?t+=Hn[o&15|64]:e===8?t+=Hn[o&63|128]:t+=Hn[o],e&1&&e>1&&e<11&&(t+="-");return Ha++,t}var va=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 nx(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 l=r[i];if(l===void 0)continue;let d=typeof l=="object"?l.key:l,m=Number(d);Array.isArray(n)&&!Number.isNaN(m)?s+=`[${m}]`:s+=(i>0?".":"")+String(d),typeof n=="object"&&n!==null?n=n[d]:n=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var ku=(e,o)=>{let t=nx(e,o);return {form:t,fields:t}},ya={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:ku(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:ku(a.issues,e)}},Gn=e=>!!e&&"~standard"in e;var Co={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function gr(e){function o(u,f,c,p){let g=a(u,f,c,p);({insert:()=>i(g,u,f),remove:()=>l(g),swap:()=>p!==void 0&&m(g,u,f,p),move:()=>p!==void 0&&d(g,u,f,p)})[c]();}function t(u,f){return `${u}[${f}]`}function a(u,f,c,p){let g=[t(u,f)];if(c==="swap")g.push(t(u,p));else if(c==="move"){let[h,w]=[Math.min(f,p),Math.max(f,p)];for(let b=h;b<=w;b++)g.push(t(u,b));}else {let h=e.getFieldValue(u),w=Array.isArray(h)?h.length:0;for(let b=f+1;b<w;b++)g.push(t(u,b));}return Object.keys(e.fieldInfo).filter(h=>g.some(w=>h.startsWith(w)))}function r(u,f){return u.replace(/\[(\d+)\]/,(c,p)=>{let g=parseInt(p,10);return `[${f==="up"?g+1:Math.max(0,g-1)}]`})}function n(u,f){(f==="up"?u:[...u].reverse()).forEach(p=>{let g=r(p.toString(),f),h=e.getFieldMeta(g);h?e.setFieldMeta(p,h):e.setFieldMeta(p,s());});}let s=()=>Co,i=(u,f,c)=>{n(u,"down"),u.forEach(p=>{p.toString().startsWith(t(f,c))&&e.setFieldMeta(p,s());});},l=u=>{n(u,"up");},d=(u,f,c,p)=>{let g=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(f,c))).map(h=>[h,e.getFieldMeta(h)]));n(u,c<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(f,p))).forEach(h=>{let w=h.replace(t(f,p),t(f,c)),b=g.get(w);b&&e.setFieldMeta(h,b);});},m=(u,f,c,p)=>{u.forEach(g=>{if(!g.toString().startsWith(t(f,c)))return;let h=g.toString().replace(t(f,c),t(f,p)),[w,b]=[e.getFieldMeta(g),e.getFieldMeta(h)];w&&e.setFieldMeta(h,w),b&&e.setFieldMeta(g,b);});};return {handleArrayFieldMetaShift:o}}var _i=class extends Oa{constructor(){super({pluginId:"form-devtools"});}},ht=new _i;function ji(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 br=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),ht.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return ht.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((l,d)=>l!==this.prevTransformArray[d]),s=a.defaultValues&&!ba(a.defaultValues,r.defaultValues)&&!this.state.isTouched,i=!ba(a.defaultState,r.defaultState)&&!this.state.isTouched;!s&&!i&&!n||(mt(()=>{this.baseStore.setState(()=>ji(Object.assign({},this.state,i?a.defaultState:{},s?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),ht.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(()=>ji({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let r=[];return mt(()=>{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(l=>({...l,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,l=[`${a}[${r}]`];for(let f=r+1;f<=(i??0);f++)l.push(`${a}[${f}]`);let d=Object.keys(this.fieldInfo).filter(f=>l.some(c=>f.startsWith(c))),m=[];return mt(()=>{d.forEach(f=>{m.push(Promise.resolve().then(()=>this.validateField(f,n)));});}),(await Promise.all(m)).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=Io(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va}),n=false,s={};return mt(()=>{for(let d of r){if(!d.validate)continue;let m=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:u,fieldErrors:f}=Kn(m),c=xr(d.cause);for(let p of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[p]===void 0)continue;let g=this.getFieldMeta(p);if(!g)continue;let{errorMap:h,errorSourceMap:w}=g,b=f?.[p],{newErrorValue:v,newSource:L}=Wn({newFormValidatorError:b,isPreviousErrorFromFormValidator:w?.[c]==="form",previousErrorValue:h?.[c]});L==="form"&&(s[p]={...s[p],[c]:b}),h?.[c]!==v&&this.setFieldMeta(p,k=>({...k,errorMap:{...k.errorMap,[c]:v},errorSourceMap:{...k.errorSourceMap,[c]:L}}));}this.state.errorMap?.[c]!==u&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[c]:u}})),(u||f)&&(n=!0);}let i=xr("submit");this.state.errorMap?.[i]&&a!=="submit"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));let l=xr("server");this.state.errorMap?.[l]&&a!=="server"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[l]:void 0}}));}),{hasErrored:n,fieldsErrorMap:s}},this.validateAsync=async a=>{let r=So(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let n=[],s;for(let d of r){if(!d.validate)continue;let m=xr(d.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let f=new AbortController;this.state.validationMetaMap[m]={lastAbortController:f},n.push(new Promise(async c=>{let p;try{p=await new Promise((b,v)=>{setTimeout(async()=>{if(f.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:f.signal},type:"validateAsync"}));}catch(L){v(L);}},d.debounceMs);});}catch(b){p=b;}let{formError:g,fieldErrors:h}=Kn(p);h&&(s=s?{...s,...h}:h);let w=xr(d.cause);for(let b of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[b]===void 0)continue;let v=this.getFieldMeta(b);if(!v)continue;let{errorMap:L,errorSourceMap:k}=v,S=s?.[b],{newErrorValue:I,newSource:x}=Wn({newFormValidatorError:S,isPreviousErrorFromFormValidator:k?.[w]==="form",previousErrorValue:L?.[w]});L?.[w]!==I&&this.setFieldMeta(b,A=>({...A,errorMap:{...A.errorMap,[w]:I},errorSourceMap:{...A.errorSourceMap,[w]:x}}));}this.baseStore.setState(b=>({...b,errorMap:{...b.errorMap,[w]:g}})),c(s?{fieldErrors:s,errorMapKey:w}:void 0);}));}let i=[],l={};if(n.length){i=await Promise.all(n);for(let d of i)if(d?.fieldErrors){let{errorMapKey:m}=d;for(let[u,f]of Object.entries(d.fieldErrors)){let p={...l[u]||{},[m]:f};l[u]=p;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),l},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>xa(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]:ga(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let s=n;return r[s]=Co,r},{}),this.setFieldValue=(a,r,n)=>{let s=n?.dontUpdateMeta??false,i=n?.dontRunListeners??false,l=n?.dontValidate??false;mt(()=>{s||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Lo(d.values,a,r)}));}),i||this.getFieldInfo(a).instance?.triggerOnChangeListener(),l||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(l=>{i.values=zi(i.values,l),delete this.fieldInfo[l],delete i.fieldMetaBase[l];}),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,l=>[...l.slice(0,r),n,...l.slice(r)],ze(s,{dontValidate:true}));let i=s?.dontValidate??false;i||await this.validateField(a,"change"),gr(this).handleArrayFieldMetaShift(a,r,"insert"),i||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,l=>l.map((d,m)=>m===r?n:d),ze(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,d=>d.filter((m,u)=>u!==r),ze(n,{dontValidate:true})),gr(this).handleArrayFieldMetaShift(a,r,"remove"),i!==null){let d=`${a}[${i}]`;this.deleteField(d);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,s)=>{this.setFieldValue(a,l=>{let d=l[r],m=l[n];return Lo(Lo(l,`${r}`,m),`${n}`,d)},ze(s,{dontValidate:true})),gr(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,l=>{let d=[...l];return d.splice(n,0,d.splice(r,1)[0]),d},ze(s,{dontValidate:true})),gr(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,[],ze(r,{dontValidate:true})),s!==null)for(let l=0;l<=s;l++){let d=`${a}[${l}]`;this.deleteField(d);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Co},values:this.options.defaultValues?Lo(r.values,a,xa(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=>ya.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ya.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Ki(),this._devtoolsSubmissionOverride=false,this.baseStore=new $t(ji({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Vt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,i=a?.[0],l=r[0],d=0,m={};for(let u of Object.keys(l.fieldMetaBase)){let f=l.fieldMetaBase[u],c=i?.fieldMetaBase[u],p=s?.[u],g=xa(l.values,u),h=p?.errors;if(!c||f.errorMap!==c.errorMap){h=Object.values(f.errorMap??{}).filter(k=>k!==void 0);let L=this.getFieldInfo(u)?.instance;L&&!L.options.disableErrorFlat&&(h=h?.flat(1));}let w=!Gi(h??[]),b=!f.isDirty,v=ba(g,xa(this.options.defaultValues,u))||ba(g,this.getFieldInfo(u)?.instance?.options.defaultValue);if(p&&p.isPristine===b&&p.isValid===w&&p.isDefaultValue===v&&p.errors===h&&f===c){m[u]=p,d++;continue}m[u]={...f,errors:h,isPristine:b,isValid:w,isDefaultValue:v};}return Object.keys(l.fieldMetaBase).length&&s&&d===Object.keys(l.fieldMetaBase).length?s:m}}),this.store=new Vt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,i=a?.[0],l=r[0],d=r[1],m=Object.values(d).filter(Boolean),u=m.some(T=>T.isValidating),f=m.every(T=>T.isValid),c=m.some(T=>T.isTouched),p=m.some(T=>T.isBlurred),g=m.every(T=>T.isDefaultValue),h=c&&l.errorMap?.onMount,w=m.some(T=>T.isDirty),b=!w,v=!!(l.errorMap?.onMount||m.some(T=>T?.errorMap?.onMount)),L=!!u,k=s?.errors??[];(!i||l.errorMap!==i.errorMap)&&(k=Object.values(l.errorMap).reduce((T,W)=>W===void 0?T:W&&hr(W)?(T.push(W.form),T):(T.push(W),T),[]));let S=k.length===0,I=f&&S,x=this.options.canSubmitWhenInvalid??false,A=l.submissionAttempts===0&&!c&&!v||!L&&!l.isSubmitting&&I||x,V=l.errorMap;if(h&&(k=k.filter(T=>T!==l.errorMap.onMount),V=Object.assign(V,{onMount:void 0})),s&&i&&s.errorMap===V&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===k&&s.isFieldsValidating===u&&s.isFieldsValid===f&&s.isFormValid===S&&s.isValid===I&&s.canSubmit===A&&s.isTouched===c&&s.isBlurred===p&&s.isPristine===b&&s.isDefaultValue===g&&s.isDirty===w&&ba(i,l))return s;let D={...l,errorMap:V,fieldMeta:this.fieldMetaDerived.state,errors:k,isFieldsValidating:u,isFieldsValid:f,isFormValid:S,isValid:I,canSubmit:A,isTouched:c,isBlurred:p,isPristine:b,isDefaultValue:g,isDirty:w},q=this.options.transform?.deps??[];if(q.length!==this.prevTransformArray.length||q.some((T,W)=>T!==this.prevTransformArray[W])){let T=Object.assign({},this,{state:D});this.options.transform?.fn(T),D=T.state,this.prevTransformArray=q;}return D}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Ui(a=>ht.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),ht.on("request-form-state",a=>{a.payload.id===this._formId&&ht.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),ht.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),ht.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 Gn(o.validate)?ya[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})),mt(()=>{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}),ht.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}),ht.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}mt(()=>{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}),mt(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),ht.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),ht.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){mt(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(hr(a)){let{formError:n,fieldErrors:s}=Kn(a);for(let i of Object.keys(this.fieldInfo))this.getFieldMeta(i)&&this.setFieldMeta(i,d=>({...d,errorMap:{...d.errorMap,[r]:s?.[i]},errorSourceMap:{...d.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 Kn(e){if(e){if(hr(e)){let o=Kn(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function xr(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 vr=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=xa(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,ze(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,ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,ze(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=Io(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),s=this.getLinkedFields(t).reduce((d,m)=>{let u=Io(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||va});return u.forEach(f=>{f.field=m;}),d.concat(u)},[]),i=false;mt(()=>{let d=(m,u)=>{let f=_n(u.cause),c=u.validate?Mu(m.runValidator({validate:u.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,p=a[f],{newErrorValue:g,newSource:h}=zn({formLevelError:p,fieldLevelError:c});m.state.meta.errorMap?.[f]!==g&&m.setMeta(w=>({...w,errorMap:{...w.errorMap,[f]:g},errorSourceMap:{...w.errorSourceMap,[f]:h}})),g&&(i=!0);};for(let m of r)d(this,m);for(let m of s)m.validate&&d(m.field,m);});let l=_n("submit");return this.state.meta.errorMap?.[l]&&t!=="submit"&&!i&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[l]:void 0},errorSourceMap:{...d.errorSourceMap,[l]:void 0}})),{hasErrored:i}},this.validateAsync=async(t,a)=>{let r=So(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),n=await a,s=this.getLinkedFields(t),i=s.reduce((f,c)=>{let p=So(t,{...c.options,form:c.form,validationLogic:c.form.options.validationLogic||va});return p.forEach(g=>{g.field=c;}),f.concat(p)},[]);this.state.meta.isValidating||this.setMeta(f=>({...f,isValidating:true}));for(let f of s)f.setMeta(c=>({...c,isValidating:true}));let l=[],d=[],m=(f,c,p)=>{let g=_n(c.cause);f.getInfo().validationMetaMap[g]?.lastAbortController.abort();let w=new AbortController;this.getInfo().validationMetaMap[g]={lastAbortController:w},p.push(new Promise(async b=>{let v;try{v=await new Promise((x,A)=>{this.timeoutIds.validations[c.cause]&&clearTimeout(this.timeoutIds.validations[c.cause]),this.timeoutIds.validations[c.cause]=setTimeout(async()=>{if(w.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:c.validate,value:{value:f.store.state.value,fieldApi:f,signal:w.signal,validationSource:"field"},type:"validateAsync"}));}catch(V){A(V);}},c.debounceMs);});}catch(x){v=x;}if(w.signal.aborted)return b(void 0);let L=Mu(v),k=n[this.name]?.[g],{newErrorValue:S,newSource:I}=zn({formLevelError:k,fieldLevelError:L});f.setMeta(x=>({...x,errorMap:{...x?.errorMap,[g]:S},errorSourceMap:{...x.errorSourceMap,[g]:I}})),b(S);}));};for(let f of r)f.validate&&m(this,f,l);for(let f of i)f.validate&&m(f.field,f,d);let u=[];(l.length||d.length)&&(u=await Promise.all(l),await Promise.all(d)),this.setMeta(f=>({...f,isValidating:false}));for(let f of s)f.setMeta(c=>({...c,isValidating:false}));return u.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[_n(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=>ya.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ya.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Vt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Co,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Gn(o.validate)?ya[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 Mu(e){if(e)return e}function _n(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 jn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,ix)}function ix(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=Tu(e);if(t.length!==Tu(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 Tu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var ko=typeof window<"u"?useLayoutEffect:useEffect;function px(e){let[o]=useState(()=>{let a=new vr({...e,form:e.form,name:e.name});return a.Field=$i,a});return ko(o.mount,[o]),ko(()=>{o.update(e);}),jn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var $i=(({children:e,...o})=>{let t=px(o),a=useMemo(()=>ga(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function xx({form:e,selector:o,children:t}){let a=jn(e.store,o);return ga(t,a)}function Xi(e){let o=useId(),[t]=useState(()=>{let a=new br({...e,formId:o}),r=a;return r.Field=function(s){return jsx($i,{...s,form:a})},r.Subscribe=function(s){return jsx(xx,{form:a,selector:s.selector,children:s.children})},r});return ko(t.mount,[]),ko(()=>{t.update(e);}),t}function Yi({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 Mx=({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),l=Xi({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:u})=>{if(u.questionType==="true-false"){let f={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctAnswer:u.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?la(f):_s(f));}else if(u.questionType==="multiple-choice"){let f={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctIndex:u.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?ia(f):Ks(f));}else if(u.questionType==="short-answer"){let f={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.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?zo(f):js(f));}else if(u.questionType==="fill-in-the-blank"){let f={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.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?Ko(f):Xs(f));}else if(u.questionType==="long-answer"){let f={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctLongAnswer:u.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?Go(f):$s(f));}o(da(false));}}),d=()=>{o(da(false));},m=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:u=>{u.preventDefault(),u.stopPropagation(),l.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:()=>{d();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(l.Field,{name:"questionType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:f=>{u.handleChange(f.target.value),i(f.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(Yi,{field:u})]})}),s&&!["short-answer","fill-in-the-blank","long-answer"].includes(s)&&jsx(l.Field,{name:"responseType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:f=>u.handleChange(f.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(Yi,{field:u})]})})]}),jsx(l.Field,{name:"feedbackMode",children:u=>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:()=>u.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.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:()=>u.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.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(Yi,{field:u})]})}),jsx(l.Field,{name:"question",validators:{onChange:({value:u})=>u?void 0:"A question is required"},children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.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:u.state.value,onChange:f=>u.handleChange(f.target.value),onBlur:u.handleBlur,placeholder:"Enter Your Question"})}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="true-false"&&jsx(l.Field,{name:"responseOptions.correctAnswer",children:u=>{let f=u.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:()=>u.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${f===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"}),f===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:()=>u.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${f===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"}),f===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(l.Field,{name:"responseOptions",validators:{onChange:({value:u})=>{if(u.options.filter(c=>!c.trim()).length>0)return "All options must have text";if(!u.correctIndex||u.correctIndex.length===0)return "Please select at least one correct answer"}},children:u=>{let f=(h,w)=>{let b=[...u.state.value.options];b[h]=w,u.handleChange({...u.state.value,options:b});},c=()=>{if(u.state.value.options.length>=6){alert("Maximum 6 options allowed");return}u.handleChange({...u.state.value,options:[...u.state.value.options,""]});},p=h=>{if(u.state.value.options.length<=2){alert("Minimum 2 options required");return}let w=u.state.value.options.filter((v,L)=>L!==h),b=u.state.value.correctIndex?.filter(v=>v!==h).map(v=>v>h?v-1:v);u.handleChange({...u.state.value,options:w,correctIndex:b});},g=h=>{let w=u.state.value.correctIndex||[];if(w.includes(h))u.handleChange({...u.state.value,correctIndex:w.filter(v=>v!==h)});else {if(w.length>=6){alert("Maximum 6 correct answers allowed");return}u.handleChange({...u.state.value,correctIndex:[...w,h]});}};return jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:u.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:u.state.value.options.map((h,w)=>{let b=!h.trim(),v=u.state.value.correctIndex?.includes(w),L=u.state.meta.isTouched&&b;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>g(w),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${v?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:v&&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 ${L?"border-red-500 bg-red-50":v?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${w+1}`,value:h,onChange:k=>f(w,k.target.value),onBlur:u.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),u.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(w),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},w)})}),jsx("button",{type:"button",onClick:c,disabled:u.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"}),u.state.value.correctIndex.length===0||u.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:u.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(l.Field,{name:"responseOptions.correctShortAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:u.state.value,onChange:f=>{u.handleChange(f.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)."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="long-answer"&&jsx(l.Field,{name:"responseOptions.correctLongAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.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:u.state.value,onChange:f=>{u.handleChange(f.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."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),jsx(l.Subscribe,{selector:u=>[u.canSubmit,u.isSubmitting],children:([u,f])=>jsx("button",{type:"submit",disabled:!u,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:f?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(m,document.body)},Du=Mx;var Ru=({text:e,position:o})=>{let t=xe(),a=d=>{t(de()),t(St({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},r=d=>{t(de()),t(St({id:e.id,fill:d}));},n=()=>{t(de()),t(St({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},s=()=>{t(de()),t(St({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},i=()=>{t(de()),t(St({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},l=d=>{t(de()),t(St({id:e.id,fontFamily:d}));};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:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>l(d.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:d=>r(d.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var Fu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:s})=>{let i=useRef(null),l=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]),d=useCallback(m=>{m.style.height="auto",m.style.height=`${m.scrollHeight}px`;let u=document.createElement("span");u.style.font=window.getComputedStyle(m).font,u.style.fontSize=m.style.fontSize,u.style.fontFamily=m.style.fontFamily,u.style.fontWeight=m.style.fontWeight,u.style.fontStyle=m.style.fontStyle,u.style.visibility="hidden",u.style.position="absolute",u.style.whiteSpace="pre";let f=m.value.split(`
4
- `),c=0;document.body.appendChild(u);for(let g of f){u.textContent=g||" ";let h=u.offsetWidth;h>c&&(c=h);}document.body.removeChild(u);let p=10;m.style.width=`${Math.max(200,c+p+20)}px`;},[]);return useEffect(()=>{let m=i.current;m&&(m.style.fontSize=`${e.fontSize*n}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,d(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,d]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(i.current=m,s.current=m,m){m.focus();let u=m.value.length;m.setSelectionRange(u,u),d(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:l},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Bu=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(T=>T.toolbar.selectedTool),i=s==="pen"||s==="eraser",l=useRef(null),[d,m]=useState(""),[u,f]=useState(false),[c,p]=useState(null);useEffect(()=>{let T=l.current;if(T)return a.current.set(e.id,T),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===g,w=()=>{f(false),m("");},b=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",v=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,k=60,S=u?40:0,I=u?54:20,x=50,A=12,V=e.data.feedbackMode==="practice"?48:0,D=12,q=30,U=k+S+q+x+A+D+V+L;return jsxs(Group,{ref:l,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:U,name:"sa-element",...i?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:U,onTransformEnd:T=>t(e.id,T),onContextMenu:T=>{T.cancelBubble=true,r(T.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:k+S+q-I,width:e.width-L*2+4,height:x+6,fill:"#ffffff",stroke:h?"#22c55e":u?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:k+S+q-I},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${x}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:T=>m(T.target.value),disabled:u,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:u?"none":"auto"}})}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:k+80,width:e.width/2+24,height:S,fill:v().bg,cornerRadius:8}),jsx(Text,{x:36,y:k+80,width:e.width-L*2,height:S,text:b(),fontSize:12,fontStyle:"bold",fill:v().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:k+S+q+x+A+D,children:[jsxs(Group,{onMouseDown:T=>{T.cancelBubble=true,p("check");},onMouseUp:T=>{T.cancelBubble=true,p(null),d.length>0&&f(true);},onMouseLeave:T=>{T.cancelBubble=true,p(null);},onTouchStart:T=>{T.cancelBubble=true,p("check");},onTouchEnd:T=>{T.cancelBubble=true,p(null),d.length>0&&f(true);},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,fill:d.length===0||u?"#9ca3af":"#096B76",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,text:u?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),u&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),w();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),w();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.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})]})]})]})});Bu.displayName="ShortAnswer";var Ou=Bu;var Vu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(Ou,{shortAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>n(i,s.id)},s.id))});var qu=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((s,i)=>{let l=s.target;o(Ko({id:i,x:l.x(),y:l.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var Tt=24,Qi=51,Cr=64,Hu=15,Jn=32,Uu=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n})=>{let s=useSelector(x=>x.toolbar.selectedTool),i=s==="pen"||s==="eraser",l=useRef(null),[d,m]=useState(""),[u,f]=useState(false),[c,p]=useState(null);useEffect(()=>{let x=l.current;if(x)return n.current.set(e.id,x),()=>{n.current.delete(e.id);}},[e.id,n]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===g,w=()=>{f(false),m("");},b=()=>{d.length>0&&f(true);},v=e.width-Tt*2,L=(v-Hu)/2,k=e.data.feedbackMode==="practice",S=useMemo(()=>{let x=Tt,A=x;x+=60;let V=x;x+=35;let D=x;x+=Qi+16;let q=x;u&&(x+=Jn+16);let U=x;return k&&(x+=Cr),x+=Tt,{questionY:A,helperTextY:V,inputY:D,feedbackY:q,buttonsY:U,totalHeight:x}},[u,k]),I=()=>u?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:l,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...i?{}:{onDragEnd:x=>a(x,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:S.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:x=>t(e.id,x),onContextMenu:x=>{x.cancelBubble=true,r?.(x.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Tt,y:S.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:v,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Tt,y:S.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:v,listening:false}),jsx(Rect,{x:Tt,y:S.inputY,width:v,height:Qi,fill:"#ffffff",stroke:I(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Tt,y:S.inputY},divProps:{style:{width:`${v}px`,height:`${Qi}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:x=>m(x.target.value),disabled:u,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),u&&jsxs(Group,{y:S.feedbackY,children:[jsx(Rect,{x:Tt,width:h?206:140,height:Jn,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Tt+10,y:0,width:16,height:Jn,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Tt+30,y:0,height:Jn,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),k&&jsxs(Group,{y:S.buttonsY,children:[jsxs(Group,{x:Tt,onMouseDown:x=>{x.cancelBubble=true,p("reset");},onMouseUp:x=>{x.cancelBubble=true,p(null),w();},onMouseLeave:x=>{x.cancelBubble=true,p(null);},onTouchStart:x=>{x.cancelBubble=true,p("reset");},onTouchEnd:x=>{x.cancelBubble=true,p(null),w();},scaleX:c==="reset"?.98:1,scaleY:c==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Cr,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Cr,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Tt+L+Hu,onMouseDown:x=>{x.cancelBubble=true,p("submit");},onMouseUp:x=>{x.cancelBubble=true,p(null),b();},onMouseLeave:x=>{x.cancelBubble=true,p(null);},onTouchStart:x=>{x.cancelBubble=true,p("submit");},onTouchEnd:x=>{x.cancelBubble=true,p(null),b();},scaleX:c==="submit"?.98:1,scaleY:c==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Cr,fill:d.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Cr,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Uu.displayName="FillInTheBlanks";var Wu=Uu;var Gu=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n})=>jsx(Fragment,{children:e.map(s=>jsx(Wu,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n},s.id))});var ol=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(U=>U.toolbar.selectedTool),i=s==="pen"||s==="eraser",l=useRef(null),[d,m]=useState(""),[u,f]=useState(false),[c,p]=useState(null);useEffect(()=>{let U=l.current;if(U)return a.current.set(e.id,U),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===g,w=()=>{f(false),m("");},b=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",v=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,k=60,S=u?60:0,I=120,x=12,A=48,V=12,D=30,q=k+S+D+I+x+V+A+L;return jsxs(Group,{ref:l,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:U=>{let T=l.current?.getStage()?.getPointerPosition();if(!T||!r)return;let W={x:e.x,y:e.y,width:e.width,height:e.height};T.x>=W.x&&T.x<=W.x+W.width&&T.y>=W.y&&T.y<=W.y+W.height&&r(U.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:q,onTransformEnd:U=>t(e.id,U)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:k,width:e.width-L*2,height:S,fill:v().bg,cornerRadius:8}),jsx(Text,{x:L,y:k,width:e.width-L*2,height:S,text:b(),fontSize:14,fontStyle:"bold",fill:v().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:k+S+x,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:k+S+D,width:e.width-L*2,height:I,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:k+S+D},divProps:{style:{width:`${e.width-L*2}px`,height:`${I}px`,pointerEvents:u?"none":"auto"}},children:jsx("textarea",{value:d,onChange:U=>m(U.target.value),disabled:u,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,useMemo,createElement,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 dd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X as X$1,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,CaretLeft,Plus,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {EyeIcon,Stack as Stack$1,X as X$2,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 du 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 ed=e=>{throw TypeError(e)};var td=(e,o,t)=>o.has(e)||ed("Cannot "+t);var _=(e,o,t)=>(td(e,o,"read from private field"),t?t.call(e):o.get(e)),Te=(e,o,t)=>o.has(e)?ed("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),ke=(e,o,t,a)=>(td(e,o,"write to private field"),o.set(e,t),t);var ad=(e,o,t,a)=>({set _(r){ke(e,o,r);},get _(){return _(e,o,a)}});var xe=()=>useDispatch(),te=e=>useSelector(e),et=xe,ut=te;var Cs=20,ks=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(),isActive:true}),Is=ks("Slide 1"),Tm={slides:[Is],currentSlideId:Is.id,history:{[Is.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false},od=createSlice({name:"canvas",initialState:Tm,reducers:{addSlide:e=>{if(e.slides.length>=Cs)return;let o=ks(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(i=>i.isActive).length<=1)return;let n=e.slides.findIndex(i=>i.id===t);if(n===-1)return;let s=e.slides[n];if(a?(s.isActive=false,s.updatedAt=Date.now()):(e.slides.splice(n,1),delete e.history[t]),e.currentSlideId===t){let i=e.slides.filter(l=>l.isActive);i.length>0&&(e.currentSlideId=i[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=Cs)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(),isActive:true,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,isActive:t.isActive!==void 0?t.isActive:true})),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(x=>x.id===a);s&&(s.timestamp=n);break;case "video":let i=t.videos.find(x=>x.id===a);i&&(i.timestamp=n);break;case "shape":let l=t.shapes.find(x=>x.id===a);l&&(l.timestamp=n);break;case "text":let d=t.texts.find(x=>x.id===a);d&&(d.timestamp=n);break;case "flashcard":let f=t.flashcards.find(x=>x.id===a);f&&(f.timestamp=n);break;case "photoFrame":let u=t.photoFrames.find(x=>x.id===a);u&&(u.timestamp=n);break;case "mcq":let c=t.multipleChoices.find(x=>x.id===a);c&&(c.timestamp=n);break;case "trueFalse":let m=t.trueFalses.find(x=>x.id===a);m&&(m.timestamp=n);break;case "shortAnswer":let p=t.shortAnswers.find(x=>x.id===a);p&&(p.timestamp=n);break;case "longAnswer":let g=t.LongAnswer.find(x=>x.id===a);g&&(g.timestamp=n);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(x=>x.id===a);h&&(h.timestamp=n);break;case "line":let y=t.lines.find(x=>x.id===a);y&&(y.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(l=>l.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(l=>l.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(l=>l.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.backgroundColor="#fff",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;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;}}}),{addSlide:Ms,deleteSlide:Ts,duplicateSlide:As,setCurrentSlide:Ps,updateSlideThumbnail:Ds,setBackgroundColor:Rs,reorderSlides:Am,loadSlides:to,addLine:Es,removeLine:Gr,addImage:Fs,updateImage:ao,deleteImage:Kr,duplicateImage:_r,addVideo:jr,updateVideo:$r,deleteVideo:Xr,duplicateVideo:Yr,toggleVideoPlaying:Uo,addShape:Bs,updateShape:oo,duplicateShape:Jr,deleteShape:Zr,addText:Os,updateText:It,deleteText:Qr,duplicateText:en,addFlashcard:Ns,updateFlashcard:ro,deleteFlashcard:tn,duplicateFlashcard:an,editFlashcard:Wo,nextFlashcard:Vs,previousFlashcard:qs,addPhotoFrame:Hs,updatePhotoFrame:Aa,deletePhotoFrame:on,duplicatePhotoFrame:rn,toggleImageDrawingMode:Us,addImageAnnotation:Ws,updateImageAnnotation:Pm,clearImageAnnotations:Dm,togglePhotoFrameDrawingMode:zs,addPhotoFrameAnnotation:Gs,updatePhotoFrameAnnotation:Rm,clearPhotoFrameAnnotations:Em,addMultipleChoice:Ks,updateMultipleChoice:ia,editMultipleChoice:Fm,deleteMultipleChoice:nn,duplicateMultipleChoice:sn,addTrueFalse:_s,updateTrueFalse:la,deleteTrueFalse:ln,duplicateTrueFalse:dn,addShortAnswer:js,updateShortAnswer:zo,deleteShortAnswer:un,duplicateShortAnswer:cn,addLongAnswer:$s,updateLongAnswer:Go,deleteLongAnswer:fn,duplicateLongAnswer:mn,addFillInTheBlanks:Xs,updateFillInTheBlanks:Ko,deleteFillInTheBlanks:pn,duplicateFillInTheBlanks:hn,setShowMcqForm:da,setShowFlashcardForm:Pa,setActivityType:Ys,setEditingActivity:_o,bringToFront:Js,sendToBack:Zs,toggleLock:Qs,setLink:gn,setAltText:xn,setAudioData:bn,updateLastLine:Bm,finalizeDrawing:ei,setLines:Om,updateLinePosition:Nm,updateLineTransform:vn,deleteLineById:yn,duplicateLine:ti,updateElementOrder:jo,clearCanvas:ai,undo:oi,redo:ri,saveToHistory:ue,toggleSketchMode:Vm,setSketchMode:ct,setEditingTextId:$o,setPresentationTitle:ni,setPresentationDescription:si,loadPresentationMetadata:ii,setMetadataLoaded:wn}=od.actions;var Xo=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},Yo=e=>e.canvas.slides.filter(o=>o.isActive),li=e=>e.canvas.slides,di=e=>e.canvas.slides.filter(o=>o.isActive).length<Cs,qm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},Jo=e=>e.canvas.presentationMetadata,ui=e=>e.canvas.metadataLoaded,rd=od.reducer;var sd=e=>{let o=xe(),t=useRef(null),a=useRef(false),r=te(m=>m.toolbar.selectedTool),n=te(m=>m.toolbar.penColor),s=te(m=>m.toolbar.strokeWidth),i=te(m=>m.canvas.isSketchMode),l=te(m=>m.canvas.slides.find(g=>g.id===m.canvas.currentSlideId)?.lines||[]),d=useCallback(m=>{t.current=m;},[]),f=useCallback(m=>{r==="pen"&&t.current&&(o(ue()),t.current.startDrawing(m),a.current=true);},[r,o]),u=useCallback(m=>{!t.current||!a.current||t.current.draw(m);},[]),c=useCallback(()=>{if(!t.current||!a.current)return;let m=t.current.stopDrawing();a.current=false,m&&m.points.length>=4&&o(Es(m)),o(ei()),e?.();},[o,e]);return {lines:l,tool:r,color:n,strokeWidth:s,isSketchMode:i,setCanvasRef:d,startDrawing:f,draw:u,stopDrawing:c}};var ud=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:n,style:s,xOffset:i=0,yOffset:l=0},d)=>{let f=useRef(null),u=useRef(false),c=useRef([]),m=useRef([]),p=useRef(null),g=useRef(t),h=useRef(a),y=useRef(r),x=useRef(n),v=useRef(i),L=useRef(l);useEffect(()=>{g.current=t,h.current=a,y.current=r,x.current=n,v.current=i,L.current=l;},[t,a,r,n,i,l]);let k=useCallback(()=>{let S=f.current;if(!S)return;let b=S.getContext("2d");b&&b.clearRect(0,0,S.width,S.height);},[]),C=useCallback(()=>{let S=f.current,b=m.current;if(!S||b.length<1)return;let T=S.getContext("2d");if(!T)return;if(T.clearRect(0,0,S.width,S.height),g.current==="eraser"?(T.globalCompositeOperation="destination-out",T.fillStyle="rgba(0,0,0,1)"):(T.globalCompositeOperation="source-over",T.fillStyle=h.current),b.length===1){T.beginPath(),T.arc(b[0].x,b[0].y,y.current/2,0,Math.PI*2),T.fill();return}let D=dd(b,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:q=>q,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(D.length<2)){T.beginPath(),T.moveTo(D[0][0],D[0][1]);for(let q=1;q<D.length;q++)T.lineTo(D[q][0],D[q][1]);T.closePath(),T.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:S=>{u.current=true;let b={x:S.x-v.current,y:S.y-L.current};c.current=[{x:S.x,y:S.y}],m.current=[b],p.current=S,C();},draw:S=>{if(!u.current||!p.current)return;let b=S.x-p.current.x,T=S.y-p.current.y;if(Math.sqrt(b*b+T*T)<2)return;let D={x:S.x-v.current,y:S.y-L.current};c.current.push({x:S.x,y:S.y}),m.current.push(D),p.current=S,C();},stopDrawing:()=>{if(!u.current)return null;if(u.current=false,c.current.length<2)return c.current=[],m.current=[],p.current=null,k(),null;let b=dd(c.current,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:N=>N,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(N=>[N[0],N[1]]),T={tool:g.current,points:b,color:h.current,strokeWidth:y.current,isSketch:true};return c.current=[],m.current=[],p.current=null,k(),T},clear:()=>{k(),c.current=[],m.current=[],p.current=null,u.current=false;},isDrawing:()=>u.current,getCanvasElement:()=>f.current}),[k,C]),useEffect(()=>{let S=f.current;S&&(S.width=e,S.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});ud.displayName="DirectDrawingCanvas";var cd=ud;var md=e=>{let o=xe(),a=te(ge)?.images||[],r=useRef(new Map),n=useRef(new Map),s=useRef(new Set);useEffect(()=>{let f=new Set(a.map(u=>u.id));s.current.forEach(u=>{if(!f.has(u)){let c=n.current.get(u);c&&(c.src="",n.current.delete(u)),r.current.delete(u);}}),s.current=f;},[a]),useEffect(()=>()=>{n.current.forEach(f=>{f.src="";}),n.current.clear(),r.current.clear();},[]);let i=useCallback(f=>{if(n.current.has(f.id))return n.current.get(f.id);let u=new window.Image;return (f.src.startsWith("http://")||f.src.startsWith("https://"))&&(u.crossOrigin="anonymous"),u.src=f.src,n.current.set(f.id,u),u},[]),l=useCallback((f,u)=>{let c=f.target,m=c.id();a.find(g=>g.id===m)&&(o(ao({id:m,x:c.x(),y:c.y(),width:c.width(),height:c.height(),rotation:c.rotation()})),u?.());},[a,o]),d=useCallback((f,u)=>{let c=u.target,m=r.current.get(f);if(!m){console.error("\u274C Image node not found for id:",f);return}let p=c.scaleX(),g=c.scaleY(),h=c.rotation(),y=m.width(),x=m.height(),v=Math.max(5,y*p),L=Math.max(5,x*g);c.scaleX(1),c.scaleY(1),m.width(v),m.height(L),o(ao({id:f,width:v,height:L,x:c.x(),y:c.y(),rotation:h})),c.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:i,imageRefs:r,handleDragEnd:l,handleImageTransformEnd:d}};var pd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),n=useCallback((i,l)=>{let d=l.target,f=d.scaleX(),u=d.scaleY(),c=d.rotation(),m=Math.max(5,d.width()*f),p=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(m),d.height(p),o(ia({id:i,width:m,height:p,x:d.x(),y:d.y(),rotation:c})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:n,mcqRefs:a,handleDragEnd:(i,l)=>{o(ia({id:l,x:i.target.x(),y:i.target.y()})),e?.();}}};var hd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),n=useCallback((i,l)=>{let d=l.target,f=d.scaleX(),u=d.scaleY(),c=d.rotation(),m=Math.max(5,d.width()*f),p=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(m),d.height(p),o(la({id:i,width:m,height:p,x:d.x(),y:d.y(),rotation:c})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:n,handleTrueFalseDragEnd:(i,l)=>{o(la({id:l,x:i.target.x(),y:i.target.y()})),e?.();},trueFalseRefs:a}};var gd=e=>{let o=xe(),a=te(ge)?.videos||[],r=useRef(new Map),n=useCallback(l=>{o(Uo(l));},[o]),s=useCallback((l,d)=>{let f=d.target;o($r({id:l,x:f.x(),y:f.y()})),e?.();},[o,e]),i=useCallback((l,d)=>{let f=d.target,u=f.scaleX(),c=f.scaleY(),m=f.rotation(),p=Math.max(5,f.width()*u),g=Math.max(5,f.height()*c);f.scaleX(1),f.scaleY(1),f.width(p),f.height(g),o($r({id:l,width:p,height:g,x:f.x(),y:f.y(),rotation:m})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:n,handleVideoDragEnd:s,handleVideoTransformEnd:i}};var vd=e=>{let o=xe(),a=te(ge)?.shapes||[],r=useRef(new Map),n=useRef(new Map),[s,i]=useState(false),l=useCallback((f,u)=>{let c=u.target;o(oo({id:f,x:c.x(),y:c.y()})),e?.();},[o,e]),d=useCallback((f,u)=>{let c=u.target,m=a.find(v=>v.id===f);if(!m)return;let p=c.scaleX(),g=c.scaleY(),h=m.type?.toLowerCase();h==="arrow"||h==="line"||(c.scaleX(1),c.scaleY(1));let x={id:f,x:c.x(),y:c.y(),width:Math.max(5,c.width()*p),height:Math.max(5,c.height()*g),rotation:c.rotation()};switch(h){case "circle":x.radius=c.width()*p/2;break;case "star":x.innerRadius=c.width()*p/4,x.outerRadius=c.width()*p/2;break;case "triangle":x.radius=c.width()*p/2;break;case "ellipse":x.radiusX=c.width()*p/2,x.radiusY=c.height()*g/2;break;case "polygon":x.radius=c.width()*p/2;break;case "ring":let v=p;x.innerRadius=m.innerRadius&&m.innerRadius*v,x.outerRadius=m.outerRadius&&m.outerRadius*v;break;case "wedge":x.radius=m.radius&&m.radius*p;break;case "arc":x.innerRadius=m.innerRadius&&m.innerRadius*p,x.outerRadius=m.outerRadius&&m.outerRadius*p;break;case "arrow":case "line":{x.scaleX=p,x.scaleY=g,delete x.width,delete x.height;break}}o(oo(x)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:s,loadedShapesRef:n,handleShapeDragEnd:l,handleShapeResizeEnd:d}};var wd=(e,o)=>{let t=et(),r=te(ge)?.texts||[],n=useRef(new Map),[s,i]=useState(null),[l,d]=useState("");return {texts:r,textRefs:n,handleDragEnd:(h,y)=>{let x=h.target;t(ue()),t(It({id:y,x:x.x(),y:x.y()})),e();},handleTransformEnd:h=>{let y=n.current.get(h);if(!y)return;let x=y.scaleX(),v=y.scaleY(),L=r.find(C=>C.id===h);if(!L)return;let k=(x+v)/2;y.scaleX(1),y.scaleY(1),t(ue()),t(It({id:h,x:y.x(),y:y.y(),width:Math.max(5,(L.width||100)*x),height:Math.max(5,(L.height||50)*v),fontSize:Math.round(Math.max(8,L.fontSize*k)),rotation:y.rotation()})),e();},handleDoubleClick:h=>{let y=r.find(x=>x.id===h);y&&!y.locked&&(i(h),d(y.text));},startEditing:h=>{let y=r.find(x=>x.id===h);y&&!y.locked&&(i(h),d(y.text));},editingTextId:s,editingValue:l,handleEditingChange:h=>{d(h);},finishEditing:()=>{if(s){let h=n.current.get(s),y=r.find(v=>v.id===s);t(ue());let x={id:s,text:l};if(y&&(y.fontWeight!==void 0&&(x.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(x.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(x.textDecoration=y.textDecoration)),o?.current&&l.trim()){let v=o.current,L=v.offsetWidth,k=v.offsetHeight,C=1;if(h){let W=h.getStage();W&&(C=W.scaleX());}let S=14,b=(L-S)/C,T=(k-S)/C,N=l.split(`
3
+ `).length,q=r.find(W=>W.id===s)?.fontSize||24,A=N*q*1.2+10;x.width=Math.max(200,b),x.height=Math.max(50,T,A);}else if(h&&l.trim()){let v=h.text(),L=h.width();h.text(l),h.width(void 0);let k=h.width(),C=h.height();h.text(v),h.width(L),x.width=Math.max(200,k+20),x.height=Math.max(50,C+20);}t(It(x)),i(null),d(""),t($o(null)),e();}}}};var Ld=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),n=useCallback((s,i)=>{let l=s.target;o(zo({id:i,x:l.x(),y:l.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var Sd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,s)=>{let i=n.target;o(Go({id:s,x:i.x(),y:i.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var Cd=e=>{let o=xe(),a=te(ge)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),s=useCallback((u,c)=>{if(n.current.has(c))return n.current.get(c);let m=new window.Image;return m.src=u,n.current.set(c,m),m},[]),i=useCallback((u,c)=>{let m=u.target,p=m.id();a.find(h=>h.id===p)&&(o(ro({id:p,x:m.x(),y:m.y()})),c?.());},[a,o]),l=useCallback((u,c)=>{let m=c.target,p=m.scaleX(),g=m.scaleY(),h=m.rotation(),y=Math.max(50,m.width()*p),x=Math.max(50,m.height()*g);m.scaleX(1),m.scaleY(1),m.width(y),m.height(x),o(ro({id:u,width:y,height:x,x:m.x(),y:m.y(),rotation:h})),m.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(u=>{o(Vs(u)),e?.();},[o,e]),f=useCallback(u=>{o(qs(u)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:r,handleDragEnd:i,handleFlashcardTransformEnd:l,handleNext:d,handlePrevious:f}};var Td=e=>{let o=xe(),a=te(ge)?.photoFrames||[],r=useRef(new Map),[n,s]=useState(new Map),i=useCallback((m,p)=>{console.log("handleDragEnd"),o(Aa({id:p,x:m.target.x(),y:m.target.y()})),e?.();},[o,e]),l=useCallback((m,p)=>{let g=p.target,h=g.scaleX(),y=g.scaleY(),x=g.rotation(),v=a.find(C=>C.id===m);if(!v)return;let L=Math.max(100,v.width*h),k=Math.max(100,v.height*y);g.scaleX(1),g.scaleY(1),o(Aa({id:m,width:L,height:k,x:g.x(),y:g.y(),rotation:x})),g.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async m=>{try{let p=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(g=>{let h=new Map(g);return h.set(m,p),h}),o(Aa({id:m,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),f=useCallback(m=>{let p=n.get(m);p&&(p.getTracks().forEach(g=>g.stop()),s(g=>{let h=new Map(g);return h.delete(m),h}),o(Aa({id:m,isCapturing:false})),e?.());},[n,o,e]),u=useCallback((m,p)=>{let g=document.createElement("canvas");g.width=p.videoWidth,g.height=p.videoHeight;let h=g.getContext("2d");if(h){h.drawImage(p,0,0,g.width,g.height);let y=g.toDataURL("image/jpeg",.8);return o(Aa({id:m,capturedImageUrl:y,isCapturing:false})),f(m),e?.(),y}return null},[o,f,e]),c=useRef(n);return useEffect(()=>{c.current=n;},[n]),useEffect(()=>()=>{c.current.forEach(m=>{m.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:i,handlePhotoFrameTransformEnd:l,startCamera:d,stopCamera:f,capturePhoto:u,cameraStreams:n}};var Ad=()=>{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,l,d,f,u,c=[])=>{if(e.current){if(n&&!c.find(g=>g.id===n)?.isPlaying){let g=s.get(n)||i.get(n)||l.get(n)||d.get(n)||f.get(n)||(u?u.get(n):null);if(g){e.current.boundBoxFunc(t),e.current.nodes([g]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var mp=(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])},Ed=(e,o)=>{let t=et(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let s=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});s&&s.startsWith("data:")&&t(Ds({id:a.current,thumbnail:s}));}catch(s){console.warn("Could not generate thumbnail (likely CORS issue with images):",s);}},[o,t]),n=mp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var hp=e=>e.flatMap(o=>[o[0],o[1]]),Sn=(e,o)=>{let t=dd(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 hp(t)};var Fd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null),i=te(v=>v.toolbar.selectedTool),l=te(v=>v.toolbar.penColor),d=te(v=>v.toolbar.strokeWidth),f=te(v=>v.canvas.isSketchMode),u=te(v=>v.canvas.slides.find(k=>k.id===v.canvas.currentSlideId)?.images.find(k=>k.id===e)),c=u?.annotations||[],m=u?.isDrawingMode||false,p=u?.width||1,g=u?.height||1,h=useCallback(v=>{if(i!=="pen"&&i!=="eraser")return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/p,k=v.y/g;s({tool:i,points:[L,k],color:l,strokeWidth:d/p,isSketch:f});},[i,l,d,f,p,g]),y=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let C;if(f)C=Sn(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,T)=>T%2===0?b/p:b/g);else {let S=v.x/p,b=v.y/g;C=[...n.points,S,b];}s(S=>S?{...S,points:C}:null);},[f,d,n,p,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Ws({imageId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:c,activeLine:n,isDrawingMode:m,startDrawing:h,draw:y,stopDrawing:x,tool:i}};var Vd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>{let{annotations:i,activeLine:l,stopDrawing:c,tool:m}=Fd(e.id);useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[c,p]);let g=x=>{{n(e.id);return}},h=x=>{return;},y=x=>{};return jsxs(Group,{listening:m!=="pen"&&m!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x){t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();let v=x.getStage()?.container();if(v){let L=k=>{let C=x.getStage()?.getPointerPosition();if(C){let S={x:e.x,y:e.y,width:e.width,height:e.height};C.x>=S.x&&C.x<=S.x+S.width&&C.y>=S.y&&C.y<=S.y+S.height&&s(k,e.id,"image");}};v.addEventListener("contextmenu",L),x._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",L);};}}else {let v=t.current.get(e.id);v?._contextMenuCleanup&&v._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:m!=="pen"&&m!=="eraser",onDragEnd:a,onTransformEnd:x=>r(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...m!=="pen"&&m!=="eraser"?{onClick:g,onTap:g,onMouseDown:g,onTouchStart:g,onMouseMove:h,onTouchMove:h,onMouseUp:y,onTouchEnd:y}:{}}),i?.map((x,v)=>{let L=x.points.map((C,S)=>S%2===0?C*e.width+e.x:C*e.height+e.y),k=x.strokeWidth*e.width;return jsx(Line,{points:L,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:k,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},v)}),l&&jsx(Line,{points:l.points.map((x,v)=>v%2===0?x*e.width+e.x:x*e.height+e.y),stroke:l.tool==="eraser"?"white":l.color,strokeWidth:l.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:l.tool==="eraser"?"destination-out":"source-over",fill:l.isSketch?l.color:void 0,closed:l.isSketch,listening:false},"active")]})});Vd.displayName="ImageWithDrawing";var xi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(i=>{let l=o(i);return l?jsx(Vd,{img:i,loadedImage:l,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s},i.id):null})}));xi.displayName="ImageLayer";var Cp=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:s,rotation:i=0,onTransformEnd:l,onDragEnd:d})=>{let f=xe(),u=useRef(null),c=m=>{f(Uo(m));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:i,onDragEnd:d,onTransformEnd:l,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:u,src:e,controls:true,autoPlay:true,onClick:()=>c(t),onSeeking:m=>m.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},qd=Cp;var Ep=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:s})=>{let[i,l]=useState(null),d=useSelector(g=>g.toolbar.selectedTool),f=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let g=new window.Image;g.src=e.thumbnailDataUrl,g.onload=()=>{l(g);};}},[e.thumbnailDataUrl]),!i)return null;let u=e.width/2,c=e.height/2,m=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(m,80));return jsxs(Group,{draggable:!f,listening:!f,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...f?{}:{onDragEnd:a,onTransformEnd:r},ref:g=>{if(s(g),g){let h=g.getStage()?.container();if(h){let y=x=>{let v=g.getStage()?.getPointerPosition();if(v){let L={x:e.x,y:e.y,width:e.width,height:e.height};v.x>=L.x&&v.x<=L.x+L.width&&v.y>=L.y&&v.y<=L.y+L.height&&n(x);}};h.addEventListener("contextmenu",y),g._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",y);};}}},children:[jsx(Image$1,{image:i,width:e.width,height:e.height,listening:!f,...f?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:u,y:c,radius:p,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:u,y:c,radius:p*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:u+p*.1,y:c,sides:3,radius:p*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},Ud=Ep;var yi=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(Ud,{video:i,isSelected:!i.isPlaying&&o===i.id,onClick:()=>a(i.id),onDragEnd:l=>r(i.id,l),onTransformEnd:l=>n(i.id,l),onContextMenu:l=>s(l,i.id,"video"),nodeRef:l=>{l?t.current.set(i.id,l):t.current.delete(i.id);}}),i.isPlaying&&(()=>{let l=i.x,d=i.y;if(i.isRecorded){let f=typeof window<"u"?window.innerWidth:i.width,u=typeof window<"u"?window.innerHeight:i.height;l=(f-i.width)/2,d=(u-i.height)/2;}return jsx(qd,{id:i.id,src:i.objectUrl,x:l,y:d,width:i.width,height:i.height,isSelected:false,rotation:i.rotation,onTransformEnd:f=>n(i.id,f),onDragEnd:f=>r(i.id,f)})})()]},i.id))}));yi.displayName="VideoLayer";var wi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:s})=>{let i=useSelector(d=>d.toolbar.selectedTool),l=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map((d,f)=>{let u=d.id||f,c={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!l,listening:!l,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},u);case "star":return jsx(Star,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "triangle":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},u);case "polygon":return jsx(RegularPolygon,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},u);case "ellipse":return jsx(Ellipse,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},u);case "ring":return jsx(Ring,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "wedge":return jsx(Wedge,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},u);case "arrow":return jsx(Arrow,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "line":return jsx(Line,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "arc":return jsx(Arc,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},u);case "rectangle":default:return jsx(Rect,{ref:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);},...c,draggable:!d.locked&&!l,...l?{}:{onDragStart:m=>{n?.();},onDragEnd:m=>t(d.id,m),onTransformEnd:m=>a(d.id,m),onClick:()=>r(d.id),onContextMenu:m=>{m.evt.preventDefault(),s(m.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},u)}})})});wi.displayName="ShapeLayer";var Gd=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:s,editingTextId:i})=>{let l=useSelector(f=>f.toolbar.selectedTool),d=l==="pen"||l==="eraser";return jsx(Fragment,{children:e.map(f=>{let u=f.id===i,c=f.fontWeight==="bold",m=c?Math.max(1,f.fontSize/25):0;return jsx(Text,{id:f.id,ref:p=>{p?o.current.set(f.id,p):o.current.delete(f.id);},text:f.text,x:f.x,y:f.y,width:f.width,height:f.height,rotation:f.rotation,draggable:!f.locked&&!u&&!d,listening:!d,fontSize:f.fontSize,fontFamily:f.fontFamily,fontStyle:f.fontStyle,fontWeight:f.fontWeight,textDecoration:f.textDecoration,fill:f.fill,stroke:c?f.fill:void 0,strokeWidth:m,align:f.align,wrap:"none",lineHeight:1.2,opacity:u?0:1,visible:!u,...d?{}:{onClick:()=>r(f.id),onTap:()=>r(f.id),onDblClick:()=>s(f.id),onDblTap:()=>s(f.id),onDragEnd:p=>t(p,f.id),onTransformEnd:()=>a(f.id),onContextMenu:p=>{p.evt.preventDefault();let g=p.evt;n(g,f.id,"text");}}},f.id)})})};var rh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:s,onPrevious:i,nodeRef:l})=>{let[d,f]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{f(h);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let u=8,c=2,m=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(m,32)),g=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:h=>{if(l(h),h){let y=h.getStage()?.container();if(y){let x=v=>{let L=h.getStage()?.getPointerPosition();if(L){let k={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=k.x&&L.x<=k.x+k.width&&L.y>=k.y&&L.y<=k.y+k.height&&n(v);}};y.addEventListener("contextmenu",x),h._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",x);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:u,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:u,stroke:"#E5E7EB",strokeWidth:c,listening:false}),jsx(Image$1,{x:c+4,y:c+4,image:d,width:e.width-(c+4)*2,height:e.height-(c+4)*2,cornerRadius:u-c,onClick:t,onTap:t}),jsx(Rect,{x:c,y:e.height-50,width:e.width-c*2,height:50,cornerRadius:[0,0,u-c,u-c],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:g+p,y:e.height/2,onClick:h=>{h.cancelBubble=true,i();},onTap:h=>{h.cancelBubble=true,i();},children:[jsx(Circle,{radius:p,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-g-p,y:e.height/2,onClick:h=>{h.cancelBubble=true,s();},onTap:h=>{h.cancelBubble=true,s();},children:[jsx(Circle,{radius:p,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"})]})},jd=rh;var Ii=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:s,onPrevious:i,onContextMenu:l})=>jsx(Fragment,{children:e.map(d=>jsx(jd,{flashcard:d,isSelected:t===d.id,onClick:()=>n(d.id),onDragEnd:a,onTransformEnd:f=>r(d.id,f),onContextMenu:f=>l(f,d.id,"flashcard"),onNext:()=>s(d.id),onPrevious:()=>i(d.id),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))}));Ii.displayName="FlashcardLayer";var Xd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null);te(v=>v.toolbar.selectedTool);let l=te(v=>v.toolbar.penColor),d=te(v=>v.toolbar.strokeWidth),f=te(v=>v.canvas.isSketchMode),u=te(v=>v.canvas.slides.find(k=>k.id===v.canvas.currentSlideId)?.photoFrames.find(k=>k.id===e)),c=u?.annotations||[],m=u?.isDrawingMode||false,p=u?.width||1,g=u?.height||1,h=useCallback(v=>{if(!m)return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/p,k=v.y/g;s({tool:"pen",points:[L,k],color:l,strokeWidth:d/p,isSketch:f});},[m,l,d,f,p,g]),y=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let C;if(f)C=Sn(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,T)=>T%2===0?b/p:b/g);else {let S=v.x/p,b=v.y/g;C=[...n.points,S,b];}s(S=>S?{...S,points:C}:null);},[f,d,n,p,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Gs({frameId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:c,activeLine:n,isDrawingMode:m,startDrawing:h,draw:y,stopDrawing:x}};var mh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:s,onCapture:i,cameraStream:l,nodeRef:d})=>{let[f,u]=useState(null),[c,m]=useState(null),p=useRef(null),g=useRef(null),h=useRef(null),y=useRef(null),x=useRef(0),v=33,L=useSelector(O=>O.toolbar.selectedTool),k=L==="pen"||L==="eraser",{annotations:C,activeLine:S,isDrawingMode:b,startDrawing:T,draw:N,stopDrawing:D}=Xd(e.id);useEffect(()=>{if(!b)return;let O=()=>{D();},j=()=>{D();};return window.addEventListener("mouseup",O),window.addEventListener("touchend",j),()=>{window.removeEventListener("mouseup",O),window.removeEventListener("touchend",j);}},[D,b]),useEffect(()=>{if(e.capturedImageUrl){let O=new window.Image;O.src=e.capturedImageUrl,O.onload=()=>{u(O);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&l){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),g.current||(g.current=document.createElement("canvas"));let O=p.current,j=g.current;O.srcObject=l;let H=()=>{j.width=O.videoWidth||640,j.height=O.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",j.width,j.height);let K=J=>{if(J-x.current<v){h.current=requestAnimationFrame(K);return}x.current=J;let ee=j.getContext("2d");if(ee&&O.readyState===O.HAVE_ENOUGH_DATA){ee.drawImage(O,0,0,j.width,j.height);let Z=j.toDataURL("image/jpeg",.6),se=new window.Image;se.onload=()=>{m(se);},se.src=Z;}h.current=requestAnimationFrame(K);};h.current=requestAnimationFrame(K);};return O.onloadedmetadata=H,O.readyState>=O.HAVE_METADATA&&H(),O.play().catch(K=>console.error("Error playing video:",K)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{m(null),y.current&&(y.current.src="");}},[e.isCapturing,l]);let q=()=>{p.current&&e.isCapturing&&i(p.current);},U=O=>{if(e.capturedImageUrl){if(!b){t();return}let j=O.currentTarget,H=j.getAbsoluteTransform().copy(),J=j.getStage()?.getPointerPosition();if(J){H.invert();let ee=H.point(J);T(ee);}O.cancelBubble=true;}else t();},A=O=>{if(!b||!e.capturedImageUrl)return;let j=O.currentTarget,H=j.getAbsoluteTransform().copy(),J=j.getStage()?.getPointerPosition();if(J){H.invert();let ee=H.point(J);N(ee);}},W=()=>{!b||!e.capturedImageUrl||D();},R=e.isCapturing?c:f,re=Math.min(e.width,e.height)*.12,V=Math.max(25,Math.min(re,50)),oe=e.width/2,z=e.height/2;return jsxs(Group,{id:e.id,draggable:!b&&!k,listening:true,x:e.x,y:e.y,...k?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:O=>{if(d(O),O){let j=O.getStage()?.container();if(j){let H=K=>{let J=O.getStage()?.getPointerPosition();if(J){let ee={x:e.x,y:e.y,width:e.width,height:e.height};J.x>=ee.x&&J.x<=ee.x+ee.width&&J.y>=ee.y&&J.y<=ee.y+ee.height&&n(K);}};j.addEventListener("contextmenu",H),O._contextMenuCleanup=()=>{j.removeEventListener("contextmenu",H);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:R?"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}}),R&&jsx(Image$1,{image:R,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:U,onTap:U,onMouseDown:U,onTouchStart:U,onMouseMove:A,onTouchMove:A,onMouseUp:W,onTouchEnd:W,...k?{}:{onDragEnd:a,onTransformEnd:r}}),C?.map((O,j)=>{let H=O.points.map((J,ee)=>ee%2===0?J*e.width:J*e.height),K=O.strokeWidth*e.width;return jsx(Line,{points:H,stroke:O.tool==="eraser"?"white":O.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:O.tool==="eraser"?"destination-out":"source-over",fill:O.isSketch?O.color:void 0,closed:O.isSketch,listening:false},j)}),S&&jsx(Line,{points:S.points.map((O,j)=>j%2===0?O*e.width:O*e.height),stroke:S.tool==="eraser"?"white":S.color,strokeWidth:S.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:S.tool==="eraser"?"destination-out":"source-over",fill:S.isSketch?S.color:void 0,closed:S.isSketch,listening:false},"active"),!R&&!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:z-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:oe-V+6,y:z-60,width:V*1.6,height:V*1.6,radius:V,fill:"white",cornerRadius:8,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?q():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?q():s();}}),jsx(Html,{groupProps:{x:oe-12,y:z-40,width:V*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?q():s();}})})]}),jsx(Text,{x:0,y:z,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:z+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:oe-24,y:z+104,width:V*1.6,height:V*1.6,radius:V,fill:"#096B76",cornerRadius:V,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?q():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?q():s();}}),jsx(Html,{groupProps:{x:oe-8,y:z+120,width:V*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?q():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"})]})]})},Qd=mh;var Ai=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:s,onCapture:i,cameraStreams:l,onContextMenu:d})=>jsx(Fragment,{children:e.map(f=>jsx(Qd,{photoFrame:f,isSelected:t===f.id,onClick:()=>n(f.id),onDragEnd:u=>a(u,f.id),onTransformEnd:u=>r(f.id,u),onContextMenu:u=>d(u,f.id,"photoFrame"),onStartCamera:()=>s(f.id),onCapture:u=>i(f.id,u),cameraStream:l.get(f.id),nodeRef:u=>{u?o.current.set(f.id,u):o.current.delete(f.id);}},f.id))}));Ai.displayName="PhotoFrameLayer";var ou=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:s,menuRef:i})=>{useEffect(()=>{let u=m=>{i?.current&&!i.current.contains(m.target)&&a();},c=m=>{m.key==="Escape"&&a();};return document.addEventListener("mousedown",u),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",c);}},[a]);let l=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(c=>!(c.showForTypes&&!c.showForTypes.includes(r)||c.hideForTypes&&c.hideForTypes.includes(r))),[r,s]),d=(u,c)=>{u==="order"||u==="lock"?t(u,c):(t(u),a());},f=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:l.map((u,c)=>jsxs("button",{onClick:m=>d(u.action,m),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] ${u.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[u.icon,jsx("span",{className:`font-medium ${u.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:u.label})]}),u.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"})})]},c))})});return createPortal(f,document.body)};var ru=({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 nu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[s,i]=useState(a),l=useRef(null);useEffect(()=>{l.current?.focus();},[]);let d=()=>{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$1,{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:l,type:"text",value:s,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"?d():u.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:d,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 su=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null);useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let s=f=>{f.preventDefault(),o(a);},i=(f,u,c)=>{c/=100;let m=u*Math.min(c,1-c)/100,p=g=>{let h=(g+f/30)%12,y=c-m*Math.max(Math.min(h-3,9-h,1),-1);return Math.round(255*y).toString(16).padStart(2,"0")};return `#${p(0)}${p(8)}${p(4)}`},d=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.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:f=>f.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$1,{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:f=>r(f.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:f=>r(f.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:f=>{let u=parseInt(f.target.value),c=i(u,100,50);r(c);},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(f=>jsx("button",{type:"button",onClick:()=>r(f),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===f.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:f},title:f},f))})]})]}),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(d,document.body)};var Yh=({imageSrc:e,onCrop:o})=>{let[t]=du(e),a=useRef(null),r=useRef(null),n=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let p=Math.min(600/t.width,400/t.height);return {width:t.width*p,height:t.height*p}},[t]),i=useMemo(()=>{let c=s.width*.5,m=s.height*.5,p=(s.width-c)/2,g=(s.height-m)/2;return {x:p,y:g,width:c,height:m}},[s]),[l,d]=useState(i);useEffect(()=>{d(i);},[i]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[l]),useEffect(()=>{o(l.x,l.y,l.width,l.height);},[l,o]);let f=()=>{let c=r.current;if(!c)return;let m=c.scaleX(),p=c.scaleY();c.scaleX(1),c.scaleY(1),d({x:c.x(),y:c.y(),width:Math.max(20,c.width()*m),height:Math.max(20,c.height()*p)});},u=()=>{let c=r.current;c&&d({x:c.x(),y:c.y(),width:c.width(),height:c.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:l.x,y:l.y,width:l.width,height:l.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:l.x,y:l.y,width:l.width,height:l.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:u,onTransformEnd:f,dragBoundFunc:c=>{let m=Math.max(0,Math.min(c.x,s.width-l.width)),p=Math.max(0,Math.min(c.y,s.height-l.height));return {x:m,y:p}}}),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:(c,m)=>m.width<20||m.height<20||m.x<0||m.y<0||m.x+m.width>s.width||m.y+m.height>s.height?c:m})]})})},uu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[s]=du(e);return useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.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:f=>f.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$1,{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(Yh,{imageSrc:e,onCrop:(f,u,c,m)=>{n({x:f,y:u,width:c,height:m});}})}),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 c=Math.min(600/s.width,400/s.height),m=r.x/c,p=r.y/c,g=r.width/c,h=r.height/c,y=document.createElement("canvas");y.width=g,y.height=h;let x=y.getContext("2d");if(!x)return;x.drawImage(s,m,p,g,h,0,0,g,h);let v=y.toDataURL("image/png");o(v);},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 nr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,n]=useState(false),[s,i]=useState(null),[l,d]=useState(0),[f,u]=useState(true),c=useRef(null),m=useRef([]),p=useRef(null),g=useRef(null),h=useRef(null),y=useRef(null),x=useRef(null),v=useRef(null);useEffect(()=>()=>{h.current&&cancelAnimationFrame(h.current),p.current&&clearInterval(p.current),g.current&&g.current.getTracks().forEach(b=>b.stop());},[]);let L=async()=>{try{let b,T=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let A=o.current.getLayers();console.log("Konva layers:",A.length),A.forEach((j,H)=>{let K=j.getChildren();console.log(`Layer ${H} children count:`,K.length);});let W=document.createElement("canvas");W.width=o.current.width(),W.height=o.current.height();let R=W.getContext("2d",{willReadFrequently:!1});if(!R){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",W.width,"x",W.height),x.current=W;let re=()=>{if(R.clearRect(0,0,W.width,W.height),A.forEach(j=>{let H=j.getCanvas()._canvas;H&&R.drawImage(H,0,0);}),a?.current){let j=a.current;R.drawImage(j,0,0);}};v.current=re,o.current.draw(),re(),await new Promise(j=>setTimeout(j,100)),console.log("Creating captureStream..."),b=W.captureStream(30),console.log("Canvas stream created, tracks:",b.getTracks().length);let oe=b.getVideoTracks()[0];oe&&console.log("Video track:",oe.label,"state:",oe.readyState);let z=0,O=()=>{re(),o?.current&&(o.current.getLayers().forEach(H=>{H.batchDraw();}),z++,z%60===0&&console.log("Drawing frame:",z)),h.current=requestAnimationFrame(O);};O();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(A){console.warn("Microphone access denied:",A);}let N=[...b.getVideoTracks()];T&&N.push(...T.getAudioTracks());let D=new MediaStream(N);g.current=D;let q="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?q="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?q="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?q="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(q="video/webm;codecs=vp8"),console.log("Using mimeType:",q);let U=new MediaRecorder(D,{mimeType:q,videoBitsPerSecond:25e5});c.current=U,m.current=[],U.ondataavailable=A=>{console.log("Data available, size:",A.data.size),A.data.size>0&&m.current.push(A.data);},U.onstop=()=>{console.log("Recording stopped, chunks:",m.current.length);let A=new Blob(m.current,{type:q});console.log("Final blob size:",A.size),o?.current&&v.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(R=>{R.batchDraw();}),v.current(),y.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",y.current.length)),D.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),h.current&&(cancelAnimationFrame(h.current),h.current=null),i(A);},U.onerror=A=>{console.error("MediaRecorder error:",A);},console.log("Starting recording..."),U.start(1e3),n(!0),d(0),p.current=setInterval(()=>{d(A=>A+1);},1e3);}catch(b){console.error("Error starting screen recording:",b),alert("Failed to start recording. Please ensure you granted permission.");}},k=()=>{c.current&&r&&(console.log("Stopping recording, state:",c.current.state),c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),n(false));},C=()=>{if(s){let b=URL.createObjectURL(s),T=document.createElement("a");T.href=b,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(b);}},S=b=>{let T=Math.floor(b/60),N=b%60;return `${T.toString().padStart(2,"0")}:${N.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:S(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:k,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$1,{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:()=>u(!f),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${f?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:f?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:L,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: ",S(l)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&s&&y.current&&(t(s,y.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:C,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),d(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 fu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[n,s]=useState(false),[i,l]=useState(null),[d,f]=useState(false),[u,c]=useState(0),m=useRef(null),p=useRef([]),g=useRef(null),h=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(b=>b.blob()).then(b=>l(b)).catch(b=>console.error("Error loading audio:",b));},[o,i]);let y=async()=>{try{let b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(b);m.current=T,p.current=[],T.ondataavailable=N=>{N.data.size>0&&p.current.push(N.data);},T.onstop=()=>{let N=new Blob(p.current,{type:"audio/webm"});l(N),b.getTracks().forEach(D=>D.stop()),g.current&&clearInterval(g.current);},T.start(),s(!0),c(0),g.current=setInterval(()=>{c(N=>N+1);},1e3);}catch(b){console.error("Error starting audio recording:",b),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{m.current&&n&&(m.current.stop(),s(false));},v=()=>{if(i){let b=URL.createObjectURL(i),T=new Audio(b);h.current=T,T.onended=()=>{f(false),URL.revokeObjectURL(b);},T.play(),f(true);}},L=()=>{h.current&&(h.current.pause(),h.current.currentTime=0,f(false));},k=async()=>{if(i){let b=new FileReader;b.onloadend=()=>{let T=b.result;t(T),r();},b.readAsDataURL(i);}},C=()=>{l(null),a();},S=b=>{let T=Math.floor(b/60),N=b%60;return `${T.toString().padStart(2,"0")}:${N.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:S(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:x,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:y,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:d?L:v,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"}),d?"Playing...":"Play Audio"]}),jsx("button",{onClick:C,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:k,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 kt=({audioData:e,x:o,y:t,width:a})=>{let[r,n]=useState(false),s=useRef(null);return jsx("button",{onClick:l=>{if(l.stopPropagation(),r&&s.current)s.current.pause(),s.current.currentTime=0,n(false);else {let d=new Audio(e);s.current=d,d.onended=()=>{n(false);},d.onerror=()=>{console.error("Error playing audio"),n(false);},d.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 hu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=te(ge),n=useMemo(()=>{if(!r)return [];let g=[];return r.images?.forEach(h=>{g.push({id:h.id,type:"image",name:"Image",timestamp:h.timestamp||0});}),r.videos?.forEach(h=>{g.push({id:h.id,type:"video",name:"Video",timestamp:h.timestamp||0});}),r.shapes?.forEach(h=>{g.push({id:h.id,type:"shape",name:`${h.type} Shape`,timestamp:h.timestamp||0});}),r.texts?.forEach(h=>{g.push({id:h.id,type:"text",name:h.text.substring(0,20)+(h.text.length>20?"...":""),timestamp:h.timestamp||0});}),r.flashcards?.forEach(h=>{g.push({id:h.id,type:"flashcard",name:`Flashcard (${h.images.length} images)`,timestamp:h.timestamp||0});}),r.photoFrames?.forEach(h=>{g.push({id:h.id,type:"photoFrame",name:"Photo Frame",timestamp:h.timestamp||0});}),r.multipleChoices?.forEach(h=>{g.push({id:h.id,type:"mcq",name:"Multiple Choice",timestamp:h.timestamp||0});}),r.trueFalses?.forEach(h=>{g.push({id:h.id,type:"trueFalse",name:"True/False",timestamp:h.timestamp||0});}),r.shortAnswers?.forEach(h=>{g.push({id:h.id,type:"shortAnswer",name:"Short Answer",timestamp:h.timestamp||0});}),r.LongAnswer?.forEach(h=>{g.push({id:h.id,type:"longAnswer",name:"Long Answer",timestamp:h.timestamp||0});}),r.fillInTheBlanks?.forEach(h=>{g.push({id:h.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:h.timestamp||0});}),r.lines?.forEach(h=>{h.id&&g.push({id:h.id,type:"line",name:"Drawn Line",timestamp:h.timestamp||0});}),g.sort((h,y)=>y.timestamp-h.timestamp)},[r]),[s,i]=useState(n),[l,d]=useState(false);useEffect(()=>{l||i(n);},[n]);let f=g=>{let h="h-5 w-5";switch(g){case "image":return jsx(Image$3,{className:h});case "video":return jsx(VideoCamera,{className:h});case "shape":return jsx(Shapes$1,{className:h});case "text":return jsx(TextT,{className:h});case "flashcard":return jsx(Cards$1,{className:h});case "photoFrame":return jsx(FrameCorners,{className:h});case "line":return jsx("span",{className:h,children:"\u270F\uFE0F"});default:return jsx(Question,{className:h})}},u=g=>{if(g===0)return;let h=s[g],y=s[g-1];a(jo({id:h.id,type:h.type,newTimestamp:y.timestamp+1}));},c=g=>{if(g===s.length-1)return;let h=s[g],y=s[g+1];a(jo({id:h.id,type:h.type,newTimestamp:y.timestamp-1}));},m=g=>{d(true),i(g);},p=()=>{d(false);let g=Date.now();s.forEach((h,y)=>{let x=g-y;a(jo({id:h.id,type:h.type,newTimestamp:x}));});};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$2,{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:m,className:"space-y-1",children:s.map((g,h)=>{let y=g.id===e;return jsxs(Reorder.Item,{value:g,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${y?"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(g.id,g.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${y?"text-blue-600":"text-gray-600"}`,children:f(g.type)}),jsx("span",{className:`text-sm ${y?"font-medium text-blue-900":"text-gray-700"}`,children:g.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:x=>{x.stopPropagation(),u(h);},disabled:h===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:x=>{x.stopPropagation(),c(h);},disabled:h===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"})})]})]},g.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 gu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>{let s=useSelector(z=>z.toolbar.selectedTool),i=s==="pen"||s==="eraser",[l,d]=useState(new Set),[f,u]=useState(false),[c,m]=useState(null),p=useRef(null);useEffect(()=>{let z=p.current;if(z)return a.current.set(e.id,z),()=>{a.current.delete(e.id);}},[e.id]);let g=new Set(e.data.responseOptions.correctIndex),h=g.size>1,y=z=>{f||d(h?O=>{let j=new Set(O);return j.has(z)?j.delete(z):j.add(z),j}:new Set([z]));},x=()=>{l.size>0&&u(true);},v=()=>{u(false),d(new Set);},L=l.size===g.size&&Array.from(l).every(z=>g.has(z)),k=Array.from(l).filter(z=>g.has(z)),C=h&&k.length>0&&!L,S=()=>L?"\u2713 Correct! Great job! \u{1F389}":C?`\u26A0 Partially correct (${k.length}/${g.size})`:"\u2717 Try again!",b=()=>L?{bg:"#dcfce7",text:"#166534"}:C?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},T=55,N=8,D=24,q=60,U=60,A=h&&!f?25:0,W=e.data.feedbackMode==="practice"?48:0,R=12,re=q+A+(f?U:0),V=e.data.responseOptions.options.length*(T+N),oe=re+V+R+W+D;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:r,onClick:z=>t(e.id),onTap:z=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:oe,width:e.width,onTransformEnd:z=>o(e.id,z),onContextMenu:z=>{z.cancelBubble=true,n(z.evt,e.id,"mcq");}}),jsx(Text,{x:D+8,y:D,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-D*2,listening:false}),h&&!f&&e.data.feedbackMode==="practice"?jsx(Text,{x:D,y:D+35,text:`Select ${g.size} answers (${l.size}/${g.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-D*2,listening:false}):null,f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:D+24,y:q+A,width:e.width-D*2-40,height:U-20,fill:b().bg,cornerRadius:8}),jsx(Text,{x:D,y:q+A,width:e.width-D*2,height:U-20,text:S(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((z,O)=>{let j=g.has(O),H=l.has(O),K=re+O*(T+N),J="#e5e7eb",ee="#ffffff",Z="#111827";return f&&j?(J="#22c55e",ee="#dcfce7",Z="#1B9D2C"):f&&H&&!j?(J="#ef4444",ee="#fee2e2",Z="#ef4444"):H&&(J="#096B76",ee="#ECFFF8",Z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:D+12,y:K+(T-20)/2,width:20,height:20,fill:H?"#096B76":"white",stroke:H?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:se=>{se.cancelBubble=true,y(O);},onTap:se=>{se.cancelBubble=true,y(O);}}),H&&jsx(Text,{x:D+12,y:K+(T-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:D+44,y:K,width:e.width-D*2-60,height:T,fill:ee,stroke:J,strokeWidth:2,cornerRadius:8,onClick:se=>{se.cancelBubble=true,y(O);},onTap:se=>{se.cancelBubble=true,y(O);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:T,text:z,fontSize:16,fill:Z,verticalAlign:"middle",listening:false})]},O)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:re+e.data.responseOptions.options.length*(T+N)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,m("check");},onMouseUp:z=>{z.cancelBubble=true,m(null),x();},onMouseLeave:z=>{z.cancelBubble=true,m(null);},onTouchStart:z=>{z.cancelBubble=true,m("check");},onTouchEnd:z=>{z.cancelBubble=true,m(null),x();},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:D+14,width:(e.width-D*2-24)/(f?2:1),height:48,fill:l.size===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:D+14,width:(e.width-D*2-24)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-D*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),v();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),v();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:D,width:(e.width-D*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:D,width:(e.width-D*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});gu.displayName="MultipleChoice";var xu=gu;var Ei=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r})=>{let n=useDispatch(),s=useSelector(H=>H.toolbar.selectedTool),i=s==="pen"||s==="eraser",[l,d]=useState(false),[f,u]=useState(new Set),[c,m]=useState(false),[p,g]=useState(false),[h,y]=useState(0),x=340,v=100,L=window.innerWidth*.4,k=window.innerHeight*.5,C=x+20,S=v+60,b=L-40,T=k-300,N=useRef(null);useEffect(()=>{let H=N.current;if(H)return r.current.set(e.id,H),()=>{r.current.delete(e.id);}},[e.id]);let D=H=>{n(ia({id:e.id,x:H.target.x(),y:H.target.y()}));},q=H=>{let K=H.target,J=K.x(),ee=K.y(),Z=window.innerWidth*.2,Se=J+Z>C&&J<C+b&&ee+50>S&&ee<S+T;d(Se);},U=(H,K)=>{let J=K.target,ee=J.x(),Z=J.y(),se=window.innerWidth*.2,Y=ee+se>C&&ee<C+b&&Z+50>S&&Z<S+T;u(Y?De=>new Set(De).add(H):De=>{let Ie=new Set(De);return Ie.delete(H),Ie}),d(false);},A=()=>{m(true);},W=()=>{m(false),u(new Set),y(H=>H+1);},R=new Set(e.data.responseOptions.correctIndex),re=f.size===R.size&&Array.from(f).every(H=>R.has(H)),V=Array.from(f).filter(H=>R.has(H)),oe=V.length>0&&!re,z=()=>re?"\u2713 Correct! Great job!":oe?`\u26A0 Partially correct (${V.length}/${R.size})`:"\u2717 Try again!",O=()=>re?{bg:"#dcfce7",text:"#166534"}:oe?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},j=()=>c?re?"#4CAF50":oe?"#f59e0b":"#ef4444":l?"#4CAF50":"#075560";return jsxs(Group,{ref:N,name:"mcq-element",width:L,height:k,draggable:!i,listening:!i,...i?{}:{onClick:H=>a(e.id),onTap:H=>a(e.id),onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"mcq");}},children:[jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:D,children:[jsx(Rect,{fill:"white",stroke:l?"#4CAF50":"#e5e7eb",strokeWidth:l?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?k-100:k-50,width:L,shadowColor:l?"#4CAF50":"transparent",shadowBlur:l?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:b,height:T,fill:"#EBF6F7",stroke:j(),strokeWidth:3,dash:[10,10],cornerRadius:8}),c&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:T+18,width:b-5,height:60,fill:O().bg,cornerRadius:8}),jsx(Text,{x:20,y:T+20,width:b,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:O().text,align:"center",verticalAlign:"middle"})]}),f.size===0&&!c&&jsx(Text,{x:20,y:60,width:b,height:T-60,text:R.size>1?`Drop ${R.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?k-200:k-160,children:[jsxs(Group,{onMouseDown:()=>{g(true),A();},onMouseUp:()=>g(false),onMouseLeave:()=>g(false),onTouchStart:()=>{g(true),A();},onTouchEnd:()=>g(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]}),c&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((H,K)=>{let J=K%2,ee=Math.floor(K/2),Z=window.innerWidth*.2,se=50,Se=10,Y=f.has(K),De=R.has(K),Ie=c&&Y,Ft="transparent";return Ie?Ft=De?"#4CAF50":"#ef4444":Y&&(Ft="#4CAF50"),jsxs(Group,{x:340+J*(Z+Se),y:v+k-80+ee*(se+Se),draggable:!c,onDragMove:q,onDragEnd:Ja=>U(K,Ja),opacity:c&&!Y?.5:1,children:[jsx(Rect,{width:Z-20,height:se,fill:"white",stroke:Ft,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Z-20,height:se,text:H,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${h}`)})]})};Ei.displayName="MultipleChoiceDragAndDrop";var bu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(xu,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:i=>r(i,s.id),onContextMenu:n},s.id):jsx(Ei,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:n},s.id))});var vu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(R=>R.toolbar.selectedTool),i=s==="pen"||s==="eraser",[l,d]=useState(null),[f,u]=useState(false),[c,m]=useState(null),p=useRef(null);useEffect(()=>{let R=p.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{l!==null&&u(true);},h=()=>{u(false),d(null);},y=e.data.responseOptions.correctAnswer,x=l===y,v=R=>{f||d(R);},L=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",k=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},C=70,S=12,b=24,T=60,N=60,D=e.data.feedbackMode==="practice"?48:0,q=12,U=T+(f?N:0),A=2*(C+S),W=U+A+q+D+b;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:R=>n(R,e.id),onClick:R=>t(e.id),onTap:R=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:W-20,width:e.width,onTransformEnd:R=>o(e.id,R),onContextMenu:R=>{R.cancelBubble=true,r(R.evt,e.id,"trueFalse");}}),jsx(Text,{x:b,y:b,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:b,y:T,width:e.width-b*2,height:N-10,fill:k().bg,cornerRadius:8}),jsx(Text,{x:b,y:T,width:e.width-b*2,height:N-10,text:L(),fontSize:16,fontStyle:"bold",fill:k().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((R,re)=>{let V=y===R.value,oe=l===R.value,z=(e.width-b*3)/2,O=b+re*(z+b),j=U,H=R.value===true,K=H?"#10b981":"#ef4444",J="#ffffff",ee="#ffffff",Z="#e5e7eb";return f&&(V?(ee=H?"#f0fdf4":"#fef2f2",Z=H?"#86efac":"#fecaca"):oe&&!V&&(ee="#fee2e2",Z="#ef4444")),oe&&!f&&(Z="#096B76",ee="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:j,width:z,height:C+50,fill:ee,stroke:Z,strokeWidth:2,cornerRadius:12,onClick:se=>{se.cancelBubble=true,v(R.value);},onTap:se=>{se.cancelBubble=true,v(R.value);}}),jsx(Circle,{x:O+z/2,y:j+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:O+z/2-14,y:j+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:J,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:O+z/2-14,y:j+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:J,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O,y:j+85,width:z,height:30,text:R.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},R.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:U+2*(C+S),children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,m("check");},onMouseUp:R=>{R.cancelBubble=true,m(null),g();},onMouseLeave:R=>{R.cancelBubble=true,m(null);},onTouchStart:R=>{R.cancelBubble=true,m("check");},onTouchEnd:R=>{R.cancelBubble=true,m(null),g();},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,fill:l===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-b*2)/2+8,onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),h();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),h();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});vu.displayName="TrueFalse";var yu=vu;var $g="#FFFFFF",Oi=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(K=>K.toolbar.selectedTool),n=r==="pen"||r==="eraser",[s,i]=useState(false),[l,d]=useState(null),[f,u]=useState(false),[c,m]=useState(false),[p,g]=useState(0),[h,y]=useState(false),x=340,v=100,L=window.innerWidth*.4,k=window.innerHeight*.5,C=L-40,S=k-300,b=20,T=60,N=C,D=S,q=L*.2-40,U=50,A=useRef(null),W=K=>{a(la({id:e.id,x:K.target.x(),y:K.target.y()}));},R=K=>{let J=K.target,ee=J.x(),Z=J.y(),se=Math.max(0,Math.min(ee+q,b+N)-Math.max(ee,b)),Se=Math.max(0,Math.min(Z+U,T+D)-Math.max(Z,T)),Y=se*Se,De=q*U;i(Y/De>=.5);},re=(K,J)=>{let ee=J.target,Z=ee.x(),se=ee.y(),Se=Math.max(0,Math.min(Z+q,b+N)-Math.max(Z,b)),Y=Math.max(0,Math.min(se+U,T+D)-Math.max(se,T)),De=Se*Y,Ie=q*U;if(De/Ie>=.5)d(K);else return;i(false);},V=()=>{u(true);},oe=()=>{u(false),d(null),g(K=>K+1);},z=e.data.responseOptions.correctAnswer,O=l===z,j=()=>O?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>O?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:A,name:"trueFalse-element",width:L,height:k,draggable:!n,listening:!n,...n?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:W,children:[jsx(Rect,{fill:"white",stroke:s?"#4CAF50":"#e5e7eb",strokeWidth:s?4:2,cornerRadius:12,height:f?k:e.data.feedbackMode==="practice"?k-50:k-100,width:L,shadowColor:s?"#4CAF50":"transparent",shadowBlur:s?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:C,height:S,fill:"transparent",stroke:s?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:C,height:60,fill:H().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:C,height:60,text:j(),fontSize:18,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle"})]}),l===null&&!f&&jsx(Text,{x:20,y:60,width:C,height:S-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:k-100,children:[jsxs(Group,{onMouseDown:()=>{l!==null&&(m(true),V());},onMouseUp:()=>m(false),onMouseLeave:()=>m(false),onTouchStart:()=>{l!==null&&(m(true),V());},onTouchEnd:()=>m(false),scaleX:c?.95:1,scaleY:c?.95:1,children:[jsx(Rect,{fill:l===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:C}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:C,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:oe,onTouchStart:oe,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:C}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:C,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,J)=>{let ee=window.innerWidth*.2,Z=50,se=10,Se=l===K.value,Y=z===K.value,De=f&&Se,Ie="transparent";return De?Ie=Y?"#4CAF50":"#ef4444":Se&&(Ie="#4CAF50"),jsxs(Group,{x:16+J*(ee+se),y:v+k-300,draggable:!f,onDragMove:R,onDragEnd:Ft=>re(K.value,Ft),opacity:f&&!Se?.5:1,children:[jsx(Rect,{width:ee-40,height:Z,fill:"#075560",stroke:Ie,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:ee-40,height:Z,text:K.label,fontSize:18,fontStyle:"bold",fill:$g,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${p}`)})]})})};Oi.displayName="TrueFalseDragAndDrop";var wu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(yu,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r},s.id):jsx(Oi,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n},s.id))});var fa=new WeakMap,bo=new WeakMap,cr={current:[]},Vi=false,ur=0,dr=new Set,Fn=new Map;function Lu(e){let o=Array.from(e).sort((t,a)=>t instanceof Vt&&t.options.deps.includes(a)?1:a instanceof Vt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(cr.current.includes(t))continue;cr.current.push(t),t.recompute();let a=bo.get(t);if(a)for(let r of a){let n=fa.get(r);n&&Lu(n);}}}function Jg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Zg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Bn(e){if(ur>0&&!Fn.has(e)&&Fn.set(e,e.prevState),dr.add(e),!(ur>0)&&!Vi)try{for(Vi=!0;dr.size>0;){let o=Array.from(dr);dr.clear();for(let t of o){let a=Fn.get(t)??t.prevState;t.prevState=a,Jg(t);}for(let t of o){let a=fa.get(t);a&&(cr.current.push(t),Lu(a));}for(let t of o){let a=fa.get(t);if(a)for(let r of a)Zg(r);}}}finally{Vi=false,cr.current=[],Fn.clear();}}function pt(e){ur++;try{e();}finally{if(ur--,ur===0){let o=dr.values().next().value;o&&Bn(o);}}}function Su(e){return typeof e=="function"}var $t=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):Su(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),Bn(this);}};var Vt=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 $t){let a=fa.get(t);a||(a=new Set,fa.set(t,a)),a.add(this);let r=bo.get(this);r||(r=new Set,bo.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 $t){let a=fa.get(t);a&&a.delete(this);let r=bo.get(this);r&&r.delete(t);}}};function Qg(e){return typeof e=="function"}function qi(e,...o){return Qg(e)?e(...o):e}function Iu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ma,ot,Je,fr,pa,Ba,Zt,vo,mr,On,pr,yo,Oa=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Te(this,ma,true);Te(this,ot);Te(this,Je);Te(this,fr);Te(this,pa);Te(this,Ba);Te(this,Zt);Te(this,vo);Te(this,mr,0);Te(this,On,5);Te(this,pr,()=>{this.debugLog("Connected to event bus"),ke(this,Ba,true),this.debugLog("Emitting queued events",_(this,pa)),_(this,pa).forEach(o=>this.emitEventToBus(o)),ke(this,pa,[]),this.stopConnectLoop(),_(this,Je).call(this).removeEventListener("tanstack-connect-success",_(this,pr));});Te(this,yo,()=>{if(_(this,Je).call(this).addEventListener("tanstack-connect-success",_(this,pr)),_(this,mr)<_(this,On)){ad(this,mr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,Je).call(this).removeEventListener("tanstack-connect",_(this,yo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});ke(this,ot,o),ke(this,ma,a),ke(this,Je,this.getGlobalTarget),ke(this,fr,t),this.debugLog(" Initializing event subscription for plugin",_(this,ot)),ke(this,pa,[]),ke(this,Ba,false),ke(this,Zt,null),ke(this,vo,r);}startConnectLoop(){_(this,Zt)!==null||_(this,Ba)||(this.debugLog(`Starting connect loop (every ${_(this,vo)}ms)`),ke(this,Zt,setInterval(_(this,yo),_(this,vo))));}stopConnectLoop(){_(this,Zt)!==null&&(clearInterval(_(this,Zt)),ke(this,Zt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,fr)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,ot)}-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 _(this,ot)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,Je).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,Je).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(!_(this,ma)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!_(this,Ba)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,pa).push({type:`${_(this,ot)}:${o}`,payload:t,pluginId:_(this,ot)}),typeof CustomEvent<"u"&&(_(this,yo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,ot)}:${o}`,payload:t,pluginId:_(this,ot)})}on(o,t){let a=`${_(this,ot)}:${o}`;if(!_(this,ma))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 _(this,Je).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{_(this,Je).call(this).removeEventListener(a,r);}}onAll(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;_(this,ot)&&r.pluginId!==_(this,ot)||o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}};ma=new WeakMap,ot=new WeakMap,Je=new WeakMap,fr=new WeakMap,pa=new WeakMap,Ba=new WeakMap,Zt=new WeakMap,vo=new WeakMap,mr=new WeakMap,On=new WeakMap,pr=new WeakMap,yo=new WeakMap;var Hi=class extends Oa{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Cu=(e,o)=>{Ui.emit(e,o);},Ui=new Hi;function ku(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var ex={enabled:true,leading:true,trailing:true,wait:0},ha,ht,Na,Va,qa,wo,Nn=class{constructor(o,t){Te(this,ha);Te(this,ht);Te(this,Na);Te(this,Va);Te(this,qa);Te(this,wo);this.fn=o,this.store=new $t(ku()),this.setOptions=a=>{this.options={...this.options,...a},_(this,Na).call(this)||this.cancel();},ke(this,ht,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:s}=n;return {...n,status:_(this,Na).call(this)?s?"pending":"idle":"disabled"}}),Cu("Throttler",this);}),ke(this,Na,()=>!!qi(this.options.enabled,this)),ke(this,Va,()=>qi(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,ht).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,s=_(this,Va).call(this);if(this.options.leading&&n>=s)_(this,qa).call(this,...a);else if(_(this,ht).call(this,{lastArgs:a}),!_(this,ha)&&this.options.trailing){let i=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,l=s-i;_(this,ht).call(this,{isPending:true}),ke(this,ha,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&_(this,qa).call(this,...d);},l));}},ke(this,qa,(...a)=>{if(!_(this,Na).call(this))return;this.fn(...a);let r=Date.now(),n=r+_(this,Va).call(this);_(this,wo).call(this),_(this,ht).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||_(this,ht).call(this,{nextExecutionTime:void 0});},_(this,Va).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,qa).call(this,...this.store.state.lastArgs);},ke(this,wo,()=>{_(this,ha)&&(clearTimeout(_(this,ha)),ke(this,ha,void 0));}),this.cancel=()=>{_(this,wo).call(this),_(this,ht).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,ht).call(this,ku());},this.key=Iu(t.key),this.options={...ex,...t},_(this,ht).call(this,this.options.initialState??{}),Ui.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,ht).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ha=new WeakMap,ht=new WeakMap,Na=new WeakMap,Va=new WeakMap,qa=new WeakMap,wo=new WeakMap;function Wi(e,o){return new Nn(e,o).maybeExecute}function ga(e,o){return typeof e=="function"?e(o):e}function xa(e,o){return Un(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Lo(e,o,t){let a=Un(o);function r(n){if(!a.length)return ga(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 Gi(e,o){let t=Un(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((d,f)=>f!==s);let{[s]:i,...l}=r;return l}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 tx=/^(\d+)$/gm,ax=/\.(\d+)(?=\.)/gm,ox=/^(\d+)\./gm,rx=/\.(\d+$)/gm,nx=/\.{2,}/gm,zi="__int__",Vn=`${zi}$1`;function Un(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(tx,Vn).replace(ax,`.${Vn}.`).replace(ox,`${Vn}.`).replace(rx,`.${Vn}`).replace(nx,".").split(".").map(o=>{if(o.startsWith(zi)){let t=o.substring(zi.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Ki(e){return !(Array.isArray(e)&&e.length===0)}function So(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 Io(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},s=t??0,i=l=>l.validators.filter(Boolean).map(d=>{let f=d?.cause||e,u=s;switch(f){case "change":u=r??s;break;case "blur":u=a??s;break;case "dynamic":u=n??s;break;case "submit":u=0;break}return e==="submit"&&(u=0),{cause:f,validate:d.fn,debounceMs:u}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:i})}var hr=e=>!!e&&typeof e=="object"&&"fields"in e;function ba(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)||!ba(e[r],o[r]))return false;return true}var Wn=({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},zn=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function ze(e,o){return e==null?o:{...e,...o}}var Ha=256,Hn=[],qn;for(;Ha--;)Hn[Ha]=(Ha+256).toString(16).substring(1);function _i(){let e=0,o,t="";if(!qn||Ha+16>256){for(qn=new Array(256),e=256;e--;)qn[e]=256*Math.random()|0;e=0,Ha=0;}for(;e<16;e++)o=qn[Ha+e],e===6?t+=Hn[o&15|64]:e===8?t+=Hn[o&63|128]:t+=Hn[o],e&1&&e>1&&e<11&&(t+="-");return Ha++,t}var va=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 sx(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 l=r[i];if(l===void 0)continue;let d=typeof l=="object"?l.key:l,f=Number(d);Array.isArray(n)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(i>0?".":"")+String(d),typeof n=="object"&&n!==null?n=n[d]:n=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var Mu=(e,o)=>{let t=sx(e,o);return {form:t,fields:t}},ya={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:Mu(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:Mu(a.issues,e)}},Gn=e=>!!e&&"~standard"in e;var Co={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function gr(e){function o(u,c,m,p){let g=a(u,c,m,p);({insert:()=>i(g,u,c),remove:()=>l(g),swap:()=>p!==void 0&&f(g,u,c,p),move:()=>p!==void 0&&d(g,u,c,p)})[m]();}function t(u,c){return `${u}[${c}]`}function a(u,c,m,p){let g=[t(u,c)];if(m==="swap")g.push(t(u,p));else if(m==="move"){let[h,y]=[Math.min(c,p),Math.max(c,p)];for(let x=h;x<=y;x++)g.push(t(u,x));}else {let h=e.getFieldValue(u),y=Array.isArray(h)?h.length:0;for(let x=c+1;x<y;x++)g.push(t(u,x));}return Object.keys(e.fieldInfo).filter(h=>g.some(y=>h.startsWith(y)))}function r(u,c){return u.replace(/\[(\d+)\]/,(m,p)=>{let g=parseInt(p,10);return `[${c==="up"?g+1:Math.max(0,g-1)}]`})}function n(u,c){(c==="up"?u:[...u].reverse()).forEach(p=>{let g=r(p.toString(),c),h=e.getFieldMeta(g);h?e.setFieldMeta(p,h):e.setFieldMeta(p,s());});}let s=()=>Co,i=(u,c,m)=>{n(u,"down"),u.forEach(p=>{p.toString().startsWith(t(c,m))&&e.setFieldMeta(p,s());});},l=u=>{n(u,"up");},d=(u,c,m,p)=>{let g=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(c,m))).map(h=>[h,e.getFieldMeta(h)]));n(u,m<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(c,p))).forEach(h=>{let y=h.replace(t(c,p),t(c,m)),x=g.get(y);x&&e.setFieldMeta(h,x);});},f=(u,c,m,p)=>{u.forEach(g=>{if(!g.toString().startsWith(t(c,m)))return;let h=g.toString().replace(t(c,m),t(c,p)),[y,x]=[e.getFieldMeta(g),e.getFieldMeta(h)];y&&e.setFieldMeta(h,y),x&&e.setFieldMeta(g,x);});};return {handleArrayFieldMetaShift:o}}var ji=class extends Oa{constructor(){super({pluginId:"form-devtools"});}},gt=new ji;function $i(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 br=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),gt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return gt.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((l,d)=>l!==this.prevTransformArray[d]),s=a.defaultValues&&!ba(a.defaultValues,r.defaultValues)&&!this.state.isTouched,i=!ba(a.defaultState,r.defaultState)&&!this.state.isTouched;!s&&!i&&!n||(pt(()=>{this.baseStore.setState(()=>$i(Object.assign({},this.state,i?a.defaultState:{},s?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),gt.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(()=>$i({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let r=[];return pt(()=>{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(l=>({...l,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,l=[`${a}[${r}]`];for(let c=r+1;c<=(i??0);c++)l.push(`${a}[${c}]`);let d=Object.keys(this.fieldInfo).filter(c=>l.some(m=>c.startsWith(m))),f=[];return pt(()=>{d.forEach(c=>{f.push(Promise.resolve().then(()=>this.validateField(c,n)));});}),(await Promise.all(f)).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=So(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va}),n=false,s={};return pt(()=>{for(let d of r){if(!d.validate)continue;let f=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:u,fieldErrors:c}=Kn(f),m=xr(d.cause);for(let p of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[p]===void 0)continue;let g=this.getFieldMeta(p);if(!g)continue;let{errorMap:h,errorSourceMap:y}=g,x=c?.[p],{newErrorValue:v,newSource:L}=Wn({newFormValidatorError:x,isPreviousErrorFromFormValidator:y?.[m]==="form",previousErrorValue:h?.[m]});L==="form"&&(s[p]={...s[p],[m]:x}),h?.[m]!==v&&this.setFieldMeta(p,k=>({...k,errorMap:{...k.errorMap,[m]:v},errorSourceMap:{...k.errorSourceMap,[m]:L}}));}this.state.errorMap?.[m]!==u&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[m]:u}})),(u||c)&&(n=!0);}let i=xr("submit");this.state.errorMap?.[i]&&a!=="submit"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));let l=xr("server");this.state.errorMap?.[l]&&a!=="server"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[l]:void 0}}));}),{hasErrored:n,fieldsErrorMap:s}},this.validateAsync=async a=>{let r=Io(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let n=[],s;for(let d of r){if(!d.validate)continue;let f=xr(d.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let c=new AbortController;this.state.validationMetaMap[f]={lastAbortController:c},n.push(new Promise(async m=>{let p;try{p=await new Promise((x,v)=>{setTimeout(async()=>{if(c.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:c.signal},type:"validateAsync"}));}catch(L){v(L);}},d.debounceMs);});}catch(x){p=x;}let{formError:g,fieldErrors:h}=Kn(p);h&&(s=s?{...s,...h}:h);let y=xr(d.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let v=this.getFieldMeta(x);if(!v)continue;let{errorMap:L,errorSourceMap:k}=v,C=s?.[x],{newErrorValue:S,newSource:b}=Wn({newFormValidatorError:C,isPreviousErrorFromFormValidator:k?.[y]==="form",previousErrorValue:L?.[y]});L?.[y]!==S&&this.setFieldMeta(x,T=>({...T,errorMap:{...T.errorMap,[y]:S},errorSourceMap:{...T.errorSourceMap,[y]:b}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[y]:g}})),m(s?{fieldErrors:s,errorMapKey:y}:void 0);}));}let i=[],l={};if(n.length){i=await Promise.all(n);for(let d of i)if(d?.fieldErrors){let{errorMapKey:f}=d;for(let[u,c]of Object.entries(d.fieldErrors)){let p={...l[u]||{},[f]:c};l[u]=p;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),l},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>xa(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]:ga(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let s=n;return r[s]=Co,r},{}),this.setFieldValue=(a,r,n)=>{let s=n?.dontUpdateMeta??false,i=n?.dontRunListeners??false,l=n?.dontValidate??false;pt(()=>{s||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Lo(d.values,a,r)}));}),i||this.getFieldInfo(a).instance?.triggerOnChangeListener(),l||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(l=>{i.values=Gi(i.values,l),delete this.fieldInfo[l],delete i.fieldMetaBase[l];}),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,l=>[...l.slice(0,r),n,...l.slice(r)],ze(s,{dontValidate:true}));let i=s?.dontValidate??false;i||await this.validateField(a,"change"),gr(this).handleArrayFieldMetaShift(a,r,"insert"),i||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,l=>l.map((d,f)=>f===r?n:d),ze(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,d=>d.filter((f,u)=>u!==r),ze(n,{dontValidate:true})),gr(this).handleArrayFieldMetaShift(a,r,"remove"),i!==null){let d=`${a}[${i}]`;this.deleteField(d);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,s)=>{this.setFieldValue(a,l=>{let d=l[r],f=l[n];return Lo(Lo(l,`${r}`,f),`${n}`,d)},ze(s,{dontValidate:true})),gr(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,l=>{let d=[...l];return d.splice(n,0,d.splice(r,1)[0]),d},ze(s,{dontValidate:true})),gr(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,[],ze(r,{dontValidate:true})),s!==null)for(let l=0;l<=s;l++){let d=`${a}[${l}]`;this.deleteField(d);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Co},values:this.options.defaultValues?Lo(r.values,a,xa(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=>ya.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ya.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??_i(),this._devtoolsSubmissionOverride=false,this.baseStore=new $t($i({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Vt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,i=a?.[0],l=r[0],d=0,f={};for(let u of Object.keys(l.fieldMetaBase)){let c=l.fieldMetaBase[u],m=i?.fieldMetaBase[u],p=s?.[u],g=xa(l.values,u),h=p?.errors;if(!m||c.errorMap!==m.errorMap){h=Object.values(c.errorMap??{}).filter(k=>k!==void 0);let L=this.getFieldInfo(u)?.instance;L&&!L.options.disableErrorFlat&&(h=h?.flat(1));}let y=!Ki(h??[]),x=!c.isDirty,v=ba(g,xa(this.options.defaultValues,u))||ba(g,this.getFieldInfo(u)?.instance?.options.defaultValue);if(p&&p.isPristine===x&&p.isValid===y&&p.isDefaultValue===v&&p.errors===h&&c===m){f[u]=p,d++;continue}f[u]={...c,errors:h,isPristine:x,isValid:y,isDefaultValue:v};}return Object.keys(l.fieldMetaBase).length&&s&&d===Object.keys(l.fieldMetaBase).length?s:f}}),this.store=new Vt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,i=a?.[0],l=r[0],d=r[1],f=Object.values(d).filter(Boolean),u=f.some(A=>A.isValidating),c=f.every(A=>A.isValid),m=f.some(A=>A.isTouched),p=f.some(A=>A.isBlurred),g=f.every(A=>A.isDefaultValue),h=m&&l.errorMap?.onMount,y=f.some(A=>A.isDirty),x=!y,v=!!(l.errorMap?.onMount||f.some(A=>A?.errorMap?.onMount)),L=!!u,k=s?.errors??[];(!i||l.errorMap!==i.errorMap)&&(k=Object.values(l.errorMap).reduce((A,W)=>W===void 0?A:W&&hr(W)?(A.push(W.form),A):(A.push(W),A),[]));let C=k.length===0,S=c&&C,b=this.options.canSubmitWhenInvalid??false,T=l.submissionAttempts===0&&!m&&!v||!L&&!l.isSubmitting&&S||b,N=l.errorMap;if(h&&(k=k.filter(A=>A!==l.errorMap.onMount),N=Object.assign(N,{onMount:void 0})),s&&i&&s.errorMap===N&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===k&&s.isFieldsValidating===u&&s.isFieldsValid===c&&s.isFormValid===C&&s.isValid===S&&s.canSubmit===T&&s.isTouched===m&&s.isBlurred===p&&s.isPristine===x&&s.isDefaultValue===g&&s.isDirty===y&&ba(i,l))return s;let D={...l,errorMap:N,fieldMeta:this.fieldMetaDerived.state,errors:k,isFieldsValidating:u,isFieldsValid:c,isFormValid:C,isValid:S,canSubmit:T,isTouched:m,isBlurred:p,isPristine:x,isDefaultValue:g,isDirty:y},q=this.options.transform?.deps??[];if(q.length!==this.prevTransformArray.length||q.some((A,W)=>A!==this.prevTransformArray[W])){let A=Object.assign({},this,{state:D});this.options.transform?.fn(A),D=A.state,this.prevTransformArray=q;}return D}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Wi(a=>gt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),gt.on("request-form-state",a=>{a.payload.id===this._formId&&gt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),gt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),gt.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 Gn(o.validate)?ya[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})),pt(()=>{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}),gt.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}),gt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}pt(()=>{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}),pt(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),gt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),gt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){pt(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(hr(a)){let{formError:n,fieldErrors:s}=Kn(a);for(let i of Object.keys(this.fieldInfo))this.getFieldMeta(i)&&this.setFieldMeta(i,d=>({...d,errorMap:{...d.errorMap,[r]:s?.[i]},errorSourceMap:{...d.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 Kn(e){if(e){if(hr(e)){let o=Kn(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function xr(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 vr=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=xa(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,ze(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,ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,ze(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,ze(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,ze(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=So(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),s=this.getLinkedFields(t).reduce((d,f)=>{let u=So(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||va});return u.forEach(c=>{c.field=f;}),d.concat(u)},[]),i=false;pt(()=>{let d=(f,u)=>{let c=_n(u.cause),m=u.validate?Tu(f.runValidator({validate:u.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,p=a[c],{newErrorValue:g,newSource:h}=zn({formLevelError:p,fieldLevelError:m});f.state.meta.errorMap?.[c]!==g&&f.setMeta(y=>({...y,errorMap:{...y.errorMap,[c]:g},errorSourceMap:{...y.errorSourceMap,[c]:h}})),g&&(i=!0);};for(let f of r)d(this,f);for(let f of s)f.validate&&d(f.field,f);});let l=_n("submit");return this.state.meta.errorMap?.[l]&&t!=="submit"&&!i&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[l]:void 0},errorSourceMap:{...d.errorSourceMap,[l]:void 0}})),{hasErrored:i}},this.validateAsync=async(t,a)=>{let r=Io(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),n=await a,s=this.getLinkedFields(t),i=s.reduce((c,m)=>{let p=Io(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||va});return p.forEach(g=>{g.field=m;}),c.concat(p)},[]);this.state.meta.isValidating||this.setMeta(c=>({...c,isValidating:true}));for(let c of s)c.setMeta(m=>({...m,isValidating:true}));let l=[],d=[],f=(c,m,p)=>{let g=_n(m.cause);c.getInfo().validationMetaMap[g]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[g]={lastAbortController:y},p.push(new Promise(async x=>{let v;try{v=await new Promise((b,T)=>{this.timeoutIds.validations[m.cause]&&clearTimeout(this.timeoutIds.validations[m.cause]),this.timeoutIds.validations[m.cause]=setTimeout(async()=>{if(y.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:m.validate,value:{value:c.store.state.value,fieldApi:c,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(N){T(N);}},m.debounceMs);});}catch(b){v=b;}if(y.signal.aborted)return x(void 0);let L=Tu(v),k=n[this.name]?.[g],{newErrorValue:C,newSource:S}=zn({formLevelError:k,fieldLevelError:L});c.setMeta(b=>({...b,errorMap:{...b?.errorMap,[g]:C},errorSourceMap:{...b.errorSourceMap,[g]:S}})),x(C);}));};for(let c of r)c.validate&&f(this,c,l);for(let c of i)c.validate&&f(c.field,c,d);let u=[];(l.length||d.length)&&(u=await Promise.all(l),await Promise.all(d)),this.setMeta(c=>({...c,isValidating:false}));for(let c of s)c.setMeta(m=>({...m,isValidating:false}));return u.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[_n(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=>ya.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ya.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Vt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Co,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Gn(o.validate)?ya[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 Tu(e){if(e)return e}function _n(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 jn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,lx)}function lx(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=Au(e);if(t.length!==Au(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 Au(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var ko=typeof window<"u"?useLayoutEffect:useEffect;function hx(e){let[o]=useState(()=>{let a=new vr({...e,form:e.form,name:e.name});return a.Field=Xi,a});return ko(o.mount,[o]),ko(()=>{o.update(e);}),jn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Xi=(({children:e,...o})=>{let t=hx(o),a=useMemo(()=>ga(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function bx({form:e,selector:o,children:t}){let a=jn(e.store,o);return ga(t,a)}function Yi(e){let o=useId(),[t]=useState(()=>{let a=new br({...e,formId:o}),r=a;return r.Field=function(s){return jsx(Xi,{...s,form:a})},r.Subscribe=function(s){return jsx(bx,{form:a,selector:s.selector,children:s.children})},r});return ko(t.mount,[]),ko(()=>{t.update(e);}),t}function Ji({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 Tx=({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),l=Yi({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:u})=>{if(u.questionType==="true-false"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctAnswer:u.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?la(c):_s(c));}else if(u.questionType==="multiple-choice"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctIndex:u.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?ia(c):Ks(c));}else if(u.questionType==="short-answer"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.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?zo(c):js(c));}else if(u.questionType==="fill-in-the-blank"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.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?Ko(c):Xs(c));}else if(u.questionType==="long-answer"){let c={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctLongAnswer:u.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?Go(c):$s(c));}o(da(false));}}),d=()=>{o(da(false));},f=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:u=>{u.preventDefault(),u.stopPropagation(),l.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:()=>{d();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(l.Field,{name:"questionType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:c=>{u.handleChange(c.target.value),i(c.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(Ji,{field:u})]})}),s&&!["short-answer","fill-in-the-blank","long-answer"].includes(s)&&jsx(l.Field,{name:"responseType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:c=>u.handleChange(c.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(Ji,{field:u})]})})]}),jsx(l.Field,{name:"feedbackMode",children:u=>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:()=>u.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.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:()=>u.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.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(Ji,{field:u})]})}),jsx(l.Field,{name:"question",validators:{onChange:({value:u})=>u?void 0:"A question is required"},children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.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:u.state.value,onChange:c=>u.handleChange(c.target.value),onBlur:u.handleBlur,placeholder:"Enter Your Question"})}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="true-false"&&jsx(l.Field,{name:"responseOptions.correctAnswer",children:u=>{let c=u.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:()=>u.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${c===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"}),c===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:()=>u.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${c===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"}),c===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(l.Field,{name:"responseOptions",validators:{onChange:({value:u})=>{if(u.options.filter(m=>!m.trim()).length>0)return "All options must have text";if(!u.correctIndex||u.correctIndex.length===0)return "Please select at least one correct answer"}},children:u=>{let c=(h,y)=>{let x=[...u.state.value.options];x[h]=y,u.handleChange({...u.state.value,options:x});},m=()=>{if(u.state.value.options.length>=6){alert("Maximum 6 options allowed");return}u.handleChange({...u.state.value,options:[...u.state.value.options,""]});},p=h=>{if(u.state.value.options.length<=2){alert("Minimum 2 options required");return}let y=u.state.value.options.filter((v,L)=>L!==h),x=u.state.value.correctIndex?.filter(v=>v!==h).map(v=>v>h?v-1:v);u.handleChange({...u.state.value,options:y,correctIndex:x});},g=h=>{let y=u.state.value.correctIndex||[];if(y.includes(h))u.handleChange({...u.state.value,correctIndex:y.filter(v=>v!==h)});else {if(y.length>=6){alert("Maximum 6 correct answers allowed");return}u.handleChange({...u.state.value,correctIndex:[...y,h]});}};return jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:u.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:u.state.value.options.map((h,y)=>{let x=!h.trim(),v=u.state.value.correctIndex?.includes(y),L=u.state.meta.isTouched&&x;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>g(y),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${v?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:v&&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 ${L?"border-red-500 bg-red-50":v?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${y+1}`,value:h,onChange:k=>c(y,k.target.value),onBlur:u.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),u.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>p(y),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},y)})}),jsx("button",{type:"button",onClick:m,disabled:u.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"}),u.state.value.correctIndex.length===0||u.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:u.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(l.Field,{name:"responseOptions.correctShortAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:u.state.value,onChange:c=>{u.handleChange(c.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)."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="long-answer"&&jsx(l.Field,{name:"responseOptions.correctLongAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.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:u.state.value,onChange:c=>{u.handleChange(c.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."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),jsx(l.Subscribe,{selector:u=>[u.canSubmit,u.isSubmitting],children:([u,c])=>jsx("button",{type:"submit",disabled:!u,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:c?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,document.body)},Ru=Tx;var Eu=({text:e,position:o})=>{let t=xe(),a=d=>{t(ue()),t(It({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},r=d=>{t(ue()),t(It({id:e.id,fill:d}));},n=()=>{t(ue()),t(It({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},s=()=>{t(ue()),t(It({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},i=()=>{t(ue()),t(It({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},l=d=>{t(ue()),t(It({id:e.id,fontFamily:d}));};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:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>l(d.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:d=>r(d.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var Bu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:s})=>{let i=useRef(null),l=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]),d=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let u=document.createElement("span");u.style.font=window.getComputedStyle(f).font,u.style.fontSize=f.style.fontSize,u.style.fontFamily=f.style.fontFamily,u.style.fontWeight=f.style.fontWeight,u.style.fontStyle=f.style.fontStyle,u.style.visibility="hidden",u.style.position="absolute",u.style.whiteSpace="pre";let c=f.value.split(`
4
+ `),m=0;document.body.appendChild(u);for(let g of c){u.textContent=g||" ";let h=u.offsetWidth;h>m&&(m=h);}document.body.removeChild(u);let p=10;f.style.width=`${Math.max(200,m+p+20)}px`;},[]);return useEffect(()=>{let f=i.current;f&&(f.style.fontSize=`${e.fontSize*n}px`,f.style.fontFamily=e.fontFamily,f.style.fontStyle=e.fontStyle,f.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",f.style.textDecoration=e.textDecoration,f.style.color=e.fill,d(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,d]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(i.current=f,s.current=f,f){f.focus();let u=f.value.length;f.setSelectionRange(u,u),d(f);}},value:o,onChange:f=>{t(f.target.value);},onKeyDown:f=>{f.key==="Escape"&&a();},style:l},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Ou=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(A=>A.toolbar.selectedTool),i=s==="pen"||s==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let A=l.current;if(A)return a.current.set(e.id,A),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===g,y=()=>{c(false),f("");},x=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",v=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,k=60,C=u?40:0,S=u?54:20,b=50,T=12,N=e.data.feedbackMode==="practice"?48:0,D=12,q=30,U=k+C+q+b+T+D+N+L;return jsxs(Group,{ref:l,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:U,name:"sa-element",...i?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:U,onTransformEnd:A=>t(e.id,A),onContextMenu:A=>{A.cancelBubble=true,r(A.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:k+C+q-S,width:e.width-L*2+4,height:b+6,fill:"#ffffff",stroke:h?"#22c55e":u?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:k+C+q-S},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${b}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:A=>f(A.target.value),disabled:u,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:u?"none":"auto"}})}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:k+80,width:e.width/2+24,height:C,fill:v().bg,cornerRadius:8}),jsx(Text,{x:36,y:k+80,width:e.width-L*2,height:C,text:x(),fontSize:12,fontStyle:"bold",fill:v().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:k+C+q+b+T+D,children:[jsxs(Group,{onMouseDown:A=>{A.cancelBubble=true,p("check");},onMouseUp:A=>{A.cancelBubble=true,p(null),d.length>0&&c(true);},onMouseLeave:A=>{A.cancelBubble=true,p(null);},onTouchStart:A=>{A.cancelBubble=true,p("check");},onTouchEnd:A=>{A.cancelBubble=true,p(null),d.length>0&&c(true);},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,fill:d.length===0||u?"#9ca3af":"#096B76",cornerRadius:8,onClick:A=>A.cancelBubble=true,onTap:A=>A.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,text:u?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),u&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),y();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),y();},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:A=>A.cancelBubble=true,onTap:A=>A.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})]})]})]})});Ou.displayName="ShortAnswer";var Nu=Ou;var qu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(Nu,{shortAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>n(i,s.id)},s.id))});var Hu=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((s,i)=>{let l=s.target;o(Ko({id:i,x:l.x(),y:l.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var Tt=24,el=51,Cr=64,Uu=15,Jn=32,Wu=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n})=>{let s=useSelector(b=>b.toolbar.selectedTool),i=s==="pen"||s==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let b=l.current;if(b)return n.current.set(e.id,b),()=>{n.current.delete(e.id);}},[e.id,n]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===g,y=()=>{c(false),f("");},x=()=>{d.length>0&&c(true);},v=e.width-Tt*2,L=(v-Uu)/2,k=e.data.feedbackMode==="practice",C=useMemo(()=>{let b=Tt,T=b;b+=60;let N=b;b+=35;let D=b;b+=el+16;let q=b;u&&(b+=Jn+16);let U=b;return k&&(b+=Cr),b+=Tt,{questionY:T,helperTextY:N,inputY:D,feedbackY:q,buttonsY:U,totalHeight:b}},[u,k]),S=()=>u?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:l,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...i?{}:{onDragEnd:b=>a(b,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:C.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:b=>t(e.id,b),onContextMenu:b=>{b.cancelBubble=true,r?.(b.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Tt,y:C.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:v,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Tt,y:C.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:v,listening:false}),jsx(Rect,{x:Tt,y:C.inputY,width:v,height:el,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Tt,y:C.inputY},divProps:{style:{width:`${v}px`,height:`${el}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:b=>f(b.target.value),disabled:u,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),u&&jsxs(Group,{y:C.feedbackY,children:[jsx(Rect,{x:Tt,width:h?206:140,height:Jn,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Tt+10,y:0,width:16,height:Jn,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Tt+30,y:0,height:Jn,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),k&&jsxs(Group,{y:C.buttonsY,children:[jsxs(Group,{x:Tt,onMouseDown:b=>{b.cancelBubble=true,p("reset");},onMouseUp:b=>{b.cancelBubble=true,p(null),y();},onMouseLeave:b=>{b.cancelBubble=true,p(null);},onTouchStart:b=>{b.cancelBubble=true,p("reset");},onTouchEnd:b=>{b.cancelBubble=true,p(null),y();},scaleX:m==="reset"?.98:1,scaleY:m==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Cr,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Cr,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Tt+L+Uu,onMouseDown:b=>{b.cancelBubble=true,p("submit");},onMouseUp:b=>{b.cancelBubble=true,p(null),x();},onMouseLeave:b=>{b.cancelBubble=true,p(null);},onTouchStart:b=>{b.cancelBubble=true,p("submit");},onTouchEnd:b=>{b.cancelBubble=true,p(null),x();},scaleX:m==="submit"?.98:1,scaleY:m==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Cr,fill:d.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Cr,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Wu.displayName="FillInTheBlanks";var zu=Wu;var Ku=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n})=>jsx(Fragment,{children:e.map(s=>jsx(zu,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n},s.id))});var rl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(U=>U.toolbar.selectedTool),i=s==="pen"||s==="eraser",l=useRef(null),[d,f]=useState(""),[u,c]=useState(false),[m,p]=useState(null);useEffect(()=>{let U=l.current;if(U)return a.current.set(e.id,U),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=u&&d.trim().toLowerCase()===g,y=()=>{c(false),f("");},x=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",v=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,k=60,C=u?60:0,S=120,b=12,T=48,N=12,D=30,q=k+C+D+S+b+N+T+L;return jsxs(Group,{ref:l,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:U=>{let A=l.current?.getStage()?.getPointerPosition();if(!A||!r)return;let W={x:e.x,y:e.y,width:e.width,height:e.height};A.x>=W.x&&A.x<=W.x+W.width&&A.y>=W.y&&A.y<=W.y+W.height&&r(U.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:q,onTransformEnd:U=>t(e.id,U)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:k,width:e.width-L*2,height:C,fill:v().bg,cornerRadius:8}),jsx(Text,{x:L,y:k,width:e.width-L*2,height:C,text:x(),fontSize:14,fontStyle:"bold",fill:v().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:k+C+b,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:k+C+D,width:e.width-L*2,height:S,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:k+C+D},divProps:{style:{width:`${e.width-L*2}px`,height:`${S}px`,pointerEvents:u?"none":"auto"}},children:jsx("textarea",{value:d,onChange:U=>f(U.target.value),disabled:u,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:u?"none":"auto"}})}),jsx(Group,{y:k+S+D+I+x+V,children:u&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),w();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),w();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:U=>U.cancelBubble=true,onTap:U=>U.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});ol.displayName="LongAnswer";var _u=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(ol,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>n(i,s.id)},s.id))});var Ua=1920,Wa=1080,Yu=3840,Ju=2160,ub=e=>{let o=0,t=0,a=Ua,r=Wa;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:Ua,height:Wa};let n=(l,d,m,u)=>{o=Math.min(o,l),t=Math.min(t,d),a=Math.max(a,l+m),r=Math.max(r,d+u);};e.lines?.forEach(l=>{if(l.points&&l.points.length>=2){let d=l.x||0,m=l.y||0,u=l.scaleX||1,f=l.scaleY||1;for(let c=0;c<l.points.length;c+=2){let p=d+l.points[c]*u,g=m+l.points[c+1]*f;o=Math.min(o,p),t=Math.min(t,g),a=Math.max(a,p),r=Math.max(r,g);}}}),e.images?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.videos?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shapes?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.texts?.forEach(l=>n(l.x,l.y,l.width||200,l.height||l.fontSize||24)),e.flashcards?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.photoFrames?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.multipleChoices?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.trueFalses?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shortAnswers?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.LongAnswer?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.fillInTheBlanks?.forEach(l=>n(l.x,l.y,l.width,l.height));let s=Math.min(a-o,Yu),i=Math.min(r-t,Ju);return o=Math.max(o,a-Yu),t=Math.max(t,r-Ju),{minX:o,minY:t,maxX:a,maxY:r,width:s,height:i}},cb=(e,o,t={minX:0,minY:0,maxX:Ua,maxY:Wa,width:Ua,height:Wa})=>{let a=Math.max(t.width,Ua),r=Math.max(t.height,Wa),n=e/o,s=a/r,i,l,d,u=0;if(n>s){l=r,i=Math.round(l*n),d=o/l;}else {i=a,l=Math.round(i/n),d=e/i;let f=r*d;u=(o-f)/2;}return {scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:u,baseWidth:i,baseHeight:l,contentOffsetX:t.minX,contentOffsetY:t.minY}},Zu=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},fb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r={enabled:true}}={})=>{let n=et(),s=te(y=>y.toolbar.selectedTool),i=te(ge),l=te(Xo),d=i?.editingActivity,m=i?.showMcqForm,u=i?.lines||[],f=useRef(null),c=useRef(null),[p,g]=useState(null),[h,w]=useState(""),b=useRef(null),[v,L]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Ua,stageHeight:Wa,offsetX:0,offsetY:0,baseWidth:Ua,baseHeight:Wa,contentOffsetX:0,contentOffsetY:0}),k=useMemo(()=>ub(i||null),[l]),[S,I]=useState(null),[x,A]=useState(null),[V,D]=useState(null),[q,U]=useState(null),[T,W]=useState(null),[R,oe]=useState(null),[O,fe]=useState(null),[z,N]=useState(false),[j,H]=useState(null),[K,J]=useState(false),ee=useRef(null),Z=useRef(null),ne=useRef(null),{debouncedGenerateThumbnail:Ie}=Rd(l,f);useEffect(()=>{let y=()=>{if(c.current){let P=c.current.getBoundingClientRect(),F=cb(P.width,P.height,k);L(F);}};y();let C=new ResizeObserver(y);return c.current&&C.observe(c.current),window.addEventListener("resize",y),()=>{C.disconnect(),window.removeEventListener("resize",y);}},[k]),useEffect(()=>{if(f.current){let y=f.current.container();y&&(y.style.cursor="");}},[s]);let Y=useCallback(()=>{f.current&&requestAnimationFrame(()=>{if(!f.current)return;f.current.getLayers().forEach(F=>F.batchDraw());let C=1/6,P=f.current.toDataURL({pixelRatio:C});w(P),Ie();});},[Ie]),De=useRef(l);useEffect(()=>{De.current!==l&&(De.current=l,Y());},[l,Y]);let Se=useRef(null),Ft=useRef(true);useEffect(()=>{if(!i)return;let y=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),C=Se.current?.count!==y;!Ft.current&&C&&setTimeout(()=>{Y();},100),Se.current={slideId:l,count:y},Ft.current=false;},[i,l,Y]),useEffect(()=>{f.current&&e&&e(f);},[e]),useEffect(()=>{ne.current&&a&&a(ne);},[a]);let{startDrawing:Ja,draw:Or,stopDrawing:Vo,setCanvasRef:xs,tool:bs,color:vs,strokeWidth:ys,isSketchMode:ws}=nd(Y),E=useRef(new Map),{images:se,getLoadedImage:Ce,imageRefs:me,handleDragEnd:re,handleImageTransformEnd:ie}=fd(Y),{videos:Re,videoRefs:lt,handleVideoClick:Gt,handleVideoDragEnd:dt,handleVideoTransformEnd:Ee}=hd(Y),{multipleChoice:Xe,handleMcqTransform:bt,mcqRefs:Kt,handleDragEnd:Za}=md(Y),{trueFalse:Qa,handleTrueFalseTransform:Nr,trueFalseRefs:Ze,handleTrueFalseDragEnd:na}=pd(Y),{shortAnswers:Ta,saRefs:qo,handleShortAnswerDragEnd:_f}=wd(Y),{longAnswers:jf,handleLongAnswerDragEnd:$f}=Ld(Y),{fillInTheBlanks:Xf,handleFillInTheBlanksDragEnd:Yf,fibRefs:Vr}=qu(Y),{transformerRef:ue,boundBoxFunc:vt}=Td(),{shapes:Jf,shapeRefs:qr,isDragging:zl,handleShapeDragEnd:Zf,handleShapeResizeEnd:Qf}=bd(Y),{texts:Ho,textRefs:sa,handleDragEnd:em,handleTransformEnd:tm,handleDoubleClick:am,startEditing:Hr,editingTextId:pe,editingValue:Gl,handleEditingChange:Kl,finishEditing:Ls}=yd(Y,ee);useEffect(()=>{t&&t(Hr);},[t,Hr]);let Ur=te(y=>y.canvas.editingTextId);useEffect(()=>{Ur&&Ur!==pe&&Hr(Ur);},[Ur,pe,Hr]);let{flashcards:om,flashcardRefs:Wr,handleDragEnd:rm,handleFlashcardTransformEnd:nm,handleNext:sm,handlePrevious:im}=Sd(Y),{photoFrames:_l,photoFrameRefs:zr,handleDragEnd:lm,handlePhotoFrameTransformEnd:dm,startCamera:um,capturePhoto:cm,cameraStreams:fm}=Md(Y);useEffect(()=>{if(ue.current){if(pe){ue.current.nodes([]),ue.current.getLayer()?.batchDraw();return}if(p&&!Re.find(P=>P.id===p)?.isPlaying){let P=E.current.get(p)||me.current.get(p)||lt.current.get(p)||qr.current.get(p)||sa.current.get(p)||Kt.current.get(p)||Wr.current.get(p)||zr.current.get(p)||qo.current.get(p)||Ze.current.get(p)||Vr.current.get(p);if(P){let F=P.attrs?.locked;if(P.visible()&&F!==true){ue.current.nodes([P]),ue.current.getLayer()?.batchDraw();return}}}ue.current.nodes([]),ue.current.getLayer()?.batchDraw();}},[p,pe,Re,E,me,lt,qr,sa,Wr,zr,_l,Kt,Ze,Vr,ue]);let He=useCallback(y=>{g(y),o?.(y);},[o]),eo=useCallback(()=>{g(null),o?.(null),ue.current&&(ue.current.nodes([]),ue.current.getLayer()?.batchDraw());},[ue,o]),jl=useCallback(y=>i?i.lines?.some(C=>C.id===y)?"line":i.images?.some(C=>C.id===y)?"image":i.videos?.some(C=>C.id===y)?"video":i.shapes?.some(C=>C.id===y)?"shape":i.texts?.some(C=>C.id===y)?"text":i.flashcards?.some(C=>C.id===y)?"flashcard":i.photoFrames?.some(C=>C.id===y)?"photoFrame":i.multipleChoices?.some(C=>C.id===y)?"mcq":i.trueFalses?.some(C=>C.id===y)?"trueFalse":i.shortAnswers?.some(C=>C.id===y)?"shortAnswer":i.LongAnswer?.some(C=>C.id===y)?"longAnswer":i.fillInTheBlanks?.some(C=>C.id===y)?"fillInTheBlanks":null:null,[i]),$l=useCallback((y,C)=>{switch(n(de()),C){case "line":n(yn(y));break;case "image":n(Kr(y));break;case "video":n(Xr(y));break;case "shape":n(Zr(y));break;case "text":n(Qr(y));break;case "flashcard":n(tn(y));break;case "photoFrame":n(on(y));break;case "mcq":n(nn(y));break;case "trueFalse":n(ln(y));break;case "shortAnswer":n(un(y));break;case "longAnswer":n(fn(y));break;case "fillInTheBlanks":n(pn(y));break}eo(),Y();},[n,eo,Y]);useEffect(()=>{let y=C=>{if(C.key!=="Delete"||!p||pe)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;C.preventDefault();let Me=jl(p);Me&&$l(p,Me);};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[p,pe,jl,$l]),useEffect(()=>{let y=ue.current;return ()=>{y&&y.nodes([]);}},[l]),useEffect(()=>{let y=C=>{pe&&C.target.tagName!=="TEXTAREA"&&Ls();};return document.addEventListener("mousedown",y),()=>{document.removeEventListener("mousedown",y);}},[pe,Ls]),useEffect(()=>{let y=pe||p;if(!y||p&&pe){A(null);return}let C=sa.current.get(y),P=f.current;if(!C||!P){A(null);return}let F=P.container().getBoundingClientRect(),Me=C.absolutePosition(),we=P.scaleX();A({x:F.left+(Me.x+C.width()*we/2)*we,y:F.top+Me.y*we});},[p,pe,Ho,sa]),useEffect(()=>{if(!pe){D(null);return}let y=sa.current.get(pe),C=f.current;if(!y||!C){D(null);return}let P=C.container().getBoundingClientRect(),F=y.absolutePosition(),Me=C.scaleX();D({top:P.top+F.y*Me,left:P.left+F.x*Me,scale:Me});},[pe,Ho,sa]);let Xl=useCallback(y=>{let C=y.target.getClassName(),P=y.target===y.target.getStage(),F=C==="Transformer"||y.target.getParent()?.getClassName()==="Transformer",Me=C==="Image",we=C==="Text",ae=C==="Group"||y.target.getParent()?.getClassName()==="Group",Bt=C==="Circle"||C==="Star"||C==="RegularPolygon"||C==="Ellipse"||C==="Ring"||C==="Wedge"||C==="Arrow"||C==="Line"||C==="Arc"||C==="Rect"&&y.target.attrs.id,wt=C==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:C,clickedOnImage:Me,clickedOnGroup:ae,tool:s,targetId:y.target.attrs?.id}),P&&!F&&!Me&&!we&&!ae&&!Bt&&!wt&&eo(),!(s==="pen"||s==="eraser")&&(Me||we||F||ae||Bt||wt))return;let Ke=y.target.getStage()?.getPointerPosition();if(!Ke)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(s)){let B=Zu(Ke,v);Ja(B);}},[s,Ja,eo,v]),Yl=useCallback(y=>{if(zl)return;let C=y.target.getStage()?.getPointerPosition();if(!C)return;let P=Zu(C,v);Or(P);},[Or,zl,v]),Jl=useCallback(()=>{Vo();},[Vo]),mm=useCallback(y=>{re(y,Y);},[re,Y]),pm=useCallback(y=>{Gt(y),He(y);},[Gt,He]),yt=useCallback((y,C,P)=>{if(y.preventDefault(),!r.enabled)return;let F=y.clientX,Me=y.clientY,we=b.current?.offsetHeight||450,ae=b.current?.offsetWidth||450,Bt=window.innerHeight,wt=window.innerWidth,Qe=F,Ke=Me;Me+we>Bt&&(Ke=Me-we),F+ae>wt&&(Qe=F-ae),I({x:Qe,y:Ke,elementId:C,elementType:P}),He(C);},[He,r.enabled]),Zl=useCallback(y=>{n(_o(y)),n(da(true));},[n]),hm=useCallback(y=>{n(Wo(y)),n(Pa(true));},[n]),gm=useCallback((y,C)=>{if(!S)return;let{elementId:P,elementType:F}=S;switch(y){case "order":if(C){let M=C.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(C){let M=C.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(I(null),F==="line")break;let Me=i?F==="image"?i.images.find(M=>M.id===P):i.videos.find(M=>M.id===P):null;W({type:"link",defaultValue:Me?.link||""});break;case "voice":if(I(null),F==="line")break;let we=i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="text"?i.texts.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):F==="mcq"?i.multipleChoices.find(M=>M.id===P):F==="fillInTheBlanks"?i.fillInTheBlanks.find(M=>M.id===P):F==="longAnswer"?i.LongAnswer.find(M=>M.id===P):F==="shortAnswer"?i.shortAnswers.find(M=>M.id===P):F==="trueFalse"?i.trueFalses.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):null:null;H({elementId:P,elementType:F,existingAudio:we?.audioData});break;case "edit":I(null);let ae=null;F==="mcq"?ae=i?.multipleChoices.find(M=>M.id===P):F==="trueFalse"?ae=i?.trueFalses.find(M=>M.id===P):F==="shortAnswer"?ae=i?.shortAnswers.find(M=>M.id===P):F==="longAnswer"?ae=i?.LongAnswer.find(M=>M.id===P):F==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(M=>M.id===P)),ae&&Zl(ae);break;case "editFlashcard":I(null);let Bt=i?.flashcards.find(M=>M.id===P);Bt&&hm(Bt);break;case "color":I(null);let wt=i?.shapes.find(M=>M.id===P);oe({elementId:P,elementType:"shape",defaultColor:wt?.color||"#096B76"});break;case "crop":if(I(null),F==="image"){let M=i?.images.find(Im=>Im.id===P);M&&fe({elementId:P,imageSrc:M.src});}break;case "draw":I(null),F==="image"?n(Us(P)):F==="photoFrame"&&n(zs(P));break;case "duplicate":n(de()),F==="line"?n(ti(P)):F==="image"?n(_r(P)):F==="video"?n(Yr(P)):F==="shape"?n(Jr(P)):F==="text"?n(en(P)):F==="flashcard"?n(an(P)):F==="photoFrame"?n(rn(P)):F==="mcq"?n(sn(P)):F==="trueFalse"?n(dn(P)):F==="shortAnswer"?n(cn(P)):F==="fillInTheBlanks"?n(hn(P)):F==="longAnswer"&&n(mn(P)),Y();break;case "infinite-clone":n(de());let Qe=5;for(let M=0;M<Qe;M++)F==="image"?n(_r(P)):F==="video"?n(Yr(P)):F==="shape"?n(Jr(P)):F==="text"?n(en(P)):F==="flashcard"?n(an(P)):F==="photoFrame"?n(rn(P)):F==="mcq"?n(sn(P)):F==="trueFalse"?n(dn(P)):F==="shortAnswer"?n(cn(P)):F==="fillInTheBlanks"?n(hn(P)):F==="longAnswer"&&n(mn(P));Y();break;case "make-response":if(I(null),F==="line")break;let Ke=`#response-${P}`;n(de()),n(gn({id:P,type:F,link:Ke})),(i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):i.multipleChoices.find(M=>M.id===P):null)?.altText||n(xn({id:P,type:F,altText:"Interactive response area"})),Y(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(I(null),F==="line")break;let B=i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):null:null;W({type:"altText",defaultValue:B?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),I(null),J(true),console.log("showLayersPanel state set to:",true);break;case "delete":n(de()),F==="line"?n(yn(P)):F==="image"?n(Kr(P)):F==="video"?n(Xr(P)):F==="shape"?n(Zr(P)):F==="text"?n(Qr(P)):F==="flashcard"?n(tn(P)):F==="photoFrame"?n(on(P)):F==="mcq"?n(nn(P)):F==="trueFalse"?n(ln(P)):F==="shortAnswer"?n(un(P)):F==="longAnswer"?n(fn(P)):F==="fillInTheBlanks"&&n(pn(P)),eo(),Y();break}},[S,n,Y,eo,i,Zl]),xm=useCallback(()=>{I(null),U(null);},[]),Is=useCallback(y=>{if(!S)return;let{elementId:C,elementType:P}=S;switch(n(de()),y){case "bring-to-front":P!=="line"&&n(Js({id:C,type:P}));break;case "send-to-back":P!=="line"&&n(Zs({id:C,type:P}));break;case "lock":case "unlock":P!=="line"&&n(Qs({id:C,type:P}));break}Y(),I(null),U(null);},[S,n,Y]),bm=useCallback(y=>{if(!S||!T)return;let{elementId:C,elementType:P}=S;n(de()),T.type==="link"&&P!=="line"?n(gn({id:C,type:P,link:y})):T.type==="altText"&&P!=="line"&&n(xn({id:C,type:P,altText:y})),Y(),W(null);},[S,T,n,Y]),vm=useCallback(y=>{if(!j)return;let{elementId:C,elementType:P}=j;n(de()),n(bn({id:C,type:P,audioData:y})),Y(),H(null);},[j,n,Y]),ym=useCallback(()=>{if(!j)return;let{elementId:y,elementType:C}=j;n(de()),n(bn({id:y,type:C,audioData:""})),Y();},[j,n,Y]),wm=useCallback(y=>{if(!R)return;let{elementId:C}=R;n(de()),n(oo({id:C,color:y})),Y(),oe(null);},[R,n,Y]),Lm=useCallback(y=>{if(!O)return;let{elementId:C}=O;n(de()),n(ao({id:C,src:y})),Y(),fe(null);},[O,n,Y]);return jsxs("div",{ref:c,className:"fixed inset-0",style:{cursor:s==="pen"?"crosshair":s==="eraser"?"":"default"},children:[s==="pen"&&jsx(ud,{ref:y=>{if(Z.current=y,xs(y),y){let C=y.getCanvasElement();C&&(ne.current=C,a&&a(ne));}},width:v.baseWidth,height:v.baseHeight,tool:bs,color:vs,strokeWidth:ys/v.scale,isSketchMode:ws,xOffset:v.contentOffsetX,yOffset:v.contentOffsetY-v.offsetY/v.scale,style:{width:v.stageWidth,height:v.stageHeight}}),jsxs(Stage,{ref:f,width:v.stageWidth,height:v.stageHeight,scaleX:v.scaleX,scaleY:v.scaleY,x:v.offsetX,y:0,onMouseDown:Xl,onMouseMove:Yl,onMouseUp:Jl,onTouchStart:Xl,onTouchMove:Yl,onTouchEnd:Jl,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:v.baseWidth,height:v.stageHeight/v.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-v.contentOffsetX,y:v.offsetY/v.scale-v.contentOffsetY,children:(()=>{let y=[];return u.forEach((C,P)=>{y.push({type:"line",timestamp:C.timestamp||P,element:{...C,id:C.id??`line-${P}`},index:P});}),Jf.forEach(C=>{y.push({type:"shape",timestamp:C.timestamp||0,element:C});}),se.forEach(C=>{y.push({type:"image",timestamp:C.timestamp||0,element:C});}),Re.forEach(C=>{y.push({type:"video",timestamp:C.timestamp||0,element:C});}),Ho.forEach(C=>{y.push({type:"text",timestamp:C.timestamp||0,element:C});}),om.forEach(C=>{y.push({type:"flashcard",timestamp:C.timestamp||0,element:C});}),_l.forEach(C=>{y.push({type:"photoFrame",timestamp:C.timestamp||0,element:C});}),Xe.forEach(C=>{y.push({type:"mcq",timestamp:C.timestamp||0,element:C});}),Qa.forEach(C=>{y.push({type:"trueFalse",timestamp:C.timestamp||0,element:C});}),Ta.forEach(C=>{y.push({type:"shortAnswer",timestamp:C.timestamp||0,element:C});}),jf.forEach(C=>{y.push({type:"longAnswer",timestamp:C.timestamp||0,element:C});}),Xf.forEach(C=>{y.push({type:"fillInTheBlanks",timestamp:C.timestamp||0,element:C});}),y.sort((C,P)=>C.timestamp-P.timestamp),y.map((C,P)=>{let F=`${C.type}-${"id"in C.element&&C.element.id||C.index||P}`,Me="id"in C.element?C.element.id:void 0,we=Me&&p===Me;switch(C.type){case "line":let ae=C.element,Bt=C.index||0,wt=ae.tool==="eraser",Qe=ae.isSketch&&ae.tool==="pen",Ke=ae.isSketch&&wt,Lt=ae.id||`line-${Bt}`;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),s==="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:Qe||Ke?void 0:ae.color,strokeWidth:Qe||Ke?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||Ke?wt?"black":ae.color:void 0,closed:Qe||Ke,tension:0,globalCompositeOperation:wt?"destination-out":"source-over",listening:true,onClick:()=>{n(de()),n(Gr(Bt));},onTap:()=>{n(de()),n(Gr(Bt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:B=>{let M=B.target.getStage();M&&(M.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:B=>{let M=B.target.getStage();M&&(M.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`);}})},F):jsxs(be__default.Fragment,{children:[jsx(Group,{id:Lt,ref:B=>{B?E.current.set(Lt,B):E.current.delete(Lt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:s==="select",listening:s==="select",onClick:()=>{s==="select"&&(console.log("Line clicked:",Lt),He(Lt));},onTap:()=>{s==="select"&&(console.log("Line tapped:",Lt),He(Lt));},onDragEnd:B=>{n(de()),n(vn({id:Lt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onTransformEnd:B=>{n(de()),n(vn({id:Lt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onMouseEnter:B=>{if(s==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(s==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),yt(M,Lt,"line");},children:jsx(Line,{points:ae.points||[],stroke:Qe||Ke?void 0:ae.color,strokeWidth:Qe||Ke?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||Ke?wt?"black":ae.color:void 0,closed:Qe||Ke,tension:0,globalCompositeOperation:wt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=E.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:vt,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"]})]},F);case "shape":return jsxs(be__default.Fragment,{children:[jsx(yi,{onSelect:He,shapes:[C.element],shapeRefs:qr,handleShapeDragEnd:Zf,handleShapeResizeEnd:Qf,onContextMenu:yt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=qr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "image":return jsxs(be__default.Fragment,{children:[jsx(gi,{images:[C.element],getLoadedImage:Ce,imageRefs:me,onDragEnd:mm,onTransform:ie,onSelect:He,onContextMenu:yt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=me.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "video":return jsxs(be__default.Fragment,{children:[jsx(vi,{videos:[C.element],selectedId:p,videoRefs:lt,onVideoClick:pm,onDragEnd:dt,onTransformEnd:Ee,onContextMenu:yt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=lt.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "text":return jsxs(be__default.Fragment,{children:[jsx(zd,{texts:[C.element],textRefs:sa,onDragEnd:em,onTransformEnd:tm,onSelect:He,onContextMenu:yt,onDoubleClick:am,editingTextId:pe,editingValue:Gl,onEditingChange:Kl}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=sa.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Ii,{flashcards:[C.element],flashcardRefs:Wr,selectedId:p,onDragEnd:rm,onTransform:nm,onSelect:He,onNext:sm,onPrevious:im,onContextMenu:yt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Wr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Ti,{photoFrames:[C.element],photoFrameRefs:zr,selectedId:p,onDragEnd:lm,onTransform:dm,onSelect:He,onStartCamera:um,onCapture:cm,cameraStreams:fm,onContextMenu:yt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=zr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(xu,{handleMcqTransform:bt,multipleChoice:[C.element],handleSelect:He,mcqRefs:Kt,handleDragEnd:Za,onContextMenu:yt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Kt.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(yu,{trueFalses:[C.element],handleTrueFalseTransform:Nr,handleSelect:He,trueFalseRefs:Ze,onContextMenu:yt,handleDragEnd:na}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ze.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(Vu,{shortAnswers:[C.element],handleSelect:He,handleTransform:bt,saRefs:qo,onContextMenu:yt,handleDragEnd:_f}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=qo.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(_u,{longAnswer:[C.element],handleSelect:He,handleTransform:bt,saRefs:qo,onContextMenu:yt,handleDragEnd:$f}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=qo.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Gu,{fillInTheBlanks:[C.element],handleSelect:He,handleTransform:bt,onContextMenu:yt,handleDragEnd:Yf,fibRefs:Vr}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Vr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:vt,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"]})]},F);default:return null}})})()})]}),S&&jsx(au,{menuRef:b,x:S.x,y:S.y,type:S.elementType,onAction:gm,onClose:xm,isDrawingMode:S.elementType==="image"?i?.images.find(y=>y.id===S.elementId)?.isDrawingMode:S.elementType==="photoFrame"?i?.photoFrames.find(y=>y.id===S.elementId)?.isDrawingMode:false}),q&&S&&jsx(ou,{x:q.x,y:q.y,items:q.type==="order"?[{label:"Bring to Front",onClick:()=>Is("bring-to-front")},{label:"Send to Back",onClick:()=>Is("send-to-back")}]:[{label:i&&(S.elementType==="image"?i.images.find(y=>y.id===S.elementId)?.locked:i.videos.find(y=>y.id===S.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Is(i&&(S.elementType==="image"?i.images.find(y=>y.id===S.elementId)?.locked:i.videos.find(y=>y.id===S.elementId)?.locked)?"unlock":"lock")}],onClose:()=>U(null)}),T&&jsx(ru,{title:T.type==="link"?"Add Link":"Add Alt Text",label:T.type==="link"?"URL":"Alternative Text",placeholder:T.type==="link"?"https://example.com":"Describe this image/video",defaultValue:T.defaultValue,onSave:bm,onClose:()=>W(null)}),R&&jsx(nu,{defaultColor:R.defaultColor,onConfirm:wm,onCancel:()=>oe(null)}),O&&jsx(du,{imageSrc:O.imageSrc,onConfirm:Lm,onCancel:()=>fe(null)}),z&&jsx(nr,{onClose:()=>N(false),stageRef:f}),j&&jsx(cu,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:vm,onDelete:ym,onClose:()=>H(null)}),K&&jsx(pu,{selectedElementId:p||void 0,onClose:()=>J(false),onSelectElement:y=>{He(y),J(false);}}),i?.images.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.videos.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.shapes?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.texts?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.flashcards?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.photoFrames?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.multipleChoices?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.trueFalses?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.shortAnswers?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.LongAnswer?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),i?.fillInTheBlanks?.filter(y=>y.audioData).map(y=>jsx(kt,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),m&&jsx(Du,{editElement:d}),x&&(()=>{let y=pe||p;if(!y)return null;let C=Ho.find(P=>P.id===y);return C?jsx(Ru,{text:C,position:x}):null})(),V&&pe&&(()=>{let y=Ho.find(C=>C.id===pe);return y?jsx(Fu,{text:y,editingValue:Gl,onEditingChange:Kl,onFinish:Ls,position:{top:V.top,left:V.left},scale:V.scale,textareaRef:ee},pe):null})()]})},mb=fb;var pb="SchooplaVideoStorage";var Yt="videos",es=()=>new Promise((e,o)=>{let t=indexedDB.open(pb,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Yt)||r.createObjectStore(Yt,{keyPath:"id"});};}),za=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await es(),n=a.transaction([Yt],"readwrite").objectStore(Yt),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,l)=>{let d=n.put(s);d.onsuccess=()=>i(!0),d.onerror=()=>l(d.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 Qu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await es(),t=e.transaction([Yt],"readonly").objectStore(Yt);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,i=new Map;s.forEach(l=>{i.set(l.id,{blob:l.blob,thumbnailDataUrl:l.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}},rl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await es(),a=o.transaction([Yt],"readwrite").objectStore(Yt);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}},ec=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await es(),t=e.transaction([Yt],"readwrite").objectStore(Yt);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},tc=e=>URL.createObjectURL(e);function wa(e,o=[]){let t=[];function a(n,s){let i=be.createContext(s),l=t.length;t=[...t,s];let d=u=>{let{scope:f,children:c,...p}=u,g=f?.[e]?.[l]||i,h=be.useMemo(()=>p,Object.values(p));return jsx(g.Provider,{value:h,children:c})};d.displayName=n+"Provider";function m(u,f){let c=f?.[e]?.[l]||i,p=be.useContext(c);if(p)return p;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${n}\``)}return [d,m]}let r=()=>{let n=t.map(s=>be.createContext(s));return function(i){let l=i?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:l}}),[i,l])}};return r.scopeName=e,[a,gb(r,...o)]}function gb(...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:l,scopeName:d})=>{let u=l(n)[`__scope${d}`];return {...i,...u}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function ac(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Mr(...e){return o=>{let t=false,a=e.map(r=>{let n=ac(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():ac(e[r],null);}}}}function Dt(...e){return be.useCallback(Mr(...e),e)}function nc(e){let o=xb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,i=be.Children.toArray(n),l=i.find(vb);if(l){let d=l.props.children,m=i.map(u=>u===l?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function xb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=wb(r),i=yb(n,r.props);return r.type!==be.Fragment&&(i.ref=a?Mr(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 bb=Symbol("radix.slottable");function vb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===bb}function yb(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 l=n(...i);return r(...i),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function wb(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 Sb=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],st=Sb.reduce((e,o)=>{let t=nc(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:s,...i}=r,l=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(l,{...i,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function je(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function nl(e){let o=Cb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,i=be.Children.toArray(n),l=i.find(Mb);if(l){let d=l.props.children,m=i.map(u=>u===l?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function Cb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=Ab(r),i=Tb(n,r.props);return r.type!==be.Fragment&&(i.ref=a?Mr(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 kb=Symbol("radix.slottable");function Mb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===kb}function Tb(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 l=n(...i);return r(...i),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function Ab(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 ts(e){let o=e+"CollectionProvider",[t,a]=wa(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=g=>{let{scope:h,children:w}=g,b=be__default.useRef(null),v=be__default.useRef(new Map).current;return jsx(r,{scope:h,itemMap:v,collectionRef:b,children:w})};s.displayName=o;let i=e+"CollectionSlot",l=nl(i),d=be__default.forwardRef((g,h)=>{let{scope:w,children:b}=g,v=n(i,w),L=Dt(h,v.collectionRef);return jsx(l,{ref:L,children:b})});d.displayName=i;let m=e+"CollectionItemSlot",u="data-radix-collection-item",f=nl(m),c=be__default.forwardRef((g,h)=>{let{scope:w,children:b,...v}=g,L=be__default.useRef(null),k=Dt(h,L),S=n(m,w);return be__default.useEffect(()=>(S.itemMap.set(L,{ref:L,...v}),()=>void S.itemMap.delete(L))),jsx(f,{[u]:"",ref:k,children:b})});c.displayName=m;function p(g){let h=n(e+"CollectionConsumer",g);return be__default.useCallback(()=>{let b=h.collectionRef.current;if(!b)return [];let v=Array.from(b.querySelectorAll(`[${u}]`));return Array.from(h.itemMap.values()).sort((S,I)=>v.indexOf(S.ref.current)-v.indexOf(I.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:s,Slot:d,ItemSlot:c},p,a]}var To=globalThis?.document?be.useLayoutEffect:()=>{};var Pb=be[" useId ".trim().toString()]||(()=>{}),Db=0;function dc(e){let[o,t]=be.useState(Pb());return To(()=>{t(a=>a??String(Db++));},[e]),(o?`radix-${o}`:"")}function uc(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Rb=be[" useInsertionEffect ".trim().toString()]||To;function ea({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=Eb({defaultProp:o,onChange:t}),i=e!==void 0,l=i?e:r;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let u=m.current;u!==i&&console.warn(`${a} is changing from ${u?"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.`),m.current=i;},[i,a]);}let d=be.useCallback(m=>{if(i){let u=Fb(m)?m(e):m;u!==e&&s.current?.(u);}else n(m);},[i,e,n,s]);return [l,d]}function Eb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return Rb(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function Fb(e){return typeof e=="function"}var Bb=be.createContext(void 0);function Po(e){let o=be.useContext(Bb);return e||o||"ltr"}var ll="rovingFocusGroup.onEntryFocus",Ob={bubbles:false,cancelable:true},Tr="RovingFocusGroup",[dl,cc,Nb]=ts(Tr),[Vb,ul]=wa(Tr,[Nb]),[qb,Hb]=Vb(Tr),fc=be.forwardRef((e,o)=>jsx(dl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(dl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Ub,{...e,ref:o})})}));fc.displayName=Tr;var Ub=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:m=false,...u}=e,f=be.useRef(null),c=Dt(o,f),p=Po(n),[g,h]=ea({prop:s,defaultProp:i??null,onChange:l,caller:Tr}),[w,b]=be.useState(false),v=uc(d),L=cc(t),k=be.useRef(false),[S,I]=be.useState(0);return be.useEffect(()=>{let x=f.current;if(x)return x.addEventListener(ll,v),()=>x.removeEventListener(ll,v)},[v]),jsx(qb,{scope:t,orientation:a,dir:p,loop:r,currentTabStopId:g,onItemFocus:be.useCallback(x=>h(x),[h]),onItemShiftTab:be.useCallback(()=>b(true),[]),onFocusableItemAdd:be.useCallback(()=>I(x=>x+1),[]),onFocusableItemRemove:be.useCallback(()=>I(x=>x-1),[]),children:jsx(st.div,{tabIndex:w||S===0?-1:0,"data-orientation":a,...u,ref:c,style:{outline:"none",...e.style},onMouseDown:je(e.onMouseDown,()=>{k.current=true;}),onFocus:je(e.onFocus,x=>{let A=!k.current;if(x.target===x.currentTarget&&A&&!w){let V=new CustomEvent(ll,Ob);if(x.currentTarget.dispatchEvent(V),!V.defaultPrevented){let D=L().filter(R=>R.focusable),q=D.find(R=>R.active),U=D.find(R=>R.id===g),W=[q,U,...D].filter(Boolean).map(R=>R.ref.current);hc(W,m);}}k.current=false;}),onBlur:je(e.onBlur,()=>b(false))})})}),mc="RovingFocusGroupItem",pc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...i}=e,l=dc(),d=n||l,m=Hb(mc,t),u=m.currentTabStopId===d,f=cc(t),{onFocusableItemAdd:c,onFocusableItemRemove:p,currentTabStopId:g}=m;return be.useEffect(()=>{if(a)return c(),()=>p()},[a,c,p]),jsx(dl.ItemSlot,{scope:t,id:d,focusable:a,active:r,children:jsx(st.span,{tabIndex:u?0:-1,"data-orientation":m.orientation,...i,ref:o,onMouseDown:je(e.onMouseDown,h=>{a?m.onItemFocus(d):h.preventDefault();}),onFocus:je(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:je(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let w=Gb(h,m.orientation,m.dir);if(w!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let v=f().filter(L=>L.focusable).map(L=>L.ref.current);if(w==="last")v.reverse();else if(w==="prev"||w==="next"){w==="prev"&&v.reverse();let L=v.indexOf(h.currentTarget);v=m.loop?Kb(v,L+1):v.slice(L+1);}setTimeout(()=>hc(v));}}),children:typeof s=="function"?s({isCurrentTabStop:u,hasTabStop:g!=null}):s})})});pc.displayName=mc;var Wb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function zb(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Gb(e,o,t){let a=zb(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Wb[a]}function hc(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Kb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var gc=fc,xc=pc;var vc="Toggle",cl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,i]=ea({prop:t,onChange:r,defaultProp:a??false,caller:vc});return jsx(st.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:je(e.onClick,()=>{e.disabled||i(!s);})})});cl.displayName=vc;var La="ToggleGroup",[wc]=wa(La,[ul]),Lc=ul(),fl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx($b,{...a,ref:o});if(t==="multiple")return jsx(Xb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${La}\``)});fl.displayName=La;var[Ic,Sc]=wc(La),$b=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,i]=ea({prop:t,defaultProp:a??"",onChange:r,caller:La});return jsx(Ic,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(Cc,{...n,ref:o})})}),Xb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,i]=ea({prop:t,defaultProp:a??[],onChange:r,caller:La}),l=be__default.useCallback(m=>i((u=[])=>[...u,m]),[i]),d=be__default.useCallback(m=>i((u=[])=>u.filter(f=>f!==m)),[i]);return jsx(Ic,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:l,onItemDeactivate:d,children:jsx(Cc,{...n,ref:o})})});fl.displayName=La;var[Yb,Jb]=wc(La),Cc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:i=true,...l}=e,d=Lc(t),m=Po(s),u={role:"group",dir:m,...l};return jsx(Yb,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(gc,{asChild:true,...d,orientation:n,dir:m,loop:i,children:jsx(st.div,{...u,ref:o})}):jsx(st.div,{...u,ref:o})})}),rs="ToggleGroupItem",Zb=be__default.forwardRef((e,o)=>{let t=Sc(rs,e.__scopeToggleGroup),a=Jb(rs,e.__scopeToggleGroup),r=Lc(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,i={...e,pressed:n,disabled:s},l=be__default.useRef(null);return a.rovingFocus?jsx(xc,{asChild:true,...r,focusable:!s,active:n,ref:l,children:jsx(yc,{...i,ref:o})}):jsx(yc,{...i,ref:o})});Zb.displayName=rs;var yc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=Sc(rs,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=n.type==="single"?s:void 0;return jsx(cl,{...i,...r,ref:o,onPressedChange:l=>{l?n.onItemActivate(a):n.onItemDeactivate(a);}})}),kc=fl;function Mc(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=Mc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function ns(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=Mc(e))&&(a&&(a+=" "),a+=o);return a}var ev=(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},tv=(e,o)=>({classGroupId:e,validator:o}),Rc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Tc=[],av="arbitrary..",ov=e=>{let o=nv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return rv(s);let i=s.split("-"),l=i[0]===""&&i.length>1?1:0;return Ec(i,l,o)},getConflictingClassGroupIds:(s,i)=>{if(i){let l=a[s],d=t[s];return l?d?ev(d,l):l:d||Tc}return t[s]||Tc}}},Ec=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let d=Ec(e,o+1,n);if(d)return d}let s=t.validators;if(s===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),l=s.length;for(let d=0;d<l;d++){let m=s[d];if(m.validator(i))return m.classGroupId}},rv=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?av+a:void 0})(),nv=e=>{let{theme:o,classGroups:t}=e;return sv(t,o)},sv=(e,o)=>{let t=Rc();for(let a in e){let r=e[a];hl(r,t,a,o);}return t},hl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];iv(s,o,t,a);}},iv=(e,o,t,a)=>{if(typeof e=="string"){lv(e,o,t);return}if(typeof e=="function"){dv(e,o,t,a);return}uv(e,o,t,a);},lv=(e,o,t)=>{let a=e===""?o:Fc(o,e);a.classGroupId=t;},dv=(e,o,t,a)=>{if(cv(e)){hl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(tv(t,e));},uv=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[i,l]=r[s];hl(l,Fc(o,i),t,a);}},Fc=(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=Rc(),t.nextPart.set(s,i)),t=i;}return t},cv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,fv=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 mv=[],Ac=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),pv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,i=0,l=0,d,m=r.length;for(let g=0;g<m;g++){let h=r[g];if(s===0&&i===0){if(h===":"){n.push(r.slice(l,g)),l=g+1;continue}if(h==="/"){d=g;continue}}h==="["?s++:h==="]"?s--:h==="("?i++:h===")"&&i--;}let u=n.length===0?r:r.slice(l),f=u,c=false;u.endsWith("!")?(f=u.slice(0,-1),c=true):u.startsWith("!")&&(f=u.slice(1),c=true);let p=d&&d>l?d-l:void 0;return Ac(n,c,f,p)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):Ac(mv,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},hv=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]==="[",l=o.has(s);i||l?(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}},gv=e=>({cache:fv(e.cacheSize),parseClassName:pv(e),sortModifiers:hv(e),...ov(e)}),xv=/\s+/,bv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],i=e.trim().split(xv),l="";for(let d=i.length-1;d>=0;d-=1){let m=i[d],{isExternal:u,modifiers:f,hasImportantModifier:c,baseClassName:p,maybePostfixModifierPosition:g}=t(m);if(u){l=m+(l.length>0?" "+l:l);continue}let h=!!g,w=a(h?p.substring(0,g):p);if(!w){if(!h){l=m+(l.length>0?" "+l:l);continue}if(w=a(p),!w){l=m+(l.length>0?" "+l:l);continue}h=false;}let b=f.length===0?"":f.length===1?f[0]:n(f).join(":"),v=c?b+"!":b,L=v+w;if(s.indexOf(L)>-1)continue;s.push(L);let k=r(w,h);for(let S=0;S<k.length;++S){let I=k[S];s.push(v+I);}l=m+(l.length>0?" "+l:l);}return l},vv=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Bc(t))&&(r&&(r+=" "),r+=a);return r},Bc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Bc(e[a]))&&(t&&(t+=" "),t+=o);return t},yv=(e,...o)=>{let t,a,r,n,s=l=>{let d=o.reduce((m,u)=>u(m),e());return t=gv(d),a=t.cache.get,r=t.cache.set,n=i,i(l)},i=l=>{let d=a(l);if(d)return d;let m=bv(l,t);return r(l,m),m};return n=s,(...l)=>n(vv(...l))},wv=[],Ve=e=>{let o=t=>t[e]||wv;return o.isThemeGetter=true,o},Oc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Nc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Lv=/^\d+\/\d+$/,Iv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Sv=/\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$/,Cv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,kv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Mv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Do=e=>Lv.test(e),le=e=>!!e&&!Number.isNaN(Number(e)),Ia=e=>!!e&&Number.isInteger(Number(e)),ml=e=>e.endsWith("%")&&le(e.slice(0,-1)),ta=e=>Iv.test(e),Tv=()=>true,Av=e=>Sv.test(e)&&!Cv.test(e),Vc=()=>false,Pv=e=>kv.test(e),Dv=e=>Mv.test(e),Rv=e=>!$(e)&&!X(e),Ev=e=>Ro(e,Uc,Vc),$=e=>Oc.test(e),_a=e=>Ro(e,Wc,Av),pl=e=>Ro(e,Vv,le),Pc=e=>Ro(e,qc,Vc),Fv=e=>Ro(e,Hc,Dv),ss=e=>Ro(e,zc,Pv),X=e=>Nc.test(e),Ar=e=>Eo(e,Wc),Bv=e=>Eo(e,qv),Dc=e=>Eo(e,qc),Ov=e=>Eo(e,Uc),Nv=e=>Eo(e,Hc),is=e=>Eo(e,zc,true),Ro=(e,o,t)=>{let a=Oc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Eo=(e,o,t=false)=>{let a=Nc.exec(e);return a?a[1]?o(a[1]):t:false},qc=e=>e==="position"||e==="percentage",Hc=e=>e==="image"||e==="url",Uc=e=>e==="length"||e==="size"||e==="bg-size",Wc=e=>e==="length",Vv=e=>e==="number",qv=e=>e==="family-name",zc=e=>e==="shadow";var Hv=()=>{let e=Ve("color"),o=Ve("font"),t=Ve("text"),a=Ve("font-weight"),r=Ve("tracking"),n=Ve("leading"),s=Ve("breakpoint"),i=Ve("container"),l=Ve("spacing"),d=Ve("radius"),m=Ve("shadow"),u=Ve("inset-shadow"),f=Ve("text-shadow"),c=Ve("drop-shadow"),p=Ve("blur"),g=Ve("perspective"),h=Ve("aspect"),w=Ve("ease"),b=Ve("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...L(),X,$],S=()=>["auto","hidden","clip","visible","scroll"],I=()=>["auto","contain","none"],x=()=>[X,$,l],A=()=>[Do,"full","auto",...x()],V=()=>[Ia,"none","subgrid",X,$],D=()=>["auto",{span:["full",Ia,X,$]},Ia,X,$],q=()=>[Ia,"auto",X,$],U=()=>["auto","min","max","fr",X,$],T=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],R=()=>["auto",...x()],oe=()=>[Do,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],O=()=>[e,X,$],fe=()=>[...L(),Dc,Pc,{position:[X,$]}],z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],N=()=>["auto","cover","contain",Ov,Ev,{size:[X,$]}],j=()=>[ml,Ar,_a],H=()=>["","none","full",d,X,$],K=()=>["",le,Ar,_a],J=()=>["solid","dashed","dotted","double"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Z=()=>[le,ml,Dc,Pc],ne=()=>["","none",p,X,$],Ie=()=>["none",le,X,$],Y=()=>["none",le,X,$],De=()=>[le,X,$],Se=()=>[Do,"full",...x()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ta],breakpoint:[ta],color:[Tv],container:[ta],"drop-shadow":[ta],ease:["in","out","in-out"],font:[Rv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ta],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ta],shadow:[ta],spacing:["px",le],text:[ta],"text-shadow":[ta],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Do,$,X,h]}],container:["container"],columns:[{columns:[le,$,X,i]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"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:k()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:A()}],"inset-x":[{"inset-x":A()}],"inset-y":[{"inset-y":A()}],start:[{start:A()}],end:[{end:A()}],top:[{top:A()}],right:[{right:A()}],bottom:[{bottom:A()}],left:[{left:A()}],visibility:["visible","invisible","collapse"],z:[{z:[Ia,"auto",X,$]}],basis:[{basis:[Do,"full","auto",i,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[le,Do,"auto","initial","none",$]}],grow:[{grow:["",le,X,$]}],shrink:[{shrink:["",le,X,$]}],order:[{order:[Ia,"first","last","none",X,$]}],"grid-cols":[{"grid-cols":V()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":V()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":U()}],"auto-rows":[{"auto-rows":U()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...T(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...T()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":T()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:R()}],mx:[{mx:R()}],my:[{my:R()}],ms:[{ms:R()}],me:[{me:R()}],mt:[{mt:R()}],mr:[{mr:R()}],mb:[{mb:R()}],ml:[{ml:R()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:oe()}],w:[{w:[i,"screen",...oe()]}],"min-w":[{"min-w":[i,"screen","none",...oe()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[s]},...oe()]}],h:[{h:["screen","lh",...oe()]}],"min-h":[{"min-h":["screen","lh","none",...oe()]}],"max-h":[{"max-h":["screen","lh",...oe()]}],"font-size":[{text:["base",t,Ar,_a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,X,pl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ml,$]}],"font-family":[{font:[Bv,$,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,X,$]}],"line-clamp":[{"line-clamp":[le,"none",X,pl]}],leading:[{leading:[n,...x()]}],"list-image":[{"list-image":["none",X,$]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",X,$]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:O()}],"text-color":[{text:O()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[le,"from-font","auto",X,_a]}],"text-decoration-color":[{decoration:O()}],"underline-offset":[{"underline-offset":[le,"auto",X,$]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:x()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",X,$]}],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",X,$]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:fe()}],"bg-repeat":[{bg:z()}],"bg-size":[{bg:N()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ia,X,$],radial:["",X,$],conic:[Ia,X,$]},Nv,Fv]}],"bg-color":[{bg:O()}],"gradient-from-pos":[{from:j()}],"gradient-via-pos":[{via:j()}],"gradient-to-pos":[{to:j()}],"gradient-from":[{from:O()}],"gradient-via":[{via:O()}],"gradient-to":[{to:O()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:O()}],"border-color-x":[{"border-x":O()}],"border-color-y":[{"border-y":O()}],"border-color-s":[{"border-s":O()}],"border-color-e":[{"border-e":O()}],"border-color-t":[{"border-t":O()}],"border-color-r":[{"border-r":O()}],"border-color-b":[{"border-b":O()}],"border-color-l":[{"border-l":O()}],"divide-color":[{divide:O()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[le,X,$]}],"outline-w":[{outline:["",le,Ar,_a]}],"outline-color":[{outline:O()}],shadow:[{shadow:["","none",m,is,ss]}],"shadow-color":[{shadow:O()}],"inset-shadow":[{"inset-shadow":["none",u,is,ss]}],"inset-shadow-color":[{"inset-shadow":O()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:O()}],"ring-offset-w":[{"ring-offset":[le,_a]}],"ring-offset-color":[{"ring-offset":O()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":O()}],"text-shadow":[{"text-shadow":["none",f,is,ss]}],"text-shadow-color":[{"text-shadow":O()}],opacity:[{opacity:[le,X,$]}],"mix-blend":[{"mix-blend":[...ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ee()}],"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":Z()}],"mask-image-linear-to-pos":[{"mask-linear-to":Z()}],"mask-image-linear-from-color":[{"mask-linear-from":O()}],"mask-image-linear-to-color":[{"mask-linear-to":O()}],"mask-image-t-from-pos":[{"mask-t-from":Z()}],"mask-image-t-to-pos":[{"mask-t-to":Z()}],"mask-image-t-from-color":[{"mask-t-from":O()}],"mask-image-t-to-color":[{"mask-t-to":O()}],"mask-image-r-from-pos":[{"mask-r-from":Z()}],"mask-image-r-to-pos":[{"mask-r-to":Z()}],"mask-image-r-from-color":[{"mask-r-from":O()}],"mask-image-r-to-color":[{"mask-r-to":O()}],"mask-image-b-from-pos":[{"mask-b-from":Z()}],"mask-image-b-to-pos":[{"mask-b-to":Z()}],"mask-image-b-from-color":[{"mask-b-from":O()}],"mask-image-b-to-color":[{"mask-b-to":O()}],"mask-image-l-from-pos":[{"mask-l-from":Z()}],"mask-image-l-to-pos":[{"mask-l-to":Z()}],"mask-image-l-from-color":[{"mask-l-from":O()}],"mask-image-l-to-color":[{"mask-l-to":O()}],"mask-image-x-from-pos":[{"mask-x-from":Z()}],"mask-image-x-to-pos":[{"mask-x-to":Z()}],"mask-image-x-from-color":[{"mask-x-from":O()}],"mask-image-x-to-color":[{"mask-x-to":O()}],"mask-image-y-from-pos":[{"mask-y-from":Z()}],"mask-image-y-to-pos":[{"mask-y-to":Z()}],"mask-image-y-from-color":[{"mask-y-from":O()}],"mask-image-y-to-color":[{"mask-y-to":O()}],"mask-image-radial":[{"mask-radial":[X,$]}],"mask-image-radial-from-pos":[{"mask-radial-from":Z()}],"mask-image-radial-to-pos":[{"mask-radial-to":Z()}],"mask-image-radial-from-color":[{"mask-radial-from":O()}],"mask-image-radial-to-color":[{"mask-radial-to":O()}],"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":L()}],"mask-image-conic-pos":[{"mask-conic":[le]}],"mask-image-conic-from-pos":[{"mask-conic-from":Z()}],"mask-image-conic-to-pos":[{"mask-conic-to":Z()}],"mask-image-conic-from-color":[{"mask-conic-from":O()}],"mask-image-conic-to-color":[{"mask-conic-to":O()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:fe()}],"mask-repeat":[{mask:z()}],"mask-size":[{mask:N()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",X,$]}],filter:[{filter:["","none",X,$]}],blur:[{blur:ne()}],brightness:[{brightness:[le,X,$]}],contrast:[{contrast:[le,X,$]}],"drop-shadow":[{"drop-shadow":["","none",c,is,ss]}],"drop-shadow-color":[{"drop-shadow":O()}],grayscale:[{grayscale:["",le,X,$]}],"hue-rotate":[{"hue-rotate":[le,X,$]}],invert:[{invert:["",le,X,$]}],saturate:[{saturate:[le,X,$]}],sepia:[{sepia:["",le,X,$]}],"backdrop-filter":[{"backdrop-filter":["","none",X,$]}],"backdrop-blur":[{"backdrop-blur":ne()}],"backdrop-brightness":[{"backdrop-brightness":[le,X,$]}],"backdrop-contrast":[{"backdrop-contrast":[le,X,$]}],"backdrop-grayscale":[{"backdrop-grayscale":["",le,X,$]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[le,X,$]}],"backdrop-invert":[{"backdrop-invert":["",le,X,$]}],"backdrop-opacity":[{"backdrop-opacity":[le,X,$]}],"backdrop-saturate":[{"backdrop-saturate":[le,X,$]}],"backdrop-sepia":[{"backdrop-sepia":["",le,X,$]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",X,$]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[le,"initial",X,$]}],ease:[{ease:["linear","initial",w,X,$]}],delay:[{delay:[le,X,$]}],animate:[{animate:["none",b,X,$]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,X,$]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Y()}],"scale-x":[{"scale-x":Y()}],"scale-y":[{"scale-y":Y()}],"scale-z":[{"scale-z":Y()}],"scale-3d":["scale-3d"],skew:[{skew:De()}],"skew-x":[{"skew-x":De()}],"skew-y":[{"skew-y":De()}],transform:[{transform:[X,$,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Se()}],"translate-x":[{"translate-x":Se()}],"translate-y":[{"translate-y":Se()}],"translate-z":[{"translate-z":Se()}],"translate-none":["translate-none"],accent:[{accent:O()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:O()}],"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",X,$]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",X,$]}],fill:[{fill:["none",...O()]}],"stroke-w":[{stroke:[le,Ar,_a,pl]}],stroke:[{stroke:["none",...O()]}],"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 Gc=yv(Hv);function Sa(...e){return Gc(ns(e))}var Wv=be.createContext({size:"default",variant:"default",spacing:0});function Ca({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(kc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Sa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(Wv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Gv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Xc=createSlice({name:"toolbar",initialState:Gv,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:Wt,setPenColor:ls,setStrokeWidth:xl,setFontSize:nP,setFontFamily:sP,setFontStyle:iP,setFontWeight:lP,setTextDecoration:dP,setTextColor:uP}=Xc.actions,Yc=Xc.reducer;var Jc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,n]=useState(null),[s,i]=useState(0),[l,d]=useState(null),[m,u]=useState(false),f=useRef(null),c=useRef([]),p=useRef(null),g=useRef(null),h=useRef(null);useEffect(()=>((async()=>{try{let x=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(x),u(!0),h.current&&(h.current.srcObject=x);}catch(x){console.error("Error accessing camera:",x),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),l&&l.getTracks().forEach(x=>x.stop());}),[]);let w=()=>{l&&(l.getTracks().forEach(I=>I.stop()),d(null),u(false));},b=async()=>{try{let I=null,x=null;try{I=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(U){console.error("Error accessing camera for recording:",U),alert("Failed to access camera for recording.");return}try{x=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let A=[...I.getVideoTracks()];x&&A.push(...x.getAudioTracks());let V=new MediaStream(A),D="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?D="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?D="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?D="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(D="video/webm;codecs=vp8");let q=new MediaRecorder(V,{mimeType:D,videoBitsPerSecond:25e5});f.current=q,c.current=[],q.ondataavailable=U=>{U.data.size>0&&c.current.push(U.data);},q.onstop=()=>{let U=new Blob(c.current,{type:D}),T=document.createElement("video");T.src=URL.createObjectURL(U),T.muted=!0,T.currentTime=.1,T.onseeked=()=>{let W=document.createElement("canvas");W.width=T.videoWidth,W.height=T.videoHeight;let R=W.getContext("2d");R&&(R.drawImage(T,0,0),g.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(T.src);},V.getTracks().forEach(W=>W.stop()),I&&I.getTracks().forEach(W=>W.stop()),x&&x.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),n(U),w();},q.onerror=U=>{console.error("MediaRecorder error:",U);},q.start(1e3),a(!0),i(0),p.current=setInterval(()=>{i(U=>U+1);},1e3);}catch(I){console.error("Error starting camera recording:",I),alert("Failed to start recording. Please check permissions.");}},v=()=>{f.current&&t&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),a(false));},L=()=>{if(r){let I=URL.createObjectURL(r),x=document.createElement("a");x.href=I,x.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(x),x.click(),document.body.removeChild(x),URL.revokeObjectURL(I);}},k=I=>{let x=Math.floor(I/60),A=I%60;return `${x.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`},S=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50 p-6",onMouseDown:I=>{I.target===I.currentTarget&&e(),I.stopPropagation();},onMouseUp:I=>I.stopPropagation(),onMouseMove:I=>I.stopPropagation(),onTouchStart:I=>I.stopPropagation(),onTouchMove:I=>I.stopPropagation(),onTouchEnd:I=>I.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:I=>I.stopPropagation(),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$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:h,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:b,disabled:!m,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"})})}),!m&&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:v,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:k(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: ",k(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:L,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&&g.current&&(o(r,g.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"})]})]})]})]})]})});return createPortal(S,document.body)};var aa=40,Qc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[i,l]=useState(false),d=useRef(null),m=useRef(null);useEffect(()=>{let b=v=>{v.key==="Escape"&&o();};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);let u=b=>{let v=b.target.files;if(!v||v.length===0)return;let L=aa-a.length;if(L<=0){alert(`You can only upload a maximum of ${aa} images`);return}let k=Array.from(v).slice(0,L);k.length<v.length&&alert(`Only ${L} more images can be added (max ${aa} total)`);let S=k.map(I=>new Promise((x,A)=>{let V=new FileReader;V.onload=D=>{D.target?.result?x(D.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(I);}));Promise.all(S).then(I=>{r(x=>[...x,...I]),m.current&&(m.current.value="");});},f=b=>{b.preventDefault(),l(false);let v=Array.from(b.dataTransfer.files).filter(I=>I.type.startsWith("image/"));if(v.length===0)return;let L=aa-a.length;if(L<=0){alert(`You can only upload a maximum of ${aa} images`);return}let k=v.slice(0,L);k.length<v.length&&alert(`Only ${L} more images can be added (max ${aa} total)`);let S=k.map(I=>new Promise((x,A)=>{let V=new FileReader;V.onload=D=>{D.target?.result?x(D.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(I);}));Promise.all(S).then(I=>{r(x=>[...x,...I]);});},c=b=>{b.preventDefault(),l(true);},p=()=>{l(false);},g=b=>{r(v=>v.filter((L,k)=>k!==b));},w=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:b=>{b.target===b.currentTarget&&o(),b.stopPropagation();},onMouseUp:b=>b.stopPropagation(),onMouseMove:b=>b.stopPropagation(),onTouchStart:b=>b.stopPropagation(),onTouchMove:b=>b.stopPropagation(),onTouchEnd:b=>b.stopPropagation(),children:jsxs("div",{ref:d,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:b=>b.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$1,{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:b=>{if(b.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>=aa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",aa," images"]}):jsxs("span",{children:[a.length,"/",aa," images"]})})]}),jsx("input",{ref:m,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:c,onDragLeave:p,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,{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((b,v)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:b,alt:`Flashcard ${v+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>g(v),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:v+1})]},v))})]}),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(w,document.body)};var ds={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}},sy={enabled:true};function yl(e){return e?{tools:{...ds.tools,...e.tools},actions:{...ds.actions,...e.actions}}:ds}var iy={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}},ly={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 By=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:r}={})=>{let n=xe(),s=te(E=>E.canvas.slides.find(se=>se.id===E.canvas.currentSlideId)),i=s?.videos||[],l=s?.editingFlashcard,d=te(E=>E.toolbar.selectedTool),m=te(E=>E.toolbar.penColor),u=s?.showMcqForm,f=s?.showFlashcardForm,c=useMemo(()=>yl(r),[r]),{tools:p,actions:g}=c,h=i.some(E=>E.isRecorded&&E.isPlaying),w=te(E=>E.toolbar.fontSize),b=te(E=>E.toolbar.fontFamily),v=te(E=>E.toolbar.fontStyle),L=te(E=>E.toolbar.fontWeight),k=te(E=>E.toolbar.textDecoration),S=te(E=>E.toolbar.textColor),[I,x]=useState(false),[A,V]=useState(false),[D,q]=useState(false),[U,T]=useState(false),[W,R]=useState(false),oe=useRef(null),O=useRef(null),fe=useMemo(()=>[{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(()=>[{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"}],[]),N=useMemo(()=>[{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"}],[]),j=useMemo(()=>fe.filter(E=>{let se=p[E.configKey];return typeof se=="boolean"?se:Array.isArray(se)?se.length>0:true}),[p,fe]),H=useMemo(()=>{let E=p.shapes;return E===false?[]:E===true?z:Array.isArray(E)?z.filter(se=>E.includes(se.name)):z},[p.shapes,z]),K=useMemo(()=>{let E=p.activities;return E===false?[]:E===true?N:Array.isArray(E)?N.filter(se=>E.includes(se.name)):N},[p.activities,N]),J=useMemo(()=>{let E=p.media;return E===false?{photoFrame:false,image:false,video:false}:E===true?{photoFrame:true,image:true,video:true}:Array.isArray(E)?{photoFrame:E.includes("photo-frame"),image:E.includes("image"),video:E.includes("video")}:{photoFrame:true,image:true,video:true}},[p.media]),ee=useMemo(()=>{let E=p.activities;return E===false?false:E===true?true:Array.isArray(E)?E.includes("flashcard"):true},[p.activities]),Z=E=>{let se=E.target.files;!se||se.length===0||(n(Wt("select")),n(ut(false)),T(false),Array.from(se).forEach(Ce=>{let me=new FileReader;me.onload=re=>{let ie=new window.Image;ie.src=re.target?.result,ie.onload=()=>{let Re=ie.width/ie.height,lt=300,Gt=300,dt=ie.width,Ee=ie.height;dt>lt&&(dt=lt,Ee=dt/Re),Ee>Gt&&(Ee=Gt,dt=Ee*Re),n(de());let Xe=(window.innerWidth-dt)/2,bt=(window.innerHeight-Ee)/2;n(Fs({id:v4(),src:ie.src,x:Xe,y:bt,width:dt,height:Ee,draggable:true,rotation:0}));};},me.readAsDataURL(Ce);}),E.target.value="");},ne=async E=>{let se=E.target.files;if(!(!se||se.length===0)){console.log("files",E),n(Wt("select")),n(ut(false)),T(false);for(let Ce of Array.from(se))try{let me=URL.createObjectURL(Ce),re=document.createElement("video");console.log("video",re),re.src=me,re.muted=!0,re.playsInline=!0,re.preload="auto",re.load(),await new Promise((Ze,na)=>{let Ta=setTimeout(()=>na(new Error("Metadata load timeout")),1e4);re.onloadedmetadata=()=>{clearTimeout(Ta),Ze();},re.onerror=()=>{clearTimeout(Ta),na(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:re.duration,width:re.videoWidth,height:re.videoHeight}),await new Promise((Ze,na)=>{let Ta=setTimeout(()=>na(new Error("Video load timeout")),1e4);re.readyState>=2?(clearTimeout(Ta),Ze()):re.onloadeddata=()=>{clearTimeout(Ta),Ze();};});let ie=Math.min(.8,re.duration/2);console.log("Seeking to:",ie),re.currentTime=ie,await new Promise(Ze=>{let na=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);re.onseeked=()=>{clearTimeout(na),console.log("Seek completed"),Ze();};});let Re=document.createElement("canvas"),lt=re.videoWidth/re.videoHeight,Gt=400,dt=400,Ee=re.videoWidth,Xe=re.videoHeight;Ee>Gt&&(Ee=Gt,Xe=Ee/lt),Xe>dt&&(Xe=dt,Ee=Xe*lt),Re.width=Ee,Re.height=Xe;let bt=Re.getContext("2d",{willReadFrequently:!1});if(!bt)throw new Error("Failed to get canvas context");if(await new Promise(Ze=>setTimeout(Ze,100)),re.videoWidth===0||re.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ee,height:Xe}),bt.drawImage(re,0,0,Ee,Xe);let Kt=Re.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Kt.length),n(de());let Za=(window.innerWidth-Ee)/2,Qa=(window.innerHeight-Xe)/2,Nr=v4();await za(Nr,Ce,Kt),n(jr({id:Nr,objectUrl:me,thumbnailDataUrl:Kt,videoBlob:Ce,x:Za,y:Qa,width:Ee,height:Xe,draggable:!0,isPlaying:!1,rotation:0})),re.src="",re.load(),console.log(`Video uploaded: ${Ce.name}`);}catch(me){console.error("Error processing video:",me),alert(`Failed to process video: ${Ce.name}`);}E.target.value="";}},Ie=(E,se,Ce)=>{n(de()),n(Wt("select")),n(ut(false));let me=300,re=300,ie=(window.innerWidth-me)/2,Re=(window.innerHeight-re)/2;n(Ce?ro({id:Ce,images:E,order:se,x:ie,y:Re,width:me,height:re,rotation:0,draggable:true}):Ns({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:E,currentIndex:0,order:se,x:ie,y:Re,width:me,height:re,rotation:0,draggable:true})),n(Pa(false));},Y=()=>{n(de()),n(Wt("select")),n(ut(false));let E=400,se=300,Ce=(window.innerWidth-E)/2,me=(window.innerHeight-se)/2;n(Hs({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ce,y:me,width:E,height:se,rotation:0,draggable:true,isCapturing:false})),R(false);},De=E=>{let me=(window.innerWidth-100)/2,re=(window.innerHeight-100)/2,ie={};switch(E.name){case "circle":case "ring":case "wedge":case "arc":ie.radius=50,(E.name==="ring"||E.name==="arc")&&(ie.innerRadius=25,ie.outerRadius=50),(E.name==="wedge"||E.name==="arc")&&(ie.angle=E.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],E.name==="arrow"&&(ie.pointerLength=10,ie.pointerWidth=10);break}let Re={id:`shape-${Date.now()}`,type:E.name,x:me,y:re,width:100,height:100,rotation:0,color:m,...ie};n(de()),n(ut(false)),n(Wt(E.name)),n(Bs(Re));},Se=E=>{if(n(Wt(E)),E==="select")n(ut(false));else if(E==="text"){n(ut(false)),n(de());let se=200,Ce=50,me=(window.innerWidth-se)/2,re=(window.innerHeight-Ce)/2,ie=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(Os({id:ie,text:"",x:me,y:re,width:se,height:Ce,rotation:0,draggable:true,fontSize:w,fontFamily:b,fontStyle:v,fontWeight:L,textDecoration:k,fill:S,align:"left"})),setTimeout(()=>{n($o(ie));},100),a&&a(ie);}else n(ut(true));},Ft=()=>{n(ai()),n(Wt("select")),n(ut(false));},Ja=()=>{o?o():t?x(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Or=()=>{V(true);},Vo=async(E,se)=>{try{n(Wt("select")),n(ut(!1));let Ce=URL.createObjectURL(E),me=document.createElement("video");me.src=Ce,me.muted=!0,me.playsInline=!0,me.preload="auto",await new Promise((Kt,Za)=>{let Qa=setTimeout(()=>Za(new Error("Metadata load timeout")),1e4);me.onloadedmetadata=()=>{clearTimeout(Qa),Kt();},me.onerror=()=>{clearTimeout(Qa),Za(new Error("Failed to load video"));};});let re=640,ie=me.videoWidth/me.videoHeight,Re=re,lt=Re/ie,Gt=window.innerWidth,dt=window.innerHeight;n(de());let Ee=(Gt-Re)/2,Xe=(dt-lt)/2,bt=v4();await za(bt,E,se),n(jr({id:bt,objectUrl:Ce,thumbnailDataUrl:se,videoBlob:E,x:Ee,y:Xe,width:Re,height:lt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),x(!1),V(!1);}catch(Ce){console.error("Error adding recorded video to canvas:",Ce),alert("Failed to add video to canvas. Please try again.");}},xs=E=>{n(Wt("select")),n(ut(false)),n(_o(null)),E&&n(Ys(E)),n(da(!u));},bs=()=>{n(Wo(null)),n(Pa(true)),R(false);},vs=()=>{q(!D);},ys=()=>{T(!U);},ws=()=>{R(!W);};return h?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ca,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:j.map((E,se)=>jsx("div",{title:E.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 2xl:py-3 ${E.name===d?"bg-primary/10":""}`,onClick:()=>{if(E.name==="image"){ys(),q(false),R(false),Se(E.name);return}else if(E.name==="shapes"){vs(),T(false),R(false),Se(E.name);return}else if(E.name==="activities"){Se(E.name),ws(),q(false),T(false);return}Se(E.name),q(false),T(false),R(false);},children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},se))}),D&&jsx(Ca,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:H.map((E,se)=>jsx("div",{title:E.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",onClick:()=>De(E),children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},se))}),U&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[J.photoFrame&&jsx("div",{title:"Photo frame",onClick:Y,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),J.image&&jsx("div",{title:"Image",onClick:()=>oe.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),J.video&&jsx("div",{title:"Video",onClick:()=>O.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})})]}),W&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[ee&&jsx("div",{title:"Flashcard",onClick:()=>bs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),K.map((E,se)=>jsx("div",{title:E.label,onClick:()=>xs(E.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},se))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Ca,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>n(oi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>n(ri()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:Ja,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6279F8]",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Or,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6BBB93]",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>Ft(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl 2xl:text-2xl"})})]})]}),jsx("input",{ref:oe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Z}),jsx("input",{ref:O,type:"file",accept:"video/*",className:"hidden",onChange:ne}),!o&&I&&t&&jsx(nr,{onClose:()=>x(false),stageRef:t,onRecordingComplete:Vo}),A&&jsx(Jc,{onClose:()=>V(false),onRecordingComplete:Vo}),f&&jsx(Qc,{editingFlashcard:l,onConfirm:Ie,onCancel:()=>n(Pa(false))})]})},Oy=By;var Sl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=It(Yo),r=It(Jo),i=(It(g=>g.canvas.slides.find(h=>h.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[l,d]=useState(false),[m,u]=useState(null),[f,c]=useState(null),p=async()=>{if(a.length===0){c({type:"error",message:"No slides to publish"});return}if(!e){c({type:"error",message:"No publish handler provided"});return}d(true),c(null);try{let g=await e(a,r,h=>{u(h);});g.success?c({type:"success",message:g.message}):c({type:"error",message:g.message});}catch(g){c({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{d(false),setTimeout(()=>{u(null),c(null);},3e3);}};return i?null:jsxs("button",{onClick:p,disabled:l||a.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Uy=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:n,showPublishButton:s=true,showBackButton:i=true,editableTitle:l=true,editableDescription:d=true,className:m="",rightContent:u,leftContent:f})=>{let c=et(),p=It(Jo),g=It(di),h=e??(g?p.title:"")??"Untitled",w=o??(g?p.description:"")??"Add a description...",[b,v]=useState(false),[L,k]=useState(false),[S,I]=useState(h),[x,A]=useState(w),V=useRef(null),D=useRef(null);useEffect(()=>{I(h);},[h]),useEffect(()=>{A(w);},[w]),useEffect(()=>{b&&V.current&&(V.current.focus(),V.current.select());},[b]),useEffect(()=>{L&&D.current&&(D.current.focus(),D.current.select());},[L]);let q=()=>{l&&v(true);},U=()=>{d&&k(true);},T=()=>{v(false),S.trim()&&S!==h?r?r(S.trim()):c(ni(S.trim())):S.trim()||I(h);},W=()=>{k(false),x.trim()&&x!==w?n?n(x.trim()):c(si(x.trim())):x.trim()||A(w);},R=O=>{O.key==="Enter"?T():O.key==="Escape"&&(I(h),v(false));},oe=O=>{O.key==="Enter"?W():O.key==="Escape"&&(A(w),k(false));};return 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-4 shadow-sm md:px-6 ${m}`,children:[f||jsxs("div",{className:"flex items-center gap-6",children:[i&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[b?jsx("input",{ref:V,type:"text",value:S,onChange:O=>I(O.target.value),onBlur:T,onKeyDown:R,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:q,title:S,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${l?"hover:border-primary cursor-text":""}`,children:S}),L?jsx("input",{ref:D,type:"text",value:x,onChange:O=>A(O.target.value),onBlur:W,onKeyDown:oe,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:U,title:x,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${d?"hover:border-primary cursor-text":""}`,children:x})]})]}),u||s&&a&&jsx(Sl,{onPublish:a})]})};function kl(e,[o,t]){return Math.min(t,Math.max(o,e))}function of(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 nf(e){let[o,t]=be.useState(void 0);return To(()=>{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 l=n.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,i=d.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 sf=["PageUp","PageDown"],lf=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],df={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Bo="Slider",[Ml,zy,Gy]=ts(Bo),[uf]=wa(Bo,[Gy]),[Ky,ms]=uf(Bo),cf=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:i=false,minStepsBetweenThumbs:l=0,defaultValue:d=[a],value:m,onValueChange:u=()=>{},onValueCommit:f=()=>{},inverted:c=false,form:p,...g}=e,h=be.useRef(new Set),w=be.useRef(0),v=s==="horizontal"?_y:jy,[L=[],k]=ea({prop:m,defaultProp:d,onChange:D=>{[...h.current][w.current]?.focus(),u(D);}}),S=be.useRef(L);function I(D){let q=Zy(L,D);V(D,q);}function x(D){V(D,w.current);}function A(){let D=S.current[w.current];L[w.current]!==D&&f(L);}function V(D,q,{commit:U}={commit:false}){let T=aw(n),W=ow(Math.round((D-a)/n)*n+a,T),R=kl(W,[a,r]);k((oe=[])=>{let O=Yy(oe,R,q);if(tw(O,l*n)){w.current=O.indexOf(R);let fe=String(O)!==String(oe);return fe&&U&&f(O),fe?O:oe}else return oe});}return jsx(Ky,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:r,valueIndexToChangeRef:w,thumbs:h.current,values:L,orientation:s,form:p,children:jsx(Ml.Provider,{scope:e.__scopeSlider,children:jsx(Ml.Slot,{scope:e.__scopeSlider,children:jsx(v,{"aria-disabled":i,"data-disabled":i?"":void 0,...g,ref:o,onPointerDown:je(g.onPointerDown,()=>{i||(S.current=L);}),min:a,max:r,inverted:c,onSlideStart:i?void 0:I,onSlideMove:i?void 0:x,onSlideEnd:i?void 0:A,onHomeKeyDown:()=>!i&&V(a,0,{commit:true}),onEndKeyDown:()=>!i&&V(r,L.length-1,{commit:true}),onStepKeyDown:({event:D,direction:q})=>{if(!i){let W=sf.includes(D.key)||D.shiftKey&&lf.includes(D.key)?10:1,R=w.current,oe=L[R],O=n*W*q;V(oe+O,R,{commit:true});}}})})})})});cf.displayName=Bo;var[ff,mf]=uf(Bo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),_y=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:i,onSlideEnd:l,onStepKeyDown:d,...m}=e,[u,f]=be.useState(null),c=Dt(o,v=>f(v)),p=be.useRef(void 0),g=Po(r),h=g==="ltr",w=h&&!n||!h&&n;function b(v){let L=p.current||u.getBoundingClientRect(),k=[0,L.width],I=Pl(k,w?[t,a]:[a,t]);return p.current=L,I(v-L.left)}return jsx(ff,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:jsx(pf,{dir:g,"data-orientation":"horizontal",...m,ref:c,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{let L=b(v.clientX);s?.(L);},onSlideMove:v=>{let L=b(v.clientX);i?.(L);},onSlideEnd:()=>{p.current=void 0,l?.();},onStepKeyDown:v=>{let k=df[w?"from-left":"from-right"].includes(v.key);d?.({event:v,direction:k?-1:1});}})})}),jy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:i,onStepKeyDown:l,...d}=e,m=be.useRef(null),u=Dt(o,m),f=be.useRef(void 0),c=!r;function p(g){let h=f.current||m.current.getBoundingClientRect(),w=[0,h.height],v=Pl(w,c?[a,t]:[t,a]);return f.current=h,v(g-h.top)}return jsx(ff,{scope:e.__scopeSlider,startEdge:c?"bottom":"top",endEdge:c?"top":"bottom",size:"height",direction:c?1:-1,children:jsx(pf,{"data-orientation":"vertical",...d,ref:u,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{let h=p(g.clientY);n?.(h);},onSlideMove:g=>{let h=p(g.clientY);s?.(h);},onSlideEnd:()=>{f.current=void 0,i?.();},onStepKeyDown:g=>{let w=df[c?"from-bottom":"from-top"].includes(g.key);l?.({event:g,direction:w?-1:1});}})})}),pf=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:i,onStepKeyDown:l,...d}=e,m=ms(Bo,t);return jsx(st.span,{...d,ref:o,onKeyDown:je(e.onKeyDown,u=>{u.key==="Home"?(s(u),u.preventDefault()):u.key==="End"?(i(u),u.preventDefault()):sf.concat(lf).includes(u.key)&&(l(u),u.preventDefault());}),onPointerDown:je(e.onPointerDown,u=>{let f=u.target;f.setPointerCapture(u.pointerId),u.preventDefault(),m.thumbs.has(f)?f.focus():a(u);}),onPointerMove:je(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:je(e.onPointerUp,u=>{let f=u.target;f.hasPointerCapture(u.pointerId)&&(f.releasePointerCapture(u.pointerId),n(u));})})}),hf="SliderTrack",gf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ms(hf,t);return jsx(st.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});gf.displayName=hf;var Tl="SliderRange",xf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ms(Tl,t),n=mf(Tl,t),s=be.useRef(null),i=Dt(o,s),l=r.values.length,d=r.values.map(f=>yf(f,r.min,r.max)),m=l>1?Math.min(...d):0,u=100-Math.max(...d);return jsx(st.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:i,style:{...e.style,[n.startEdge]:m+"%",[n.endEdge]:u+"%"}})});xf.displayName=Tl;var Al="SliderThumb",bf=be.forwardRef((e,o)=>{let t=zy(e.__scopeSlider),[a,r]=be.useState(null),n=Dt(o,i=>r(i)),s=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx($y,{...e,ref:n,index:s})}),$y=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=ms(Al,t),i=mf(Al,t),[l,d]=be.useState(null),m=Dt(o,b=>d(b)),u=l?s.form||!!l.closest("form"):true,f=nf(l),c=s.values[a],p=c===void 0?0:yf(c,s.min,s.max),g=Jy(a,s.values.length),h=f?.[i.size],w=h?Qy(h,p,i.direction):0;return be.useEffect(()=>{if(l)return s.thumbs.add(l),()=>{s.thumbs.delete(l);}},[l,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${p}% + ${w}px)`},children:[jsx(Ml.ItemSlot,{scope:e.__scopeSlider,children:jsx(st.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":s.min,"aria-valuenow":c,"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:m,style:c===void 0?{display:"none"}:e.style,onFocus:je(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),u&&jsx(vf,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:c},a)]})});bf.displayName=Al;var Xy="RadioBubbleInput",vf=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=Dt(r,a),s=of(o);return be.useEffect(()=>{let i=r.current;if(!i)return;let l=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==o&&m){let u=new Event("input",{bubbles:true});m.call(i,o),i.dispatchEvent(u);}},[s,o]),jsx(st.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});vf.displayName=Xy;function Yy(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function yf(e,o,t){let n=100/(t-o)*(e-o);return kl(n,[0,100])}function Jy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Zy(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 Qy(e,o,t){let a=e/2,n=Pl([0,50],[0,a]);return (a-n(o)*t)*t}function ew(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function tw(e,o){if(o>0){let t=ew(e);return Math.min(...t)>=o}return true}function Pl(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 aw(e){return (String(e).split(".")[1]||"").length}function ow(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var wf=cf,Lf=gf,If=xf,Sf=bf;function kf({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:i,...l}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(wf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Sa("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),...l,children:[jsx(Lf,{"data-slot":"slider-track",className:Sa("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(If,{"data-slot":"slider-range",className:Sa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:d.length},(m,u)=>jsx(Sf,{"data-slot":"slider-thumb",className:Sa("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)},u))]})}var iw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],lw=({colors:e=iw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let n=te(i=>i.toolbar.penColor),s=xe();return jsxs("div",{className:`absolute bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:p-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(kf,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:i=>s(xl(i[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(Ca,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(i=>jsx("button",{value:i.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${n===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>s(ls(i.value))},i.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>s(ls(i.target.value))}),jsx(Plus,{color:"#00000099"})]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center px-2 2xl:px-4",children:jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033] lg:h-12 lg:w-12",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>s(Rs(i.target.value))})})})]})};function dw({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var Tf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),cw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),Rl=e=>{let o=cw(e);return o.charAt(0).toUpperCase()+o.slice(1)},ps=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Af=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Pf={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},l)=>createElement("svg",{ref:l,...Pf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:ps("lucide",r),...!n&&!Af(i)&&{"aria-hidden":"true"},...i},[...s.map(([d,m])=>createElement(d,m)),...Array.isArray(n)?n:[n]]));var hs=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(Rf,{ref:n,iconNode:o,className:ps(`lucide-${Tf(Rl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=Rl(e),t};var hw=[["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"}]],Er=hs("copy",hw);var gw=[["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"}]],Fr=hs("trash-2",gw);var Ff=({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(Er,{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(Fr,{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:`Page ${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 yw=()=>{let e=et(),o=It(Yo),t=It(Xo),a=It(li),[r,n]=useState(true),l=(It(c=>c.canvas.slides.find(p=>p.id===c.canvas.currentSlideId))?.videos||[]).some(c=>c.isRecorded&&c.isPlaying),d=()=>{a&&e(Ms());},m=c=>{e(Ps(c));},u=c=>{e(As(c));},f=c=>{o.length>1&&e(Ts(c));};return l?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:"Pages"})]}),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((c,p)=>jsx(Ff,{slide:c,index:p,isSelected:c.id===t,isSingleSlide:o.length===1,onSelect:()=>m(c.id),onDuplicate:()=>u(c.id),onDelete:()=>f(c.id)},c.id))}),jsxs("button",{onClick:d,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 Page"]})]})]}),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 ww="SchooplaEditorDB",Lw=1,ka="slides",Ma="metadata",El="schoopla_current_slide_id",Nf="presentation_metadata",Br=()=>new Promise((e,o)=>{let t=indexedDB.open(ww,Lw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ka)||r.createObjectStore(ka,{keyPath:"id"}),r.objectStoreNames.contains(Ma)||r.createObjectStore(Ma,{keyPath:"id"});};}),Fl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Br(),a=o.transaction([ka],"readwrite").objectStore(ka);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);}}},Bl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Br(),t=e.transaction([ka],"readonly").objectStore(ka);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}}},gs=async()=>{try{let e=await Br(),o=e.transaction([ka,Ma],"readwrite"),t=o.objectStore(ka),a=o.objectStore(Ma);await new Promise((r,n)=>{let s=t.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(El),localStorage.removeItem("schoopla_presentation_metadata"),await ec(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Ol=e=>{try{localStorage.setItem(El,e);}catch(o){console.error("Error saving current slide ID:",o);}},Nl=()=>{try{return localStorage.getItem(El)}catch(e){return console.error("Error loading current slide ID:",e),null}},Vl=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},ql=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await Br(),a=o.transaction([Ma],"readwrite").objectStore(Ma);await new Promise((r,n)=>{let s=a.put({id:Nf,...e});s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Hl=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await Br(),t=e.transaction([Ma],"readonly").objectStore(Ma);return new Promise((a,r)=>{let n=t.get(Nf);n.onsuccess=()=>{e.close();let s=n.result;if(s){let{id:i,...l}=s;console.log("\u2705 Loaded presentation metadata:",l),a(l);}else console.log("No presentation metadata found"),a(null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var Iw=["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/reorderSlides"],Sw=["canvas/clearCanvas"],Cw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],kw=Vl((e,o)=>{Fl(e),Ol(o);},500),Mw=Vl(e=>{ql(e);},500),Tw=(e,o)=>{Fl(e),Ol(o);},Ul=false,Vf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;rl(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=>{rl(i.id).catch(l=>{console.error("Error deleting video blob:",l);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),i=n.canvas.slides.find(l=>l.id===n.canvas.currentSlideId)?.videos.find(l=>l.id===r);i&&i.videoBlob&&setTimeout(()=>{let l=e.getState(),m=l.canvas.slides.find(u=>u.id===l.canvas.currentSlideId)?.videos.find(u=>u.id!==r&&u.x===i.x+20&&u.y===i.y+20);m&&i.videoBlob&&za(m.id,i.videoBlob,m.thumbnailDataUrl).catch(u=>{console.error("Error saving duplicated video blob:",u);});},0);}let a=o(t);if(t.type&&Sw.includes(t.type)){if(!Ul){Ul=true;try{let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;Tw(n,s);}finally{setTimeout(()=>{Ul=false;},0);}}}else if(t.type&&Iw.includes(t.type)){let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;kw(n,s);}else if(t.type&&Cw.includes(t.type)){let r=e.getState(),{presentationMetadata:n}=r.canvas;Mw(n);}return a});new QueryClient;var Dw=configureStore({reducer:{toolbar:Yc,canvas:od},middleware:e=>e({serializableCheck:false}).concat(Vf)});var Rw=(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}),l=document.createElement("a");l.download=`${n}.${t}`,l.href=i,document.body.appendChild(l),l.click(),document.body.removeChild(l);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},Ew=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",l=e.toDataURL({mimeType:i,quality:a,pixelRatio:r});fetch(l).then(d=>d.blob()).then(d=>n(d)).catch(d=>s(d));}catch(i){s(i);}})},Fw=(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 Bw=(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,l=o.y+s*r;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-l,2))},Wl=(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=Bw(e[s],r,n);i>t&&(t=i,a=s);}if(t>o){let s=Wl(e.slice(0,a+1),o),i=Wl(e.slice(a),o);return [...s.slice(0,-1),...i]}return [r,n]},Ow=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Nw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},qf=(e,o=1.5)=>{if(e.length<=4)return e;let t=Ow(e),a=Wl(t,o);return Nw(a)},Hf=(e,o=1.5)=>({...e,points:qf(e.points,o)}),Vw=(e,o=1.5)=>e.map(t=>Hf(t,o)),qw=(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 Hw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Uf=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:l,height:d}=i;if(l>t||d>a){let p=l/d;l>d?(l=Math.min(l,t),d=l/p):(d=Math.min(d,a),l=d*p);}let m=document.createElement("canvas");m.width=l,m.height=d;let u=m.getContext("2d");if(!u){s(new Error("Failed to get canvas context"));return}u.drawImage(i,0,0,l,d);let f=Hw(e),c=m.toDataURL(f,r);n(c);},i.onerror=s,i.src=e;})};var Ya=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},Oo=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",No=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",Uw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,s=[],i=0;for(let l of e){let d=[],m=[],u=[];for(let f of l.images){let c=f.src;if(t&&c.startsWith("data:"))try{c=await Uf(c,{maxWidth:a,maxHeight:r,quality:n});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(c.startsWith("data:")){let p=Ya(c),g=Oo(c);i+=p.byteLength;let h={id:f.id,x:f.x,y:f.y,width:f.width,height:f.height,draggable:f.draggable,rotation:f.rotation,locked:f.locked,link:f.link,altText:f.altText,zIndex:f.zIndex,buffer:p,mimeType:g};if(f.audioData&&f.audioData.startsWith("data:")){let w=Ya(f.audioData),b=Oo(f.audioData);i+=w.byteLength,h.audioBuffer=w,h.audioMimeType=b;}d.push(h);}}for(let f of l.videos){let c,p;if(f.videoBlob)c=await f.videoBlob.arrayBuffer(),p=f.videoBlob.type;else if(f.videoData&&f.videoData.startsWith("data:"))c=Ya(f.videoData),p=Oo(f.videoData);else {console.warn(`Video ${f.id} has no blob or videoData, skipping`);continue}i+=c.byteLength;let g={id:f.id,thumbnailDataUrl:f.thumbnailDataUrl,x:f.x,y:f.y,width:f.width,height:f.height,draggable:f.draggable,isPlaying:f.isPlaying,rotation:f.rotation,locked:f.locked,link:f.link,altText:f.altText,zIndex:f.zIndex,isRecorded:f.isRecorded,buffer:c,mimeType:p};if(f.audioData&&f.audioData.startsWith("data:")){let h=Ya(f.audioData),w=Oo(f.audioData);i+=h.byteLength,g.audioBuffer=h,g.audioMimeType=w;}m.push(g);}for(let f of l.photoFrames){let c={id:f.id,x:f.x,y:f.y,width:f.width,height:f.height,rotation:f.rotation,draggable:f.draggable,locked:f.locked,link:f.link,altText:f.altText,zIndex:f.zIndex,isCapturing:f.isCapturing};if(f.capturedImageUrl&&f.capturedImageUrl.startsWith("data:")){let p=Ya(f.capturedImageUrl),g=Oo(f.capturedImageUrl);i+=p.byteLength,c.buffer=p,c.mimeType=g;}if(f.audioData&&f.audioData.startsWith("data:")){let p=Ya(f.audioData),g=Oo(f.audioData);i+=p.byteLength,c.audioBuffer=p,c.audioMimeType=g;}u.push(c);}s.push({...l,images:d,videos:m,photoFrames:u});}return {slides:s,totalSize:i}},Ww=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},zw=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((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)=>{a.images.forEach((n,s)=>{let i=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${No(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,i,l),n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),m=`${n.id}_audio.${No(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,d,m);}}),a.videos.forEach((n,s)=>{let i=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${No(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,i,l),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let d=Ya(n.thumbnailDataUrl),m=new Blob([d],{type:"image/jpeg"}),u=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,m,u);}if(n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),m=`${n.id}_audio.${No(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,d,m);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let i=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${No(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,i,l);}if(n.audioBuffer&&n.audioMimeType){let i=new Blob([n.audioBuffer],{type:n.audioMimeType}),l=`${n.id}_audio.${No(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,i,l);}});}),o};var _w=()=>{let e=et(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await Bl(),n=Nl(),s=await Hl();if(r&&r.length>0){let i=await Qu(),l=r.map(m=>{if(m.videos&&m.videos.length>0){let u=m.videos.map(f=>{let c=i.get(f.id);if(c){let p=tc(c.blob);return {...f,objectUrl:p,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return f});return {...m,videos:u}}return m}),d=n&&l.find(m=>m.id===n)?n:l[0].id;e(to({slides:l,currentSlideId:d}));}e(s?ii({title:s.title,description:s.description}):wn(!0));}catch(r){console.error("Error loading persisted slides:",r),e(wn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var zf=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||""})),Gf=new WeakSet,Kf=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await za(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},jw=()=>{let e=et(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Gf.has(a))return;Gf.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await gs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let i=n&&r.find(d=>d.id===n)?n:r[0].id,l=zf(r);e(to({slides:l,currentSlideId:i})),await Kf(l);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await gs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let i=n&&r.find(d=>d.id===n)?n:r[0].id,l=zf(r);e(to({slides:l,currentSlideId:i})),await Kf(l);},[e]);return {loadSlides:o,reloadSlides:t}};/*! 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:u?"none":"auto"}})}),jsx(Group,{y:k+C+D+S+b+N,children:u&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),y();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),y();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:U=>U.cancelBubble=true,onTap:U=>U.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});rl.displayName="LongAnswer";var ju=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(rl,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:i=>n(i,s.id)},s.id))});var Ua=1920,Wa=1080,Ju=3840,Zu=2160,cb=e=>{let o=0,t=0,a=Ua,r=Wa;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:Ua,height:Wa};let n=(l,d,f,u)=>{o=Math.min(o,l),t=Math.min(t,d),a=Math.max(a,l+f),r=Math.max(r,d+u);};e.lines?.forEach(l=>{if(l.points&&l.points.length>=2){let d=l.x||0,f=l.y||0,u=l.scaleX||1,c=l.scaleY||1;for(let m=0;m<l.points.length;m+=2){let p=d+l.points[m]*u,g=f+l.points[m+1]*c;o=Math.min(o,p),t=Math.min(t,g),a=Math.max(a,p),r=Math.max(r,g);}}}),e.images?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.videos?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shapes?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.texts?.forEach(l=>n(l.x,l.y,l.width||200,l.height||l.fontSize||24)),e.flashcards?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.photoFrames?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.multipleChoices?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.trueFalses?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shortAnswers?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.LongAnswer?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.fillInTheBlanks?.forEach(l=>n(l.x,l.y,l.width,l.height));let s=Math.min(a-o,Ju),i=Math.min(r-t,Zu);return o=Math.max(o,a-Ju),t=Math.max(t,r-Zu),{minX:o,minY:t,maxX:a,maxY:r,width:s,height:i}},fb=(e,o,t={minX:0,minY:0,maxX:Ua,maxY:Wa,width:Ua,height:Wa})=>{let a=Math.max(t.width,Ua),r=Math.max(t.height,Wa),n=e/o,s=a/r,i,l,d,u=0;if(n>s){l=r,i=Math.round(l*n),d=o/l;}else {i=a,l=Math.round(i/n),d=e/i;let c=r*d;u=(o-c)/2;}return {scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:u,baseWidth:i,baseHeight:l,contentOffsetX:t.minX,contentOffsetY:t.minY}},Qu=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},mb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:r={enabled:true}}={})=>{let n=et(),s=te(w=>w.toolbar.selectedTool),i=te(ge),l=te(Xo),d=i?.editingActivity,f=i?.showMcqForm,u=i?.lines||[],c=useRef(null),m=useRef(null),[p,g]=useState(null),[h,y]=useState(""),x=useRef(null),[v,L]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Ua,stageHeight:Wa,offsetX:0,offsetY:0,baseWidth:Ua,baseHeight:Wa,contentOffsetX:0,contentOffsetY:0}),k=useMemo(()=>cb(i||null),[l]),[C,S]=useState(null),[b,T]=useState(null),[N,D]=useState(null),[q,U]=useState(null),[A,W]=useState(null),[R,re]=useState(null),[V,oe]=useState(null),[z,O]=useState(false),[j,H]=useState(null),[K,J]=useState(false),ee=useRef(null),Z=useRef(null),se=useRef(null),{debouncedGenerateThumbnail:Se}=Ed(l,c);useEffect(()=>{let w=()=>{if(m.current){let P=m.current.getBoundingClientRect(),F=fb(P.width,P.height,k);L(F);}};w();let I=new ResizeObserver(w);return m.current&&I.observe(m.current),window.addEventListener("resize",w),()=>{I.disconnect(),window.removeEventListener("resize",w);}},[k]),useEffect(()=>{if(c.current){let w=c.current.container();w&&(w.style.cursor="");}},[s]);let Y=useCallback(()=>{c.current&&requestAnimationFrame(()=>{if(!c.current)return;c.current.getLayers().forEach(F=>F.batchDraw());let I=1/6,P=c.current.toDataURL({pixelRatio:I});y(P),Se();});},[Se]),De=useRef(l);useEffect(()=>{De.current!==l&&(De.current=l,Y());},[l,Y]);let Ie=useRef(null),Ft=useRef(true);useEffect(()=>{if(!i)return;let w=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),I=Ie.current?.count!==w;!Ft.current&&I&&setTimeout(()=>{Y();},100),Ie.current={slideId:l,count:w},Ft.current=false;},[i,l,Y]),useEffect(()=>{c.current&&e&&e(c);},[e]),useEffect(()=>{se.current&&a&&a(se);},[a]);let{startDrawing:Ja,draw:Or,stopDrawing:Vo,setCanvasRef:xs,tool:bs,color:vs,strokeWidth:ys,isSketchMode:ws}=sd(Y),E=useRef(new Map),{images:ie,getLoadedImage:Ce,imageRefs:me,handleDragEnd:ne,handleImageTransformEnd:le}=md(Y),{videos:Re,videoRefs:lt,handleVideoClick:Gt,handleVideoDragEnd:dt,handleVideoTransformEnd:Ee}=gd(Y),{multipleChoice:Xe,handleMcqTransform:vt,mcqRefs:Kt,handleDragEnd:Za}=pd(Y),{trueFalse:Qa,handleTrueFalseTransform:Nr,trueFalseRefs:Ze,handleTrueFalseDragEnd:na}=hd(Y),{shortAnswers:Ta,saRefs:qo,handleShortAnswerDragEnd:jf}=Ld(Y),{longAnswers:$f,handleLongAnswerDragEnd:Xf}=Sd(Y),{fillInTheBlanks:Yf,handleFillInTheBlanksDragEnd:Jf,fibRefs:Vr}=Hu(Y),{transformerRef:ce,boundBoxFunc:yt}=Ad(),{shapes:Zf,shapeRefs:qr,isDragging:Gl,handleShapeDragEnd:Qf,handleShapeResizeEnd:em}=vd(Y),{texts:Ho,textRefs:sa,handleDragEnd:tm,handleTransformEnd:am,handleDoubleClick:om,startEditing:Hr,editingTextId:pe,editingValue:Kl,handleEditingChange:_l,finishEditing:Ls}=wd(Y,ee);useEffect(()=>{t&&t(Hr);},[t,Hr]);let Ur=te(w=>w.canvas.editingTextId);useEffect(()=>{Ur&&Ur!==pe&&Hr(Ur);},[Ur,pe,Hr]);let{flashcards:rm,flashcardRefs:Wr,handleDragEnd:nm,handleFlashcardTransformEnd:sm,handleNext:im,handlePrevious:lm}=Cd(Y),{photoFrames:jl,photoFrameRefs:zr,handleDragEnd:dm,handlePhotoFrameTransformEnd:um,startCamera:cm,capturePhoto:fm,cameraStreams:mm}=Td(Y);useEffect(()=>{if(ce.current){if(pe){ce.current.nodes([]),ce.current.getLayer()?.batchDraw();return}if(p&&!Re.find(P=>P.id===p)?.isPlaying){let P=E.current.get(p)||me.current.get(p)||lt.current.get(p)||qr.current.get(p)||sa.current.get(p)||Kt.current.get(p)||Wr.current.get(p)||zr.current.get(p)||qo.current.get(p)||Ze.current.get(p)||Vr.current.get(p);if(P){let F=P.attrs?.locked;if(P.visible()&&F!==true){ce.current.nodes([P]),ce.current.getLayer()?.batchDraw();return}}}ce.current.nodes([]),ce.current.getLayer()?.batchDraw();}},[p,pe,Re,E,me,lt,qr,sa,Wr,zr,jl,Kt,Ze,Vr,ce]);let He=useCallback(w=>{g(w),o?.(w);},[o]),eo=useCallback(()=>{g(null),o?.(null),ce.current&&(ce.current.nodes([]),ce.current.getLayer()?.batchDraw());},[ce,o]),$l=useCallback(w=>i?i.lines?.some(I=>I.id===w)?"line":i.images?.some(I=>I.id===w)?"image":i.videos?.some(I=>I.id===w)?"video":i.shapes?.some(I=>I.id===w)?"shape":i.texts?.some(I=>I.id===w)?"text":i.flashcards?.some(I=>I.id===w)?"flashcard":i.photoFrames?.some(I=>I.id===w)?"photoFrame":i.multipleChoices?.some(I=>I.id===w)?"mcq":i.trueFalses?.some(I=>I.id===w)?"trueFalse":i.shortAnswers?.some(I=>I.id===w)?"shortAnswer":i.LongAnswer?.some(I=>I.id===w)?"longAnswer":i.fillInTheBlanks?.some(I=>I.id===w)?"fillInTheBlanks":null:null,[i]),Xl=useCallback((w,I)=>{switch(n(ue()),I){case "line":n(yn(w));break;case "image":n(Kr(w));break;case "video":n(Xr(w));break;case "shape":n(Zr(w));break;case "text":n(Qr(w));break;case "flashcard":n(tn(w));break;case "photoFrame":n(on(w));break;case "mcq":n(nn(w));break;case "trueFalse":n(ln(w));break;case "shortAnswer":n(un(w));break;case "longAnswer":n(fn(w));break;case "fillInTheBlanks":n(pn(w));break}eo(),Y();},[n,eo,Y]);useEffect(()=>{let w=I=>{if(I.key!=="Delete"||!p||pe)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;I.preventDefault();let Me=$l(p);Me&&Xl(p,Me);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[p,pe,$l,Xl]),useEffect(()=>{let w=ce.current;return ()=>{w&&w.nodes([]);}},[l]),useEffect(()=>{let w=I=>{pe&&I.target.tagName!=="TEXTAREA"&&Ls();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[pe,Ls]),useEffect(()=>{let w=pe||p;if(!w||p&&pe){T(null);return}let I=sa.current.get(w),P=c.current;if(!I||!P){T(null);return}let F=P.container().getBoundingClientRect(),Me=I.absolutePosition(),we=P.scaleX();T({x:F.left+(Me.x+I.width()*we/2)*we,y:F.top+Me.y*we});},[p,pe,Ho,sa]),useEffect(()=>{if(!pe){D(null);return}let w=sa.current.get(pe),I=c.current;if(!w||!I){D(null);return}let P=I.container().getBoundingClientRect(),F=w.absolutePosition(),Me=I.scaleX();D({top:P.top+F.y*Me,left:P.left+F.x*Me,scale:Me});},[pe,Ho,sa]);let Yl=useCallback(w=>{let I=w.target.getClassName(),P=w.target===w.target.getStage(),F=I==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",Me=I==="Image",we=I==="Text",ae=I==="Group"||w.target.getParent()?.getClassName()==="Group",Bt=I==="Circle"||I==="Star"||I==="RegularPolygon"||I==="Ellipse"||I==="Ring"||I==="Wedge"||I==="Arrow"||I==="Line"||I==="Arc"||I==="Rect"&&w.target.attrs.id,Lt=I==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:I,clickedOnImage:Me,clickedOnGroup:ae,tool:s,targetId:w.target.attrs?.id}),P&&!F&&!Me&&!we&&!ae&&!Bt&&!Lt&&eo(),!(s==="pen"||s==="eraser")&&(Me||we||F||ae||Bt||Lt))return;let Ke=w.target.getStage()?.getPointerPosition();if(!Ke)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(s)){let B=Qu(Ke,v);Ja(B);}},[s,Ja,eo,v]),Jl=useCallback(w=>{if(Gl)return;let I=w.target.getStage()?.getPointerPosition();if(!I)return;let P=Qu(I,v);Or(P);},[Or,Gl,v]),Zl=useCallback(()=>{Vo();},[Vo]),pm=useCallback(w=>{ne(w,Y);},[ne,Y]),hm=useCallback(w=>{Gt(w),He(w);},[Gt,He]),wt=useCallback((w,I,P)=>{if(w.preventDefault(),!r.enabled)return;let F=w.clientX,Me=w.clientY,we=x.current?.offsetHeight||450,ae=x.current?.offsetWidth||450,Bt=window.innerHeight,Lt=window.innerWidth,Qe=F,Ke=Me;Me+we>Bt&&(Ke=Me-we),F+ae>Lt&&(Qe=F-ae),S({x:Qe,y:Ke,elementId:I,elementType:P}),He(I);},[He,r.enabled]),Ql=useCallback(w=>{n(_o(w)),n(da(true));},[n]),gm=useCallback(w=>{n(Wo(w)),n(Pa(true));},[n]),xm=useCallback((w,I)=>{if(!C)return;let{elementId:P,elementType:F}=C;switch(w){case "order":if(I){let M=I.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(I){let M=I.target.getBoundingClientRect();U({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(S(null),F==="line")break;let Me=i?F==="image"?i.images.find(M=>M.id===P):i.videos.find(M=>M.id===P):null;W({type:"link",defaultValue:Me?.link||""});break;case "voice":if(S(null),F==="line")break;let we=i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="text"?i.texts.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):F==="mcq"?i.multipleChoices.find(M=>M.id===P):F==="fillInTheBlanks"?i.fillInTheBlanks.find(M=>M.id===P):F==="longAnswer"?i.LongAnswer.find(M=>M.id===P):F==="shortAnswer"?i.shortAnswers.find(M=>M.id===P):F==="trueFalse"?i.trueFalses.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):null:null;H({elementId:P,elementType:F,existingAudio:we?.audioData});break;case "edit":S(null);let ae=null;F==="mcq"?ae=i?.multipleChoices.find(M=>M.id===P):F==="trueFalse"?ae=i?.trueFalses.find(M=>M.id===P):F==="shortAnswer"?ae=i?.shortAnswers.find(M=>M.id===P):F==="longAnswer"?ae=i?.LongAnswer.find(M=>M.id===P):F==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(M=>M.id===P)),ae&&Ql(ae);break;case "editFlashcard":S(null);let Bt=i?.flashcards.find(M=>M.id===P);Bt&&gm(Bt);break;case "color":S(null);let Lt=i?.shapes.find(M=>M.id===P);re({elementId:P,elementType:"shape",defaultColor:Lt?.color||"#096B76"});break;case "crop":if(S(null),F==="image"){let M=i?.images.find(Im=>Im.id===P);M&&oe({elementId:P,imageSrc:M.src});}break;case "draw":S(null),F==="image"?n(Us(P)):F==="photoFrame"&&n(zs(P));break;case "duplicate":n(ue()),F==="line"?n(ti(P)):F==="image"?n(_r(P)):F==="video"?n(Yr(P)):F==="shape"?n(Jr(P)):F==="text"?n(en(P)):F==="flashcard"?n(an(P)):F==="photoFrame"?n(rn(P)):F==="mcq"?n(sn(P)):F==="trueFalse"?n(dn(P)):F==="shortAnswer"?n(cn(P)):F==="fillInTheBlanks"?n(hn(P)):F==="longAnswer"&&n(mn(P)),Y();break;case "infinite-clone":n(ue());let Qe=5;for(let M=0;M<Qe;M++)F==="image"?n(_r(P)):F==="video"?n(Yr(P)):F==="shape"?n(Jr(P)):F==="text"?n(en(P)):F==="flashcard"?n(an(P)):F==="photoFrame"?n(rn(P)):F==="mcq"?n(sn(P)):F==="trueFalse"?n(dn(P)):F==="shortAnswer"?n(cn(P)):F==="fillInTheBlanks"?n(hn(P)):F==="longAnswer"&&n(mn(P));Y();break;case "make-response":if(S(null),F==="line")break;let Ke=`#response-${P}`;n(ue()),n(gn({id:P,type:F,link:Ke})),(i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):F==="flashcard"?i.flashcards.find(M=>M.id===P):F==="photoFrame"?i.photoFrames.find(M=>M.id===P):i.multipleChoices.find(M=>M.id===P):null)?.altText||n(xn({id:P,type:F,altText:"Interactive response area"})),Y(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(S(null),F==="line")break;let B=i?F==="image"?i.images.find(M=>M.id===P):F==="video"?i.videos.find(M=>M.id===P):F==="shape"?i.shapes.find(M=>M.id===P):null:null;W({type:"altText",defaultValue:B?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),S(null),J(true),console.log("showLayersPanel state set to:",true);break;case "delete":n(ue()),F==="line"?n(yn(P)):F==="image"?n(Kr(P)):F==="video"?n(Xr(P)):F==="shape"?n(Zr(P)):F==="text"?n(Qr(P)):F==="flashcard"?n(tn(P)):F==="photoFrame"?n(on(P)):F==="mcq"?n(nn(P)):F==="trueFalse"?n(ln(P)):F==="shortAnswer"?n(un(P)):F==="longAnswer"?n(fn(P)):F==="fillInTheBlanks"&&n(pn(P)),eo(),Y();break}},[C,n,Y,eo,i,Ql]),bm=useCallback(()=>{S(null),U(null);},[]),Ss=useCallback(w=>{if(!C)return;let{elementId:I,elementType:P}=C;switch(n(ue()),w){case "bring-to-front":P!=="line"&&n(Js({id:I,type:P}));break;case "send-to-back":P!=="line"&&n(Zs({id:I,type:P}));break;case "lock":case "unlock":P!=="line"&&n(Qs({id:I,type:P}));break}Y(),S(null),U(null);},[C,n,Y]),vm=useCallback(w=>{if(!C||!A)return;let{elementId:I,elementType:P}=C;n(ue()),A.type==="link"&&P!=="line"?n(gn({id:I,type:P,link:w})):A.type==="altText"&&P!=="line"&&n(xn({id:I,type:P,altText:w})),Y(),W(null);},[C,A,n,Y]),ym=useCallback(w=>{if(!j)return;let{elementId:I,elementType:P}=j;n(ue()),n(bn({id:I,type:P,audioData:w})),Y(),H(null);},[j,n,Y]),wm=useCallback(()=>{if(!j)return;let{elementId:w,elementType:I}=j;n(ue()),n(bn({id:w,type:I,audioData:""})),Y();},[j,n,Y]),Lm=useCallback(w=>{if(!R)return;let{elementId:I}=R;n(ue()),n(oo({id:I,color:w})),Y(),re(null);},[R,n,Y]),Sm=useCallback(w=>{if(!V)return;let{elementId:I}=V;n(ue()),n(ao({id:I,src:w})),Y(),oe(null);},[V,n,Y]);return jsxs("div",{ref:m,className:"fixed inset-0",style:{cursor:s==="pen"?"crosshair":s==="eraser"?"":"default"},children:[s==="pen"&&jsx(cd,{ref:w=>{if(Z.current=w,xs(w),w){let I=w.getCanvasElement();I&&(se.current=I,a&&a(se));}},width:v.baseWidth,height:v.baseHeight,tool:bs,color:vs,strokeWidth:ys/v.scale,isSketchMode:ws,xOffset:v.contentOffsetX,yOffset:v.contentOffsetY-v.offsetY/v.scale,style:{width:v.stageWidth,height:v.stageHeight}}),jsxs(Stage,{ref:c,width:v.stageWidth,height:v.stageHeight,scaleX:v.scaleX,scaleY:v.scaleY,x:v.offsetX,y:0,onMouseDown:Yl,onMouseMove:Jl,onMouseUp:Zl,onTouchStart:Yl,onTouchMove:Jl,onTouchEnd:Zl,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:v.baseWidth,height:v.stageHeight/v.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-v.contentOffsetX,y:v.offsetY/v.scale-v.contentOffsetY,children:(()=>{let w=[];return u.forEach((I,P)=>{w.push({type:"line",timestamp:I.timestamp||P,element:{...I,id:I.id??`line-${P}`},index:P});}),Zf.forEach(I=>{w.push({type:"shape",timestamp:I.timestamp||0,element:I});}),ie.forEach(I=>{w.push({type:"image",timestamp:I.timestamp||0,element:I});}),Re.forEach(I=>{w.push({type:"video",timestamp:I.timestamp||0,element:I});}),Ho.forEach(I=>{w.push({type:"text",timestamp:I.timestamp||0,element:I});}),rm.forEach(I=>{w.push({type:"flashcard",timestamp:I.timestamp||0,element:I});}),jl.forEach(I=>{w.push({type:"photoFrame",timestamp:I.timestamp||0,element:I});}),Xe.forEach(I=>{w.push({type:"mcq",timestamp:I.timestamp||0,element:I});}),Qa.forEach(I=>{w.push({type:"trueFalse",timestamp:I.timestamp||0,element:I});}),Ta.forEach(I=>{w.push({type:"shortAnswer",timestamp:I.timestamp||0,element:I});}),$f.forEach(I=>{w.push({type:"longAnswer",timestamp:I.timestamp||0,element:I});}),Yf.forEach(I=>{w.push({type:"fillInTheBlanks",timestamp:I.timestamp||0,element:I});}),w.sort((I,P)=>I.timestamp-P.timestamp),w.map((I,P)=>{let F=`${I.type}-${"id"in I.element&&I.element.id||I.index||P}`,Me="id"in I.element?I.element.id:void 0,we=Me&&p===Me;switch(I.type){case "line":let ae=I.element,Bt=I.index||0,Lt=ae.tool==="eraser",Qe=ae.isSketch&&ae.tool==="pen",Ke=ae.isSketch&&Lt,St=ae.id||`line-${Bt}`;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),s==="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:Qe||Ke?void 0:ae.color,strokeWidth:Qe||Ke?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||Ke?Lt?"black":ae.color:void 0,closed:Qe||Ke,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,onClick:()=>{n(ue()),n(Gr(Bt));},onTap:()=>{n(ue()),n(Gr(Bt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:B=>{let M=B.target.getStage();M&&(M.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:B=>{let M=B.target.getStage();M&&(M.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`);}})},F):jsxs(be__default.Fragment,{children:[jsx(Group,{id:St,ref:B=>{B?E.current.set(St,B):E.current.delete(St);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:s==="select",listening:s==="select",onClick:()=>{s==="select"&&(console.log("Line clicked:",St),He(St));},onTap:()=>{s==="select"&&(console.log("Line tapped:",St),He(St));},onDragEnd:B=>{n(ue()),n(vn({id:St,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onTransformEnd:B=>{n(ue()),n(vn({id:St,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onMouseEnter:B=>{if(s==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(s==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),wt(M,St,"line");},children:jsx(Line,{points:ae.points||[],stroke:Qe||Ke?void 0:ae.color,strokeWidth:Qe||Ke?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Qe||Ke?Lt?"black":ae.color:void 0,closed:Qe||Ke,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=E.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:yt,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"]})]},F);case "shape":return jsxs(be__default.Fragment,{children:[jsx(wi,{onSelect:He,shapes:[I.element],shapeRefs:qr,handleShapeDragEnd:Qf,handleShapeResizeEnd:em,onContextMenu:wt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=qr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "image":return jsxs(be__default.Fragment,{children:[jsx(xi,{images:[I.element],getLoadedImage:Ce,imageRefs:me,onDragEnd:pm,onTransform:le,onSelect:He,onContextMenu:wt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=me.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "video":return jsxs(be__default.Fragment,{children:[jsx(yi,{videos:[I.element],selectedId:p,videoRefs:lt,onVideoClick:hm,onDragEnd:dt,onTransformEnd:Ee,onContextMenu:wt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=lt.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "text":return jsxs(be__default.Fragment,{children:[jsx(Gd,{texts:[I.element],textRefs:sa,onDragEnd:tm,onTransformEnd:am,onSelect:He,onContextMenu:wt,onDoubleClick:om,editingTextId:pe,editingValue:Kl,onEditingChange:_l}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=sa.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Ii,{flashcards:[I.element],flashcardRefs:Wr,selectedId:p,onDragEnd:nm,onTransform:sm,onSelect:He,onNext:im,onPrevious:lm,onContextMenu:wt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=Wr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Ai,{photoFrames:[I.element],photoFrameRefs:zr,selectedId:p,onDragEnd:dm,onTransform:um,onSelect:He,onStartCamera:cm,onCapture:fm,cameraStreams:mm,onContextMenu:wt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=zr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(bu,{handleMcqTransform:vt,multipleChoice:[I.element],handleSelect:He,mcqRefs:Kt,handleDragEnd:Za,onContextMenu:wt}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=Kt.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(wu,{trueFalses:[I.element],handleTrueFalseTransform:Nr,handleSelect:He,trueFalseRefs:Ze,onContextMenu:wt,handleDragEnd:na}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=Ze.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(qu,{shortAnswers:[I.element],handleSelect:He,handleTransform:vt,saRefs:qo,onContextMenu:wt,handleDragEnd:jf}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=qo.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(ju,{longAnswer:[I.element],handleSelect:He,handleTransform:vt,saRefs:qo,onContextMenu:wt,handleDragEnd:Xf}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=qo.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Ku,{fillInTheBlanks:[I.element],handleSelect:He,handleTransform:vt,onContextMenu:wt,handleDragEnd:Jf,fibRefs:Vr}),we&&!pe&&p&&jsx(Transformer,{ref:B=>{if(B&&ce.current!==B){ce.current=B;let M=Vr.current.get(p);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:yt,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"]})]},F);default:return null}})})()})]}),C&&jsx(ou,{menuRef:x,x:C.x,y:C.y,type:C.elementType,onAction:xm,onClose:bm,isDrawingMode:C.elementType==="image"?i?.images.find(w=>w.id===C.elementId)?.isDrawingMode:C.elementType==="photoFrame"?i?.photoFrames.find(w=>w.id===C.elementId)?.isDrawingMode:false}),q&&C&&jsx(ru,{x:q.x,y:q.y,items:q.type==="order"?[{label:"Bring to Front",onClick:()=>Ss("bring-to-front")},{label:"Send to Back",onClick:()=>Ss("send-to-back")}]:[{label:i&&(C.elementType==="image"?i.images.find(w=>w.id===C.elementId)?.locked:i.videos.find(w=>w.id===C.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Ss(i&&(C.elementType==="image"?i.images.find(w=>w.id===C.elementId)?.locked:i.videos.find(w=>w.id===C.elementId)?.locked)?"unlock":"lock")}],onClose:()=>U(null)}),A&&jsx(nu,{title:A.type==="link"?"Add Link":"Add Alt Text",label:A.type==="link"?"URL":"Alternative Text",placeholder:A.type==="link"?"https://example.com":"Describe this image/video",defaultValue:A.defaultValue,onSave:vm,onClose:()=>W(null)}),R&&jsx(su,{defaultColor:R.defaultColor,onConfirm:Lm,onCancel:()=>re(null)}),V&&jsx(uu,{imageSrc:V.imageSrc,onConfirm:Sm,onCancel:()=>oe(null)}),z&&jsx(nr,{onClose:()=>O(false),stageRef:c}),j&&jsx(fu,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:ym,onDelete:wm,onClose:()=>H(null)}),K&&jsx(hu,{selectedElementId:p||void 0,onClose:()=>J(false),onSelectElement:w=>{He(w),J(false);}}),i?.images.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.videos.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.shapes?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.texts?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.flashcards?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),i?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),f&&jsx(Ru,{editElement:d}),b&&(()=>{let w=pe||p;if(!w)return null;let I=Ho.find(P=>P.id===w);return I?jsx(Eu,{text:I,position:b}):null})(),N&&pe&&(()=>{let w=Ho.find(I=>I.id===pe);return w?jsx(Bu,{text:w,editingValue:Kl,onEditingChange:_l,onFinish:Ls,position:{top:N.top,left:N.left},scale:N.scale,textareaRef:ee},pe):null})()]})},pb=mb;var hb="SchooplaVideoStorage";var Yt="videos",es=()=>new Promise((e,o)=>{let t=indexedDB.open(hb,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(Yt)||r.createObjectStore(Yt,{keyPath:"id"});};}),za=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await es(),n=a.transaction([Yt],"readwrite").objectStore(Yt),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,l)=>{let d=n.put(s);d.onsuccess=()=>i(!0),d.onerror=()=>l(d.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 ec=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await es(),t=e.transaction([Yt],"readonly").objectStore(Yt);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,i=new Map;s.forEach(l=>{i.set(l.id,{blob:l.blob,thumbnailDataUrl:l.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}},nl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await es(),a=o.transaction([Yt],"readwrite").objectStore(Yt);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}},tc=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await es(),t=e.transaction([Yt],"readwrite").objectStore(Yt);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},ac=e=>URL.createObjectURL(e);function wa(e,o=[]){let t=[];function a(n,s){let i=be.createContext(s),l=t.length;t=[...t,s];let d=u=>{let{scope:c,children:m,...p}=u,g=c?.[e]?.[l]||i,h=be.useMemo(()=>p,Object.values(p));return jsx(g.Provider,{value:h,children:m})};d.displayName=n+"Provider";function f(u,c){let m=c?.[e]?.[l]||i,p=be.useContext(m);if(p)return p;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${n}\``)}return [d,f]}let r=()=>{let n=t.map(s=>be.createContext(s));return function(i){let l=i?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:l}}),[i,l])}};return r.scopeName=e,[a,xb(r,...o)]}function xb(...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:l,scopeName:d})=>{let u=l(n)[`__scope${d}`];return {...i,...u}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function oc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Mr(...e){return o=>{let t=false,a=e.map(r=>{let n=oc(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():oc(e[r],null);}}}}function Dt(...e){return be.useCallback(Mr(...e),e)}function sc(e){let o=bb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,i=be.Children.toArray(n),l=i.find(yb);if(l){let d=l.props.children,f=i.map(u=>u===l?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function bb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=Lb(r),i=wb(n,r.props);return r.type!==be.Fragment&&(i.ref=a?Mr(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 vb=Symbol("radix.slottable");function yb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===vb}function wb(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 l=n(...i);return r(...i),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function Lb(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 Cb=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],st=Cb.reduce((e,o)=>{let t=sc(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:s,...i}=r,l=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(l,{...i,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function je(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function sl(e){let o=kb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,i=be.Children.toArray(n),l=i.find(Tb);if(l){let d=l.props.children,f=i.map(u=>u===l?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function kb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=Pb(r),i=Ab(n,r.props);return r.type!==be.Fragment&&(i.ref=a?Mr(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 Mb=Symbol("radix.slottable");function Tb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Mb}function Ab(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 l=n(...i);return r(...i),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function Pb(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 ts(e){let o=e+"CollectionProvider",[t,a]=wa(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=g=>{let{scope:h,children:y}=g,x=be__default.useRef(null),v=be__default.useRef(new Map).current;return jsx(r,{scope:h,itemMap:v,collectionRef:x,children:y})};s.displayName=o;let i=e+"CollectionSlot",l=sl(i),d=be__default.forwardRef((g,h)=>{let{scope:y,children:x}=g,v=n(i,y),L=Dt(h,v.collectionRef);return jsx(l,{ref:L,children:x})});d.displayName=i;let f=e+"CollectionItemSlot",u="data-radix-collection-item",c=sl(f),m=be__default.forwardRef((g,h)=>{let{scope:y,children:x,...v}=g,L=be__default.useRef(null),k=Dt(h,L),C=n(f,y);return be__default.useEffect(()=>(C.itemMap.set(L,{ref:L,...v}),()=>void C.itemMap.delete(L))),jsx(c,{[u]:"",ref:k,children:x})});m.displayName=f;function p(g){let h=n(e+"CollectionConsumer",g);return be__default.useCallback(()=>{let x=h.collectionRef.current;if(!x)return [];let v=Array.from(x.querySelectorAll(`[${u}]`));return Array.from(h.itemMap.values()).sort((C,S)=>v.indexOf(C.ref.current)-v.indexOf(S.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:s,Slot:d,ItemSlot:m},p,a]}var To=globalThis?.document?be.useLayoutEffect:()=>{};var Db=be[" useId ".trim().toString()]||(()=>{}),Rb=0;function uc(e){let[o,t]=be.useState(Db());return To(()=>{t(a=>a??String(Rb++));},[e]),(o?`radix-${o}`:"")}function cc(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Eb=be[" useInsertionEffect ".trim().toString()]||To;function ea({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=Fb({defaultProp:o,onChange:t}),i=e!==void 0,l=i?e:r;{let f=be.useRef(e!==void 0);be.useEffect(()=>{let u=f.current;u!==i&&console.warn(`${a} is changing from ${u?"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.`),f.current=i;},[i,a]);}let d=be.useCallback(f=>{if(i){let u=Bb(f)?f(e):f;u!==e&&s.current?.(u);}else n(f);},[i,e,n,s]);return [l,d]}function Fb({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 Bb(e){return typeof e=="function"}var Ob=be.createContext(void 0);function Po(e){let o=be.useContext(Ob);return e||o||"ltr"}var dl="rovingFocusGroup.onEntryFocus",Nb={bubbles:false,cancelable:true},Tr="RovingFocusGroup",[ul,fc,Vb]=ts(Tr),[qb,cl]=wa(Tr,[Vb]),[Hb,Ub]=qb(Tr),mc=be.forwardRef((e,o)=>jsx(ul.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(ul.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Wb,{...e,ref:o})})}));mc.displayName=Tr;var Wb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:f=false,...u}=e,c=be.useRef(null),m=Dt(o,c),p=Po(n),[g,h]=ea({prop:s,defaultProp:i??null,onChange:l,caller:Tr}),[y,x]=be.useState(false),v=cc(d),L=fc(t),k=be.useRef(false),[C,S]=be.useState(0);return be.useEffect(()=>{let b=c.current;if(b)return b.addEventListener(dl,v),()=>b.removeEventListener(dl,v)},[v]),jsx(Hb,{scope:t,orientation:a,dir:p,loop:r,currentTabStopId:g,onItemFocus:be.useCallback(b=>h(b),[h]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>S(b=>b+1),[]),onFocusableItemRemove:be.useCallback(()=>S(b=>b-1),[]),children:jsx(st.div,{tabIndex:y||C===0?-1:0,"data-orientation":a,...u,ref:m,style:{outline:"none",...e.style},onMouseDown:je(e.onMouseDown,()=>{k.current=true;}),onFocus:je(e.onFocus,b=>{let T=!k.current;if(b.target===b.currentTarget&&T&&!y){let N=new CustomEvent(dl,Nb);if(b.currentTarget.dispatchEvent(N),!N.defaultPrevented){let D=L().filter(R=>R.focusable),q=D.find(R=>R.active),U=D.find(R=>R.id===g),W=[q,U,...D].filter(Boolean).map(R=>R.ref.current);gc(W,f);}}k.current=false;}),onBlur:je(e.onBlur,()=>x(false))})})}),pc="RovingFocusGroupItem",hc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...i}=e,l=uc(),d=n||l,f=Ub(pc,t),u=f.currentTabStopId===d,c=fc(t),{onFocusableItemAdd:m,onFocusableItemRemove:p,currentTabStopId:g}=f;return be.useEffect(()=>{if(a)return m(),()=>p()},[a,m,p]),jsx(ul.ItemSlot,{scope:t,id:d,focusable:a,active:r,children:jsx(st.span,{tabIndex:u?0:-1,"data-orientation":f.orientation,...i,ref:o,onMouseDown:je(e.onMouseDown,h=>{a?f.onItemFocus(d):h.preventDefault();}),onFocus:je(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:je(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){f.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let y=Kb(h,f.orientation,f.dir);if(y!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let v=c().filter(L=>L.focusable).map(L=>L.ref.current);if(y==="last")v.reverse();else if(y==="prev"||y==="next"){y==="prev"&&v.reverse();let L=v.indexOf(h.currentTarget);v=f.loop?_b(v,L+1):v.slice(L+1);}setTimeout(()=>gc(v));}}),children:typeof s=="function"?s({isCurrentTabStop:u,hasTabStop:g!=null}):s})})});hc.displayName=pc;var zb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Gb(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Kb(e,o,t){let a=Gb(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return zb[a]}function gc(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function _b(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var xc=mc,bc=hc;var yc="Toggle",fl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,i]=ea({prop:t,onChange:r,defaultProp:a??false,caller:yc});return jsx(st.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:je(e.onClick,()=>{e.disabled||i(!s);})})});fl.displayName=yc;var La="ToggleGroup",[Lc]=wa(La,[cl]),Sc=cl(),ml=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Xb,{...a,ref:o});if(t==="multiple")return jsx(Yb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${La}\``)});ml.displayName=La;var[Ic,Cc]=Lc(La),Xb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,i]=ea({prop:t,defaultProp:a??"",onChange:r,caller:La});return jsx(Ic,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(kc,{...n,ref:o})})}),Yb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,i]=ea({prop:t,defaultProp:a??[],onChange:r,caller:La}),l=be__default.useCallback(f=>i((u=[])=>[...u,f]),[i]),d=be__default.useCallback(f=>i((u=[])=>u.filter(c=>c!==f)),[i]);return jsx(Ic,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:l,onItemDeactivate:d,children:jsx(kc,{...n,ref:o})})});ml.displayName=La;var[Jb,Zb]=Lc(La),kc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:i=true,...l}=e,d=Sc(t),f=Po(s),u={role:"group",dir:f,...l};return jsx(Jb,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(xc,{asChild:true,...d,orientation:n,dir:f,loop:i,children:jsx(st.div,{...u,ref:o})}):jsx(st.div,{...u,ref:o})})}),rs="ToggleGroupItem",Qb=be__default.forwardRef((e,o)=>{let t=Cc(rs,e.__scopeToggleGroup),a=Zb(rs,e.__scopeToggleGroup),r=Sc(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,i={...e,pressed:n,disabled:s},l=be__default.useRef(null);return a.rovingFocus?jsx(bc,{asChild:true,...r,focusable:!s,active:n,ref:l,children:jsx(wc,{...i,ref:o})}):jsx(wc,{...i,ref:o})});Qb.displayName=rs;var wc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=Cc(rs,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=n.type==="single"?s:void 0;return jsx(fl,{...i,...r,ref:o,onPressedChange:l=>{l?n.onItemActivate(a):n.onItemDeactivate(a);}})}),Mc=ml;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 ns(){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 tv=(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},av=(e,o)=>({classGroupId:e,validator:o}),Ec=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Ac=[],ov="arbitrary..",rv=e=>{let o=sv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return nv(s);let i=s.split("-"),l=i[0]===""&&i.length>1?1:0;return Fc(i,l,o)},getConflictingClassGroupIds:(s,i)=>{if(i){let l=a[s],d=t[s];return l?d?tv(d,l):l:d||Ac}return t[s]||Ac}}},Fc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let d=Fc(e,o+1,n);if(d)return d}let s=t.validators;if(s===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),l=s.length;for(let d=0;d<l;d++){let f=s[d];if(f.validator(i))return f.classGroupId}},nv=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?ov+a:void 0})(),sv=e=>{let{theme:o,classGroups:t}=e;return iv(t,o)},iv=(e,o)=>{let t=Ec();for(let a in e){let r=e[a];gl(r,t,a,o);}return t},gl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];lv(s,o,t,a);}},lv=(e,o,t,a)=>{if(typeof e=="string"){dv(e,o,t);return}if(typeof e=="function"){uv(e,o,t,a);return}cv(e,o,t,a);},dv=(e,o,t)=>{let a=e===""?o:Bc(o,e);a.classGroupId=t;},uv=(e,o,t,a)=>{if(fv(e)){gl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(av(t,e));},cv=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[i,l]=r[s];gl(l,Bc(o,i),t,a);}},Bc=(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=Ec(),t.nextPart.set(s,i)),t=i;}return t},fv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,mv=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 pv=[],Pc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),hv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,i=0,l=0,d,f=r.length;for(let g=0;g<f;g++){let h=r[g];if(s===0&&i===0){if(h===":"){n.push(r.slice(l,g)),l=g+1;continue}if(h==="/"){d=g;continue}}h==="["?s++:h==="]"?s--:h==="("?i++:h===")"&&i--;}let u=n.length===0?r:r.slice(l),c=u,m=false;u.endsWith("!")?(c=u.slice(0,-1),m=true):u.startsWith("!")&&(c=u.slice(1),m=true);let p=d&&d>l?d-l:void 0;return Pc(n,m,c,p)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):Pc(pv,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},gv=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]==="[",l=o.has(s);i||l?(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}},xv=e=>({cache:mv(e.cacheSize),parseClassName:hv(e),sortModifiers:gv(e),...rv(e)}),bv=/\s+/,vv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],i=e.trim().split(bv),l="";for(let d=i.length-1;d>=0;d-=1){let f=i[d],{isExternal:u,modifiers:c,hasImportantModifier:m,baseClassName:p,maybePostfixModifierPosition:g}=t(f);if(u){l=f+(l.length>0?" "+l:l);continue}let h=!!g,y=a(h?p.substring(0,g):p);if(!y){if(!h){l=f+(l.length>0?" "+l:l);continue}if(y=a(p),!y){l=f+(l.length>0?" "+l:l);continue}h=false;}let x=c.length===0?"":c.length===1?c[0]:n(c).join(":"),v=m?x+"!":x,L=v+y;if(s.indexOf(L)>-1)continue;s.push(L);let k=r(y,h);for(let C=0;C<k.length;++C){let S=k[C];s.push(v+S);}l=f+(l.length>0?" "+l:l);}return l},yv=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Oc(t))&&(r&&(r+=" "),r+=a);return r},Oc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Oc(e[a]))&&(t&&(t+=" "),t+=o);return t},wv=(e,...o)=>{let t,a,r,n,s=l=>{let d=o.reduce((f,u)=>u(f),e());return t=xv(d),a=t.cache.get,r=t.cache.set,n=i,i(l)},i=l=>{let d=a(l);if(d)return d;let f=vv(l,t);return r(l,f),f};return n=s,(...l)=>n(yv(...l))},Lv=[],Ve=e=>{let o=t=>t[e]||Lv;return o.isThemeGetter=true,o},Nc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Vc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Sv=/^\d+\/\d+$/,Iv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Cv=/\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$/,kv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Mv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Tv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Do=e=>Sv.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Sa=e=>!!e&&Number.isInteger(Number(e)),pl=e=>e.endsWith("%")&&de(e.slice(0,-1)),ta=e=>Iv.test(e),Av=()=>true,Pv=e=>Cv.test(e)&&!kv.test(e),qc=()=>false,Dv=e=>Mv.test(e),Rv=e=>Tv.test(e),Ev=e=>!$(e)&&!X(e),Fv=e=>Ro(e,Wc,qc),$=e=>Nc.test(e),_a=e=>Ro(e,zc,Pv),hl=e=>Ro(e,qv,de),Dc=e=>Ro(e,Hc,qc),Bv=e=>Ro(e,Uc,Rv),ss=e=>Ro(e,Gc,Dv),X=e=>Vc.test(e),Ar=e=>Eo(e,zc),Ov=e=>Eo(e,Hv),Rc=e=>Eo(e,Hc),Nv=e=>Eo(e,Wc),Vv=e=>Eo(e,Uc),is=e=>Eo(e,Gc,true),Ro=(e,o,t)=>{let a=Nc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Eo=(e,o,t=false)=>{let a=Vc.exec(e);return a?a[1]?o(a[1]):t:false},Hc=e=>e==="position"||e==="percentage",Uc=e=>e==="image"||e==="url",Wc=e=>e==="length"||e==="size"||e==="bg-size",zc=e=>e==="length",qv=e=>e==="number",Hv=e=>e==="family-name",Gc=e=>e==="shadow";var Uv=()=>{let e=Ve("color"),o=Ve("font"),t=Ve("text"),a=Ve("font-weight"),r=Ve("tracking"),n=Ve("leading"),s=Ve("breakpoint"),i=Ve("container"),l=Ve("spacing"),d=Ve("radius"),f=Ve("shadow"),u=Ve("inset-shadow"),c=Ve("text-shadow"),m=Ve("drop-shadow"),p=Ve("blur"),g=Ve("perspective"),h=Ve("aspect"),y=Ve("ease"),x=Ve("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...L(),X,$],C=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],b=()=>[X,$,l],T=()=>[Do,"full","auto",...b()],N=()=>[Sa,"none","subgrid",X,$],D=()=>["auto",{span:["full",Sa,X,$]},Sa,X,$],q=()=>[Sa,"auto",X,$],U=()=>["auto","min","max","fr",X,$],A=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],R=()=>["auto",...b()],re=()=>[Do,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],V=()=>[e,X,$],oe=()=>[...L(),Rc,Dc,{position:[X,$]}],z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],O=()=>["auto","cover","contain",Nv,Fv,{size:[X,$]}],j=()=>[pl,Ar,_a],H=()=>["","none","full",d,X,$],K=()=>["",de,Ar,_a],J=()=>["solid","dashed","dotted","double"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Z=()=>[de,pl,Rc,Dc],se=()=>["","none",p,X,$],Se=()=>["none",de,X,$],Y=()=>["none",de,X,$],De=()=>[de,X,$],Ie=()=>[Do,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ta],breakpoint:[ta],color:[Av],container:[ta],"drop-shadow":[ta],ease:["in","out","in-out"],font:[Ev],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ta],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ta],shadow:[ta],spacing:["px",de],text:[ta],"text-shadow":[ta],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Do,$,X,h]}],container:["container"],columns:[{columns:[de,$,X,i]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"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:k()}],overflow:[{overflow:C()}],"overflow-x":[{"overflow-x":C()}],"overflow-y":[{"overflow-y":C()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[Sa,"auto",X,$]}],basis:[{basis:[Do,"full","auto",i,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Do,"auto","initial","none",$]}],grow:[{grow:["",de,X,$]}],shrink:[{shrink:["",de,X,$]}],order:[{order:[Sa,"first","last","none",X,$]}],"grid-cols":[{"grid-cols":N()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":N()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":U()}],"auto-rows":[{"auto-rows":U()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...A(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...A()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":A()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:R()}],mx:[{mx:R()}],my:[{my:R()}],ms:[{ms:R()}],me:[{me:R()}],mt:[{mt:R()}],mr:[{mr:R()}],mb:[{mb:R()}],ml:[{ml:R()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:re()}],w:[{w:[i,"screen",...re()]}],"min-w":[{"min-w":[i,"screen","none",...re()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[s]},...re()]}],h:[{h:["screen","lh",...re()]}],"min-h":[{"min-h":["screen","lh","none",...re()]}],"max-h":[{"max-h":["screen","lh",...re()]}],"font-size":[{text:["base",t,Ar,_a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,X,hl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",pl,$]}],"font-family":[{font:[Ov,$,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,X,$]}],"line-clamp":[{"line-clamp":[de,"none",X,hl]}],leading:[{leading:[n,...b()]}],"list-image":[{"list-image":["none",X,$]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",X,$]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",X,_a]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[de,"auto",X,$]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",X,$]}],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",X,$]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:oe()}],"bg-repeat":[{bg:z()}],"bg-size":[{bg:O()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Sa,X,$],radial:["",X,$],conic:[Sa,X,$]},Vv,Bv]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:j()}],"gradient-via-pos":[{via:j()}],"gradient-to-pos":[{to:j()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,X,$]}],"outline-w":[{outline:["",de,Ar,_a]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",f,is,ss]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",u,is,ss]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[de,_a]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",c,is,ss]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[de,X,$]}],"mix-blend":[{"mix-blend":[...ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ee()}],"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":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":Z()}],"mask-image-linear-to-pos":[{"mask-linear-to":Z()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":Z()}],"mask-image-t-to-pos":[{"mask-t-to":Z()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":Z()}],"mask-image-r-to-pos":[{"mask-r-to":Z()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":Z()}],"mask-image-b-to-pos":[{"mask-b-to":Z()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":Z()}],"mask-image-l-to-pos":[{"mask-l-to":Z()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":Z()}],"mask-image-x-to-pos":[{"mask-x-to":Z()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":Z()}],"mask-image-y-to-pos":[{"mask-y-to":Z()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[X,$]}],"mask-image-radial-from-pos":[{"mask-radial-from":Z()}],"mask-image-radial-to-pos":[{"mask-radial-to":Z()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"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":L()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":Z()}],"mask-image-conic-to-pos":[{"mask-conic-to":Z()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:oe()}],"mask-repeat":[{mask:z()}],"mask-size":[{mask:O()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",X,$]}],filter:[{filter:["","none",X,$]}],blur:[{blur:se()}],brightness:[{brightness:[de,X,$]}],contrast:[{contrast:[de,X,$]}],"drop-shadow":[{"drop-shadow":["","none",m,is,ss]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",de,X,$]}],"hue-rotate":[{"hue-rotate":[de,X,$]}],invert:[{invert:["",de,X,$]}],saturate:[{saturate:[de,X,$]}],sepia:[{sepia:["",de,X,$]}],"backdrop-filter":[{"backdrop-filter":["","none",X,$]}],"backdrop-blur":[{"backdrop-blur":se()}],"backdrop-brightness":[{"backdrop-brightness":[de,X,$]}],"backdrop-contrast":[{"backdrop-contrast":[de,X,$]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,X,$]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,X,$]}],"backdrop-invert":[{"backdrop-invert":["",de,X,$]}],"backdrop-opacity":[{"backdrop-opacity":[de,X,$]}],"backdrop-saturate":[{"backdrop-saturate":[de,X,$]}],"backdrop-sepia":[{"backdrop-sepia":["",de,X,$]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",X,$]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",X,$]}],ease:[{ease:["linear","initial",y,X,$]}],delay:[{delay:[de,X,$]}],animate:[{animate:["none",x,X,$]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,X,$]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:Se()}],"rotate-x":[{"rotate-x":Se()}],"rotate-y":[{"rotate-y":Se()}],"rotate-z":[{"rotate-z":Se()}],scale:[{scale:Y()}],"scale-x":[{"scale-x":Y()}],"scale-y":[{"scale-y":Y()}],"scale-z":[{"scale-z":Y()}],"scale-3d":["scale-3d"],skew:[{skew:De()}],"skew-x":[{"skew-x":De()}],"skew-y":[{"skew-y":De()}],transform:[{transform:[X,$,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ie()}],"translate-x":[{"translate-x":Ie()}],"translate-y":[{"translate-y":Ie()}],"translate-z":[{"translate-z":Ie()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"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",X,$]}],"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":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"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",X,$]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[de,Ar,_a,hl]}],stroke:[{stroke:["none",...V()]}],"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 Kc=wv(Uv);function Ia(...e){return Kc(ns(e))}var zv=be.createContext({size:"default",variant:"default",spacing:0});function Ca({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(Mc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ia("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(zv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Kv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Yc=createSlice({name:"toolbar",initialState:Kv,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:Wt,setPenColor:ls,setStrokeWidth:bl,setFontSize:sP,setFontFamily:iP,setFontStyle:lP,setFontWeight:dP,setTextDecoration:uP,setTextColor:cP}=Yc.actions,Jc=Yc.reducer;var Zc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,n]=useState(null),[s,i]=useState(0),[l,d]=useState(null),[f,u]=useState(false),c=useRef(null),m=useRef([]),p=useRef(null),g=useRef(null),h=useRef(null);useEffect(()=>((async()=>{try{let b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(b),u(!0),h.current&&(h.current.srcObject=b);}catch(b){console.error("Error accessing camera:",b),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{p.current&&clearInterval(p.current),l&&l.getTracks().forEach(b=>b.stop());}),[]);let y=()=>{l&&(l.getTracks().forEach(S=>S.stop()),d(null),u(false));},x=async()=>{try{let S=null,b=null;try{S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(U){console.error("Error accessing camera for recording:",U),alert("Failed to access camera for recording.");return}try{b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(U){console.warn("Microphone access denied:",U);}let T=[...S.getVideoTracks()];b&&T.push(...b.getAudioTracks());let N=new MediaStream(T),D="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?D="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?D="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?D="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(D="video/webm;codecs=vp8");let q=new MediaRecorder(N,{mimeType:D,videoBitsPerSecond:25e5});c.current=q,m.current=[],q.ondataavailable=U=>{U.data.size>0&&m.current.push(U.data);},q.onstop=()=>{let U=new Blob(m.current,{type:D}),A=document.createElement("video");A.src=URL.createObjectURL(U),A.muted=!0,A.currentTime=.1,A.onseeked=()=>{let W=document.createElement("canvas");W.width=A.videoWidth,W.height=A.videoHeight;let R=W.getContext("2d");R&&(R.drawImage(A,0,0),g.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(A.src);},N.getTracks().forEach(W=>W.stop()),S&&S.getTracks().forEach(W=>W.stop()),b&&b.getTracks().forEach(W=>W.stop()),p.current&&clearInterval(p.current),n(U),y();},q.onerror=U=>{console.error("MediaRecorder error:",U);},q.start(1e3),a(!0),i(0),p.current=setInterval(()=>{i(U=>U+1);},1e3);}catch(S){console.error("Error starting camera recording:",S),alert("Failed to start recording. Please check permissions.");}},v=()=>{c.current&&t&&(c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),a(false));},L=()=>{if(r){let S=URL.createObjectURL(r),b=document.createElement("a");b.href=S,b.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(S);}},k=S=>{let b=Math.floor(S/60),T=S%60;return `${b.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`},C=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50 p-6",onMouseDown:S=>{S.target===S.currentTarget&&e(),S.stopPropagation();},onMouseUp:S=>S.stopPropagation(),onMouseMove:S=>S.stopPropagation(),onTouchStart:S=>S.stopPropagation(),onTouchMove:S=>S.stopPropagation(),onTouchEnd:S=>S.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:S=>S.stopPropagation(),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$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:h,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:x,disabled:!f,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"})})}),!f&&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:v,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:k(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: ",k(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:L,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&&g.current&&(o(r,g.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"})]})]})]})]})]})});return createPortal(C,document.body)};var aa=40,ef=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[i,l]=useState(false),d=useRef(null),f=useRef(null);useEffect(()=>{let x=v=>{v.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let u=x=>{let v=x.target.files;if(!v||v.length===0)return;let L=aa-a.length;if(L<=0){alert(`You can only upload a maximum of ${aa} images`);return}let k=Array.from(v).slice(0,L);k.length<v.length&&alert(`Only ${L} more images can be added (max ${aa} total)`);let C=k.map(S=>new Promise((b,T)=>{let N=new FileReader;N.onload=D=>{D.target?.result?b(D.target.result):T(new Error("Failed to read file"));},N.onerror=T,N.readAsDataURL(S);}));Promise.all(C).then(S=>{r(b=>[...b,...S]),f.current&&(f.current.value="");});},c=x=>{x.preventDefault(),l(false);let v=Array.from(x.dataTransfer.files).filter(S=>S.type.startsWith("image/"));if(v.length===0)return;let L=aa-a.length;if(L<=0){alert(`You can only upload a maximum of ${aa} images`);return}let k=v.slice(0,L);k.length<v.length&&alert(`Only ${L} more images can be added (max ${aa} total)`);let C=k.map(S=>new Promise((b,T)=>{let N=new FileReader;N.onload=D=>{D.target?.result?b(D.target.result):T(new Error("Failed to read file"));},N.onerror=T,N.readAsDataURL(S);}));Promise.all(C).then(S=>{r(b=>[...b,...S]);});},m=x=>{x.preventDefault(),l(true);},p=()=>{l(false);},g=x=>{r(v=>v.filter((L,k)=>k!==x));},y=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:d,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:x=>x.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$1,{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:x=>{if(x.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>=aa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",aa," images"]}):jsxs("span",{children:[a.length,"/",aa," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:c,onDragOver:m,onDragLeave:p,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,{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((x,v)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${v+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>g(v),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:v+1})]},v))})]}),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(y,document.body)};var ds={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}},iy={enabled:true};function wl(e){return e?{tools:{...ds.tools,...e.tools},actions:{...ds.actions,...e.actions}}:ds}var ly={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}},dy={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 Oy=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:r}={})=>{let n=xe(),s=te(E=>E.canvas.slides.find(ie=>ie.id===E.canvas.currentSlideId)),i=s?.videos||[],l=s?.editingFlashcard,d=te(E=>E.toolbar.selectedTool),f=te(E=>E.toolbar.penColor),u=s?.showMcqForm,c=s?.showFlashcardForm,m=useMemo(()=>wl(r),[r]),{tools:p,actions:g}=m,h=i.some(E=>E.isRecorded&&E.isPlaying),y=te(E=>E.toolbar.fontSize),x=te(E=>E.toolbar.fontFamily),v=te(E=>E.toolbar.fontStyle),L=te(E=>E.toolbar.fontWeight),k=te(E=>E.toolbar.textDecoration),C=te(E=>E.toolbar.textColor),[S,b]=useState(false),[T,N]=useState(false),[D,q]=useState(false),[U,A]=useState(false),[W,R]=useState(false),re=useRef(null),V=useRef(null),oe=useMemo(()=>[{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(()=>[{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"}],[]),O=useMemo(()=>[{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"}],[]),j=useMemo(()=>oe.filter(E=>{let ie=p[E.configKey];return typeof ie=="boolean"?ie:Array.isArray(ie)?ie.length>0:true}),[p,oe]),H=useMemo(()=>{let E=p.shapes;return E===false?[]:E===true?z:Array.isArray(E)?z.filter(ie=>E.includes(ie.name)):z},[p.shapes,z]),K=useMemo(()=>{let E=p.activities;return E===false?[]:E===true?O:Array.isArray(E)?O.filter(ie=>E.includes(ie.name)):O},[p.activities,O]),J=useMemo(()=>{let E=p.media;return E===false?{photoFrame:false,image:false,video:false}:E===true?{photoFrame:true,image:true,video:true}:Array.isArray(E)?{photoFrame:E.includes("photo-frame"),image:E.includes("image"),video:E.includes("video")}:{photoFrame:true,image:true,video:true}},[p.media]),ee=useMemo(()=>{let E=p.activities;return E===false?false:E===true?true:Array.isArray(E)?E.includes("flashcard"):true},[p.activities]),Z=E=>{let ie=E.target.files;!ie||ie.length===0||(n(Wt("select")),n(ct(false)),A(false),Array.from(ie).forEach(Ce=>{let me=new FileReader;me.onload=ne=>{let le=new window.Image;le.src=ne.target?.result,le.onload=()=>{let Re=le.width/le.height,lt=300,Gt=300,dt=le.width,Ee=le.height;dt>lt&&(dt=lt,Ee=dt/Re),Ee>Gt&&(Ee=Gt,dt=Ee*Re),n(ue());let Xe=(window.innerWidth-dt)/2,vt=(window.innerHeight-Ee)/2;n(Fs({id:v4(),src:le.src,x:Xe,y:vt,width:dt,height:Ee,draggable:true,rotation:0}));};},me.readAsDataURL(Ce);}),E.target.value="");},se=async E=>{let ie=E.target.files;if(!(!ie||ie.length===0)){console.log("files",E),n(Wt("select")),n(ct(false)),A(false);for(let Ce of Array.from(ie))try{let me=URL.createObjectURL(Ce),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,na)=>{let Ta=setTimeout(()=>na(new Error("Metadata load timeout")),1e4);ne.onloadedmetadata=()=>{clearTimeout(Ta),Ze();},ne.onerror=()=>{clearTimeout(Ta),na(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ne.duration,width:ne.videoWidth,height:ne.videoHeight}),await new Promise((Ze,na)=>{let Ta=setTimeout(()=>na(new Error("Video load timeout")),1e4);ne.readyState>=2?(clearTimeout(Ta),Ze()):ne.onloadeddata=()=>{clearTimeout(Ta),Ze();};});let le=Math.min(.8,ne.duration/2);console.log("Seeking to:",le),ne.currentTime=le,await new Promise(Ze=>{let na=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Ze();},5e3);ne.onseeked=()=>{clearTimeout(na),console.log("Seek completed"),Ze();};});let Re=document.createElement("canvas"),lt=ne.videoWidth/ne.videoHeight,Gt=400,dt=400,Ee=ne.videoWidth,Xe=ne.videoHeight;Ee>Gt&&(Ee=Gt,Xe=Ee/lt),Xe>dt&&(Xe=dt,Ee=Xe*lt),Re.width=Ee,Re.height=Xe;let vt=Re.getContext("2d",{willReadFrequently:!1});if(!vt)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:Ee,height:Xe}),vt.drawImage(ne,0,0,Ee,Xe);let Kt=Re.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Kt.length),n(ue());let Za=(window.innerWidth-Ee)/2,Qa=(window.innerHeight-Xe)/2,Nr=v4();await za(Nr,Ce,Kt),n(jr({id:Nr,objectUrl:me,thumbnailDataUrl:Kt,videoBlob:Ce,x:Za,y:Qa,width:Ee,height:Xe,draggable:!0,isPlaying:!1,rotation:0})),ne.src="",ne.load(),console.log(`Video uploaded: ${Ce.name}`);}catch(me){console.error("Error processing video:",me),alert(`Failed to process video: ${Ce.name}`);}E.target.value="";}},Se=(E,ie,Ce)=>{n(ue()),n(Wt("select")),n(ct(false));let me=300,ne=300,le=(window.innerWidth-me)/2,Re=(window.innerHeight-ne)/2;n(Ce?ro({id:Ce,images:E,order:ie,x:le,y:Re,width:me,height:ne,rotation:0,draggable:true}):Ns({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:E,currentIndex:0,order:ie,x:le,y:Re,width:me,height:ne,rotation:0,draggable:true})),n(Pa(false));},Y=()=>{n(ue()),n(Wt("select")),n(ct(false));let E=400,ie=300,Ce=(window.innerWidth-E)/2,me=(window.innerHeight-ie)/2;n(Hs({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:Ce,y:me,width:E,height:ie,rotation:0,draggable:true,isCapturing:false})),R(false);},De=E=>{let me=(window.innerWidth-100)/2,ne=(window.innerHeight-100)/2,le={};switch(E.name){case "circle":case "ring":case "wedge":case "arc":le.radius=50,(E.name==="ring"||E.name==="arc")&&(le.innerRadius=25,le.outerRadius=50),(E.name==="wedge"||E.name==="arc")&&(le.angle=E.name==="wedge"?60:90);break;case "ellipse":le.radiusX=60,le.radiusY=40;break;case "triangle":le.radius=50,le.sides=3;break;case "polygon":le.radius=50,le.sides=6;break;case "star":le.innerRadius=25,le.outerRadius=50,le.numPoints=5;break;case "arrow":case "line":le.points=[0,0,100,0],E.name==="arrow"&&(le.pointerLength=10,le.pointerWidth=10);break}let Re={id:`shape-${Date.now()}`,type:E.name,x:me,y:ne,width:100,height:100,rotation:0,color:f,...le};n(ue()),n(ct(false)),n(Wt(E.name)),n(Bs(Re));},Ie=E=>{if(n(Wt(E)),E==="select")n(ct(false));else if(E==="text"){n(ct(false)),n(ue());let ie=200,Ce=50,me=(window.innerWidth-ie)/2,ne=(window.innerHeight-Ce)/2,le=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(Os({id:le,text:"",x:me,y:ne,width:ie,height:Ce,rotation:0,draggable:true,fontSize:y,fontFamily:x,fontStyle:v,fontWeight:L,textDecoration:k,fill:C,align:"left"})),setTimeout(()=>{n($o(le));},100),a&&a(le);}else n(ct(true));},Ft=()=>{n(ai()),n(Wt("select")),n(ct(false));},Ja=()=>{o?o():t?b(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Or=()=>{N(true);},Vo=async(E,ie)=>{try{n(Wt("select")),n(ct(!1));let Ce=URL.createObjectURL(E),me=document.createElement("video");me.src=Ce,me.muted=!0,me.playsInline=!0,me.preload="auto",await new Promise((Kt,Za)=>{let Qa=setTimeout(()=>Za(new Error("Metadata load timeout")),1e4);me.onloadedmetadata=()=>{clearTimeout(Qa),Kt();},me.onerror=()=>{clearTimeout(Qa),Za(new Error("Failed to load video"));};});let ne=640,le=me.videoWidth/me.videoHeight,Re=ne,lt=Re/le,Gt=window.innerWidth,dt=window.innerHeight;n(ue());let Ee=(Gt-Re)/2,Xe=(dt-lt)/2,vt=v4();await za(vt,E,ie),n(jr({id:vt,objectUrl:Ce,thumbnailDataUrl:ie,videoBlob:E,x:Ee,y:Xe,width:Re,height:lt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),b(!1),N(!1);}catch(Ce){console.error("Error adding recorded video to canvas:",Ce),alert("Failed to add video to canvas. Please try again.");}},xs=E=>{n(Wt("select")),n(ct(false)),n(_o(null)),E&&n(Ys(E)),n(da(!u));},bs=()=>{n(Wo(null)),n(Pa(true)),R(false);},vs=()=>{q(!D);},ys=()=>{A(!U);},ws=()=>{R(!W);};return h?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ca,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:j.map((E,ie)=>jsx("div",{title:E.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 2xl:py-3 ${E.name===d?"bg-primary/10":""}`,onClick:()=>{if(E.name==="image"){ys(),q(false),R(false),Ie(E.name);return}else if(E.name==="shapes"){vs(),A(false),R(false),Ie(E.name);return}else if(E.name==="activities"){Ie(E.name),ws(),q(false),A(false);return}Ie(E.name),q(false),A(false),R(false);},children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ie))}),D&&jsx(Ca,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:H.map((E,ie)=>jsx("div",{title:E.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",onClick:()=>De(E),children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ie))}),U&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[J.photoFrame&&jsx("div",{title:"Photo frame",onClick:Y,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),J.image&&jsx("div",{title:"Image",onClick:()=>re.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),J.video&&jsx("div",{title:"Video",onClick:()=>V.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})})]}),W&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[ee&&jsx("div",{title:"Flashcard",onClick:()=>bs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),K.map((E,ie)=>jsx("div",{title:E.label,onClick:()=>xs(E.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ie))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Ca,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>n(oi()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>n(ri()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:Ja,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6279F8]",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Or,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6BBB93]",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>Ft(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl 2xl:text-2xl"})})]})]}),jsx("input",{ref:re,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Z}),jsx("input",{ref:V,type:"file",accept:"video/*",className:"hidden",onChange:se}),!o&&S&&t&&jsx(nr,{onClose:()=>b(false),stageRef:t,onRecordingComplete:Vo}),T&&jsx(Zc,{onClose:()=>N(false),onRecordingComplete:Vo}),c&&jsx(ef,{editingFlashcard:l,onConfirm:Se,onCancel:()=>n(Pa(false))})]})},Ny=Oy;var Cl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let r=ut(Yo),n=ut(li),s=a?n:r,i=ut(Jo),f=(ut(x=>x.canvas.slides.find(v=>v.id===x.canvas.currentSlideId))?.videos||[]).some(x=>x.isRecorded&&x.isPlaying),[u,c]=useState(false),[m,p]=useState(null),[g,h]=useState(null),y=async()=>{if(r.length===0){h({type:"error",message:"No slides to publish"});return}if(!e){h({type:"error",message:"No publish handler provided"});return}c(true),h(null);try{let x=await e(s,i,v=>{p(v);});x.success?h({type:"success",message:x.message}):h({type:"error",message:x.message});}catch(x){h({type:"error",message:x instanceof Error?x.message:"An unexpected error occurred"});}finally{c(false),setTimeout(()=>{p(null),h(null);},3e3);}};return f?null:jsxs("button",{onClick:y,disabled:u||r.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Wy=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:n,showPublishButton:s=true,showBackButton:i=true,editableTitle:l=true,editableDescription:d=true,className:f="",rightContent:u,leftContent:c,includeInactiveSlides:m=false})=>{let p=et(),g=ut(Jo),h=ut(ui),y=e??(h?g.title:"")??"Untitled",x=o??(h?g.description:"")??"Add a description...",[v,L]=useState(false),[k,C]=useState(false),[S,b]=useState(y),[T,N]=useState(x),D=useRef(null),q=useRef(null);useEffect(()=>{b(y);},[y]),useEffect(()=>{N(x);},[x]),useEffect(()=>{v&&D.current&&(D.current.focus(),D.current.select());},[v]),useEffect(()=>{k&&q.current&&(q.current.focus(),q.current.select());},[k]);let U=()=>{l&&L(true);},A=()=>{d&&C(true);},W=()=>{L(false),S.trim()&&S!==y?r?r(S.trim()):p(ni(S.trim())):S.trim()||b(y);},R=()=>{C(false),T.trim()&&T!==x?n?n(T.trim()):p(si(T.trim())):T.trim()||N(x);},re=oe=>{oe.key==="Enter"?W():oe.key==="Escape"&&(b(y),L(false));},V=oe=>{oe.key==="Enter"?R():oe.key==="Escape"&&(N(x),C(false));};return 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-4 shadow-sm md:px-6 ${f}`,children:[c||jsxs("div",{className:"flex items-center gap-6",children:[i&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[v?jsx("input",{ref:D,type:"text",value:S,onChange:oe=>b(oe.target.value),onBlur:W,onKeyDown:re,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:U,title:S,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${l?"hover:border-primary cursor-text":""}`,children:S}),k?jsx("input",{ref:q,type:"text",value:T,onChange:oe=>N(oe.target.value),onBlur:R,onKeyDown:V,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:A,title:T,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${d?"hover:border-primary cursor-text":""}`,children:T})]})]}),u||s&&a&&jsx(Cl,{onPublish:a,includeInactiveSlides:m})]})};function Ml(e,[o,t]){return Math.min(t,Math.max(o,e))}function rf(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 sf(e){let[o,t]=be.useState(void 0);return To(()=>{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 l=n.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,i=d.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 lf=["PageUp","PageDown"],df=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],uf={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Bo="Slider",[Tl,Gy,Ky]=ts(Bo),[cf]=wa(Bo,[Ky]),[_y,ms]=cf(Bo),ff=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:i=false,minStepsBetweenThumbs:l=0,defaultValue:d=[a],value:f,onValueChange:u=()=>{},onValueCommit:c=()=>{},inverted:m=false,form:p,...g}=e,h=be.useRef(new Set),y=be.useRef(0),v=s==="horizontal"?jy:$y,[L=[],k]=ea({prop:f,defaultProp:d,onChange:D=>{[...h.current][y.current]?.focus(),u(D);}}),C=be.useRef(L);function S(D){let q=Qy(L,D);N(D,q);}function b(D){N(D,y.current);}function T(){let D=C.current[y.current];L[y.current]!==D&&c(L);}function N(D,q,{commit:U}={commit:false}){let A=ow(n),W=rw(Math.round((D-a)/n)*n+a,A),R=Ml(W,[a,r]);k((re=[])=>{let V=Jy(re,R,q);if(aw(V,l*n)){y.current=V.indexOf(R);let oe=String(V)!==String(re);return oe&&U&&c(V),oe?V:re}else return re});}return jsx(_y,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:r,valueIndexToChangeRef:y,thumbs:h.current,values:L,orientation:s,form:p,children:jsx(Tl.Provider,{scope:e.__scopeSlider,children:jsx(Tl.Slot,{scope:e.__scopeSlider,children:jsx(v,{"aria-disabled":i,"data-disabled":i?"":void 0,...g,ref:o,onPointerDown:je(g.onPointerDown,()=>{i||(C.current=L);}),min:a,max:r,inverted:m,onSlideStart:i?void 0:S,onSlideMove:i?void 0:b,onSlideEnd:i?void 0:T,onHomeKeyDown:()=>!i&&N(a,0,{commit:true}),onEndKeyDown:()=>!i&&N(r,L.length-1,{commit:true}),onStepKeyDown:({event:D,direction:q})=>{if(!i){let W=lf.includes(D.key)||D.shiftKey&&df.includes(D.key)?10:1,R=y.current,re=L[R],V=n*W*q;N(re+V,R,{commit:true});}}})})})})});ff.displayName=Bo;var[mf,pf]=cf(Bo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),jy=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:i,onSlideEnd:l,onStepKeyDown:d,...f}=e,[u,c]=be.useState(null),m=Dt(o,v=>c(v)),p=be.useRef(void 0),g=Po(r),h=g==="ltr",y=h&&!n||!h&&n;function x(v){let L=p.current||u.getBoundingClientRect(),k=[0,L.width],S=Dl(k,y?[t,a]:[a,t]);return p.current=L,S(v-L.left)}return jsx(mf,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(hf,{dir:g,"data-orientation":"horizontal",...f,ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{let L=x(v.clientX);s?.(L);},onSlideMove:v=>{let L=x(v.clientX);i?.(L);},onSlideEnd:()=>{p.current=void 0,l?.();},onStepKeyDown:v=>{let k=uf[y?"from-left":"from-right"].includes(v.key);d?.({event:v,direction:k?-1:1});}})})}),$y=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:i,onStepKeyDown:l,...d}=e,f=be.useRef(null),u=Dt(o,f),c=be.useRef(void 0),m=!r;function p(g){let h=c.current||f.current.getBoundingClientRect(),y=[0,h.height],v=Dl(y,m?[a,t]:[t,a]);return c.current=h,v(g-h.top)}return jsx(mf,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:jsx(hf,{"data-orientation":"vertical",...d,ref:u,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{let h=p(g.clientY);n?.(h);},onSlideMove:g=>{let h=p(g.clientY);s?.(h);},onSlideEnd:()=>{c.current=void 0,i?.();},onStepKeyDown:g=>{let y=uf[m?"from-bottom":"from-top"].includes(g.key);l?.({event:g,direction:y?-1:1});}})})}),hf=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:i,onStepKeyDown:l,...d}=e,f=ms(Bo,t);return jsx(st.span,{...d,ref:o,onKeyDown:je(e.onKeyDown,u=>{u.key==="Home"?(s(u),u.preventDefault()):u.key==="End"?(i(u),u.preventDefault()):lf.concat(df).includes(u.key)&&(l(u),u.preventDefault());}),onPointerDown:je(e.onPointerDown,u=>{let c=u.target;c.setPointerCapture(u.pointerId),u.preventDefault(),f.thumbs.has(c)?c.focus():a(u);}),onPointerMove:je(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:je(e.onPointerUp,u=>{let c=u.target;c.hasPointerCapture(u.pointerId)&&(c.releasePointerCapture(u.pointerId),n(u));})})}),gf="SliderTrack",xf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ms(gf,t);return jsx(st.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});xf.displayName=gf;var Al="SliderRange",bf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ms(Al,t),n=pf(Al,t),s=be.useRef(null),i=Dt(o,s),l=r.values.length,d=r.values.map(c=>wf(c,r.min,r.max)),f=l>1?Math.min(...d):0,u=100-Math.max(...d);return jsx(st.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:i,style:{...e.style,[n.startEdge]:f+"%",[n.endEdge]:u+"%"}})});bf.displayName=Al;var Pl="SliderThumb",vf=be.forwardRef((e,o)=>{let t=Gy(e.__scopeSlider),[a,r]=be.useState(null),n=Dt(o,i=>r(i)),s=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx(Xy,{...e,ref:n,index:s})}),Xy=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=ms(Pl,t),i=pf(Pl,t),[l,d]=be.useState(null),f=Dt(o,x=>d(x)),u=l?s.form||!!l.closest("form"):true,c=sf(l),m=s.values[a],p=m===void 0?0:wf(m,s.min,s.max),g=Zy(a,s.values.length),h=c?.[i.size],y=h?ew(h,p,i.direction):0;return be.useEffect(()=>{if(l)return s.thumbs.add(l),()=>{s.thumbs.delete(l);}},[l,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${p}% + ${y}px)`},children:[jsx(Tl.ItemSlot,{scope:e.__scopeSlider,children:jsx(st.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":s.min,"aria-valuenow":m,"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:f,style:m===void 0?{display:"none"}:e.style,onFocus:je(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),u&&jsx(yf,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:m},a)]})});vf.displayName=Pl;var Yy="RadioBubbleInput",yf=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=Dt(r,a),s=rf(o);return be.useEffect(()=>{let i=r.current;if(!i)return;let l=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==o&&f){let u=new Event("input",{bubbles:true});f.call(i,o),i.dispatchEvent(u);}},[s,o]),jsx(st.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});yf.displayName=Yy;function Jy(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function wf(e,o,t){let n=100/(t-o)*(e-o);return Ml(n,[0,100])}function Zy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Qy(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 ew(e,o,t){let a=e/2,n=Dl([0,50],[0,a]);return (a-n(o)*t)*t}function tw(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function aw(e,o){if(o>0){let t=tw(e);return Math.min(...t)>=o}return true}function Dl(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 ow(e){return (String(e).split(".")[1]||"").length}function rw(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Lf=ff,Sf=xf,If=bf,Cf=vf;function Mf({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:i,...l}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(Lf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Ia("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),...l,children:[jsx(Sf,{"data-slot":"slider-track",className:Ia("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(If,{"data-slot":"slider-range",className:Ia("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:d.length},(f,u)=>jsx(Cf,{"data-slot":"slider-thumb",className:Ia("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)},u))]})}var lw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],dw=({colors:e=lw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let n=te(i=>i.toolbar.penColor),s=xe();return jsxs("div",{className:`absolute bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:p-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(Mf,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:i=>s(bl(i[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(Ca,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(i=>jsx("button",{value:i.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${n===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>s(ls(i.value))},i.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>s(ls(i.target.value))}),jsx(Plus,{color:"#00000099"})]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center px-2 2xl:px-4",children:jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033] lg:h-12 lg:w-12",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>s(Rs(i.target.value))})})})]})};function uw({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var Af=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),El=e=>{let o=fw(e);return o.charAt(0).toUpperCase()+o.slice(1)},ps=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Pf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Df={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 Ef=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:s,...i},l)=>createElement("svg",{ref:l,...Df,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:ps("lucide",r),...!n&&!Pf(i)&&{"aria-hidden":"true"},...i},[...s.map(([d,f])=>createElement(d,f)),...Array.isArray(n)?n:[n]]));var hs=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(Ef,{ref:n,iconNode:o,className:ps(`lucide-${Af(El(e))}`,`lucide-${e}`,a),...r}));return t.displayName=El(e),t};var gw=[["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"}]],Er=hs("copy",gw);var xw=[["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"}]],Fr=hs("trash-2",xw);var Bf=({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(Er,{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(Fr,{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:`Page ${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 ww=({softDelete:e=false})=>{let o=et(),t=ut(Yo),a=ut(Xo),r=ut(di),[n,s]=useState(true),d=(ut(p=>p.canvas.slides.find(g=>g.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),f=()=>{r&&o(Ms());},u=p=>{o(Ps(p));},c=p=>{o(As(p));},m=p=>{t.length>1&&o(Ts({id:p,softDelete:e}));};return d?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:n?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:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[t.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:t.map((p,g)=>jsx(Bf,{slide:p,index:g,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>u(p.id),onDuplicate:()=>c(p.id),onDelete:()=>m(p.id)},p.id))}),jsxs("button",{onClick:f,disabled:!r,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${r?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!n&&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 Lw="SchooplaEditorDB",Sw=1,ka="slides",Ma="metadata",Fl="schoopla_current_slide_id",Vf="presentation_metadata",Br=()=>new Promise((e,o)=>{let t=indexedDB.open(Lw,Sw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ka)||r.createObjectStore(ka,{keyPath:"id"}),r.objectStoreNames.contains(Ma)||r.createObjectStore(Ma,{keyPath:"id"});};}),Bl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Br(),a=o.transaction([ka],"readwrite").objectStore(ka);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);}}},Ol=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Br(),t=e.transaction([ka],"readonly").objectStore(ka);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}}},gs=async()=>{try{let e=await Br(),o=e.transaction([ka,Ma],"readwrite"),t=o.objectStore(ka),a=o.objectStore(Ma);await new Promise((r,n)=>{let s=t.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(Fl),localStorage.removeItem("schoopla_presentation_metadata"),await tc(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Nl=e=>{try{localStorage.setItem(Fl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Vl=()=>{try{return localStorage.getItem(Fl)}catch(e){return console.error("Error loading current slide ID:",e),null}},ql=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Hl=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await Br(),a=o.transaction([Ma],"readwrite").objectStore(Ma);await new Promise((r,n)=>{let s=a.put({id:Vf,...e});s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Ul=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await Br(),t=e.transaction([Ma],"readonly").objectStore(Ma);return new Promise((a,r)=>{let n=t.get(Vf);n.onsuccess=()=>{e.close();let s=n.result;if(s){let{id:i,...l}=s;console.log("\u2705 Loaded presentation metadata:",l),a(l);}else console.log("No presentation metadata found"),a(null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var Iw=["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/reorderSlides"],Cw=["canvas/clearCanvas"],kw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],Mw=ql((e,o)=>{Bl(e),Nl(o);},500),Tw=ql(e=>{Hl(e);},500),Aw=(e,o)=>{Bl(e),Nl(o);},Wl=false,qf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;nl(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=>{nl(i.id).catch(l=>{console.error("Error deleting video blob:",l);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),i=n.canvas.slides.find(l=>l.id===n.canvas.currentSlideId)?.videos.find(l=>l.id===r);i&&i.videoBlob&&setTimeout(()=>{let l=e.getState(),f=l.canvas.slides.find(u=>u.id===l.canvas.currentSlideId)?.videos.find(u=>u.id!==r&&u.x===i.x+20&&u.y===i.y+20);f&&i.videoBlob&&za(f.id,i.videoBlob,f.thumbnailDataUrl).catch(u=>{console.error("Error saving duplicated video blob:",u);});},0);}let a=o(t);if(t.type&&Cw.includes(t.type)){if(!Wl){Wl=true;try{let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;Aw(n,s);}finally{setTimeout(()=>{Wl=false;},0);}}}else if(t.type&&Iw.includes(t.type)){let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;Mw(n,s);}else if(t.type&&kw.includes(t.type)){let r=e.getState(),{presentationMetadata:n}=r.canvas;Tw(n);}return a});new QueryClient;var Rw=configureStore({reducer:{toolbar:Jc,canvas:rd},middleware:e=>e({serializableCheck:false}).concat(qf)});var Ew=(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}),l=document.createElement("a");l.download=`${n}.${t}`,l.href=i,document.body.appendChild(l),l.click(),document.body.removeChild(l);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},Fw=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",l=e.toDataURL({mimeType:i,quality:a,pixelRatio:r});fetch(l).then(d=>d.blob()).then(d=>n(d)).catch(d=>s(d));}catch(i){s(i);}})},Bw=(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 Ow=(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,l=o.y+s*r;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-l,2))},zl=(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=Ow(e[s],r,n);i>t&&(t=i,a=s);}if(t>o){let s=zl(e.slice(0,a+1),o),i=zl(e.slice(a),o);return [...s.slice(0,-1),...i]}return [r,n]},Nw=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Vw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Hf=(e,o=1.5)=>{if(e.length<=4)return e;let t=Nw(e),a=zl(t,o);return Vw(a)},Uf=(e,o=1.5)=>({...e,points:Hf(e.points,o)}),qw=(e,o=1.5)=>e.map(t=>Uf(t,o)),Hw=(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 Uw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Wf=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:l,height:d}=i;if(l>t||d>a){let p=l/d;l>d?(l=Math.min(l,t),d=l/p):(d=Math.min(d,a),l=d*p);}let f=document.createElement("canvas");f.width=l,f.height=d;let u=f.getContext("2d");if(!u){s(new Error("Failed to get canvas context"));return}u.drawImage(i,0,0,l,d);let c=Uw(e),m=f.toDataURL(c,r);n(m);},i.onerror=s,i.src=e;})};var Ya=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},Oo=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",No=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",Ww=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,s=[],i=0;for(let l of e){let d=[],f=[],u=[];for(let c of l.images){let m=c.src;if(t&&m.startsWith("data:"))try{m=await Wf(m,{maxWidth:a,maxHeight:r,quality:n});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(m.startsWith("data:")){let p=Ya(m),g=Oo(m);i+=p.byteLength;let h={id:c.id,x:c.x,y:c.y,width:c.width,height:c.height,draggable:c.draggable,rotation:c.rotation,locked:c.locked,link:c.link,altText:c.altText,zIndex:c.zIndex,buffer:p,mimeType:g};if(c.audioData&&c.audioData.startsWith("data:")){let y=Ya(c.audioData),x=Oo(c.audioData);i+=y.byteLength,h.audioBuffer=y,h.audioMimeType=x;}d.push(h);}}for(let c of l.videos){let m,p;if(c.videoBlob)m=await c.videoBlob.arrayBuffer(),p=c.videoBlob.type;else if(c.videoData&&c.videoData.startsWith("data:"))m=Ya(c.videoData),p=Oo(c.videoData);else {console.warn(`Video ${c.id} has no blob or videoData, skipping`);continue}i+=m.byteLength;let g={id:c.id,thumbnailDataUrl:c.thumbnailDataUrl,x:c.x,y:c.y,width:c.width,height:c.height,draggable:c.draggable,isPlaying:c.isPlaying,rotation:c.rotation,locked:c.locked,link:c.link,altText:c.altText,zIndex:c.zIndex,isRecorded:c.isRecorded,buffer:m,mimeType:p};if(c.audioData&&c.audioData.startsWith("data:")){let h=Ya(c.audioData),y=Oo(c.audioData);i+=h.byteLength,g.audioBuffer=h,g.audioMimeType=y;}f.push(g);}for(let c of l.photoFrames){let m={id:c.id,x:c.x,y:c.y,width:c.width,height:c.height,rotation:c.rotation,draggable:c.draggable,locked:c.locked,link:c.link,altText:c.altText,zIndex:c.zIndex,isCapturing:c.isCapturing};if(c.capturedImageUrl&&c.capturedImageUrl.startsWith("data:")){let p=Ya(c.capturedImageUrl),g=Oo(c.capturedImageUrl);i+=p.byteLength,m.buffer=p,m.mimeType=g;}if(c.audioData&&c.audioData.startsWith("data:")){let p=Ya(c.audioData),g=Oo(c.audioData);i+=p.byteLength,m.audioBuffer=p,m.audioMimeType=g;}u.push(m);}s.push({...l,images:d,videos:f,photoFrames:u});}return {slides:s,totalSize:i}},zw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},Gw=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((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)=>{a.images.forEach((n,s)=>{let i=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${No(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,i,l),n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${No(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,d,f);}}),a.videos.forEach((n,s)=>{let i=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${No(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,i,l),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let d=Ya(n.thumbnailDataUrl),f=new Blob([d],{type:"image/jpeg"}),u=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,f,u);}if(n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${No(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,d,f);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let i=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${No(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,i,l);}if(n.audioBuffer&&n.audioMimeType){let i=new Blob([n.audioBuffer],{type:n.audioMimeType}),l=`${n.id}_audio.${No(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,i,l);}});}),o};var jw=()=>{let e=et(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await Ol(),n=Vl(),s=await Ul();if(r&&r.length>0){let i=await ec(),l=r.map(f=>{if(f.videos&&f.videos.length>0){let u=f.videos.map(c=>{let m=i.get(c.id);if(m){let p=ac(m.blob);return {...c,objectUrl:p,thumbnailDataUrl:m.thumbnailDataUrl,videoBlob:m.blob}}else return c});return {...f,videos:u}}return f}),d=n&&l.find(f=>f.id===n)?n:l[0].id;e(to({slides:l,currentSlideId:d}));}e(s?ii({title:s.title,description:s.description}):wn(!0));}catch(r){console.error("Error loading persisted slides:",r),e(wn(true));}finally{t(false);}})();},[e]),{isLoading:o}};var Gf=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||""})),Kf=new WeakSet,_f=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await za(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},$w=()=>{let e=et(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Kf.has(a))return;Kf.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await gs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let i=n&&r.find(d=>d.id===n)?n:r[0].id,l=Gf(r);e(to({slides:l,currentSlideId:i})),await _f(l);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await gs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let i=n&&r.find(d=>d.id===n)?n:r[0].id,l=Gf(r);e(to({slides:l,currentSlideId:i})),await _f(l);},[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{ly as BASIC_EDITOR_TOOLBAR_CONFIG,lw as BottomToolbar,mb as Canvas,sy as DEFAULT_CONTEXT_MENU_CONFIG,ds as DEFAULT_TOOLBAR_CONFIG,dw as EditorRoot,Sl as PublishButton,nr as ScreenRecorder,yw as SlideNavigation,Oy as Toolbar,Uy as TopNavBar,iy as VIEWER_TOOLBAR_CONFIG,Xs as addFillInTheBlanks,Ns as addFlashcard,Fs as addImage,Ws as addImageAnnotation,Es as addLine,$s as addLongAnswer,Ks as addMultipleChoice,Hs as addPhotoFrame,Gs as addPhotoFrameAnnotation,Bs as addShape,js as addShortAnswer,Ms as addSlide,Os as addText,_s as addTrueFalse,jr as addVideo,Ww as arrayBufferToBase64,Js as bringToFront,ai as clearCanvas,Pm as clearImageAnnotations,gs as clearLocalData,Rm as clearPhotoFrameAnnotations,ks as createEmptySlide,pn as deleteFillInTheBlanks,tn as deleteFlashcard,Kr as deleteImage,yn as deleteLineById,fn as deleteLongAnswer,nn as deleteMultipleChoice,on as deletePhotoFrame,Zr as deleteShape,un as deleteShortAnswer,Ts as deleteSlide,Qr as deleteText,ln as deleteTrueFalse,Xr as deleteVideo,hn as duplicateFillInTheBlanks,an as duplicateFlashcard,_r as duplicateImage,ti as duplicateLine,mn as duplicateLongAnswer,sn as duplicateMultipleChoice,rn as duplicatePhotoFrame,Jr as duplicateShape,cn as duplicateShortAnswer,As as duplicateSlide,en as duplicateText,dn as duplicateTrueFalse,Yr as duplicateVideo,Wo as editFlashcard,Em as editMultipleChoice,Ew as exportSlideAsBlob,Rw as exportSlideAsImage,ei as finalizeDrawing,qw as getCompressionStats,Fw as getSlideDataURL,Nl as loadCurrentSlideId,Bl as loadFromIndexedDB,ii as loadPresentationMetadata,Hl as loadPresentationMetadataFromDB,to as loadSlides,yl as mergeToolbarConfig,Vs as nextFlashcard,zw as prepareFormData,Uw as prepareSlidesForPublishing,qs as previousFlashcard,ri as redo,Gr as removeLine,Tm as reorderSlides,ql as savePresentationMetadata,de as saveToHistory,Yo as selectAllSlides,li as selectCanAddSlide,ge as selectCurrentSlide,Xo as selectCurrentSlideId,di as selectMetadataLoaded,Jo as selectPresentationMetadata,Vm as selectSlideById,Zs as sendToBack,Ys as setActivityType,xn as setAltText,bn as setAudioData,Rs as setBackgroundColor,Ps as setCurrentSlide,_o as setEditingActivity,$o as setEditingTextId,Bm as setLines,gn as setLink,wn as setMetadataLoaded,ls as setPenColor,si as setPresentationDescription,ni as setPresentationTitle,Pa as setShowFlashcardForm,da as setShowMcqForm,ut as setSketchMode,xl as setStrokeWidth,Wt as setTool,qf as simplifyFlatPoints,Hf as simplifyLine,Vw as simplifyLines,Dw as store,Us as toggleImageDrawingMode,Qs as toggleLock,zs as togglePhotoFrameDrawingMode,Nm as toggleSketchMode,Uo as toggleVideoPlaying,oi as undo,jo as updateElementOrder,Ko as updateFillInTheBlanks,ro as updateFlashcard,ao as updateImage,Am as updateImageAnnotation,Fm as updateLastLine,Om as updateLinePosition,vn as updateLineTransform,Go as updateLongAnswer,ia as updateMultipleChoice,Aa as updatePhotoFrame,Dm as updatePhotoFrameAnnotation,oo as updateShape,zo as updateShortAnswer,Ds as updateSlideThumbnail,St as updateText,la as updateTrueFalse,$r as updateVideo,xe as useDispatch,jw as useInitialSlides,te as useSelector,_w as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
+ */export{dy as BASIC_EDITOR_TOOLBAR_CONFIG,dw as BottomToolbar,pb as Canvas,iy as DEFAULT_CONTEXT_MENU_CONFIG,ds as DEFAULT_TOOLBAR_CONFIG,uw as EditorRoot,Cl as PublishButton,nr as ScreenRecorder,ww as SlideNavigation,Ny as Toolbar,Wy as TopNavBar,ly as VIEWER_TOOLBAR_CONFIG,Xs as addFillInTheBlanks,Ns as addFlashcard,Fs as addImage,Ws as addImageAnnotation,Es as addLine,$s as addLongAnswer,Ks as addMultipleChoice,Hs as addPhotoFrame,Gs as addPhotoFrameAnnotation,Bs as addShape,js as addShortAnswer,Ms as addSlide,Os as addText,_s as addTrueFalse,jr as addVideo,zw as arrayBufferToBase64,Js as bringToFront,ai as clearCanvas,Dm as clearImageAnnotations,gs as clearLocalData,Em as clearPhotoFrameAnnotations,ks as createEmptySlide,pn as deleteFillInTheBlanks,tn as deleteFlashcard,Kr as deleteImage,yn as deleteLineById,fn as deleteLongAnswer,nn as deleteMultipleChoice,on as deletePhotoFrame,Zr as deleteShape,un as deleteShortAnswer,Ts as deleteSlide,Qr as deleteText,ln as deleteTrueFalse,Xr as deleteVideo,hn as duplicateFillInTheBlanks,an as duplicateFlashcard,_r as duplicateImage,ti as duplicateLine,mn as duplicateLongAnswer,sn as duplicateMultipleChoice,rn as duplicatePhotoFrame,Jr as duplicateShape,cn as duplicateShortAnswer,As as duplicateSlide,en as duplicateText,dn as duplicateTrueFalse,Yr as duplicateVideo,Wo as editFlashcard,Fm as editMultipleChoice,Fw as exportSlideAsBlob,Ew as exportSlideAsImage,ei as finalizeDrawing,Hw as getCompressionStats,Bw as getSlideDataURL,Vl as loadCurrentSlideId,Ol as loadFromIndexedDB,ii as loadPresentationMetadata,Ul as loadPresentationMetadataFromDB,to as loadSlides,wl as mergeToolbarConfig,Vs as nextFlashcard,Gw as prepareFormData,Ww as prepareSlidesForPublishing,qs as previousFlashcard,ri as redo,Gr as removeLine,Am as reorderSlides,Hl as savePresentationMetadata,ue as saveToHistory,Yo as selectAllSlides,li as selectAllSlidesIncludingInactive,di as selectCanAddSlide,ge as selectCurrentSlide,Xo as selectCurrentSlideId,ui as selectMetadataLoaded,Jo as selectPresentationMetadata,qm as selectSlideById,Zs as sendToBack,Ys as setActivityType,xn as setAltText,bn as setAudioData,Rs as setBackgroundColor,Ps as setCurrentSlide,_o as setEditingActivity,$o as setEditingTextId,Om as setLines,gn as setLink,wn as setMetadataLoaded,ls as setPenColor,si as setPresentationDescription,ni as setPresentationTitle,Pa as setShowFlashcardForm,da as setShowMcqForm,ct as setSketchMode,bl as setStrokeWidth,Wt as setTool,Hf as simplifyFlatPoints,Uf as simplifyLine,qw as simplifyLines,Rw as store,Us as toggleImageDrawingMode,Qs as toggleLock,zs as togglePhotoFrameDrawingMode,Vm as toggleSketchMode,Uo as toggleVideoPlaying,oi as undo,jo as updateElementOrder,Ko as updateFillInTheBlanks,ro as updateFlashcard,ao as updateImage,Pm as updateImageAnnotation,Bm as updateLastLine,Nm as updateLinePosition,vn as updateLineTransform,Go as updateLongAnswer,ia as updateMultipleChoice,Aa as updatePhotoFrame,Rm as updatePhotoFrameAnnotation,oo as updateShape,zo as updateShortAnswer,Ds as updateSlideThumbnail,It as updateText,la as updateTrueFalse,$r as updateVideo,xe as useDispatch,$w as useInitialSlides,te as useSelector,jw as useSlidesPersistence};//# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map