@turnix-co/konva-editor 2.0.0 → 2.0.1

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 ut,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,createElement,useMemo,useId,useLayoutEffect}from'react';import {Group,Image,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 ci from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {EyeIcon,Stack as Stack$1,X as X$1,DotsSixVertical,ArrowUp,ArrowDown,Question,FrameCorners,Cards as Cards$1,TextT as TextT$1,Shapes,VideoCamera,Image as Image$2}from'@phosphor-icons/react';import {Stop,X,Microphone,MicrophoneSlash,Record,Download,Selection,Pen,Eraser,TextT,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,List,Image as Image$1,Video,Cards,Camera,ListChecksIcon,ToggleRight,Textbox,Article,TextUnderline,ArrowUUpLeft,ArrowUDownRight,Trash,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,TextB,TextItalic,Warning,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {createPortal}from'react-dom';import ml from'use-image';import {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 ti=e=>{throw TypeError(e)};var ai=(e,o,a)=>o.has(e)||ti("Cannot "+a);var W=(e,o,a)=>(ai(e,o,"read from private field"),a?a.call(e):o.get(e)),Se=(e,o,a)=>o.has(e)?ti("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,a),be=(e,o,a,t)=>(ai(e,o,"write to private field"),o.set(e,a),a);var oi=(e,o,a,t)=>({set _(r){be(e,o,r);},get _(){return W(e,o,t)}});var pe=()=>useDispatch(),$=e=>useSelector(e),yt=pe,Vt=$;var Gr=20,ri=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()}),zr=ri("Slide 1"),cu={slides:[zr],currentSlideId:zr.id,history:{[zr.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null},si=createSlice({name:"canvas",initialState:cu,reducers:{addSlide:e=>{if(e.slides.length>=Gr)return;let o=ri(`Slide ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{if(e.slides.length<=1)return;let a=e.slides.findIndex(t=>t.id===o.payload);if(a!==-1&&(e.slides.splice(a,1),delete e.history[o.payload],e.currentSlideId===o.payload)){let t=Math.max(0,a-1);e.currentSlideId=e.slides[t].id;}},duplicateSlide:(e,o)=>{if(e.slides.length>=Gr)return;let a=e.slides.findIndex(i=>i.id===o.payload);if(a===-1)return;let t=e.slides[a],r={...t,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${t.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),lines:JSON.parse(JSON.stringify(t.lines)),images:JSON.parse(JSON.stringify(t.images)),videos:JSON.parse(JSON.stringify(t.videos)),shapes:JSON.parse(JSON.stringify(t.shapes)),flashcards:JSON.parse(JSON.stringify(t.flashcards)),photoFrames:JSON.parse(JSON.stringify(t.photoFrames))};e.slides.splice(a+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(t=>t.id===o.payload)&&(e.currentSlideId=o.payload);},updateSlideThumbnail:(e,o)=>{let a=e.slides.find(t=>t.id===o.payload.id);a&&(a.thumbnail=o.payload.thumbnail,a.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.backgroundColor=o.payload,a.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:a,toIndex:t}=o.payload;if(a<0||a>=e.slides.length||t<0||t>=e.slides.length)return;let[r]=e.slides.splice(a,1);e.slides.splice(t,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(a=>({...a,showMcqForm:false})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(a=>{e.history[a.id]={past:[],future:[]};});},addLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...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};a.lines.push(t),a.updatedAt=Date.now();}},removeLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&o.payload>=0&&o.payload<a.lines.length&&(a.lines.splice(o.payload,1),a.updatedAt=Date.now());},updateLastLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&a.lines.length>0&&(a.lines[a.lines.length-1].points=o.payload,a.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(a=>a.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.lines=o.payload,a.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.find(r=>r.id===o.payload.id);t&&(t.x=o.payload.x,t.y=o.payload.y,a.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.find(r=>r.id===o.payload.id);t&&(t.x=o.payload.x,t.y=o.payload.y,t.scaleX=o.payload.scaleX,t.scaleY=o.payload.scaleY,t.rotation=o.payload.rotation,a.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.findIndex(r=>r.id===o.payload);t!==-1&&(a.lines.splice(t,1),a.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.find(r=>r.id===o.payload);if(t){let r={...t,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(t.x||0)+20,y:(t.y||0)+20,timestamp:Date.now()};a.lines.push(r),a.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,newTimestamp:i}=o.payload;switch(r){case "image":let n=a.images.find(h=>h.id===t);n&&(n.timestamp=i);break;case "video":let u=a.videos.find(h=>h.id===t);u&&(u.timestamp=i);break;case "shape":let c=a.shapes.find(h=>h.id===t);c&&(c.timestamp=i);break;case "text":let s=a.texts.find(h=>h.id===t);s&&(s.timestamp=i);break;case "flashcard":let l=a.flashcards.find(h=>h.id===t);l&&(l.timestamp=i);break;case "photoFrame":let p=a.photoFrames.find(h=>h.id===t);p&&(p.timestamp=i);break;case "mcq":let f=a.multipleChoices.find(h=>h.id===t);f&&(f.timestamp=i);break;case "trueFalse":let d=a.trueFalses.find(h=>h.id===t);d&&(d.timestamp=i);break;case "shortAnswer":let m=a.shortAnswers.find(h=>h.id===t);m&&(m.timestamp=i);break;case "longAnswer":let x=a.LongAnswer.find(h=>h.id===t);x&&(x.timestamp=i);break;case "fillInTheBlanks":let g=a.fillInTheBlanks.find(h=>h.id===t);g&&(g.timestamp=i);break;case "line":let y=a.lines.find(h=>h.id===t);y&&(y.timestamp=i);break}a.updatedAt=Date.now();}},addImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.images.push(t),a.updatedAt=Date.now();}},updateImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.images[t]={...a.images[t],...o.payload},a.updatedAt=Date.now());}},deleteImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.images=a.images.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload);if(t){let r={...t,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.images.push(r),a.updatedAt=Date.now();}}},addVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.videos.push(t),a.updatedAt=Date.now();}},updateVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.videos.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.videos[t]={...a.videos[t],...o.payload},a.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.videos.find(r=>r.id===o.payload);t&&(t.isPlaying=!t.isPlaying,a.updatedAt=Date.now());}},deleteVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.videos=a.videos.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.videos.find(r=>r.id===o.payload);if(t){let r={...t,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,isPlaying:false,timestamp:Date.now()};a.videos.push(r),a.updatedAt=Date.now();}}},addShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.shapes?.push(t),a.updatedAt=Date.now();}},updateShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shapes.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.shapes[t]={...a.shapes[t],...o.payload},a.updatedAt=Date.now());}},duplicateShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shapes.find(r=>r.id===o.payload);if(t){let r={...t,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.shapes.push(r),a.updatedAt=Date.now();}}},deleteShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.shapes=a.shapes.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},addMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.multipleChoices||(a.multipleChoices=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.multipleChoices.length>0){let r=a.multipleChoices[a.multipleChoices.length-1];t.x=r.x+20,t.y=r.y+20;}a.multipleChoices.push(t),a.updatedAt=Date.now();}},updateMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a&&a.multipleChoices){let t=a.multipleChoices.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.multipleChoices[t]={...a.multipleChoices[t],...o.payload},a.updatedAt=Date.now());}},editMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a&&a.multipleChoices){let t=a.multipleChoices.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.multipleChoices[t]={...a.multipleChoices[t],...o.payload},a.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.multipleChoices.find(r=>r.id===o.payload);if(t){let r={...t,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.multipleChoices.push(r),a.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.multipleChoices=a.multipleChoices.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},addTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.trueFalses||(a.trueFalses=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.trueFalses.length>0){let r=a.trueFalses[a.trueFalses.length-1];t.x=r.x+20,t.y=r.y+20;}a.trueFalses.push(t),a.updatedAt=Date.now();}},updateTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.trueFalses.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.trueFalses[t]={...a.trueFalses[t],...o.payload},a.updatedAt=Date.now());}},deleteTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.trueFalses=a.trueFalses.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.trueFalses.find(r=>r.id===o.payload);if(t){let r={...t,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.trueFalses.push(r),a.updatedAt=Date.now();}}},addShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.shortAnswers||(a.shortAnswers=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.shortAnswers.length>0){let r=a.shortAnswers[a.shortAnswers.length-1];t.x=r.x+20,t.y=r.y+20;}a.shortAnswers.push(t),a.updatedAt=Date.now();}},updateShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shortAnswers.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.shortAnswers[t]={...a.shortAnswers[t],...o.payload},a.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shortAnswers.find(r=>r.id===o.payload);if(t){let r={...t,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.shortAnswers.push(r),a.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.shortAnswers=a.shortAnswers.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},addLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.LongAnswer||(a.LongAnswer=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.LongAnswer.length>0){let r=a.LongAnswer[a.LongAnswer.length-1];t.x=r.x+20,t.y=r.y+20;}a.LongAnswer.push(t),a.updatedAt=Date.now();}},updateLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.LongAnswer.find(r=>r.id===o.payload.id);t&&(Object.assign(t,o.payload),a.updatedAt=Date.now());}},deleteLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.LongAnswer=a.LongAnswer.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.LongAnswer.find(r=>r.id===o.payload);if(t){let r={...t,id:`${t.id}-copy-${Date.now()}`,timestamp:Date.now()};a.LongAnswer.push(r),a.updatedAt=Date.now();}}},setShowMcqForm(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.showMcqForm=o.payload,a.updatedAt=Date.now());},setShowFlashcardForm(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.showFlashcardForm=o.payload,a.updatedAt=Date.now());},addFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.fillInTheBlanks||(a.fillInTheBlanks=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.fillInTheBlanks.length>0){let r=a.fillInTheBlanks[a.fillInTheBlanks.length-1];t.x=r.x+20,t.y=r.y+20;}a.fillInTheBlanks.push(t),a.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.fillInTheBlanks[t]={...a.fillInTheBlanks[t],...o.payload},a.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.fillInTheBlanks=a.fillInTheBlanks.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.fillInTheBlanks.find(r=>r.id===o.payload);if(t){let r={...t,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.fillInTheBlanks.push(r),a.updatedAt=Date.now();}}},setActivityType(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.activityType=o.payload,a.updatedAt=Date.now());},setEditingActivity(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.editingActivity=o.payload,a.updatedAt=Date.now());},bringToFront(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r}=o.payload;if(r==="image"){let i=a.images.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.images.splice(i,1);a.images.push(n);}}else if(r==="video"){let i=a.videos.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.videos.splice(i,1);a.videos.push(n);}}else if(r==="shape"){let i=a.shapes.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.shapes.splice(i,1);a.shapes.push(n);}}else if(r==="flashcard"){let i=a.flashcards.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.flashcards.splice(i,1);a.flashcards.push(n);}}else if(r==="photoFrame"){let i=a.photoFrames.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.photoFrames.splice(i,1);a.photoFrames.push(n);}}else if(r==="text"){let i=a.texts.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.texts.splice(i,1);a.texts.push(n);}}else if(r==="trueFalse"){let i=a.trueFalses.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.trueFalses.splice(i,1);a.trueFalses.push(n);}}else if(r==="shortAnswer"){let i=a.shortAnswers.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.shortAnswers.splice(i,1);a.shortAnswers.push(n);}}else if(r==="fillInTheBlanks"){let i=a.fillInTheBlanks.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.fillInTheBlanks.splice(i,1);a.fillInTheBlanks.push(n);}}a.updatedAt=Date.now();}},sendToBack(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r}=o.payload;if(r==="image"){let i=a.images.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.images.splice(i,1);a.images.unshift(n);}}else if(r==="video"){let i=a.videos.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.videos.splice(i,1);a.videos.unshift(n);}}else if(r==="shape"){let i=a.shapes.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.shapes.splice(i,1);a.shapes.unshift(n);}}else if(r==="flashcard"){let i=a.flashcards.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.flashcards.splice(i,1);a.flashcards.unshift(n);}}else if(r==="photoFrame"){let i=a.photoFrames.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.photoFrames.splice(i,1);a.photoFrames.unshift(n);}}else if(r==="text"){let i=a.texts.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.texts.splice(i,1);a.texts.unshift(n);}}a.updatedAt=Date.now();}},toggleLock(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r}=o.payload,n=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(u=>u.id===t);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),a.updatedAt=Date.now());}},setLink(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,link:i}=o.payload,u=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="mcq"?a.multipleChoices:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(c=>c.id===t);u&&(u.link=i,a.updatedAt=Date.now());}},setAltText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,altText:i}=o.payload,u=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(c=>c.id===t);u&&(u.altText=i,a.updatedAt=Date.now());}},setAudioData(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,audioData:i}=o.payload,u=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(c=>c.id===t);u&&(u.audioData=i,a.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(a=>a.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.updatedAt=Date.now());},addText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.texts.push(t),a.updatedAt=Date.now();}},updateText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.texts.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.texts[t]={...a.texts[t],...o.payload},a.updatedAt=Date.now());}},deleteText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.texts=a.texts.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.texts.find(r=>r.id===o.payload);if(t){let r={...t,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.texts.push(r),a.updatedAt=Date.now();}}},addFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}a.flashcards.push(t),a.updatedAt=Date.now();}},updateFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.flashcards[t]={...a.flashcards[t],...o.payload},a.updatedAt=Date.now());}},deleteFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.flashcards=a.flashcards.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.find(r=>r.id===o.payload);if(t){let r={...t,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,currentIndex:0,timestamp:Date.now()};a.flashcards.push(r),a.updatedAt=Date.now();}}},editFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.editingFlashcard=o.payload);},nextFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.find(r=>r.id===o.payload);if(t&&t.images.length>0){if(t.order==="sequential")t.currentIndex=(t.currentIndex+1)%t.images.length;else {t.navigationHistory||(t.navigationHistory=[t.currentIndex]);let r=t.images.map((i,n)=>n).filter(i=>i!==t.currentIndex);if(r.length>0){let i=r[Math.floor(Math.random()*r.length)];t.navigationHistory.push(i),t.currentIndex=i;}}a.updatedAt=Date.now();}}},previousFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.find(r=>r.id===o.payload);t&&t.images.length>0&&(t.order==="sequential"?t.currentIndex=(t.currentIndex-1+t.images.length)%t.images.length:t.navigationHistory&&t.navigationHistory.length>1&&(t.navigationHistory.pop(),t.currentIndex=t.navigationHistory[t.navigationHistory.length-1]),a.updatedAt=Date.now());}},addPhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.photoFrames.push(t),a.updatedAt=Date.now();}},updatePhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.photoFrames[t]={...a.photoFrames[t],...o.payload},a.updatedAt=Date.now());}},deletePhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.photoFrames=a.photoFrames.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload);if(t){let r={...t,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,isCapturing:false,timestamp:Date.now()};a.photoFrames.push(r),a.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload);t&&(t.isDrawingMode=!t.isDrawingMode,t.annotations||(t.annotations=[]),a.updatedAt=Date.now());}},addImageAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload.imageId);t&&(t.annotations||(t.annotations=[]),t.annotations.push(o.payload.line),a.updatedAt=Date.now());}},updateImageAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload.imageId);t&&t.annotations&&t.annotations.length>0&&(t.annotations[t.annotations.length-1].points=o.payload.points,a.updatedAt=Date.now());}},clearImageAnnotations(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload);t&&(t.annotations=[],a.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload);t&&(t.isDrawingMode=!t.isDrawingMode,t.annotations||(t.annotations=[]),a.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload.frameId);t&&(t.annotations||(t.annotations=[]),t.annotations.push(o.payload.line),a.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload.frameId);t&&t.annotations&&t.annotations.length>0&&(t.annotations[t.annotations.length-1].points=o.payload.points,a.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload);t&&(t.annotations=[],a.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let a=e.slides.findIndex(t=>t.id===e.currentSlideId);if(a>=0)try{let t=e.slides[a];o.future.unshift(JSON.parse(JSON.stringify(t)));let r=o.past.pop();e.slides[a]=r;}catch(t){console.warn("Failed to undo - data too large:",t),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let a=e.slides.findIndex(t=>t.id===e.currentSlideId);if(a>=0)try{let t=e.slides[a];o.past.push(JSON.parse(JSON.stringify(t)));let r=o.future.shift();e.slides[a]=r;}catch(t){console.warn("Failed to redo - data too large:",t),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(a=>a.id===e.currentSlideId);if(o>=0){let a=e.slides[o],t=e.history[e.currentSlideId];if(t)try{let r=JSON.parse(JSON.stringify(a));t.past.push(r),t.future=[],t.past.length>20&&t.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),t.past.length>5&&(t.past=t.past.slice(-5)),t.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;}}}),{addSlide:jr,deleteSlide:Xr,duplicateSlide:$r,setCurrentSlide:_r,updateSlideThumbnail:Yr,setBackgroundColor:Jr,reorderSlides:fu,loadSlides:Qr,addLine:Zr,removeLine:jo,addImage:es,updateImage:Ia,deleteImage:ts,duplicateImage:Xo,addVideo:$o,updateVideo:_o,deleteVideo:as,duplicateVideo:Yo,toggleVideoPlaying:Ga,addShape:os,updateShape:wa,duplicateShape:Jo,deleteShape:rs,addText:ss,updateText:st,deleteText:ns,duplicateText:Qo,addFlashcard:is,updateFlashcard:Sa,deleteFlashcard:ls,duplicateFlashcard:Zo,editFlashcard:ja,nextFlashcard:ds,previousFlashcard:us,addPhotoFrame:cs,updatePhotoFrame:la,deletePhotoFrame:fs,duplicatePhotoFrame:er,toggleImageDrawingMode:ms,addImageAnnotation:ps,updateImageAnnotation:mu,clearImageAnnotations:pu,togglePhotoFrameDrawingMode:hs,addPhotoFrameAnnotation:gs,updatePhotoFrameAnnotation:hu,clearPhotoFrameAnnotations:gu,addMultipleChoice:xs,updateMultipleChoice:Ht,editMultipleChoice:xu,deleteMultipleChoice:bs,duplicateMultipleChoice:tr,addTrueFalse:vs,updateTrueFalse:Ut,deleteTrueFalse:Ls,duplicateTrueFalse:ar,addShortAnswer:ys,updateShortAnswer:Xa,deleteShortAnswer:Is,duplicateShortAnswer:or,addLongAnswer:ws,updateLongAnswer:$a,deleteLongAnswer:Ss,duplicateLongAnswer:rr,addFillInTheBlanks:Cs,updateFillInTheBlanks:_a,deleteFillInTheBlanks:ks,duplicateFillInTheBlanks:sr,setShowMcqForm:Wt,setShowFlashcardForm:da,setActivityType:Ms,setEditingActivity:Ya,bringToFront:As,sendToBack:Ds,toggleLock:Ts,setLink:nr,setAltText:ir,setAudioData:lr,updateLastLine:bu,finalizeDrawing:Fs,setLines:vu,updateLinePosition:Lu,updateLineTransform:dr,deleteLineById:Ps,duplicateLine:Es,updateElementOrder:Ja,clearCanvas:Rs,undo:Bs,redo:Os,saveToHistory:oe,toggleSketchMode:yu,setSketchMode:Xe,setEditingTextId:Qa}=si.actions,Za=e=>e.canvas.currentSlideId,ce=e=>{let o=e.canvas.currentSlideId,a=e.canvas.slides.findIndex(t=>t.id===o);return a>=0?e.canvas.slides[a]:void 0},eo=e=>e.canvas.slides,qs=e=>e.canvas.slides.length<Gr,Iu=e=>o=>{let a=o.canvas.slides.findIndex(t=>t.id===e);return a>=0?o.canvas.slides[a]:void 0},ni=si.reducer;var li=e=>{let o=pe(),a=useRef(null),t=useRef(false),r=$(d=>d.toolbar.selectedTool),i=$(d=>d.toolbar.penColor),n=$(d=>d.toolbar.strokeWidth),u=$(d=>d.canvas.isSketchMode),c=$(d=>d.canvas.slides.find(x=>x.id===d.canvas.currentSlideId)?.lines||[]),s=useCallback(d=>{a.current=d;},[]),l=useCallback(d=>{r==="pen"&&a.current&&(o(oe()),a.current.startDrawing(d),t.current=true);},[r,o]),p=useCallback(d=>{!a.current||!t.current||a.current.draw(d);},[]),f=useCallback(()=>{if(!a.current||!t.current)return;let d=a.current.stopDrawing();t.current=false,d&&d.points.length>=4&&o(Zr(d)),o(Fs()),e?.();},[o,e]);return {lines:c,tool:r,color:i,strokeWidth:n,isSketchMode:u,setCanvasRef:s,startDrawing:l,draw:p,stopDrawing:f}};var fi=forwardRef(({width:e,height:o,tool:a,color:t,strokeWidth:r,isSketchMode:i,style:n},u)=>{let c=useRef(null),s=useRef(false),l=useRef([]),p=useRef(null),f=useRef(a),d=useRef(t),m=useRef(r),x=useRef(i);useEffect(()=>{f.current=a,d.current=t,m.current=r,x.current=i;},[a,t,r,i]);let g=useCallback(()=>{let h=c.current;if(!h)return;let b=h.getContext("2d");b&&b.clearRect(0,0,h.width,h.height);},[]),y=useCallback(()=>{let h=c.current,b=l.current;if(!h||b.length<1)return;let L=h.getContext("2d");if(!L)return;if(L.clearRect(0,0,h.width,h.height),f.current==="eraser"?(L.globalCompositeOperation="destination-out",L.fillStyle="rgba(0,0,0,1)"):(L.globalCompositeOperation="source-over",L.fillStyle=d.current),b.length===1){L.beginPath(),L.arc(b[0].x,b[0].y,m.current/2,0,Math.PI*2),L.fill();return}let I=ci(b,{size:m.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:k=>k,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(I.length<2)){L.beginPath(),L.moveTo(I[0][0],I[0][1]);for(let k=1;k<I.length;k++)L.lineTo(I[k][0],I[k][1]);L.closePath(),L.fill();}},[]);return useImperativeHandle(u,()=>({startDrawing:h=>{s.current=true,l.current=[{x:h.x,y:h.y}],p.current=h,y();},draw:h=>{if(!s.current||!p.current)return;let b=h.x-p.current.x,L=h.y-p.current.y;Math.sqrt(b*b+L*L)<2||(l.current.push({x:h.x,y:h.y}),p.current=h,y());},stopDrawing:()=>{if(!s.current)return null;if(s.current=false,l.current.length<2)return l.current=[],p.current=null,g(),null;let b=ci(l.current,{size:m.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:C=>C,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(C=>[C[0],C[1]]),L={tool:f.current,points:b,color:d.current,strokeWidth:m.current,isSketch:true};return l.current=[],p.current=null,g(),L},clear:()=>{g(),l.current=[],p.current=null,s.current=false;},isDrawing:()=>s.current,getCanvasElement:()=>c.current}),[g,y]),useEffect(()=>{let h=c.current;h&&(h.width=e,h.height=o);},[e,o]),jsx("canvas",{ref:c,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});fi.displayName="DirectDrawingCanvas";var mi=fi;var hi=e=>{let o=pe(),t=$(ce)?.images||[],r=useRef(new Map),i=useRef(new Map),n=useRef(new Set);useEffect(()=>{let l=new Set(t.map(p=>p.id));n.current.forEach(p=>{if(!l.has(p)){let f=i.current.get(p);f&&(f.src="",i.current.delete(p)),r.current.delete(p);}}),n.current=l;},[t]),useEffect(()=>()=>{i.current.forEach(l=>{l.src="";}),i.current.clear(),r.current.clear();},[]);let u=useCallback(l=>{if(i.current.has(l.id))return i.current.get(l.id);let p=new window.Image;return p.src=l.src,i.current.set(l.id,p),p},[]),c=useCallback((l,p)=>{let f=l.target,d=f.id();t.find(x=>x.id===d)&&(o(Ia({id:d,x:f.x(),y:f.y(),width:f.width(),height:f.height(),rotation:f.rotation()})),p?.());},[t,o]),s=useCallback((l,p)=>{let f=p.target,d=r.current.get(l);if(!d){console.error("\u274C Image node not found for id:",l);return}let m=f.scaleX(),x=f.scaleY(),g=f.rotation(),y=d.width(),h=d.height(),b=Math.max(5,y*m),L=Math.max(5,h*x);f.scaleX(1),f.scaleY(1),d.width(b),d.height(L),o(Ia({id:l,width:b,height:L,x:f.x(),y:f.y(),rotation:g})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:t,getLoadedImage:u,imageRefs:r,handleDragEnd:c,handleImageTransformEnd:s}};var gi=e=>{let o=useDispatch(),a=useSelector(ce),t=useRef(new Map),r=useMemo(()=>a?.multipleChoices||[],[a?.multipleChoices]),i=useCallback((u,c)=>{let s=c.target,l=s.scaleX(),p=s.scaleY(),f=s.rotation(),d=Math.max(5,s.width()*l),m=Math.max(5,s.height()*p);s.scaleX(1),s.scaleY(1),s.width(d),s.height(m),o(Ht({id:u,width:d,height:m,x:s.x(),y:s.y(),rotation:f})),s.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:i,mcqRefs:t,handleDragEnd:(u,c)=>{o(Ht({id:c,x:u.target.x(),y:u.target.y()})),e?.();}}};var xi=e=>{let o=useDispatch(),a=useSelector(ce),t=useRef(new Map),r=useMemo(()=>a?.trueFalses||[],[a?.trueFalses]),i=useCallback((u,c)=>{let s=c.target,l=s.scaleX(),p=s.scaleY(),f=s.rotation(),d=Math.max(5,s.width()*l),m=Math.max(5,s.height()*p);s.scaleX(1),s.scaleY(1),s.width(d),s.height(m),o(Ut({id:u,width:d,height:m,x:s.x(),y:s.y(),rotation:f})),s.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:i,handleTrueFalseDragEnd:(u,c)=>{o(Ut({id:c,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:t}};var bi=e=>{let o=pe(),t=$(ce)?.videos||[],r=useRef(new Map),i=useCallback(c=>{o(Ga(c));},[o]),n=useCallback((c,s)=>{let l=s.target;o(_o({id:c,x:l.x(),y:l.y()})),e?.();},[o,e]),u=useCallback((c,s)=>{let l=s.target,p=l.scaleX(),f=l.scaleY(),d=l.rotation(),m=Math.max(5,l.width()*p),x=Math.max(5,l.height()*f);l.scaleX(1),l.scaleY(1),l.width(m),l.height(x),o(_o({id:c,width:m,height:x,x:l.x(),y:l.y(),rotation:d})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:t,videoRefs:r,handleVideoClick:i,handleVideoDragEnd:n,handleVideoTransformEnd:u}};var yi=e=>{let o=pe(),t=$(ce)?.shapes||[],r=useRef(new Map),i=useRef(new Map),[n,u]=useState(false),c=useCallback((l,p)=>{let f=p.target;o(wa({id:l,x:f.x(),y:f.y()})),e?.();},[o,e]),s=useCallback((l,p)=>{let f=p.target,d=t.find(b=>b.id===l);if(!d)return;let m=f.scaleX(),x=f.scaleY(),g=d.type?.toLowerCase();g==="arrow"||g==="line"||(f.scaleX(1),f.scaleY(1));let h={id:l,x:f.x(),y:f.y(),width:Math.max(5,f.width()*m),height:Math.max(5,f.height()*x),rotation:f.rotation()};switch(g){case "circle":h.radius=f.width()*m/2;break;case "star":h.innerRadius=f.width()*m/4,h.outerRadius=f.width()*m/2;break;case "triangle":h.radius=f.width()*m/2;break;case "ellipse":h.radiusX=f.width()*m/2,h.radiusY=f.height()*x/2;break;case "polygon":h.radius=f.width()*m/2;break;case "ring":let b=m;h.innerRadius=d.innerRadius&&d.innerRadius*b,h.outerRadius=d.outerRadius&&d.outerRadius*b;break;case "wedge":h.radius=d.radius&&d.radius*m;break;case "arc":h.innerRadius=d.innerRadius&&d.innerRadius*m,h.outerRadius=d.outerRadius&&d.outerRadius*m;break;case "arrow":case "line":{h.scaleX=m,h.scaleY=x,delete h.width,delete h.height;break}}o(wa(h)),e?.();},[o,e,t]);return {shapes:t,shapeRefs:r,isDragging:n,loadedShapesRef:i,handleShapeDragEnd:c,handleShapeResizeEnd:s}};var wi=(e,o)=>{let a=yt(),r=$(ce)?.texts||[],i=useRef(new Map),[n,u]=useState(null),[c,s]=useState("");return {texts:r,textRefs:i,handleDragEnd:(g,y)=>{let h=g.target;a(oe()),a(st({id:y,x:h.x(),y:h.y()})),e();},handleTransformEnd:g=>{let y=i.current.get(g);if(!y)return;let h=y.scaleX(),b=y.scaleY(),L=r.find(I=>I.id===g);if(!L)return;let C=(h+b)/2;y.scaleX(1),y.scaleY(1),a(oe()),a(st({id:g,x:y.x(),y:y.y(),width:Math.max(5,(L.width||100)*h),height:Math.max(5,(L.height||50)*b),fontSize:Math.round(Math.max(8,L.fontSize*C)),rotation:y.rotation()})),e();},handleDoubleClick:g=>{let y=r.find(h=>h.id===g);y&&!y.locked&&(u(g),s(y.text));},startEditing:g=>{let y=r.find(h=>h.id===g);y&&!y.locked&&(u(g),s(y.text));},editingTextId:n,editingValue:c,handleEditingChange:g=>{s(g);},finishEditing:()=>{if(n){let g=i.current.get(n),y=r.find(b=>b.id===n);a(oe());let h={id:n,text:c};if(y&&(y.fontWeight!==void 0&&(h.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(h.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(h.textDecoration=y.textDecoration)),o?.current&&c.trim()){let b=o.current,L=b.offsetWidth,C=b.offsetHeight,I=1;if(g){let G=g.getStage();G&&(I=G.scaleX());}let k=14,w=(L-k)/I,q=(C-k)/I,U=c.split(`
3
- `).length,R=r.find(G=>G.id===n)?.fontSize||24,T=U*R*1.2+10;h.width=Math.max(200,w),h.height=Math.max(50,q,T);}else if(g&&c.trim()){let b=g.text(),L=g.width();g.text(c),g.width(void 0);let C=g.width(),I=g.height();g.text(b),g.width(L),h.width=Math.max(200,C+20),h.height=Math.max(50,I+20);}a(st(h)),u(null),s(""),a(Qa(null)),e();}}}};var Si=e=>{let o=useDispatch(),t=useSelector(ce)?.shortAnswers||[],r=useRef(new Map),i=useCallback((n,u)=>{let c=n.target;o(Xa({id:u,x:c.x(),y:c.y()})),e?.();},[o,e]);return {shortAnswers:t,saRefs:r,handleShortAnswerDragEnd:i}};var Ci=e=>{let o=useDispatch(),a=useSelector(ce),t=useMemo(()=>a?.LongAnswer||[],[a?.LongAnswer]),r=useCallback((i,n)=>{let u=i.target;o($a({id:n,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:t,handleLongAnswerDragEnd:r}};var Mi=e=>{let o=pe(),t=$(ce)?.flashcards||[],r=useRef(new Map),i=useRef(new Map),n=useCallback((p,f)=>{if(i.current.has(f))return i.current.get(f);let d=new window.Image;return d.src=p,i.current.set(f,d),d},[]),u=useCallback((p,f)=>{let d=p.target,m=d.id();t.find(g=>g.id===m)&&(o(Sa({id:m,x:d.x(),y:d.y()})),f?.());},[t,o]),c=useCallback((p,f)=>{let d=f.target,m=d.scaleX(),x=d.scaleY(),g=d.rotation(),y=Math.max(50,d.width()*m),h=Math.max(50,d.height()*x);d.scaleX(1),d.scaleY(1),d.width(y),d.height(h),o(Sa({id:p,width:y,height:h,x:d.x(),y:d.y(),rotation:g})),d.getLayer()?.batchDraw(),e?.();},[o,e]),s=useCallback(p=>{o(ds(p)),e?.();},[o,e]),l=useCallback(p=>{o(us(p)),e?.();},[o,e]);return {flashcards:t,getLoadedImage:n,flashcardRefs:r,handleDragEnd:u,handleFlashcardTransformEnd:c,handleNext:s,handlePrevious:l}};var Ti=e=>{let o=pe(),t=$(ce)?.photoFrames||[],r=useRef(new Map),[i,n]=useState(new Map),u=useCallback((d,m)=>{console.log("handleDragEnd"),o(la({id:m,x:d.target.x(),y:d.target.y()})),e?.();},[o,e]),c=useCallback((d,m)=>{let x=m.target,g=x.scaleX(),y=x.scaleY(),h=x.rotation(),b=t.find(I=>I.id===d);if(!b)return;let L=Math.max(100,b.width*g),C=Math.max(100,b.height*y);x.scaleX(1),x.scaleY(1),o(la({id:d,width:L,height:C,x:x.x(),y:x.y(),rotation:h})),x.getLayer()?.batchDraw(),e?.();},[o,e,t]),s=useCallback(async d=>{try{let m=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(x=>{let g=new Map(x);return g.set(d,m),g}),o(la({id:d,isCapturing:!0})),e?.(),m}catch(m){return console.error("Error accessing camera:",m),null}},[o,e]),l=useCallback(d=>{let m=i.get(d);m&&(m.getTracks().forEach(x=>x.stop()),n(x=>{let g=new Map(x);return g.delete(d),g}),o(la({id:d,isCapturing:false})),e?.());},[i,o,e]),p=useCallback((d,m)=>{let x=document.createElement("canvas");x.width=m.videoWidth,x.height=m.videoHeight;let g=x.getContext("2d");if(g){g.drawImage(m,0,0,x.width,x.height);let y=x.toDataURL("image/jpeg",.8);return o(la({id:d,capturedImageUrl:y,isCapturing:false})),l(d),e?.(),y}return null},[o,l,e]),f=useRef(i);return useEffect(()=>{f.current=i;},[i]),useEffect(()=>()=>{f.current.forEach(d=>{d.getTracks().forEach(m=>m.stop());});},[]),{photoFrames:t,photoFrameRefs:r,handleDragEnd:u,handlePhotoFrameTransformEnd:c,startCamera:s,stopCamera:l,capturePhoto:p,cameraStreams:i}};var Fi=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),a=useCallback((i,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),t=useCallback((i,n,u,c,s,l,p=[])=>{if(e.current){if(i&&!p.find(m=>m.id===i)?.isPlaying){let m=n.get(i)||u.get(i)||c.get(i)||s.get(i)||l.get(i);if(m){e.current.boundBoxFunc(a),e.current.nodes([m]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:t,deselectTransformer:r,boundBoxFunc:a}};var Yu=(e,o)=>{let a=useRef(void 0);return useEffect(()=>()=>{a.current&&clearTimeout(a.current);},[]),useCallback((...t)=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{e(...t);},o);},[o])},Bi=(e,o)=>{let a=yt(),t=useRef(e);useEffect(()=>{t.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:.2,mimeType:"image/jpeg",quality:.6});a(Yr({id:t.current,thumbnail:n}));}catch(n){console.error("Error generating thumbnail:",n);}},[o,a]),i=Yu(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:i}};var Qu=e=>e.flatMap(o=>[o[0],o[1]]),cr=(e,o)=>{let a=ci(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:t=>t,start:{taper:0,cap:true},end:{taper:0,cap:true}});return Qu(a)};var Oi=e=>{let o=pe(),a=useRef(false),t=useRef(false),r=useRef([]),[i,n]=useState(null),u=$(b=>b.toolbar.selectedTool),c=$(b=>b.toolbar.penColor),s=$(b=>b.toolbar.strokeWidth),l=$(b=>b.canvas.isSketchMode),p=$(b=>b.canvas.slides.find(C=>C.id===b.canvas.currentSlideId)?.images.find(C=>C.id===e)),f=p?.annotations||[],d=p?.isDrawingMode||false,m=p?.width||1,x=p?.height||1,g=useCallback(b=>{if(u!=="pen"&&u!=="eraser")return;a.current=true,t.current=false,r.current=[{x:b.x,y:b.y}];let L=b.x/m,C=b.y/x;n({tool:u,points:[L,C],color:c,strokeWidth:s/m,isSketch:l});},[u,c,s,l,m,x]),y=useCallback(b=>{if(!a.current||!i)return;t.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-L.x,2)+Math.pow(b.y-L.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(l)I=cr(r.current,{size:s*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,q)=>q%2===0?w/m:w/x);else {let k=b.x/m,w=b.y/x;I=[...i.points,k,w];}n(k=>k?{...k,points:I}:null);},[l,s,i,m,x]),h=useCallback(()=>{a.current&&(i&&i.points.length>0&&o(ps({imageId:e,line:i})),n(null),a.current=false,t.current=false,r.current=[]);},[o,e,i]);return {annotations:f,activeLine:i,isDrawingMode:d,startDrawing:g,draw:y,stopDrawing:h,tool:u}};var Hi=memo(({img:e,loadedImage:o,imageRefs:a,onDragEnd:t,onTransform:r,onSelect:i,onContextMenu:n})=>{let{annotations:u,activeLine:c,stopDrawing:f,tool:d}=Oi(e.id);useEffect(()=>{let h=a.current.get(e.id);h&&(h.width()!==e.width||h.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:h.width(),konvaHeight:h.height()}),h.width(e.width),h.height(e.height),h.getLayer()?.batchDraw());},[e.id,e.width,e.height,a]);let m=false;useEffect(()=>{return;},[f,m]);let x=h=>{{i(e.id);return}},g=h=>{return;},y=h=>{};return jsxs(Group,{listening:d!=="pen"&&d!=="eraser",children:[jsx(Image,{id:e.id,ref:h=>{if(h){a.current.set(e.id,h),h.width(e.width),h.height(e.height),h.getLayer()?.batchDraw();let b=h.getStage()?.container();if(b){let L=C=>{let I=h.getStage()?.getPointerPosition();if(I){let k={x:e.x,y:e.y,width:e.width,height:e.height};I.x>=k.x&&I.x<=k.x+k.width&&I.y>=k.y&&I.y<=k.y+k.height&&n(C,e.id,"image");}};b.addEventListener("contextmenu",L),h._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",L);};}}else {let b=a.current.get(e.id);b?._contextMenuCleanup&&b._contextMenuCleanup(),a.current.delete(e.id);}},rotation:e.rotation,draggable:d!=="pen"&&d!=="eraser",onDragEnd:t,onTransformEnd:h=>r(e.id,h),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...d!=="pen"&&d!=="eraser"?{onClick:x,onTap:x,onMouseDown:x,onTouchStart:x,onMouseMove:g,onTouchMove:g,onMouseUp:y,onTouchEnd:y}:{}}),u?.map((h,b)=>{let L=h.points.map((I,k)=>k%2===0?I*e.width+e.x:I*e.height+e.y),C=h.strokeWidth*e.width;return jsx(Line,{points:L,stroke:h.tool==="eraser"?"white":h.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:h.tool==="eraser"?"destination-out":"source-over",fill:h.isSketch?h.color:void 0,closed:h.isSketch,listening:false},b)}),c&&jsx(Line,{points:c.points.map((h,b)=>b%2===0?h*e.width+e.x:h*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});Hi.displayName="ImageWithDrawing";var zs=memo(({images:e,getLoadedImage:o,imageRefs:a,onDragEnd:t,onTransform:r,onSelect:i,onContextMenu:n})=>jsx(Fragment,{children:e.map(u=>{let c=o(u);return c?jsx(Hi,{img:u,loadedImage:c,imageRefs:a,onDragEnd:t,onTransform:r,onSelect:i,onContextMenu:n},u.id):null})}));zs.displayName="ImageLayer";var lc=({src:e,x:o,id:a,y:t,width:r,height:i,isSelected:n,rotation:u=0,onTransformEnd:c,onDragEnd:s})=>{let l=pe(),p=useRef(null),f=d=>{l(Ga(d));};return jsxs(Group,{draggable:true,x:o,y:t,width:r,height:i,rotation:u,onDragEnd:s,onTransformEnd:c,children:[jsx(Rect,{width:r,height:i,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${i}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:p,src:e,controls:true,autoPlay:true,onClick:()=>f(a),onSeeking:d=>d.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Ui=lc;var gc=({video:e,isSelected:o,onClick:a,onDragEnd:t,onTransformEnd:r,onContextMenu:i,nodeRef:n})=>{let[u,c]=useState(null),s=useSelector(x=>x.toolbar.selectedTool),l=s==="pen"||s==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let x=new window.Image;x.src=e.thumbnailDataUrl,x.onload=()=>{c(x);};}},[e.thumbnailDataUrl]),!u)return null;let p=e.width/2,f=e.height/2,d=Math.min(e.width,e.height)*.08,m=Math.max(40,Math.min(d,80));return jsxs(Group,{draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...l?{}:{onDragEnd:t,onTransformEnd:r},ref:x=>{if(n(x),x){let g=x.getStage()?.container();if(g){let y=h=>{let b=x.getStage()?.getPointerPosition();if(b){let L={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=L.x&&b.x<=L.x+L.width&&b.y>=L.y&&b.y<=L.y+L.height&&i(h);}};g.addEventListener("contextmenu",y),x._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",y);};}}},children:[jsx(Image,{image:u,width:e.width,height:e.height,listening:!l,...l?{}:{onClick:a,onTap:a},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:p,y:f,radius:m,fill:"white",listening:!l,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...l?{}:{onClick:a,onTap:a}}),jsx(Circle,{x:p,y:f,radius:m*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!l,...l?{}:{onClick:a,onTap:a}}),jsx(RegularPolygon,{x:p+m*.1,y:f,sides:3,radius:m*.35,fill:"white",rotation:90,listening:!l,...l?{}:{onClick:a,onTap:a}})]})},Ki=gc;var Xs=memo(({videos:e,selectedId:o,videoRefs:a,onVideoClick:t,onDragEnd:r,onTransformEnd:i,onContextMenu:n})=>jsx(Fragment,{children:e.map(u=>jsxs(ut.Fragment,{children:[jsx(Ki,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>t(u.id),onDragEnd:c=>r(u.id,c),onTransformEnd:c=>i(u.id,c),onContextMenu:c=>n(c,u.id,"video"),nodeRef:c=>{c?a.current.set(u.id,c):a.current.delete(u.id);}}),u.isPlaying&&(()=>{let c=u.x,s=u.y;if(u.isRecorded){let l=typeof window<"u"?window.innerWidth:u.width,p=typeof window<"u"?window.innerHeight:u.height;c=(l-u.width)/2,s=(p-u.height)/2;}return jsx(Ui,{id:u.id,src:u.objectUrl,x:c,y:s,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:l=>i(u.id,l),onDragEnd:l=>r(u.id,l)})})()]},u.id))}));Xs.displayName="VideoLayer";var $s=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:a,handleShapeResizeEnd:t,onSelect:r,handleShapeDragStart:i,onContextMenu:n})=>{let u=useSelector(s=>s.toolbar.selectedTool),c=u==="pen"||u==="eraser";return jsx(Fragment,{children:e.map((s,l)=>{let p=s.id||l,f={id:s.id,x:s.x,y:s.y,rotation:s.rotation,draggable:!s.locked&&!c,listening:!c,fill:s.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(s.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},radius:s.radius||s.width/2,width:s.width,height:s.width},p);case "star":return jsx(Star,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},numPoints:5,innerRadius:s.innerRadius||s.width/4,outerRadius:s.outerRadius||s.width/2},p);case "triangle":return jsx(RegularPolygon,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},sides:3,radius:s.radius||s.width/2},p);case "polygon":return jsx(RegularPolygon,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},sides:s.sides||6,radius:s.radius||s.width/2},p);case "ellipse":return jsx(Ellipse,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},radiusX:s.radiusX||s.width/2,radiusY:s.radiusY||s.height/2},p);case "ring":return jsx(Ring,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},innerRadius:s.innerRadius||s.width/4,outerRadius:s.outerRadius||s.width/2},p);case "wedge":return jsx(Wedge,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},radius:s.radius||s.width/2,angle:s.angle||60},p);case "arrow":return jsx(Arrow,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,scaleX:s.scaleX||1,scaleY:s.scaleY||1,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},points:s.points||[0,0,s.width,0],pointerLength:s.pointerLength||10,pointerWidth:s.pointerWidth||10,stroke:"#000000",strokeWidth:s.strokeWidth||3,fill:"transparent"},p);case "line":return jsx(Line,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,scaleX:s.scaleX||1,scaleY:s.scaleY||1,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},points:s.points||[0,0,s.width,0],stroke:"#000000",strokeWidth:s.strokeWidth||3,fill:"transparent"},p);case "arc":return jsx(Arc,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},innerRadius:s.innerRadius||s.width/4,outerRadius:s.outerRadius||s.width/2,angle:s.angle||90},p);case "rectangle":default:return jsx(Rect,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},width:s.width,height:s.height,cornerRadius:s.type==="rounded-rectangle"?10:0},p)}})})});$s.displayName="ShapeLayer";var ji=({texts:e,textRefs:o,onDragEnd:a,onTransformEnd:t,onSelect:r,onContextMenu:i,onDoubleClick:n,editingTextId:u})=>{let c=useSelector(l=>l.toolbar.selectedTool),s=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map(l=>{let p=l.id===u,f=l.fontWeight==="bold",d=f?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!p&&!s,listening:!s,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:f?l.fill:void 0,strokeWidth:d,align:l.align,wrap:"none",lineHeight:1.2,opacity:p?0:1,visible:!p,...s?{}:{onClick:()=>r(l.id),onTap:()=>r(l.id),onDblClick:()=>n(l.id),onDblTap:()=>n(l.id),onDragEnd:m=>a(m,l.id),onTransformEnd:()=>t(l.id),onContextMenu:m=>{m.evt.preventDefault();let x=m.evt;i(x,l.id,"text");}}},l.id)})})};var Uc=({flashcard:e,isSelected:o,onClick:a,onDragEnd:t,onTransformEnd:r,onContextMenu:i,onNext:n,onPrevious:u,nodeRef:c})=>{let[s,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let g=new window.Image;g.src=e.images[e.currentIndex],g.onload=()=>{l(g);};}},[e.images,e.currentIndex]),!s||e.images.length===0)return null;let p=8,f=2,d=Math.min(e.width,e.height)*.08,m=Math.max(16,Math.min(d,32)),x=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:t,onTransformEnd:r,ref:g=>{if(c(g),g){let y=g.getStage()?.container();if(y){let h=b=>{let L=g.getStage()?.getPointerPosition();if(L){let C={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=C.x&&L.x<=C.x+C.width&&L.y>=C.y&&L.y<=C.y+C.height&&i(b);}};y.addEventListener("contextmenu",h),g._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",h);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:p,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:a,onTap:a}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:p,stroke:"#E5E7EB",strokeWidth:f,listening:false}),jsx(Image,{x:f+4,y:f+4,image:s,width:e.width-(f+4)*2,height:e.height-(f+4)*2,cornerRadius:p-f,onClick:a,onTap:a}),jsx(Rect,{x:f,y:e.height-50,width:e.width-f*2,height:50,cornerRadius:[0,0,p-f,p-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:x+m,y:e.height/2,onClick:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:m,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-x-m,y:e.height/2,onClick:g=>{g.cancelBubble=true,n();},onTap:g=>{g.cancelBubble=true,n();},children:[jsx(Circle,{radius:m,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"})]})},_i=Uc;var Js=memo(({flashcards:e,flashcardRefs:o,selectedId:a,onDragEnd:t,onTransform:r,onSelect:i,onNext:n,onPrevious:u,onContextMenu:c})=>jsx(Fragment,{children:e.map(s=>jsx(_i,{flashcard:s,isSelected:a===s.id,onClick:()=>i(s.id),onDragEnd:t,onTransformEnd:l=>r(s.id,l),onContextMenu:l=>c(l,s.id,"flashcard"),onNext:()=>n(s.id),onPrevious:()=>u(s.id),nodeRef:l=>{l?o.current.set(s.id,l):o.current.delete(s.id);}},s.id))}));Js.displayName="FlashcardLayer";var Ji=e=>{let o=pe(),a=useRef(false),t=useRef(false),r=useRef([]),[i,n]=useState(null);$(b=>b.toolbar.selectedTool);let c=$(b=>b.toolbar.penColor),s=$(b=>b.toolbar.strokeWidth),l=$(b=>b.canvas.isSketchMode),p=$(b=>b.canvas.slides.find(C=>C.id===b.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),f=p?.annotations||[],d=p?.isDrawingMode||false,m=p?.width||1,x=p?.height||1,g=useCallback(b=>{if(!d)return;a.current=true,t.current=false,r.current=[{x:b.x,y:b.y}];let L=b.x/m,C=b.y/x;n({tool:"pen",points:[L,C],color:c,strokeWidth:s/m,isSketch:l});},[d,c,s,l,m,x]),y=useCallback(b=>{if(!a.current||!i)return;t.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-L.x,2)+Math.pow(b.y-L.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(l)I=cr(r.current,{size:s*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,q)=>q%2===0?w/m:w/x);else {let k=b.x/m,w=b.y/x;I=[...i.points,k,w];}n(k=>k?{...k,points:I}:null);},[l,s,i,m,x]),h=useCallback(()=>{a.current&&(i&&i.points.length>0&&o(gs({frameId:e,line:i})),n(null),a.current=false,t.current=false,r.current=[]);},[o,e,i]);return {annotations:f,activeLine:i,isDrawingMode:d,startDrawing:g,draw:y,stopDrawing:h}};var _c=({photoFrame:e,isSelected:o,onClick:a,onDragEnd:t,onTransformEnd:r,onContextMenu:i,onStartCamera:n,onCapture:u,cameraStream:c,nodeRef:s})=>{let[l,p]=useState(null),[f,d]=useState(null),m=useRef(null),x=useRef(null),g=useRef(null),y=useRef(null),h=useRef(0),b=33,L=useSelector(D=>D.toolbar.selectedTool),C=L==="pen"||L==="eraser",{annotations:I,activeLine:k,isDrawingMode:w,startDrawing:q,draw:U,stopDrawing:O}=Ji(e.id);useEffect(()=>{if(!w)return;let D=()=>{O();},V=()=>{O();};return window.addEventListener("mouseup",D),window.addEventListener("touchend",V),()=>{window.removeEventListener("mouseup",D),window.removeEventListener("touchend",V);}},[O,w]),useEffect(()=>{if(e.capturedImageUrl){let D=new window.Image;D.src=e.capturedImageUrl,D.onload=()=>{p(D);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&c){m.current||(m.current=document.createElement("video"),m.current.autoplay=true,m.current.playsInline=true),x.current||(x.current=document.createElement("canvas"));let D=m.current,V=x.current;D.srcObject=c;let j=()=>{V.width=D.videoWidth||640,V.height=D.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",V.width,V.height);let te=Z=>{if(Z-h.current<b){g.current=requestAnimationFrame(te);return}h.current=Z;let ae=V.getContext("2d");if(ae&&D.readyState===D.HAVE_ENOUGH_DATA){ae.drawImage(D,0,0,V.width,V.height);let Ce=V.toDataURL("image/jpeg",.6),_=new window.Image;_.onload=()=>{d(_);},_.src=Ce;}g.current=requestAnimationFrame(te);};g.current=requestAnimationFrame(te);};return D.onloadedmetadata=j,D.readyState>=D.HAVE_METADATA&&j(),D.play().catch(te=>console.error("Error playing video:",te)),()=>{g.current&&(cancelAnimationFrame(g.current),g.current=null);}}return ()=>{d(null),y.current&&(y.current.src="");}},[e.isCapturing,c]);let R=()=>{m.current&&e.isCapturing&&u(m.current);},E=D=>{if(e.capturedImageUrl){if(!w){a();return}let V=D.currentTarget,j=V.getAbsoluteTransform().copy(),Z=V.getStage()?.getPointerPosition();if(Z){j.invert();let ae=j.point(Z);q(ae);}D.cancelBubble=true;}else a();},T=D=>{if(!w||!e.capturedImageUrl)return;let V=D.currentTarget,j=V.getAbsoluteTransform().copy(),Z=V.getStage()?.getPointerPosition();if(Z){j.invert();let ae=j.point(Z);U(ae);}},G=()=>{!w||!e.capturedImageUrl||O();},z=e.isCapturing?f:l,me=Math.min(e.width,e.height)*.12,J=Math.max(25,Math.min(me,50)),de=e.width/2,N=e.height/2;return jsxs(Group,{id:e.id,draggable:!w&&!C,listening:true,x:e.x,y:e.y,...C?{}:{onDragEnd:t,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:D=>{if(s(D),D){let V=D.getStage()?.container();if(V){let j=te=>{let Z=D.getStage()?.getPointerPosition();if(Z){let ae={x:e.x,y:e.y,width:e.width,height:e.height};Z.x>=ae.x&&Z.x<=ae.x+ae.width&&Z.y>=ae.y&&Z.y<=ae.y+ae.height&&i(te);}};V.addEventListener("contextmenu",j),D._contextMenuCleanup=()=>{V.removeEventListener("contextmenu",j);};}}},children:[jsx(Rect,{x:0,y:0,width:e.width,height:e.height,fill:z?"transparent":"#f0f0f0",stroke:o?"transparent":"#4A90E2",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:a,onTap:a}),z&&jsx(Image,{image:z,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:E,onTap:E,onMouseDown:E,onTouchStart:E,onMouseMove:T,onTouchMove:T,onMouseUp:G,onTouchEnd:G,...C?{}:{onDragEnd:t,onTransformEnd:r}}),I?.map((D,V)=>{let j=D.points.map((Z,ae)=>ae%2===0?Z*e.width:Z*e.height),te=D.strokeWidth*e.width;return jsx(Line,{points:j,stroke:D.tool==="eraser"?"white":D.color,strokeWidth:te,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:D.tool==="eraser"?"destination-out":"source-over",fill:D.isSketch?D.color:void 0,closed:D.isSketch,listening:false},V)}),k&&jsx(Line,{points:k.points.map((D,V)=>V%2===0?D*e.width:D*e.height),stroke:k.tool==="eraser"?"white":k.color,strokeWidth:k.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:k.tool==="eraser"?"destination-out":"source-over",fill:k.isSketch?k.color:void 0,closed:k.isSketch,listening:false},"active"),!z&&!e.isCapturing&&jsx(Text,{x:0,y:N-20,width:e.width,height:40,text:"Click to start camera",fontSize:16,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Circle,{x:de,y:e.height*.75,radius:J,fill:e.isCapturing?"#E74C3C":"#4A90E2",shadowColor:"black",shadowBlur:5,shadowOpacity:.3,listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?R():n();},onTap:D=>{D.cancelBubble=true,e.isCapturing?R():n();}}),jsx(Text,{x:de-J,y:e.height*.75-8,width:J*2,height:16,text:e.isCapturing?"\u{1F4F8}":"\u{1F4F7}",fontSize:20,fontFamily:"Arial",fill:"white",align:"center",verticalAlign:"middle",listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?R():n();},onTap:D=>{D.cancelBubble=true,e.isCapturing?R():n();}})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"})]})]})},al=_c;var on=memo(({photoFrames:e,photoFrameRefs:o,selectedId:a,onDragEnd:t,onTransform:r,onSelect:i,onStartCamera:n,onCapture:u,cameraStreams:c,onContextMenu:s})=>jsx(Fragment,{children:e.map(l=>jsx(al,{photoFrame:l,isSelected:a===l.id,onClick:()=>i(l.id),onDragEnd:p=>t(p,l.id),onTransformEnd:p=>r(l.id,p),onContextMenu:p=>s(p,l.id,"photoFrame"),onStartCamera:()=>n(l.id),onCapture:p=>u(l.id,p),cameraStream:c.get(l.id),nodeRef:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);}},l.id))}));on.displayName="PhotoFrameLayer";var il=({x:e,y:o,onAction:a,onClose:t,type:r,isDrawingMode:i})=>{let n=useRef(null);useEffect(()=>{let s=p=>{n.current&&!n.current.contains(p.target)&&t();},l=p=>{p.key==="Escape"&&t();};return document.addEventListener("mousedown",s),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",l);}},[t]);let u=[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5"})},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5"})},...r==="mcq"||r==="trueFalse"||r==="shortAnswer"||r==="longAnswer"||r==="fillInTheBlanks"?[{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5"})}]:[],...r==="shape"?[{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5"})}]:[],...r==="image"?[{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5"})},{action:"draw",label:i?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5"})}]:[],...r==="photoFrame"?[{action:"draw",label:i?"Exit Drawing Mode":"Draw on Frame",icon:jsx(PencilSimple,{className:"h-5 w-5"})}]:[],...r==="flashcard"?[{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5"})}]:[],{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5"})},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5"}),isDanger:true}],c=(s,l)=>{s==="order"||s==="lock"?a(s,l):(a(s),t());};return jsx("div",{ref:n,className:"fixed z-100 min-w-[200px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:u.map((s,l)=>jsxs("button",{onClick:p=>c(s.action,p),className:`flex w-full items-center justify-between px-4 py-2.5 text-left text-sm transition-colors hover:bg-gray-50 ${s.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"} ${l!==0?"border-t border-gray-100":""}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[s.icon,jsx("span",{className:"font-medium",children:s.label})]}),s.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"})})]},s.action))})})};var ll=({x:e,y:o,items:a,onClose:t})=>{let r=useRef(null);return useEffect(()=>{let i=n=>{r.current&&!r.current.contains(n.target)&&t();};return document.addEventListener("mousedown",i),()=>{document.removeEventListener("mousedown",i);}},[t]),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:a.map((i,n)=>jsx("button",{onClick:()=>{i.onClick(),t();},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:i.label})},n))})})};var dl=({title:e,label:o,placeholder:a,defaultValue:t="",onSave:r,onClose:i})=>{let[n,u]=useState(t),c=useRef(null);useEffect(()=>{c.current?.focus();},[]);let s=()=>{r(n),i();};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:i,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:c,type:"text",value:n,onChange:p=>u(p.target.value),onKeyDown:p=>{p.key==="Enter"?s():p.key==="Escape"&&i();},placeholder:a,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:i,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:s,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 ul=({defaultColor:e="#096B76",onConfirm:o,onCancel:a})=>{let[t,r]=useState(e),i=useRef(null);useEffect(()=>{let l=p=>{p.key==="Escape"&&a();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[a]);let n=l=>{l.preventDefault(),o(t);},u=(l,p,f)=>{f/=100;let d=p*Math.min(f,1-f)/100,m=x=>{let g=(x+l/30)%12,y=f-d*Math.max(Math.min(g-3,9-g,1),-1);return Math.round(255*y).toString(16).padStart(2,"0")};return `#${m(0)}${m(8)}${m(4)}`},s=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{ref:i,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:l=>l.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:a,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:n,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:t}}),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:t,onChange:l=>r(l.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:t,onChange:l=>r(l.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:l=>{let p=parseInt(l.target.value),f=u(p,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(l=>jsx("button",{type:"button",onClick:()=>r(l),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${t.toUpperCase()===l.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:l},title:l},l))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:a,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(s,document.body)};var Ff=({imageSrc:e,onCrop:o})=>{let[a]=ml(e),t=useRef(null),r=useRef(null),i=useRef(null),n=useMemo(()=>{if(!a)return {width:600,height:400};let m=Math.min(600/a.width,400/a.height);return {width:a.width*m,height:a.height*m}},[a]),u=useMemo(()=>{let f=n.width*.5,d=n.height*.5,m=(n.width-f)/2,x=(n.height-d)/2;return {x:m,y:x,width:f,height:d}},[n]),[c,s]=useState(u);useEffect(()=>{s(u);},[u]),useEffect(()=>{i.current&&r.current&&(i.current.nodes([r.current]),i.current.getLayer()?.batchDraw());},[c]),useEffect(()=>{o(c.x,c.y,c.width,c.height);},[c,o]);let l=()=>{let f=r.current;if(!f)return;let d=f.scaleX(),m=f.scaleY();f.scaleX(1),f.scaleY(1),s({x:f.x(),y:f.y(),width:Math.max(20,f.width()*d),height:Math.max(20,f.height()*m)});},p=()=>{let f=r.current;f&&s({x:f.x(),y:f.y(),width:f.width(),height:f.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image,{ref:t,image:a,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:c.x,y:c.y,width:c.width,height:c.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:c.x,y:c.y,width:c.width,height:c.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:p,onTransformEnd:l,dragBoundFunc:f=>{let d=Math.max(0,Math.min(f.x,n.width-c.width)),m=Math.max(0,Math.min(f.y,n.height-c.height));return {x:d,y:m}}}),jsx(Transformer,{ref:i,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,d)=>d.width<20||d.height<20||d.x<0||d.y<0||d.x+d.width>n.width||d.y+d.height>n.height?f:d})]})})},pl=({imageSrc:e,onConfirm:o,onCancel:a})=>{let t=useRef(null),[r,i]=useState({x:0,y:0,width:0,height:0}),[n]=ml(e);return useEffect(()=>{let l=p=>{p.key==="Escape"&&a();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[a]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{ref:t,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:l=>l.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:a,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(Ff,{imageSrc:e,onCrop:(l,p,f,d)=>{i({x:l,y:p,width:f,height:d});}})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:a,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:()=>{if(!n)return;let f=Math.min(600/n.width,400/n.height),d=r.x/f,m=r.y/f,x=r.width/f,g=r.height/f,y=document.createElement("canvas");y.width=x,y.height=g;let h=y.getContext("2d");if(!h)return;h.drawImage(n,d,m,x,g,0,0,x,g);let b=y.toDataURL("image/png");o(b);},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),document.body)};var no=({onClose:e,stageRef:o,onRecordingComplete:a,directDrawingCanvasRef:t})=>{let[r,i]=useState(false),[n,u]=useState(null),[c,s]=useState(0),[l,p]=useState(true),f=useRef(null),d=useRef([]),m=useRef(null),x=useRef(null),g=useRef(null),y=useRef(null),h=useRef(null),b=useRef(null);useEffect(()=>()=>{g.current&&cancelAnimationFrame(g.current),m.current&&clearInterval(m.current),x.current&&x.current.getTracks().forEach(w=>w.stop());},[]);let L=async()=>{try{let w,q=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((V,j)=>{let te=V.getChildren();console.log(`Layer ${j} children count:`,te.length);});let G=document.createElement("canvas");G.width=o.current.width(),G.height=o.current.height();let z=G.getContext("2d",{willReadFrequently:!1});if(!z){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",G.width,"x",G.height),h.current=G;let me=()=>{if(z.clearRect(0,0,G.width,G.height),T.forEach(V=>{let j=V.getCanvas()._canvas;j&&z.drawImage(j,0,0);}),t?.current){let V=t.current;z.drawImage(V,0,0);}};b.current=me,o.current.draw(),me(),await new Promise(V=>setTimeout(V,100)),console.log("Creating captureStream..."),w=G.captureStream(30),console.log("Canvas stream created, tracks:",w.getTracks().length);let de=w.getVideoTracks()[0];de&&console.log("Video track:",de.label,"state:",de.readyState);let N=0,D=()=>{me(),o?.current&&(o.current.getLayers().forEach(j=>{j.batchDraw();}),N++,N%60===0&&console.log("Drawing frame:",N)),g.current=requestAnimationFrame(D);};D();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(l)try{q=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(T){console.warn("Microphone access denied:",T);}let U=[...w.getVideoTracks()];q&&U.push(...q.getAudioTracks());let O=new MediaStream(U);x.current=O;let R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8"),console.log("Using mimeType:",R);let E=new MediaRecorder(O,{mimeType:R,videoBitsPerSecond:25e5});f.current=E,d.current=[],E.ondataavailable=T=>{console.log("Data available, size:",T.data.size),T.data.size>0&&d.current.push(T.data);},E.onstop=()=>{console.log("Recording stopped, chunks:",d.current.length);let T=new Blob(d.current,{type:R});console.log("Final blob size:",T.size),o?.current&&b.current&&h.current&&(o.current.draw(),o.current.getLayers().forEach(z=>{z.batchDraw();}),b.current(),y.current=h.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",y.current.length)),O.getTracks().forEach(G=>G.stop()),m.current&&clearInterval(m.current),g.current&&(cancelAnimationFrame(g.current),g.current=null),u(T);},E.onerror=T=>{console.error("MediaRecorder error:",T);},console.log("Starting recording..."),E.start(1e3),i(!0),s(0),m.current=setInterval(()=>{s(T=>T+1);},1e3);}catch(w){console.error("Error starting screen recording:",w),alert("Failed to start recording. Please ensure you granted permission.");}},C=()=>{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)),i(false));},I=()=>{if(n){let w=URL.createObjectURL(n),q=document.createElement("a");q.href=w,q.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(q),q.click(),document.body.removeChild(q),URL.revokeObjectURL(w);}},k=w=>{let q=Math.floor(w/60),U=w%60;return `${q.toString().padStart(2,"0")}:${U.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:k(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:C,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-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[!n&&jsxs("div",{className:"text-center",children:[jsx("p",{className:"mb-4 text-sm text-gray-600",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsx("div",{className:"mb-4 flex items-center justify-center gap-2",children:jsx("button",{onClick:()=>p(!l),className:`flex items-center gap-2 rounded-lg border px-4 py-2 text-sm transition-colors ${l?"border-blue-500 bg-blue-50 text-blue-700":"border-gray-300 bg-white text-gray-700 hover:bg-gray-50"}`,children:l?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5"}),"Microphone Off"]})})}),jsxs("button",{onClick:L,className:"flex items-center gap-2 rounded-lg bg-red-600 px-6 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]}),n&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(n),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",k(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{a&&n&&y.current&&(a(n,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:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{u(null),s(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 bg-blue-50 p-3",children:jsxs("p",{className:"text-xs 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 gl=({elementType:e,existingAudio:o,onSave:a,onDelete:t,onClose:r})=>{let[i,n]=useState(false),[u,c]=useState(null),[s,l]=useState(false),[p,f]=useState(0),d=useRef(null),m=useRef([]),x=useRef(null),g=useRef(null);useEffect(()=>{o&&!u&&fetch(o).then(w=>w.blob()).then(w=>c(w)).catch(w=>console.error("Error loading audio:",w));},[o,u]);let y=async()=>{try{let w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),q=new MediaRecorder(w);d.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:"audio/webm"});c(U),w.getTracks().forEach(O=>O.stop()),x.current&&clearInterval(x.current);},q.start(),n(!0),f(0),x.current=setInterval(()=>{f(U=>U+1);},1e3);}catch(w){console.error("Error starting audio recording:",w),alert("Failed to start recording. Please allow microphone access.");}},h=()=>{d.current&&i&&(d.current.stop(),n(false));},b=()=>{if(u){let w=URL.createObjectURL(u),q=new Audio(w);g.current=q,q.onended=()=>{l(false),URL.revokeObjectURL(w);},q.play(),l(true);}},L=()=>{g.current&&(g.current.pause(),g.current.currentTime=0,l(false));},C=async()=>{if(u){let w=new FileReader;w.onloadend=()=>{let q=w.result;a(q),r();},w.readAsDataURL(u);}},I=()=>{c(null),t();},k=w=>{let q=Math.floor(w/60),U=w%60;return `${q.toString().padStart(2,"0")}:${U.toString().padStart(2,"0")}`};return i?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:k(p)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:h,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-4",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:"mb-6",children:[!u&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:y,className:"flex w-full items-center justify-center gap-2 rounded-lg bg-red-600 px-6 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),u&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:s?L:b,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),s?"Playing...":"Play Audio"]}),jsx("button",{onClick:I,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:C,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]})]}),jsx("div",{className:"flex justify-end",children:jsx("button",{onClick:r,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"})})]})})};var it=({audioData:e,x:o,y:a,width:t})=>{let[r,i]=useState(false),n=useRef(null);return jsx("button",{onClick:c=>{if(c.stopPropagation(),r&&n.current)n.current.pause(),n.current.currentTime=0,i(false);else {let s=new Audio(e);n.current=s,s.onended=()=>{i(false);},s.onerror=()=>{console.error("Error playing audio"),i(false);},s.play(),i(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+t-35}px`,top:`${a+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 vl=({selectedElementId:e,onClose:o,onSelectElement:a})=>{let t=pe(),r=$(ce),i=useMemo(()=>{if(!r)return [];let x=[];return r.images?.forEach(g=>{x.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),r.videos?.forEach(g=>{x.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),r.shapes?.forEach(g=>{x.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),r.texts?.forEach(g=>{x.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),r.flashcards?.forEach(g=>{x.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),r.photoFrames?.forEach(g=>{x.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),r.multipleChoices?.forEach(g=>{x.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),r.trueFalses?.forEach(g=>{x.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),r.shortAnswers?.forEach(g=>{x.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),r.LongAnswer?.forEach(g=>{x.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),r.fillInTheBlanks?.forEach(g=>{x.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),r.lines?.forEach(g=>{g.id&&x.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),x.sort((g,y)=>y.timestamp-g.timestamp)},[r]),[n,u]=useState(i),[c,s]=useState(false);useEffect(()=>{c||u(i);},[i]);let l=x=>{let g="h-5 w-5";switch(x){case "image":return jsx(Image$2,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes,{className:g});case "text":return jsx(TextT$1,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx("span",{className:g,children:"\u270F\uFE0F"});default:return jsx(Question,{className:g})}},p=x=>{if(x===0)return;let g=n[x],y=n[x-1];t(Ja({id:g.id,type:g.type,newTimestamp:y.timestamp+1}));},f=x=>{if(x===n.length-1)return;let g=n[x],y=n[x+1];t(Ja({id:g.id,type:g.type,newTimestamp:y.timestamp-1}));},d=x=>{s(true),u(x);},m=()=>{s(false);let x=Date.now();n.forEach((g,y)=>{let h=x-y;t(Ja({id:g.id,type:g.type,newTimestamp:h}));});};return jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-gray-200 bg-white shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 p-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Stack$1,{className:"h-5 w-5 text-gray-700",weight:"bold"}),jsx("h3",{className:"font-semibold text-gray-900",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto p-2",children:n.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:n,onReorder:d,className:"space-y-1",children:n.map((x,g)=>{let y=x.id===e;return jsxs(Reorder.Item,{value:x,onDragEnd:m,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:()=>a(x.id,x.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${y?"text-blue-600":"text-gray-600"}`,children:l(x.type)}),jsx("span",{className:`text-sm ${y?"font-medium text-blue-900":"text-gray-700"}`,children:x.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:h=>{h.stopPropagation(),p(g);},disabled:g===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:h=>{h.stopPropagation(),f(g);},disabled:g===n.length-1,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move down (backward)",children:jsx(ArrowDown,{className:"h-4 w-4"})})]})]},x.id)})})}),jsx("div",{className:"border-t border-gray-200 p-3 text-xs text-gray-500",children:jsx("p",{children:"Drag to reorder \u2022 Top layers appear above bottom layers"})})]})]})};var Ll=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:a,mcqRefs:t,handleDragEnd:r,onContextMenu:i})=>{let n=useSelector(N=>N.toolbar.selectedTool),u=n==="pen"||n==="eraser",[c,s]=useState(new Set),[l,p]=useState(false),[f,d]=useState(null),m=useRef(null);useEffect(()=>{let N=m.current;if(N)return t.current.set(e.id,N),()=>{t.current.delete(e.id);}},[e.id]);let x=new Set(e.data.responseOptions.correctIndex),g=x.size>1,y=N=>{l||s(g?D=>{let V=new Set(D);return V.has(N)?V.delete(N):V.add(N),V}:new Set([N]));},h=()=>{c.size>0&&p(true);},b=()=>{p(false),s(new Set);},L=c.size===x.size&&Array.from(c).every(N=>x.has(N)),C=Array.from(c).filter(N=>x.has(N)),I=g&&C.length>0&&!L,k=()=>L?"\u2713 Correct! Great job! \u{1F389}":I?`\u26A0 Partially correct (${C.length}/${x.size})`:"\u2717 Try again!",w=()=>L?{bg:"#dcfce7",text:"#166534"}:I?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},q=55,U=8,O=24,R=60,E=60,T=g&&!l?25:0,G=e.data.feedbackMode==="practice"?48:0,z=12,me=R+T+(l?E:0),J=e.data.responseOptions.options.length*(q+U),de=me+J+z+G+O;return jsxs(Group,{ref:m,name:"mcq-element",draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...u?{}:{onDragEnd:r,onClick:N=>a(e.id),onTap:N=>a(e.id),onContextMenu:N=>{let D=m.current?.getStage()?.getPointerPosition();if(D){let V={x:e.x,y:e.y,width:e.width,height:e.height};if(D.x>=V.x&&D.x<=V.x+V.width&&D.y>=V.y&&D.y<=V.y+V.height){let j=N.evt;i(j,e.id,"mcq");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:de,width:e.width,onTransformEnd:N=>o(e.id,N)}),jsx(Text,{x:O,y:O,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-O*2,listening:false}),g&&!l&&e.data.feedbackMode==="practice"?jsx(Text,{x:O,y:O+35,text:`Select ${x.size} answers (${c.size}/${x.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-O*2,listening:false}):null,l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:O,y:R+T,width:e.width-O*2,height:E,fill:w().bg,cornerRadius:8}),jsx(Text,{x:O,y:R+T,width:e.width-O*2,height:E,text:k(),fontSize:16,fontStyle:"bold",fill:w().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((N,D)=>{let V=x.has(D),j=c.has(D),te=me+D*(q+U),Z="#e5e7eb",ae="#ffffff";return l&&V?(Z="#22c55e",ae="#dcfce7"):l&&j&&!V?(Z="#ef4444",ae="#fee2e2"):j&&(Z="#096B76",ae="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:te,width:e.width-O*2,height:q,fill:ae,stroke:Z,strokeWidth:2,cornerRadius:8,onClick:Ce=>{Ce.cancelBubble=true,y(D);},onTap:Ce=>{Ce.cancelBubble=true,y(D);}}),jsx(Rect,{x:O+12,y:te+(q-20)/2,width:20,height:20,fill:j?"#096B76":"white",stroke:j?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:g?4:10,listening:false}),j&&jsx(Text,{x:O+12,y:te+(q-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O+44,y:te,width:e.width-O*2-80,height:q,text:N,fontSize:16,fill:"#111827",verticalAlign:"middle",listening:false}),l&&V&&jsx(Text,{x:e.width-O-30,y:te+(q-24)/2,width:24,height:24,text:"\u2713",fontSize:20,fill:"#22c55e",align:"center",verticalAlign:"middle",listening:false}),l&&j&&!V&&jsx(Text,{x:e.width-O-30,y:te+(q-24)/2,width:24,height:24,text:"\u2717",fontSize:20,fill:"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},D)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:me+e.data.responseOptions.options.length*(q+U)+12,children:[jsxs(Group,{onMouseDown:N=>{N.cancelBubble=true,d("check");},onMouseUp:N=>{N.cancelBubble=true,d(null),h();},onMouseLeave:N=>{N.cancelBubble=true,d(null);},onTouchStart:N=>{N.cancelBubble=true,d("check");},onTouchEnd:N=>{N.cancelBubble=true,d(null),h();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:O,width:(e.width-O*2-8)/(l?2:1),height:48,fill:c.size===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:O,width:(e.width-O*2-8)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-O*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),b();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),b();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:O,width:(e.width-O*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:O,width:(e.width-O*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ll.displayName="MultipleChoice";var yl=Ll;var xm="#FFFFFF",ln=({multipleChoice:e,onContextMenu:o,handleMcqTransform:a})=>{let t=useDispatch(),r=useSelector(D=>D.toolbar.selectedTool),i=r==="pen"||r==="eraser",[n,u]=useState(false),[c,s]=useState(new Set),[l,p]=useState(false),[f,d]=useState(false),[m,x]=useState(0),g=340,y=100,h=window.innerWidth*.5,b=window.innerHeight*.5,L=g+20,C=y+60,I=h-40,k=b-160,w=useRef(null),q=D=>{t(Ht({id:e.id,x:D.target.x(),y:D.target.y()}));},U=D=>{let V=D.target,j=V.x(),te=V.y(),Z=window.innerWidth*.2,Ce=j+Z>L&&j<L+I&&te+50>C&&te<C+k;u(Ce);},O=(D,V)=>{let j=V.target,te=j.x(),Z=j.y(),ae=window.innerWidth*.2,_=te+ae>L&&te<L+I&&Z+50>C&&Z<C+k;s(_?Pe=>new Set(Pe).add(D):Pe=>{let vt=new Set(Pe);return vt.delete(D),vt}),u(false);},R=()=>{p(true);},E=()=>{p(false),s(new Set),x(D=>D+1);},T=new Set(e.data.responseOptions.correctIndex),G=c.size===T.size&&Array.from(c).every(D=>T.has(D)),z=Array.from(c).filter(D=>T.has(D));Array.from(c).filter(D=>!T.has(D));let J=z.length>0&&!G,de=()=>G?"\u2713 Correct! Great job!":J?`\u26A0 Partially correct (${z.length}/${T.size})`:"\u2717 Try again!",N=()=>G?{bg:"#dcfce7",text:"#166534"}:J?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"};return jsxs(Group,{ref:w,name:"mcq-element",width:h,height:b,draggable:!i,listening:!i,...i?{}:{onContextMenu:D=>{D.evt.preventDefault(),o(D.evt,e.id,"mcq");}},children:[jsxs(Group,{x:g,y,rotation:e.rotation,onDragEnd:q,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?b-10:b-50,width:h,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:h-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:I,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:I,height:60,fill:N().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:I,height:60,text:de(),fontSize:18,fontStyle:"bold",fill:N().text,align:"center",verticalAlign:"middle"})]}),c.size===0&&!l&&jsx(Text,{x:20,y:60,width:I,height:k-60,text:T.size>1?`Drop ${T.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),c.size>0&&!l&&jsx(Text,{x:20,y:b-120,width:I,text:`${c.size} of ${T.size} answers selected`,fontSize:16,fill:"#6b7280",align:"center"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:b-90,children:[jsxs(Group,{onMouseDown:()=>{d(true),R();},onMouseUp:()=>d(false),onMouseLeave:()=>d(false),onTouchStart:()=>{d(true),R();},onTouchEnd:()=>d(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((D,V)=>{let j=V%2,te=Math.floor(V/2),Z=window.innerWidth*.2,ae=50,Ce=10,_=c.has(V),Pe=T.has(V),vt=l&&_,B="transparent";return vt?B=Pe?"#4CAF50":"#ef4444":_&&(B="#4CAF50"),jsxs(Group,{x:420+j*(Z+Ce),y:y+b+20+te*(ae+Ce),draggable:!l,onDragMove:U,onDragEnd:se=>O(V,se),opacity:l&&!_?.5:1,children:[jsx(Rect,{width:Z,height:ae,fill:"#075560",stroke:B,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z,height:ae,text:D,fontSize:18,fontStyle:"bold",fill:xm,align:"center",verticalAlign:"middle",listening:false}),vt&&jsx(Text,{x:Z-30,y:5,width:25,height:25,text:Pe?"\u2713":"\u2717",fontSize:20,fontStyle:"bold",fill:Pe?"#4CAF50":"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},`${V}-${m}`)})]})};ln.displayName="MultipleChoiceDragAndDrop";var Il=({multipleChoice:e,handleMcqTransform:o,handleSelect:a,mcqRefs:t,handleDragEnd:r,onContextMenu:i})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(yl,{multipleChoice:n,handleMcqTransform:o,handleSelect:a,mcqRefs:t,handleDragEnd:u=>r(u,n.id),onContextMenu:i},n.id):jsx(ln,{multipleChoice:n,handleMcqTransform:o,handleSelect:a,mcqRefs:t,onContextMenu:i},n.id))});var wl=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,onContextMenu:r,handleDragEnd:i})=>{let n=useSelector(z=>z.toolbar.selectedTool),u=n==="pen"||n==="eraser",[c,s]=useState(null),[l,p]=useState(false),[f,d]=useState(null),m=useRef(null);useEffect(()=>{let z=m.current;if(z)return t.current.set(e.id,z),()=>{t.current.delete(e.id);}},[e.id]);let x=()=>{c!==null&&p(true);},g=()=>{p(false),s(null);},y=e.data.responseOptions.correctAnswer,h=c===y,b=z=>{l||s(z);},L=()=>h?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=70,k=12,w=24,q=60,U=60,O=e.data.feedbackMode==="practice"?48:0,R=12,E=q+(l?U:0),T=2*(I+k),G=E+T+R+O+w;return jsxs(Group,{ref:m,name:"trueFalse-element",draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...u?{}:{onDragEnd:z=>i(z,e.id),onClick:z=>a(e.id),onTap:z=>a(e.id),onContextMenu:z=>{let me=m.current?.getStage()?.getPointerPosition();if(me){let J={x:e.x,y:e.y,width:e.width,height:e.height};if(me.x>=J.x&&me.x<=J.x+J.width&&me.y>=J.y&&me.y<=J.y+J.height){let de=z.evt;r(de,e.id,"trueFalse");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:G,width:e.width,onTransformEnd:z=>o(e.id,z)}),jsx(Text,{x:w,y:w,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-w*2,listening:false}),l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:w,y:q,width:e.width-w*2,height:U,fill:C().bg,cornerRadius:8}),jsx(Text,{x:w,y:q,width:e.width-w*2,height:U,text:L(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,[{label:"True",value:true},{label:"False",value:false}].map((z,me)=>{let J=y===z.value,de=c===z.value,N=E+me*(I+k),D="#e5e7eb",V="#ffffff";return l&&J?(D="#22c55e",V="#dcfce7"):l&&de&&!J?(D="#ef4444",V="#fee2e2"):de&&(D="#096B76",V="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:w,y:N,width:e.width-w*2,height:I,fill:V,stroke:D,strokeWidth:2,cornerRadius:8,onClick:j=>{j.cancelBubble=true,b(z.value);},onTap:j=>{j.cancelBubble=true,b(z.value);}}),jsx(Rect,{x:w+12,y:N+(I-24)/2,width:24,height:24,fill:de?"#096B76":"white",stroke:de?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:12,listening:false}),de&&jsx(Rect,{x:w+12+6,y:N+(I-24)/2+6,width:12,height:12,fill:"white",cornerRadius:6,listening:false}),jsx(Text,{x:w+48,y:N,width:e.width-w*2-80,height:I,text:z.label,fontSize:18,fontStyle:"bold",fill:"#111827",verticalAlign:"middle",listening:false}),l&&J&&jsx(Text,{x:e.width-w-30,y:N+(I-24)/2,width:24,height:24,text:"\u2713",fontSize:20,fill:"#22c55e",align:"center",verticalAlign:"middle",listening:false}),l&&de&&!J&&jsx(Text,{x:e.width-w-30,y:N+(I-24)/2,width:24,height:24,text:"\u2717",fontSize:20,fill:"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},z.label)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:E+2*(I+k)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,d("check");},onMouseUp:z=>{z.cancelBubble=true,d(null),x();},onMouseLeave:z=>{z.cancelBubble=true,d(null);},onTouchStart:z=>{z.cancelBubble=true,d("check");},onTouchEnd:z=>{z.cancelBubble=true,d(null),x();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:w,width:(e.width-w*2-8)/(l?2:1),height:48,fill:c===null||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:w,width:(e.width-w*2-8)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-w*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),g();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),g();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:w,width:(e.width-w*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:w,width:(e.width-w*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});wl.displayName="TrueFalse";var Sl=wl;var Am="#FFFFFF",cn=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:a})=>{let t=useDispatch(),r=useSelector(J=>J.toolbar.selectedTool),i=r==="pen"||r==="eraser",[n,u]=useState(false),[c,s]=useState(null),[l,p]=useState(false),[f,d]=useState(false),[m,x]=useState(0),g=340,y=100,h=window.innerWidth*.5,b=window.innerHeight*.5,L=g+20,C=y+60,I=h-40,k=b-160,w=useRef(null),q=J=>{t(Ut({id:e.id,x:J.target.x(),y:J.target.y()}));},U=J=>{let de=J.target,N=de.x(),D=de.y(),V=window.innerWidth*.2,te=N+V>L&&N<L+I&&D+50>C&&D<C+k;u(te);},O=(J,de)=>{let N=de.target,D=N.x(),V=N.y(),j=window.innerWidth*.2,Z=D+j>L&&D<L+I&&V+50>C&&V<C+k;s(Z?J:null),u(false);},R=()=>{p(true);},E=()=>{p(false),s(null),x(J=>J+1);},T=e.data.responseOptions.correctAnswer,G=c===T,z=()=>G?"\u2713 Correct! Great job!":"\u2717 Try again!",me=()=>G?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsxs(Group,{ref:w,name:"trueFalse-element",width:h,height:b,draggable:!i,listening:!i,...i?{}:{onContextMenu:J=>{J.evt.preventDefault(),o(J.evt,e.id,"trueFalse");}},children:[jsxs(Group,{x:g,y,rotation:e.rotation,onDragEnd:q,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?b+10:b-50,width:h,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:h-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:I,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:I,height:60,fill:me().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:I,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:me().text,align:"center",verticalAlign:"middle"})]}),c===null&&!l&&jsx(Text,{x:20,y:60,width:I,height:k-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),c!==null&&!l&&jsxs(Fragment,{children:[jsx(Text,{x:20,y:60+(k-60)/2-25,width:I,text:c?"True":"False",fontSize:32,fontStyle:"bold",fill:"#075560",align:"center"}),jsx(Text,{x:20,y:b-120,width:I,text:"Answer selected",fontSize:16,fill:"#6b7280",align:"center"})]}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:b-90,children:[jsxs(Group,{onMouseDown:()=>{c!==null&&(d(true),R());},onMouseUp:()=>d(false),onMouseLeave:()=>d(false),onTouchStart:()=>{c!==null&&(d(true),R());},onTouchEnd:()=>d(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:c===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),[{value:true,label:"True"},{value:false,label:"False"}].map((J,de)=>{let N=window.innerWidth*.2,D=50,V=10,j=c===J.value,te=T===J.value,Z=l&&j,ae="transparent";return Z?ae=te?"#4CAF50":"#ef4444":j&&(ae="#4CAF50"),jsxs(Group,{x:420+de*(N+V),y:y+b+20,draggable:!l,onDragMove:U,onDragEnd:Ce=>O(J.value,Ce),opacity:l&&!j?.5:1,children:[jsx(Rect,{width:N,height:D,fill:"#075560",stroke:ae,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:N,height:D,text:J.label,fontSize:18,fontStyle:"bold",fill:Am,align:"center",verticalAlign:"middle",listening:false}),Z&&jsx(Text,{x:N-30,y:5,width:25,height:25,text:te?"\u2713":"\u2717",fontSize:20,fontStyle:"bold",fill:te?"#4CAF50":"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},`${J.value}-${m}`)})]})};cn.displayName="TrueFalseDragAndDrop";var kl=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,handleDragEnd:r,onContextMenu:i})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Sl,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,onContextMenu:i,handleDragEnd:r},n.id):jsx(cn,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,onContextMenu:i},n.id))});var $t=new WeakMap,Pa=new WeakMap,po={current:[]},mn=false,mo=0,fo=new Set,yr=new Map;function Ml(e){let o=Array.from(e).sort((a,t)=>a instanceof ht&&a.options.deps.includes(t)?1:t instanceof ht&&t.options.deps.includes(a)?-1:0);for(let a of o){if(po.current.includes(a))continue;po.current.push(a),a.recompute();let t=Pa.get(a);if(t)for(let r of t){let i=$t.get(r);i&&Ml(i);}}}function Tm(e){let o={prevVal:e.prevState,currentVal:e.state};for(let a of e.listeners)a(o);}function Fm(e){let o={prevVal:e.prevState,currentVal:e.state};for(let a of e.listeners)a(o);}function Ir(e){if(mo>0&&!yr.has(e)&&yr.set(e,e.prevState),fo.add(e),!(mo>0)&&!mn)try{for(mn=!0;fo.size>0;){let o=Array.from(fo);fo.clear();for(let a of o){let t=yr.get(a)??a.prevState;a.prevState=t,Tm(a);}for(let a of o){let t=$t.get(a);t&&(po.current.push(a),Ml(t));}for(let a of o){let t=$t.get(a);if(t)for(let r of t)Fm(r);}}}finally{mn=false,po.current=[],yr.clear();}}function $e(e){mo++;try{e();}finally{if(mo--,mo===0){let o=fo.values().next().value;o&&Ir(o);}}}function Al(e){return typeof e=="function"}var St=class{constructor(o,a){this.listeners=new Set,this.subscribe=t=>{var r,i;this.listeners.add(t);let n=(i=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:i.call(r,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.prevState=o,this.state=o,this.options=a;}setState(o){var a,t,r;this.prevState=this.state,(a=this.options)!=null&&a.updateFn?this.state=this.options.updateFn(this.prevState)(o):Al(o)?this.state=o(this.prevState):this.state=o,(r=(t=this.options)==null?void 0:t.onUpdate)==null||r.call(t),Ir(this);}};var ht=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let a=this.options.deps.length,t=new Array(a),r=new Array(a);for(let i=0;i<a;i++){let n=this.options.deps[i];t[i]=n.prevState,r[i]=n.state;}return this.lastSeenDepValues=r,{prevDepVals:t,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var a,t;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(t=(a=this.options).onUpdate)==null||t.call(a);},this.checkIfRecalculationNeededDeeply=()=>{for(let i of this.options.deps)i instanceof e&&i.checkIfRecalculationNeededDeeply();let a=false,t=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let i=0;i<r.length;i++)if(r[i]!==t[i]){a=true;break}a&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let a of this._subscriptions)a();}),this.subscribe=a=>{var t,r;this.listeners.add(a);let i=(r=(t=this.options).onSubscribe)==null?void 0:r.call(t,a,this);return ()=>{this.listeners.delete(a),i?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let a of o)if(a instanceof e)a.registerOnGraph(),this.registerOnGraph(a.options.deps);else if(a instanceof St){let t=$t.get(a);t||(t=new Set,$t.set(a,t)),t.add(this);let r=Pa.get(this);r||(r=new Set,Pa.set(this,r)),r.add(a);}}unregisterFromGraph(o=this.options.deps){for(let a of o)if(a instanceof e)this.unregisterFromGraph(a.options.deps);else if(a instanceof St){let t=$t.get(a);t&&t.delete(this);let r=Pa.get(this);r&&r.delete(a);}}};function Pm(e){return typeof e=="function"}function pn(e,...o){return Pm(e)?e(...o):e}function Dl(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var _t,ze,Ue,ho,Yt,pa,Pt,Ea,go,wr,xo,Ra,ha=class{constructor({pluginId:o,debug:a=false,enabled:t=true,reconnectEveryMs:r=1e3}){Se(this,_t,true);Se(this,ze);Se(this,Ue);Se(this,ho);Se(this,Yt);Se(this,pa);Se(this,Pt);Se(this,Ea);Se(this,go,0);Se(this,wr,5);Se(this,xo,()=>{this.debugLog("Connected to event bus"),be(this,pa,true),this.debugLog("Emitting queued events",W(this,Yt)),W(this,Yt).forEach(o=>this.emitEventToBus(o)),be(this,Yt,[]),this.stopConnectLoop(),W(this,Ue).call(this).removeEventListener("tanstack-connect-success",W(this,xo));});Se(this,Ra,()=>{if(W(this,Ue).call(this).addEventListener("tanstack-connect-success",W(this,xo)),W(this,go)<W(this,wr)){oi(this,go)._++,this.dispatchCustomEvent("tanstack-connect",{});return}W(this,Ue).call(this).removeEventListener("tanstack-connect",W(this,Ra)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});be(this,ze,o),be(this,_t,t),be(this,Ue,this.getGlobalTarget),be(this,ho,a),this.debugLog(" Initializing event subscription for plugin",W(this,ze)),be(this,Yt,[]),be(this,pa,false),be(this,Pt,null),be(this,Ea,r);}startConnectLoop(){W(this,Pt)!==null||W(this,pa)||(this.debugLog(`Starting connect loop (every ${W(this,Ea)}ms)`),be(this,Pt,setInterval(W(this,Ra),W(this,Ea))));}stopConnectLoop(){W(this,Pt)!==null&&(clearInterval(W(this,Pt)),be(this,Pt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){W(this,ho)&&console.log(`\u{1F334} [tanstack-devtools:${W(this,ze)}-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 W(this,ze)}dispatchCustomEventShim(o,a){try{let t=new Event(o,{detail:a});W(this,Ue).call(this).dispatchEvent(t);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,a){try{W(this,Ue).call(this).dispatchEvent(new CustomEvent(o,{detail:a}));}catch{this.dispatchCustomEventShim(o,a);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,a){if(!W(this,_t)){this.debugLog("Event bus client is disabled, not emitting event",o,a);return}if(!W(this,pa)){this.debugLog("Bus not available, will be pushed as soon as connected"),W(this,Yt).push({type:`${W(this,ze)}:${o}`,payload:a,pluginId:W(this,ze)}),typeof CustomEvent<"u"&&(W(this,Ra).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${W(this,ze)}:${o}`,payload:a,pluginId:W(this,ze)})}on(o,a){let t=`${W(this,ze)}:${o}`;if(!W(this,_t))return this.debugLog("Event bus client is disabled, not registering event",t),()=>{};let r=i=>{this.debugLog("Received event from bus",i.detail),a(i.detail);};return W(this,Ue).call(this).addEventListener(t,r),this.debugLog("Registered event to bus",t),()=>{W(this,Ue).call(this).removeEventListener(t,r);}}onAll(o){if(!W(this,_t))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let a=t=>{let r=t.detail;o(r);};return W(this,Ue).call(this).addEventListener("tanstack-devtools-global",a),()=>W(this,Ue).call(this).removeEventListener("tanstack-devtools-global",a)}onAllPluginEvents(o){if(!W(this,_t))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let a=t=>{let r=t.detail;W(this,ze)&&r.pluginId!==W(this,ze)||o(r);};return W(this,Ue).call(this).addEventListener("tanstack-devtools-global",a),()=>W(this,Ue).call(this).removeEventListener("tanstack-devtools-global",a)}};_t=new WeakMap,ze=new WeakMap,Ue=new WeakMap,ho=new WeakMap,Yt=new WeakMap,pa=new WeakMap,Pt=new WeakMap,Ea=new WeakMap,go=new WeakMap,wr=new WeakMap,xo=new WeakMap,Ra=new WeakMap;var hn=class extends ha{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Tl=(e,o)=>{gn.emit(e,o);},gn=new hn;function Fl(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Em={enabled:true,leading:true,trailing:true,wait:0},Jt,_e,ga,xa,ba,Ba,Sr=class{constructor(o,a){Se(this,Jt);Se(this,_e);Se(this,ga);Se(this,xa);Se(this,ba);Se(this,Ba);this.fn=o,this.store=new St(Fl()),this.setOptions=t=>{this.options={...this.options,...t},W(this,ga).call(this)||this.cancel();},be(this,_e,t=>{this.store.setState(r=>{let i={...r,...t},{isPending:n}=i;return {...i,status:W(this,ga).call(this)?n?"pending":"idle":"disabled"}}),Tl("Throttler",this);}),be(this,ga,()=>!!pn(this.options.enabled,this)),be(this,xa,()=>pn(this.options.wait,this)),this.maybeExecute=(...t)=>{W(this,_e).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),i=r-this.store.state.lastExecutionTime,n=W(this,xa).call(this);if(this.options.leading&&i>=n)W(this,ba).call(this,...t);else if(W(this,_e).call(this,{lastArgs:t}),!W(this,Jt)&&this.options.trailing){let u=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,c=n-u;W(this,_e).call(this,{isPending:true}),be(this,Jt,setTimeout(()=>{let{lastArgs:s}=this.store.state;s!==void 0&&W(this,ba).call(this,...s);},c));}},be(this,ba,(...t)=>{if(!W(this,ga).call(this))return;this.fn(...t);let r=Date.now(),i=r+W(this,xa).call(this);W(this,Ba).call(this),W(this,_e).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:i,isPending:false,lastArgs:void 0}),this.options.onExecute?.(t,this),setTimeout(()=>{this.store.state.isPending||W(this,_e).call(this,{nextExecutionTime:void 0});},W(this,xa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&W(this,ba).call(this,...this.store.state.lastArgs);},be(this,Ba,()=>{W(this,Jt)&&(clearTimeout(W(this,Jt)),be(this,Jt,void 0));}),this.cancel=()=>{W(this,Ba).call(this),W(this,_e).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{W(this,_e).call(this,Fl());},this.key=Dl(a.key),this.options={...Em,...a},W(this,_e).call(this,this.options.initialState??{}),gn.on("d-Throttler",t=>{t.payload.key===this.key&&(W(this,_e).call(this,t.payload.store.state),this.setOptions(t.payload.options));});}};Jt=new WeakMap,_e=new WeakMap,ga=new WeakMap,xa=new WeakMap,ba=new WeakMap,Ba=new WeakMap;function xn(e,o){return new Sr(e,o).maybeExecute}function Qt(e,o){return typeof e=="function"?e(o):e}function Zt(e,o){return Ar(o).reduce((t,r)=>{if(t===null)return null;if(typeof t<"u")return t[r]},e)}function Oa(e,o,a){let t=Ar(o);function r(i){if(!t.length)return Qt(a,i);let n=t.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(i))return typeof i=="object"?(i===null&&(i={}),{...i,[n]:r(i[n])}):{[n]:r()};if(Array.isArray(i)&&typeof n=="number"){let u=i.slice(0,n);return [...u.length?u:new Array(n),r(i[n]),...i.slice(n+1)]}return [...new Array(n),r()]}return r(e)}function vn(e,o){let a=Ar(o);function t(r){if(!r)return;if(a.length===1){let n=a[0];if(Array.isArray(r)&&typeof n=="number")return r.filter((s,l)=>l!==n);let{[n]:u,...c}=r;return c}let i=a.shift();if(typeof i=="string"&&typeof r=="object")return {...r,[i]:t(r[i])};if(typeof i=="number"&&Array.isArray(r)){if(i>=r.length)return r;let n=r.slice(0,i);return [...n.length?n:new Array(i),t(r[i]),...r.slice(i+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return t(e)}var Rm=/^(\d+)$/gm,Bm=/\.(\d+)(?=\.)/gm,Om=/^(\d+)\./gm,qm=/\.(\d+$)/gm,Nm=/\.{2,}/gm,bn="__int__",Cr=`${bn}$1`;function Ar(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(Rm,Cr).replace(Bm,`.${Cr}.`).replace(Om,`${Cr}.`).replace(qm,`.${Cr}`).replace(Nm,".").split(".").map(o=>{if(o.startsWith(bn)){let a=o.substring(bn.length),t=parseInt(a,10);return String(t)===a?t:a}return o})}function Ln(e){return !(Array.isArray(e)&&e.length===0)}function qa(e,o){let a=t=>t.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:a})}function Na(e,o){let{asyncDebounceMs:a}=o,{onBlurAsyncDebounceMs:t,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:i}=o.validators||{},n=a??0,u=c=>c.validators.filter(Boolean).map(s=>{let l=s?.cause||e,p=n;switch(l){case "change":p=r??n;break;case "blur":p=t??n;break;case "dynamic":p=i??n;break;case "submit":p=0;break}return e==="submit"&&(p=0),{cause:l,validate:s.fn,debounceMs:p}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var bo=e=>!!e&&typeof e=="object"&&"fields"in e;function ea(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,i]of e)if(!o.has(r)||!Object.is(i,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 a=Object.keys(e),t=Object.keys(o);if(a.length!==t.length)return false;for(let r of a)if(!t.includes(r)||!ea(e[r],o[r]))return false;return true}var Dr=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:a})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:a?{newErrorValue:a,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},Tr=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Te(e,o){return e==null?o:{...e,...o}}var va=256,Mr=[],kr;for(;va--;)Mr[va]=(va+256).toString(16).substring(1);function yn(){let e=0,o,a="";if(!kr||va+16>256){for(kr=new Array(256),e=256;e--;)kr[e]=256*Math.random()|0;e=0,va=0;}for(;e<16;e++)o=kr[va+e],e===6?a+=Mr[o&15|64]:e===8?a+=Mr[o&63|128]:a+=Mr[o],e&1&&e>1&&e<11&&(a+="-");return va++,a}var ta=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,a=o?void 0:{fn:e.validators.onMount,cause:"mount"},t={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},i={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[a],form:e.form});case "submit":return e.runValidation({validators:[t,r,i,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,n],form:e.form});case "change":return e.runValidation({validators:[t,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Vm(e,o){let a=new Map;for(let t of e){let r=t.path??[],i=o,n="";for(let u=0;u<r.length;u++){let c=r[u];if(c===void 0)continue;let s=typeof c=="object"?c.key:c,l=Number(s);Array.isArray(i)&&!Number.isNaN(l)?n+=`[${l}]`:n+=(u>0?".":"")+String(s),typeof i=="object"&&i!==null?i=i[s]:i=void 0;}a.set(n,(a.get(n)??[]).concat(t));}return Object.fromEntries(a)}var Pl=(e,o)=>{let a=Vm(e,o);return {form:a,fields:a}},aa={validate({value:e,validationSource:o},a){let t=a["~standard"].validate(e);if(t instanceof Promise)throw new Error("async function passed to sync validator");if(t.issues)return o==="field"?t.issues:Pl(t.issues,e)},async validateAsync({value:e,validationSource:o},a){let t=await a["~standard"].validate(e);if(t.issues)return o==="field"?t.issues:Pl(t.issues,e)}},Fr=e=>!!e&&"~standard"in e;var Va={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function vo(e){function o(p,f,d,m){let x=t(p,f,d,m);({insert:()=>u(x,p,f),remove:()=>c(x),swap:()=>m!==void 0&&l(x,p,f,m),move:()=>m!==void 0&&s(x,p,f,m)})[d]();}function a(p,f){return `${p}[${f}]`}function t(p,f,d,m){let x=[a(p,f)];if(d==="swap")x.push(a(p,m));else if(d==="move"){let[g,y]=[Math.min(f,m),Math.max(f,m)];for(let h=g;h<=y;h++)x.push(a(p,h));}else {let g=e.getFieldValue(p),y=Array.isArray(g)?g.length:0;for(let h=f+1;h<y;h++)x.push(a(p,h));}return Object.keys(e.fieldInfo).filter(g=>x.some(y=>g.startsWith(y)))}function r(p,f){return p.replace(/\[(\d+)\]/,(d,m)=>{let x=parseInt(m,10);return `[${f==="up"?x+1:Math.max(0,x-1)}]`})}function i(p,f){(f==="up"?p:[...p].reverse()).forEach(m=>{let x=r(m.toString(),f),g=e.getFieldMeta(x);g?e.setFieldMeta(m,g):e.setFieldMeta(m,n());});}let n=()=>Va,u=(p,f,d)=>{i(p,"down"),p.forEach(m=>{m.toString().startsWith(a(f,d))&&e.setFieldMeta(m,n());});},c=p=>{i(p,"up");},s=(p,f,d,m)=>{let x=new Map(Object.keys(e.fieldInfo).filter(g=>g.startsWith(a(f,d))).map(g=>[g,e.getFieldMeta(g)]));i(p,d<m?"up":"down"),Object.keys(e.fieldInfo).filter(g=>g.startsWith(a(f,m))).forEach(g=>{let y=g.replace(a(f,m),a(f,d)),h=x.get(y);h&&e.setFieldMeta(g,h);});},l=(p,f,d,m)=>{p.forEach(x=>{if(!x.toString().startsWith(a(f,d)))return;let g=x.toString().replace(a(f,d),a(f,m)),[y,h]=[e.getFieldMeta(x),e.getFieldMeta(g)];y&&e.setFieldMeta(g,y),h&&e.setFieldMeta(x,h);});};return {handleArrayFieldMetaShift:o}}var In=class extends ha{constructor(){super({pluginId:"form-devtools"});}},Ye=new In;function wn(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 yo=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let t=this.fieldMetaDerived.mount(),r=this.store.mount(),i=()=>{t(),r(),Ye.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return Ye.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),i},this.update=t=>{if(!t)return;let r=this.options;this.options=t;let i=!!t.transform?.deps?.some((c,s)=>c!==this.prevTransformArray[s]),n=t.defaultValues&&!ea(t.defaultValues,r.defaultValues)&&!this.state.isTouched,u=!ea(t.defaultState,r.defaultState)&&!this.state.isTouched;!n&&!u&&!i||($e(()=>{this.baseStore.setState(()=>wn(Object.assign({},this.state,u?t.defaultState:{},n?{values:t.defaultValues}:{},i?{_force_re_eval:!this.state._force_re_eval}:{})));}),Ye.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(t,r)=>{let{fieldMeta:i}=this.state,n=this.resetFieldMeta(i);t&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:t}),this.baseStore.setState(()=>wn({...this.options.defaultState,values:t??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async t=>{let r=[];return $e(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let u=n.instance;r.push(Promise.resolve().then(()=>u.validate(t,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(c=>({...c,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(t,r,i)=>{let n=this.getFieldValue(t),u=Array.isArray(n)?Math.max(n.length-1,0):null,c=[`${t}[${r}]`];for(let f=r+1;f<=(u??0);f++)c.push(`${t}[${f}]`);let s=Object.keys(this.fieldInfo).filter(f=>c.some(d=>f.startsWith(d))),l=[];return $e(()=>{s.forEach(f=>{l.push(Promise.resolve().then(()=>this.validateField(f,i)));});}),(await Promise.all(l)).flat()},this.validateField=(t,r)=>{let i=this.fieldInfo[t]?.instance;return i?(i.state.meta.isTouched||i.setMeta(n=>({...n,isTouched:true})),i.validate(r)):[]},this.validateSync=t=>{let r=qa(t,{...this.options,form:this,validationLogic:this.options.validationLogic||ta}),i=false,n={};return $e(()=>{for(let s of r){if(!s.validate)continue;let l=this.runValidator({validate:s.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:p,fieldErrors:f}=Pr(l),d=Lo(s.cause);for(let m of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[m]===void 0)continue;let x=this.getFieldMeta(m);if(!x)continue;let{errorMap:g,errorSourceMap:y}=x,h=f?.[m],{newErrorValue:b,newSource:L}=Dr({newFormValidatorError:h,isPreviousErrorFromFormValidator:y?.[d]==="form",previousErrorValue:g?.[d]});L==="form"&&(n[m]={...n[m],[d]:h}),g?.[d]!==b&&this.setFieldMeta(m,C=>({...C,errorMap:{...C.errorMap,[d]:b},errorSourceMap:{...C.errorSourceMap,[d]:L}}));}this.state.errorMap?.[d]!==p&&this.baseStore.setState(m=>({...m,errorMap:{...m.errorMap,[d]:p}})),(p||f)&&(i=!0);}let u=Lo("submit");this.state.errorMap?.[u]&&t!=="submit"&&!i&&this.baseStore.setState(s=>({...s,errorMap:{...s.errorMap,[u]:void 0}}));let c=Lo("server");this.state.errorMap?.[c]&&t!=="server"&&!i&&this.baseStore.setState(s=>({...s,errorMap:{...s.errorMap,[c]:void 0}}));}),{hasErrored:i,fieldsErrorMap:n}},this.validateAsync=async t=>{let r=Na(t,{...this.options,form:this,validationLogic:this.options.validationLogic||ta});this.state.isFormValidating||this.baseStore.setState(s=>({...s,isFormValidating:true}));let i=[],n;for(let s of r){if(!s.validate)continue;let l=Lo(s.cause);this.state.validationMetaMap[l]?.lastAbortController.abort();let f=new AbortController;this.state.validationMetaMap[l]={lastAbortController:f},i.push(new Promise(async d=>{let m;try{m=await new Promise((h,b)=>{setTimeout(async()=>{if(f.signal.aborted)return h(void 0);try{h(await this.runValidator({validate:s.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:f.signal},type:"validateAsync"}));}catch(L){b(L);}},s.debounceMs);});}catch(h){m=h;}let{formError:x,fieldErrors:g}=Pr(m);g&&(n=n?{...n,...g}:g);let y=Lo(s.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let b=this.getFieldMeta(h);if(!b)continue;let{errorMap:L,errorSourceMap:C}=b,I=n?.[h],{newErrorValue:k,newSource:w}=Dr({newFormValidatorError:I,isPreviousErrorFromFormValidator:C?.[y]==="form",previousErrorValue:L?.[y]});L?.[y]!==k&&this.setFieldMeta(h,q=>({...q,errorMap:{...q.errorMap,[y]:k},errorSourceMap:{...q.errorSourceMap,[y]:w}}));}this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[y]:x}})),d(n?{fieldErrors:n,errorMapKey:y}:void 0);}));}let u=[],c={};if(i.length){u=await Promise.all(i);for(let s of u)if(s?.fieldErrors){let{errorMapKey:l}=s;for(let[p,f]of Object.entries(s.fieldErrors)){let m={...c[p]||{},[l]:f};c[p]=m;}}}return this.baseStore.setState(s=>({...s,isFormValidating:false})),c},this.validate=t=>{let{hasErrored:r,fieldsErrorMap:i}=this.validateSync(t);return r&&!this.options.asyncAlways?i:this.validateAsync(t)},this.getFieldValue=t=>Zt(this.state.values,t),this.getFieldMeta=t=>this.state.fieldMeta[t],this.getFieldInfo=t=>{var r;return (r=this.fieldInfo)[t]||(r[t]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(t,r)=>{this.baseStore.setState(i=>({...i,fieldMetaBase:{...i.fieldMetaBase,[t]:Qt(r,i.fieldMetaBase[t])}}));},this.resetFieldMeta=t=>Object.keys(t).reduce((r,i)=>{let n=i;return r[n]=Va,r},{}),this.setFieldValue=(t,r,i)=>{let n=i?.dontUpdateMeta??false,u=i?.dontRunListeners??false,c=i?.dontValidate??false;$e(()=>{n||this.setFieldMeta(t,s=>({...s,isTouched:!0,isDirty:!0,errorMap:{...s?.errorMap,onMount:void 0}})),this.baseStore.setState(s=>({...s,values:Oa(s.values,t,r)}));}),u||this.getFieldInfo(t).instance?.triggerOnChangeListener(),c||this.validateField(t,"change");},this.deleteField=t=>{let i=[...Object.keys(this.fieldInfo).filter(n=>{let u=t.toString();return n!==u&&n.startsWith(u)}),t];this.baseStore.setState(n=>{let u={...n};return i.forEach(c=>{u.values=vn(u.values,c),delete this.fieldInfo[c],delete u.fieldMetaBase[c];}),u});},this.pushFieldValue=(t,r,i)=>{this.setFieldValue(t,n=>[...Array.isArray(n)?n:[],r],i);},this.insertFieldValue=async(t,r,i,n)=>{this.setFieldValue(t,c=>[...c.slice(0,r),i,...c.slice(r)],Te(n,{dontValidate:true}));let u=n?.dontValidate??false;u||await this.validateField(t,"change"),vo(this).handleArrayFieldMetaShift(t,r,"insert"),u||await this.validateArrayFieldsStartingFrom(t,r,"change");},this.replaceFieldValue=async(t,r,i,n)=>{this.setFieldValue(t,c=>c.map((s,l)=>l===r?i:s),Te(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(t,"change"),await this.validateArrayFieldsStartingFrom(t,r,"change"));},this.removeFieldValue=async(t,r,i)=>{let n=this.getFieldValue(t),u=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(t,s=>s.filter((l,p)=>p!==r),Te(i,{dontValidate:true})),vo(this).handleArrayFieldMetaShift(t,r,"remove"),u!==null){let s=`${t}[${u}]`;this.deleteField(s);}(i?.dontValidate??false)||(await this.validateField(t,"change"),await this.validateArrayFieldsStartingFrom(t,r,"change"));},this.swapFieldValues=(t,r,i,n)=>{this.setFieldValue(t,c=>{let s=c[r],l=c[i];return Oa(Oa(c,`${r}`,l),`${i}`,s)},Te(n,{dontValidate:true})),vo(this).handleArrayFieldMetaShift(t,r,"swap",i),(n?.dontValidate??false)||(this.validateField(t,"change"),this.validateField(`${t}[${r}]`,"change"),this.validateField(`${t}[${i}]`,"change"));},this.moveFieldValues=(t,r,i,n)=>{this.setFieldValue(t,c=>{let s=[...c];return s.splice(i,0,s.splice(r,1)[0]),s},Te(n,{dontValidate:true})),vo(this).handleArrayFieldMetaShift(t,r,"move",i),(n?.dontValidate??false)||(this.validateField(t,"change"),this.validateField(`${t}[${r}]`,"change"),this.validateField(`${t}[${i}]`,"change"));},this.clearFieldValues=(t,r)=>{let i=this.getFieldValue(t),n=Array.isArray(i)?Math.max(i.length-1,0):null;if(this.setFieldValue(t,[],Te(r,{dontValidate:true})),n!==null)for(let c=0;c<=n;c++){let s=`${t}[${c}]`;this.deleteField(s);}(r?.dontValidate??false)||this.validateField(t,"change");},this.resetField=t=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[t]:Va},values:this.options.defaultValues?Oa(r.values,t,Zt(this.options.defaultValues,t)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((t,[r,i])=>(Object.keys(i).length&&i.errors.length&&(t[r]={errors:i.errors,errorMap:i.errorMap}),t),{})}),this.parseValuesWithSchema=t=>aa.validate({value:this.state.values,validationSource:"form"},t),this.parseValuesWithSchemaAsync=t=>aa.validateAsync({value:this.state.values,validationSource:"form"},t),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??yn(),this._devtoolsSubmissionOverride=false,this.baseStore=new St(wn({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new ht({deps:[this.baseStore],fn:({prevDepVals:t,currDepVals:r,prevVal:i})=>{let n=i,u=t?.[0],c=r[0],s=0,l={};for(let p of Object.keys(c.fieldMetaBase)){let f=c.fieldMetaBase[p],d=u?.fieldMetaBase[p],m=n?.[p],x=Zt(c.values,p),g=m?.errors;if(!d||f.errorMap!==d.errorMap){g=Object.values(f.errorMap??{}).filter(C=>C!==void 0);let L=this.getFieldInfo(p)?.instance;L&&!L.options.disableErrorFlat&&(g=g?.flat(1));}let y=!Ln(g??[]),h=!f.isDirty,b=ea(x,Zt(this.options.defaultValues,p))||ea(x,this.getFieldInfo(p)?.instance?.options.defaultValue);if(m&&m.isPristine===h&&m.isValid===y&&m.isDefaultValue===b&&m.errors===g&&f===d){l[p]=m,s++;continue}l[p]={...f,errors:g,isPristine:h,isValid:y,isDefaultValue:b};}return Object.keys(c.fieldMetaBase).length&&n&&s===Object.keys(c.fieldMetaBase).length?n:l}}),this.store=new ht({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:t,currDepVals:r,prevVal:i})=>{let n=i,u=t?.[0],c=r[0],s=r[1],l=Object.values(s).filter(Boolean),p=l.some(T=>T.isValidating),f=l.every(T=>T.isValid),d=l.some(T=>T.isTouched),m=l.some(T=>T.isBlurred),x=l.every(T=>T.isDefaultValue),g=d&&c.errorMap?.onMount,y=l.some(T=>T.isDirty),h=!y,b=!!(c.errorMap?.onMount||l.some(T=>T?.errorMap?.onMount)),L=!!p,C=n?.errors??[];(!u||c.errorMap!==u.errorMap)&&(C=Object.values(c.errorMap).reduce((T,G)=>G===void 0?T:G&&bo(G)?(T.push(G.form),T):(T.push(G),T),[]));let I=C.length===0,k=f&&I,w=this.options.canSubmitWhenInvalid??false,q=c.submissionAttempts===0&&!d&&!b||!L&&!c.isSubmitting&&k||w,U=c.errorMap;if(g&&(C=C.filter(T=>T!==c.errorMap.onMount),U=Object.assign(U,{onMount:void 0})),n&&u&&n.errorMap===U&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===p&&n.isFieldsValid===f&&n.isFormValid===I&&n.isValid===k&&n.canSubmit===q&&n.isTouched===d&&n.isBlurred===m&&n.isPristine===h&&n.isDefaultValue===x&&n.isDirty===y&&ea(u,c))return n;let O={...c,errorMap:U,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:p,isFieldsValid:f,isFormValid:I,isValid:k,canSubmit:q,isTouched:d,isBlurred:m,isPristine:h,isDefaultValue:x,isDirty:y},R=this.options.transform?.deps??[];if(R.length!==this.prevTransformArray.length||R.some((T,G)=>T!==this.prevTransformArray[G])){let T=Object.assign({},this,{state:O});this.options.transform?.fn(T),O=T.state,this.prevTransformArray=R;}return O}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let a=xn(t=>Ye.emit("form-state",{id:this._formId,state:t}),{wait:300});this.store.subscribe(()=>{a(this.store.state);}),Ye.on("request-form-state",t=>{t.payload.id===this._formId&&Ye.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Ye.on("request-form-reset",t=>{t.payload.id===this._formId&&this.reset();}),Ye.on("request-form-force-submit",t=>{t.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 Fr(o.validate)?aa[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})),$e(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(i=>({...i,isTouched:!0})));});});let a=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:a});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let t=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){t(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:a}),Ye.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){t(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:a}),Ye.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}$e(()=>{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:a});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:a}),$e(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),Ye.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),t();});}catch(r){throw this.baseStore.setState(i=>({...i,isSubmitSuccessful:false})),Ye.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),t(),r}}setErrorMap(o){$e(()=>{Object.entries(o).forEach(([a,t])=>{let r=a;if(bo(t)){let{formError:i,fieldErrors:n}=Pr(t);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,s=>({...s,errorMap:{...s.errorMap,[r]:n?.[u]},errorSourceMap:{...s.errorSourceMap,[r]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[r]:i}}));}else this.baseStore.setState(i=>({...i,errorMap:{...i.errorMap,[r]:t}}));});});}};function Pr(e){if(e){if(bo(e)){let o=Pr(e.form).formError,a=e.fields;return {formError:o,fieldErrors:a}}return {formError:e}}return {formError:void 0}}function Lo(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 Io=class{constructor(o){this.options={},this.mount=()=>{let a=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let t=this.getInfo();t.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let i=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});i&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:i},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),a},this.update=a=>{this.options=a;let t=this.name!==a.name;if(this.name=a.name,this.state.value===void 0){let r=Zt(a.form.options.defaultValues,a.name),i=a.defaultValue??r;t?this.setValue(n=>n||i,{dontUpdateMeta:true}):i!==void 0&&this.setValue(i,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(a,t)=>{this.form.setFieldValue(this.name,a,Te(t,{dontRunListeners:true,dontValidate:true})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=a=>this.form.setFieldMeta(this.name,a),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(a,t)=>{this.form.pushFieldValue(this.name,a,Te(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(a,t,r)=>{this.form.insertFieldValue(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(a,t,r)=>{this.form.replaceFieldValue(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(a,t)=>{this.form.removeFieldValue(this.name,a,Te(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(a,t,r)=>{this.form.swapFieldValues(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(a,t,r)=>{this.form.moveFieldValues(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=a=>{this.form.clearFieldValues(this.name,Te(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=a=>{let t=Object.values(this.form.fieldInfo),r=[];for(let i of t){if(!i.instance)continue;let{onChangeListenTo:n,onBlurListenTo:u}=i.instance.options.validators||{};a==="change"&&n?.includes(this.name)&&r.push(i.instance),a==="blur"&&u?.includes(this.name)&&r.push(i.instance);}return r},this.validateSync=(a,t)=>{let r=qa(a,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ta}),n=this.getLinkedFields(a).reduce((s,l)=>{let p=qa(a,{...l.options,form:l.form,validationLogic:l.form.options.validationLogic||ta});return p.forEach(f=>{f.field=l;}),s.concat(p)},[]),u=false;$e(()=>{let s=(l,p)=>{let f=Er(p.cause),d=p.validate?El(l.runValidator({validate:p.validate,value:{value:l.store.state.value,validationSource:"field",fieldApi:l},type:"validate"})):void 0,m=t[f],{newErrorValue:x,newSource:g}=Tr({formLevelError:m,fieldLevelError:d});l.state.meta.errorMap?.[f]!==x&&l.setMeta(y=>({...y,errorMap:{...y.errorMap,[f]:x},errorSourceMap:{...y.errorSourceMap,[f]:g}})),x&&(u=!0);};for(let l of r)s(this,l);for(let l of n)l.validate&&s(l.field,l);});let c=Er("submit");return this.state.meta.errorMap?.[c]&&a!=="submit"&&!u&&this.setMeta(s=>({...s,errorMap:{...s.errorMap,[c]:void 0},errorSourceMap:{...s.errorSourceMap,[c]:void 0}})),{hasErrored:u}},this.validateAsync=async(a,t)=>{let r=Na(a,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ta}),i=await t,n=this.getLinkedFields(a),u=n.reduce((f,d)=>{let m=Na(a,{...d.options,form:d.form,validationLogic:d.form.options.validationLogic||ta});return m.forEach(x=>{x.field=d;}),f.concat(m)},[]);this.state.meta.isValidating||this.setMeta(f=>({...f,isValidating:true}));for(let f of n)f.setMeta(d=>({...d,isValidating:true}));let c=[],s=[],l=(f,d,m)=>{let x=Er(d.cause);f.getInfo().validationMetaMap[x]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[x]={lastAbortController:y},m.push(new Promise(async h=>{let b;try{b=await new Promise((w,q)=>{this.timeoutIds.validations[d.cause]&&clearTimeout(this.timeoutIds.validations[d.cause]),this.timeoutIds.validations[d.cause]=setTimeout(async()=>{if(y.signal.aborted)return w(void 0);try{w(await this.runValidator({validate:d.validate,value:{value:f.store.state.value,fieldApi:f,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(U){q(U);}},d.debounceMs);});}catch(w){b=w;}if(y.signal.aborted)return h(void 0);let L=El(b),C=i[this.name]?.[x],{newErrorValue:I,newSource:k}=Tr({formLevelError:C,fieldLevelError:L});f.setMeta(w=>({...w,errorMap:{...w?.errorMap,[x]:I},errorSourceMap:{...w.errorSourceMap,[x]:k}})),h(I);}));};for(let f of r)f.validate&&l(this,f,c);for(let f of u)f.validate&&l(f.field,f,s);let p=[];(c.length||s.length)&&(p=await Promise.all(c),await Promise.all(s)),this.setMeta(f=>({...f,isValidating:false}));for(let f of n)f.setMeta(d=>({...d,isValidating:false}));return p.filter(Boolean)},this.validate=(a,t)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(a),{hasErrored:i}=this.validateSync(a,r[this.name]??{});if(i&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Er(a)]?.lastAbortController.abort(),this.state.meta.errors;let n=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(a);return this.validateAsync(a,n)},this.handleChange=a=>{this.setValue(a);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(t=>({...t,isTouched:true})),this.state.meta.isBlurred||this.setMeta(t=>({...t,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=a=>aa.validate({value:this.state.value,validationSource:"field"},a),this.parseValueWithSchemaAsync=a=>aa.validateAsync({value:this.state.value,validationSource:"field"},a),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new ht({deps:[this.form.store],fn:()=>{let a=this.form.getFieldValue(this.name),t=this.form.getFieldMeta(this.name)??{...Va,...o.defaultMeta};return {value:a,meta:t}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Fr(o.validate)?aa[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(a=>({...a,errorMap:{...a.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 a=this.options.listeners?.onBlurDebounceMs;a&&a>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});},a)):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 a=this.options.listeners?.onChangeDebounceMs;a&&a>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});},a)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function El(e){if(e)return e}function Er(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 Rr(e,o=a=>a){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Um)}function Um(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[t,r]of e)if(!o.has(t)||!Object.is(r,o.get(t)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let t of e)if(!o.has(t))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let a=Rl(e);if(a.length!==Rl(o).length)return false;for(let t=0;t<a.length;t++)if(!Object.prototype.hasOwnProperty.call(o,a[t])||!Object.is(e[a[t]],o[a[t]]))return false;return true}function Rl(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Ha=typeof window<"u"?useLayoutEffect:useEffect;function $m(e){let[o]=useState(()=>{let t=new Io({...e,form:e.form,name:e.name});return t.Field=Sn,t});return Ha(o.mount,[o]),Ha(()=>{o.update(e);}),Rr(o.store,e.mode==="array"?a=>[a.meta,Object.keys(a.value??[]).length]:void 0),o}var Sn=(({children:e,...o})=>{let a=$m(o),t=useMemo(()=>Qt(e,a),[e,a,a.state.value,a.state.meta]);return jsx(Fragment,{children:t})});function Jm({form:e,selector:o,children:a}){let t=Rr(e.store,o);return Qt(a,t)}function Cn(e){let o=useId(),[a]=useState(()=>{let t=new yo({...e,formId:o}),r=t;return r.Field=function(n){return jsx(Sn,{...n,form:t})},r.Subscribe=function(n){return jsx(Jm,{form:t,selector:n.selector,children:n.children})},r});return Ha(a.mount,[]),Ha(()=>{a.update(e);}),a}function kn({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 tp=({editElement:e})=>{let o=useDispatch(),a=useSelector(ce),t=!!e,r=e?.data.questionType||a?.activityType||"multiple-choice",[i,n]=useState(r),u=Cn({defaultValues:{questionType:r,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:s})=>{if(s.questionType==="true-false"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctAnswer:s.responseOptions.correctAnswer??false}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:300,rotation:t?e.rotation:0};o(t?Ut(l):vs(l));}else if(s.questionType==="multiple-choice"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctIndex:s.responseOptions.correctIndex??[]}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?Ht(l):xs(l));}else if(s.questionType==="short-answer"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctShortAnswer:s.responseOptions.correctShortAnswer??""}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?Xa(l):ys(l));}else if(s.questionType==="fill-in-the-blank"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctShortAnswer:s.responseOptions.correctShortAnswer??""}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?_a(l):Cs(l));}else if(s.questionType==="long-answer"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctLongAnswer:s.responseOptions.correctLongAnswer??""}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?$a(l):ws(l));}o(Wt(false));}}),c=()=>{o(Wt(false));};return 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",{className:"h-fit max-h-[calc(100vh-300px)] w-full max-w-2xl overflow-y-auto rounded-lg bg-white p-6",children:jsxs("form",{className:"relative h-full max-h-[calc(100vh-300px)] w-full max-w-2xl rounded-lg bg-white p-6",onSubmit:s=>{s.preventDefault(),s.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-4",children:[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:()=>{c();},children:jsx("span",{className:"text-xl",children:"\u2715"})}),jsx("h2",{className:"text-xl font-bold text-gray-900",children:t?"Edit Question":"Add Question"}),jsx("div",{className:"w-8"})]}),jsx(u.Field,{name:"questionType",children:s=>jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:s.name,name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:l=>{s.handleChange(l.target.value),n(l.target.value);},disabled:t,className:`w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none ${t?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"\u2630 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"})})})]}),t&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Question type cannot be changed when editing"}),jsx(kn,{field:s})]})}),i&&!["short-answer","fill-in-the-blank","long-answer"].includes(i)&&jsx(u.Field,{name:"responseType",children:s=>jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:s.name,name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:l=>s.handleChange(l.target.value),className:"w-full appearance-none rounded-lg border border-gray-300 bg-white px-4 py-3 pr-10 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none",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(kn,{field:s})]})}),jsx(u.Field,{name:"feedbackMode",children:s=>jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Feedback Mode"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:s.name,name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:l=>s.handleChange(l.target.value),disabled:i==="long-answer",className:`w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none ${i==="long-answer"?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"practice",children:"Practice Mode"}),jsx("option",{value:"test",children:"Assessment Mode"})]}),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"})})})]}),i==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(kn,{field:s})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:s})=>s?void 0:"A question is required"},children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"w-full resize-none rounded-lg border border-gray-300 bg-white px-4 py-3 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none",value:s.state.value,onChange:l=>s.handleChange(l.target.value),onBlur:s.handleBlur})}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}),jsxs("button",{type:"button",className:"flex w-full items-center justify-center gap-2 rounded-lg border-2 border-gray-300 bg-white px-4 py-3 font-medium text-gray-900 transition-colors hover:border-gray-400 hover:bg-gray-50",children:[jsx("span",{children:"\u{1F50D}"}),jsx("span",{children:"Find Questions"})]}),i==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{className:"text-sm font-semibold text-gray-900",children:"Correct Answer"}),jsxs("div",{className:"flex gap-4",children:[jsxs("button",{type:"button",onClick:()=>s.handleChange(true),className:`flex flex-1 items-center justify-center gap-3 rounded-lg border-2 px-6 py-4 transition-colors ${s.state.value===true?"border-green-500 bg-green-50":"border-gray-300 bg-white hover:border-gray-400"}`,children:[jsx("div",{className:`flex h-6 w-6 items-center justify-center rounded-full border-2 ${s.state.value===true?"border-green-500 bg-green-500":"border-gray-300"}`,children:s.state.value===true&&jsx("div",{className:"h-3 w-3 rounded-full bg-white"})}),jsx("span",{className:"text-lg font-semibold text-black",children:"True"})]}),jsxs("button",{type:"button",onClick:()=>s.handleChange(false),className:`flex flex-1 items-center justify-center gap-3 rounded-lg border-2 px-6 py-4 transition-colors ${s.state.value===false?"border-green-500 bg-green-50":"border-gray-300 bg-white hover:border-gray-400"}`,children:[jsx("div",{className:`flex h-6 w-6 items-center justify-center rounded-full border-2 ${s.state.value===false?"border-green-500 bg-green-500":"border-gray-300"}`,children:s.state.value===false&&jsx("div",{className:"h-3 w-3 rounded-full bg-white"})}),jsx("span",{className:"text-lg font-semibold text-black",children:"False"})]})]}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Select the correct answer for this true/false question"})]})}),i==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:s})=>{if(s.options.filter(p=>!p.trim()).length>0)return "All options must have text";if(!s.correctIndex||s.correctIndex.length===0)return "Please select at least one correct answer"}},children:s=>{let l=(m,x)=>{let g=[...s.state.value.options];g[m]=x,s.handleChange({...s.state.value,options:g});},p=()=>{if(s.state.value.options.length>=6){alert("Maximum 6 options allowed");return}s.handleChange({...s.state.value,options:[...s.state.value.options,""]});},f=m=>{if(s.state.value.options.length<=2){alert("Minimum 2 options required");return}let x=s.state.value.options.filter((y,h)=>h!==m),g=s.state.value.correctIndex?.filter(y=>y!==m).map(y=>y>m?y-1:y);s.handleChange({...s.state.value,options:x,correctIndex:g});},d=m=>{let x=s.state.value.correctIndex||[];if(x.includes(m))s.handleChange({...s.state.value,correctIndex:x.filter(y=>y!==m)});else {if(x.length>=6){alert("Maximum 6 correct answers allowed");return}s.handleChange({...s.state.value,correctIndex:[...x,m]});}};return jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:["Response Options (",s.state.value.options.length,"/6)"]}),jsx("button",{type:"button",onClick:p,disabled:s.state.value.options.length>=6,className:"rounded-lg bg-[#096B76] px-3 py-1 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50",children:"+ Add Option"})]}),jsx("div",{className:"flex flex-col gap-3",children:s.state.value.options.map((m,x)=>{let g=!m.trim(),y=s.state.value.correctIndex?.includes(x),h=s.state.meta.isTouched&&g;return jsxs("div",{className:`flex items-center gap-3 rounded-lg border-2 px-4 py-3 transition-colors ${h?"border-red-500 bg-red-50":y?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:[jsx("button",{type:"button",onClick:()=>d(x),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors ${y?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:y&&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("input",{type:"text",placeholder:`Option ${x+1}`,value:m,onChange:b=>l(x,b.target.value),onBlur:s.handleBlur,className:"flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"}),s.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>f(x),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded bg-red-500 text-white transition-colors hover:bg-red-600",children:jsx("span",{className:"text-sm",children:"\u2715"})})]},x)})}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Click the box to mark the correct answer"}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}}),(i==="short-answer"||i==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:s.state.value,onChange:l=>{s.handleChange(l.target.value);},className:"w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors focus:border-[#096B76] focus:outline-none"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Learners must write this answer exactly (case-insensitive)."}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}),i==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:s.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:s.state.value,onChange:l=>{s.handleChange(l.target.value);},rows:6,className:"w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors focus:border-[#096B76] focus:outline-none"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"This will be used as a reference answer for manual grading."}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:s=>[s.canSubmit,s.isSubmitting],children:([s,l])=>jsx("button",{type:"submit",disabled:!s,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:l?"Saving...":t?"Update Question":"Save Question"})})]})})})},Ol=tp;var ql=({text:e,position:o})=>{let a=pe(),t=s=>{a(oe()),a(st({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+s))}));},r=s=>{a(oe()),a(st({id:e.id,fill:s}));},i=()=>{a(oe()),a(st({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{a(oe()),a(st({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},u=()=>{a(oe()),a(st({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},c=s=>{a(oe()),a(st({id:e.id,fontFamily:s}));};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:s=>s.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:s=>c(s.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:()=>t(-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:()=>t(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:i,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:jsx(TextB,{size:16,weight:"bold"})}),jsx("button",{onClick:n,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:jsx(TextItalic,{size:16,weight:"bold"})}),jsx("button",{onClick:u,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:s=>r(s.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var Vl=({text:e,editingValue:o,onEditingChange:a,onFinish:t,position:r,scale:i,textareaRef:n})=>{let u=useRef(null),c=useMemo(()=>({fontSize:`${e.fontSize*i}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,i]),s=useCallback(l=>{l.style.height="auto",l.style.height=`${l.scrollHeight}px`;let p=document.createElement("span");p.style.font=window.getComputedStyle(l).font,p.style.fontSize=l.style.fontSize,p.style.fontFamily=l.style.fontFamily,p.style.fontWeight=l.style.fontWeight,p.style.fontStyle=l.style.fontStyle,p.style.visibility="hidden",p.style.position="absolute",p.style.whiteSpace="pre";let f=l.value.split(`
4
- `),d=0;document.body.appendChild(p);for(let x of f){p.textContent=x||" ";let g=p.offsetWidth;g>d&&(d=g);}document.body.removeChild(p);let m=10;l.style.width=`${Math.max(200,d+m+20)}px`;},[]);return useEffect(()=>{let l=u.current;l&&(l.style.fontSize=`${e.fontSize*i}px`,l.style.fontFamily=e.fontFamily,l.style.fontStyle=e.fontStyle,l.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",l.style.textDecoration=e.textDecoration,l.style.color=e.fill,s(l));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,i,s]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:l=>{if(u.current=l,n.current=l,l){l.focus();let p=l.value.length;l.setSelectionRange(p,p),s(l);}},value:o,onChange:l=>{a(l.target.value);},onKeyDown:l=>{l.key==="Escape"&&t();},style:c},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Hl=memo(({shortAnswer:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>{let n=useSelector(E=>E.toolbar.selectedTool),u=n==="pen"||n==="eraser",c=useRef(null),[s,l]=useState(""),[p,f]=useState(false),[d,m]=useState(null);useEffect(()=>{let E=c.current;if(E)return t.current.set(e.id,E),()=>{t.current.delete(e.id);}},[e.id,t]);let x=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=p&&s.trim().toLowerCase()===x,y=()=>{f(false),l("");},h=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",b=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,C=60,I=p?50:0,k=50,w=12,q=e.data.feedbackMode==="practice"?48:0,U=12,O=30,R=C+I+O+k+w+U+q+L;return jsxs(Group,{ref:c,draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"sa-element",...u?{}:{onDragEnd:i,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let T=c.current?.getStage()?.getPointerPosition();if(!T)return;let G={x:e.x,y:e.y,width:e.width,height:e.height};T.x>=G.x&&T.x<=G.x+G.width&&T.y>=G.y&&T.y<=G.y+G.height&&r(E.evt,e.id,"shortAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:R,onTransformEnd:E=>a(e.id,E)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:I,text:h(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer:",x:L,y:C+I+w,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+I+O,width:e.width-L*2,height:k,fill:"#ffffff",stroke:g?"#22c55e":p?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${C+I+O}px`,left:`${L}px`,width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:p?"none":"auto"}},children:jsx("input",{type:"text",value:s,onChange:E=>l(E.target.value),disabled:p,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:p?"none":"auto"}})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C+I+O+k+w+U,children:[!p&&jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,m("check");},onMouseUp:E=>{E.cancelBubble=true,m(null),s.length>0&&f(true);},onMouseLeave:E=>{E.cancelBubble=true,m(null);},onTouchStart:E=>{E.cancelBubble=true,m("check");},onTouchEnd:E=>{E.cancelBubble=true,m(null),s.length>0&&f(true);},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:s.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),p&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),y();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),y();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.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})]})]})]})});Hl.displayName="ShortAnswer";var Ul=Hl;var Kl=({shortAnswers:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>jsx(Fragment,{children:e.map(n=>jsx(Ul,{shortAnswer:n,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:u=>i(u,n.id)},n.id))});var zl=e=>{let o=useDispatch(),t=useSelector(ce)?.fillInTheBlanks||[],r=useRef(new Map),i=useCallback((n,u)=>{let c=n.target;o(_a({id:u,x:c.x(),y:c.y()})),e?.();},[o,e]);return {fillInTheBlanks:t,fibRefs:r,handleFillInTheBlanksDragEnd:i}};var Gl=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:a,handleDragEnd:t,onContextMenu:r})=>{let i=useSelector(R=>R.toolbar.selectedTool),n=i==="pen"||i==="eraser",u=useRef(null),[c,s]=useState(""),[l,p]=useState(false),[f,d]=useState(null);useEffect(()=>{if(u.current)return ()=>{}},[e.id]);let m=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=l&&c.trim().toLowerCase()===m,g=()=>{p(false),s("");},y=()=>x?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",h=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=24,L=80,C=l?50:0,I=45,k=8,w=20,q=e.data.feedbackMode==="practice"?48:0,U=12,O=L+C+k+w+k+U+q+b;return jsxs(Group,{ref:u,draggable:!n,listening:!n,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...n?{}:{onDragEnd:R=>t(R,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:R=>{let E=u.current?.getStage()?.getPointerPosition();if(!E||!r)return;let T={x:e.x,y:e.y,width:e.width,height:e.height};E.x>=T.x&&E.x<=T.x+T.width&&E.y>=T.y&&E.y<=T.y+T.height&&r(R.evt,e.id,"fillInTheBlanks");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:O,onTransformEnd:R=>a(e.id,R)}),jsx(Text,{text:e.data.question,x:b,y:b,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2-200,listening:false}),jsx(Rect,{x:e.width-b-180,y:b+10,width:180,height:I,fill:"#ffffff",stroke:x?"#22c55e":l?"#ef4444":"#096B76",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${b+10}px`,left:`${e.width-b-180}px`,width:"180px",height:`${I}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:c,onChange:R=>s(R.target.value),disabled:l,placeholder:"__________",className:"h-full w-full border-0 bg-white px-2 text-center text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:l?"none":"auto"}})}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:b,y:L,width:e.width-b*2,height:C,fill:h().bg,cornerRadius:8}),jsx(Text,{x:b,y:L,width:e.width-b*2,height:C,text:y(),fontSize:16,fontStyle:"bold",fill:h().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"\u26A0\uFE0F Answer is case sensitive",x:b,y:L+C+k,fontSize:10,fontStyle:"italic",fill:"#6b7280",width:e.width-b*2,listening:false}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:L+C+k+w+k+U,children:[!l&&jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,d("check");},onMouseUp:R=>{R.cancelBubble=true,d(null),c.length>0&&p(true);},onMouseLeave:R=>{R.cancelBubble=true,d(null);},onTouchStart:R=>{R.cancelBubble=true,d("check");},onTouchEnd:R=>{R.cancelBubble=true,d(null),c.length>0&&p(true);},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:c.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),g();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),g();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*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,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Gl.displayName="FillInTheBlanks";var jl=Gl;var $l=({fillInTheBlanks:e,handleSelect:o,handleTransform:a,onContextMenu:t,handleDragEnd:r})=>jsx(Fragment,{children:e.map(i=>jsx(jl,{fillInTheBlank:i,handleSelect:o,handleTransform:a,onContextMenu:t,handleDragEnd:r},i.id))});var Pn=memo(({longAnswer:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>{let n=useSelector(E=>E.toolbar.selectedTool),u=n==="pen"||n==="eraser",c=useRef(null),[s,l]=useState(""),[p,f]=useState(false),[d,m]=useState(null);useEffect(()=>{let E=c.current;if(E)return t.current.set(e.id,E),()=>{t.current.delete(e.id);}},[e.id,t]);let x=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",g=p&&s.trim().toLowerCase()===x,y=()=>{f(false),l("");},h=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",b=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,C=60,I=p?60:0,k=120,w=12,q=48,U=12,O=30,R=C+I+O+k+w+U+q+L;return jsxs(Group,{ref:c,draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...u?{}:{onDragEnd:i,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let T=c.current?.getStage()?.getPointerPosition();if(!T||!r)return;let G={x:e.x,y:e.y,width:e.width,height:e.height};T.x>=G.x&&T.x<=G.x+G.width&&T.y>=G.y&&T.y<=G.y+G.height&&r(E.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:R,onTransformEnd:E=>a(e.id,E)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:I,text:h(),fontSize:14,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:C+I+w,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+I+O,width:e.width-L*2,height:k,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${C+I+O}px`,left:`${L}px`,width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:p?"none":"auto"}},children:jsx("textarea",{value:s,onChange:E=>l(E.target.value),disabled:p,placeholder:`Type your extended answer here...\r
2
+ export{default as Konva}from'konva';import ut,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,createElement,useMemo,useId,useLayoutEffect}from'react';import {Group,Image,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 fi from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {EyeIcon,Stack as Stack$1,X as X$1,DotsSixVertical,ArrowUp,ArrowDown,Question,FrameCorners,Cards as Cards$1,TextT as TextT$1,Shapes,VideoCamera,Image as Image$2}from'@phosphor-icons/react';import {Stop,X,Microphone,MicrophoneSlash,Record,Download,Selection,Pen,Eraser,TextT,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,List,Image as Image$1,Video,Cards,Camera,ListChecksIcon,ToggleRight,Textbox,Article,TextUnderline,ArrowUUpLeft,ArrowUDownRight,Trash,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,TextB,TextItalic,Warning,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {createPortal}from'react-dom';import pl from'use-image';import {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 ai=e=>{throw TypeError(e)};var oi=(e,o,a)=>o.has(e)||ai("Cannot "+a);var W=(e,o,a)=>(oi(e,o,"read from private field"),a?a.call(e):o.get(e)),Se=(e,o,a)=>o.has(e)?ai("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,a),be=(e,o,a,t)=>(oi(e,o,"write to private field"),o.set(e,a),a);var ri=(e,o,a,t)=>({set _(r){be(e,o,r);},get _(){return W(e,o,t)}});var pe=()=>useDispatch(),$=e=>useSelector(e),yt=pe,Vt=$;var Gr=20,si=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()}),zr=si("Slide 1"),pu={slides:[zr],currentSlideId:zr.id,history:{[zr.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null},ni=createSlice({name:"canvas",initialState:pu,reducers:{addSlide:e=>{if(e.slides.length>=Gr)return;let o=si(`Slide ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{if(e.slides.length<=1)return;let a=e.slides.findIndex(t=>t.id===o.payload);if(a!==-1&&(e.slides.splice(a,1),delete e.history[o.payload],e.currentSlideId===o.payload)){let t=Math.max(0,a-1);e.currentSlideId=e.slides[t].id;}},duplicateSlide:(e,o)=>{if(e.slides.length>=Gr)return;let a=e.slides.findIndex(i=>i.id===o.payload);if(a===-1)return;let t=e.slides[a],r={...t,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${t.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),lines:JSON.parse(JSON.stringify(t.lines)),images:JSON.parse(JSON.stringify(t.images)),videos:JSON.parse(JSON.stringify(t.videos)),shapes:JSON.parse(JSON.stringify(t.shapes)),flashcards:JSON.parse(JSON.stringify(t.flashcards)),photoFrames:JSON.parse(JSON.stringify(t.photoFrames))};e.slides.splice(a+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(t=>t.id===o.payload)&&(e.currentSlideId=o.payload);},updateSlideThumbnail:(e,o)=>{let a=e.slides.find(t=>t.id===o.payload.id);a&&(a.thumbnail=o.payload.thumbnail,a.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.backgroundColor=o.payload,a.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:a,toIndex:t}=o.payload;if(a<0||a>=e.slides.length||t<0||t>=e.slides.length)return;let[r]=e.slides.splice(a,1);e.slides.splice(t,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(a=>({...a,showMcqForm:false})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(a=>{e.history[a.id]={past:[],future:[]};});},addLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...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};a.lines.push(t),a.updatedAt=Date.now();}},removeLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&o.payload>=0&&o.payload<a.lines.length&&(a.lines.splice(o.payload,1),a.updatedAt=Date.now());},updateLastLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&a.lines.length>0&&(a.lines[a.lines.length-1].points=o.payload,a.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(a=>a.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.lines=o.payload,a.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.find(r=>r.id===o.payload.id);t&&(t.x=o.payload.x,t.y=o.payload.y,a.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.find(r=>r.id===o.payload.id);t&&(t.x=o.payload.x,t.y=o.payload.y,t.scaleX=o.payload.scaleX,t.scaleY=o.payload.scaleY,t.rotation=o.payload.rotation,a.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.findIndex(r=>r.id===o.payload);t!==-1&&(a.lines.splice(t,1),a.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.lines.find(r=>r.id===o.payload);if(t){let r={...t,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(t.x||0)+20,y:(t.y||0)+20,timestamp:Date.now()};a.lines.push(r),a.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,newTimestamp:i}=o.payload;switch(r){case "image":let n=a.images.find(h=>h.id===t);n&&(n.timestamp=i);break;case "video":let u=a.videos.find(h=>h.id===t);u&&(u.timestamp=i);break;case "shape":let c=a.shapes.find(h=>h.id===t);c&&(c.timestamp=i);break;case "text":let s=a.texts.find(h=>h.id===t);s&&(s.timestamp=i);break;case "flashcard":let l=a.flashcards.find(h=>h.id===t);l&&(l.timestamp=i);break;case "photoFrame":let p=a.photoFrames.find(h=>h.id===t);p&&(p.timestamp=i);break;case "mcq":let f=a.multipleChoices.find(h=>h.id===t);f&&(f.timestamp=i);break;case "trueFalse":let d=a.trueFalses.find(h=>h.id===t);d&&(d.timestamp=i);break;case "shortAnswer":let m=a.shortAnswers.find(h=>h.id===t);m&&(m.timestamp=i);break;case "longAnswer":let x=a.LongAnswer.find(h=>h.id===t);x&&(x.timestamp=i);break;case "fillInTheBlanks":let g=a.fillInTheBlanks.find(h=>h.id===t);g&&(g.timestamp=i);break;case "line":let y=a.lines.find(h=>h.id===t);y&&(y.timestamp=i);break}a.updatedAt=Date.now();}},addImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.images.push(t),a.updatedAt=Date.now();}},updateImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.images[t]={...a.images[t],...o.payload},a.updatedAt=Date.now());}},deleteImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.images=a.images.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateImage(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload);if(t){let r={...t,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.images.push(r),a.updatedAt=Date.now();}}},addVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.videos.push(t),a.updatedAt=Date.now();}},updateVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.videos.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.videos[t]={...a.videos[t],...o.payload},a.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.videos.find(r=>r.id===o.payload);t&&(t.isPlaying=!t.isPlaying,a.updatedAt=Date.now());}},deleteVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.videos=a.videos.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateVideo(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.videos.find(r=>r.id===o.payload);if(t){let r={...t,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,isPlaying:false,timestamp:Date.now()};a.videos.push(r),a.updatedAt=Date.now();}}},addShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.shapes?.push(t),a.updatedAt=Date.now();}},updateShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shapes.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.shapes[t]={...a.shapes[t],...o.payload},a.updatedAt=Date.now());}},duplicateShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shapes.find(r=>r.id===o.payload);if(t){let r={...t,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.shapes.push(r),a.updatedAt=Date.now();}}},deleteShape(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.shapes=a.shapes.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},addMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.multipleChoices||(a.multipleChoices=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.multipleChoices.length>0){let r=a.multipleChoices[a.multipleChoices.length-1];t.x=r.x+20,t.y=r.y+20;}a.multipleChoices.push(t),a.updatedAt=Date.now();}},updateMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a&&a.multipleChoices){let t=a.multipleChoices.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.multipleChoices[t]={...a.multipleChoices[t],...o.payload},a.updatedAt=Date.now());}},editMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a&&a.multipleChoices){let t=a.multipleChoices.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.multipleChoices[t]={...a.multipleChoices[t],...o.payload},a.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.multipleChoices.find(r=>r.id===o.payload);if(t){let r={...t,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.multipleChoices.push(r),a.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.multipleChoices=a.multipleChoices.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},addTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.trueFalses||(a.trueFalses=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.trueFalses.length>0){let r=a.trueFalses[a.trueFalses.length-1];t.x=r.x+20,t.y=r.y+20;}a.trueFalses.push(t),a.updatedAt=Date.now();}},updateTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.trueFalses.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.trueFalses[t]={...a.trueFalses[t],...o.payload},a.updatedAt=Date.now());}},deleteTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.trueFalses=a.trueFalses.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateTrueFalse(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.trueFalses.find(r=>r.id===o.payload);if(t){let r={...t,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.trueFalses.push(r),a.updatedAt=Date.now();}}},addShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.shortAnswers||(a.shortAnswers=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.shortAnswers.length>0){let r=a.shortAnswers[a.shortAnswers.length-1];t.x=r.x+20,t.y=r.y+20;}a.shortAnswers.push(t),a.updatedAt=Date.now();}},updateShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shortAnswers.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.shortAnswers[t]={...a.shortAnswers[t],...o.payload},a.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.shortAnswers.find(r=>r.id===o.payload);if(t){let r={...t,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.shortAnswers.push(r),a.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.shortAnswers=a.shortAnswers.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},addLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.LongAnswer||(a.LongAnswer=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.LongAnswer.length>0){let r=a.LongAnswer[a.LongAnswer.length-1];t.x=r.x+20,t.y=r.y+20;}a.LongAnswer.push(t),a.updatedAt=Date.now();}},updateLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.LongAnswer.find(r=>r.id===o.payload.id);t&&(Object.assign(t,o.payload),a.updatedAt=Date.now());}},deleteLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.LongAnswer=a.LongAnswer.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateLongAnswer(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.LongAnswer.find(r=>r.id===o.payload);if(t){let r={...t,id:`${t.id}-copy-${Date.now()}`,timestamp:Date.now()};a.LongAnswer.push(r),a.updatedAt=Date.now();}}},setShowMcqForm(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.showMcqForm=o.payload,a.updatedAt=Date.now());},setShowFlashcardForm(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.showFlashcardForm=o.payload,a.updatedAt=Date.now());},addFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){a.fillInTheBlanks||(a.fillInTheBlanks=[]);let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.fillInTheBlanks.length>0){let r=a.fillInTheBlanks[a.fillInTheBlanks.length-1];t.x=r.x+20,t.y=r.y+20;}a.fillInTheBlanks.push(t),a.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.fillInTheBlanks[t]={...a.fillInTheBlanks[t],...o.payload},a.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.fillInTheBlanks=a.fillInTheBlanks.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.fillInTheBlanks.find(r=>r.id===o.payload);if(t){let r={...t,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.fillInTheBlanks.push(r),a.updatedAt=Date.now();}}},setActivityType(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.activityType=o.payload,a.updatedAt=Date.now());},setEditingActivity(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.editingActivity=o.payload,a.updatedAt=Date.now());},bringToFront(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r}=o.payload;if(r==="image"){let i=a.images.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.images.splice(i,1);a.images.push(n);}}else if(r==="video"){let i=a.videos.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.videos.splice(i,1);a.videos.push(n);}}else if(r==="shape"){let i=a.shapes.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.shapes.splice(i,1);a.shapes.push(n);}}else if(r==="flashcard"){let i=a.flashcards.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.flashcards.splice(i,1);a.flashcards.push(n);}}else if(r==="photoFrame"){let i=a.photoFrames.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.photoFrames.splice(i,1);a.photoFrames.push(n);}}else if(r==="text"){let i=a.texts.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.texts.splice(i,1);a.texts.push(n);}}else if(r==="trueFalse"){let i=a.trueFalses.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.trueFalses.splice(i,1);a.trueFalses.push(n);}}else if(r==="shortAnswer"){let i=a.shortAnswers.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.shortAnswers.splice(i,1);a.shortAnswers.push(n);}}else if(r==="fillInTheBlanks"){let i=a.fillInTheBlanks.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.fillInTheBlanks.splice(i,1);a.fillInTheBlanks.push(n);}}a.updatedAt=Date.now();}},sendToBack(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r}=o.payload;if(r==="image"){let i=a.images.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.images.splice(i,1);a.images.unshift(n);}}else if(r==="video"){let i=a.videos.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.videos.splice(i,1);a.videos.unshift(n);}}else if(r==="shape"){let i=a.shapes.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.shapes.splice(i,1);a.shapes.unshift(n);}}else if(r==="flashcard"){let i=a.flashcards.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.flashcards.splice(i,1);a.flashcards.unshift(n);}}else if(r==="photoFrame"){let i=a.photoFrames.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.photoFrames.splice(i,1);a.photoFrames.unshift(n);}}else if(r==="text"){let i=a.texts.findIndex(n=>n.id===t);if(i!==-1){let[n]=a.texts.splice(i,1);a.texts.unshift(n);}}a.updatedAt=Date.now();}},toggleLock(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r}=o.payload,n=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(u=>u.id===t);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),a.updatedAt=Date.now());}},setLink(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,link:i}=o.payload,u=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="mcq"?a.multipleChoices:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(c=>c.id===t);u&&(u.link=i,a.updatedAt=Date.now());}},setAltText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,altText:i}=o.payload,u=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(c=>c.id===t);u&&(u.altText=i,a.updatedAt=Date.now());}},setAudioData(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let{id:t,type:r,audioData:i}=o.payload,u=(r==="image"?a.images:r==="video"?a.videos:r==="shape"?a.shapes:r==="flashcard"?a.flashcards:r==="photoFrame"?a.photoFrames:r==="trueFalse"?a.trueFalses:r==="shortAnswer"?a.shortAnswers:r==="fillInTheBlanks"?a.fillInTheBlanks:a.texts).find(c=>c.id===t);u&&(u.audioData=i,a.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(a=>a.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.updatedAt=Date.now());},addText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.texts.push(t),a.updatedAt=Date.now();}},updateText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.texts.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.texts[t]={...a.texts[t],...o.payload},a.updatedAt=Date.now());}},deleteText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.texts=a.texts.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateText(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.texts.find(r=>r.id===o.payload);if(t){let r={...t,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,timestamp:Date.now()};a.texts.push(r),a.updatedAt=Date.now();}}},addFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(a.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}a.flashcards.push(t),a.updatedAt=Date.now();}},updateFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.flashcards[t]={...a.flashcards[t],...o.payload},a.updatedAt=Date.now());}},deleteFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.flashcards=a.flashcards.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicateFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.find(r=>r.id===o.payload);if(t){let r={...t,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,currentIndex:0,timestamp:Date.now()};a.flashcards.push(r),a.updatedAt=Date.now();}}},editFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.editingFlashcard=o.payload);},nextFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.find(r=>r.id===o.payload);if(t&&t.images.length>0){if(t.order==="sequential")t.currentIndex=(t.currentIndex+1)%t.images.length;else {t.navigationHistory||(t.navigationHistory=[t.currentIndex]);let r=t.images.map((i,n)=>n).filter(i=>i!==t.currentIndex);if(r.length>0){let i=r[Math.floor(Math.random()*r.length)];t.navigationHistory.push(i),t.currentIndex=i;}}a.updatedAt=Date.now();}}},previousFlashcard(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.flashcards.find(r=>r.id===o.payload);t&&t.images.length>0&&(t.order==="sequential"?t.currentIndex=(t.currentIndex-1+t.images.length)%t.images.length:t.navigationHistory&&t.navigationHistory.length>1&&(t.navigationHistory.pop(),t.currentIndex=t.navigationHistory[t.navigationHistory.length-1]),a.updatedAt=Date.now());}},addPhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t={...o.payload,timestamp:o.payload.timestamp||Date.now()};a.photoFrames.push(t),a.updatedAt=Date.now();}},updatePhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.findIndex(r=>r.id===o.payload.id);t!==-1&&(a.photoFrames[t]={...a.photoFrames[t],...o.payload},a.updatedAt=Date.now());}},deletePhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);a&&(a.photoFrames=a.photoFrames.filter(t=>t.id!==o.payload),a.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload);if(t){let r={...t,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:t.x+20,y:t.y+20,isCapturing:false,timestamp:Date.now()};a.photoFrames.push(r),a.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload);t&&(t.isDrawingMode=!t.isDrawingMode,t.annotations||(t.annotations=[]),a.updatedAt=Date.now());}},addImageAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload.imageId);t&&(t.annotations||(t.annotations=[]),t.annotations.push(o.payload.line),a.updatedAt=Date.now());}},updateImageAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload.imageId);t&&t.annotations&&t.annotations.length>0&&(t.annotations[t.annotations.length-1].points=o.payload.points,a.updatedAt=Date.now());}},clearImageAnnotations(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.images.find(r=>r.id===o.payload);t&&(t.annotations=[],a.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload);t&&(t.isDrawingMode=!t.isDrawingMode,t.annotations||(t.annotations=[]),a.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload.frameId);t&&(t.annotations||(t.annotations=[]),t.annotations.push(o.payload.line),a.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload.frameId);t&&t.annotations&&t.annotations.length>0&&(t.annotations[t.annotations.length-1].points=o.payload.points,a.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let a=e.slides.find(t=>t.id===e.currentSlideId);if(a){let t=a.photoFrames.find(r=>r.id===o.payload);t&&(t.annotations=[],a.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let a=e.slides.findIndex(t=>t.id===e.currentSlideId);if(a>=0)try{let t=e.slides[a];o.future.unshift(JSON.parse(JSON.stringify(t)));let r=o.past.pop();e.slides[a]=r;}catch(t){console.warn("Failed to undo - data too large:",t),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let a=e.slides.findIndex(t=>t.id===e.currentSlideId);if(a>=0)try{let t=e.slides[a];o.past.push(JSON.parse(JSON.stringify(t)));let r=o.future.shift();e.slides[a]=r;}catch(t){console.warn("Failed to redo - data too large:",t),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(a=>a.id===e.currentSlideId);if(o>=0){let a=e.slides[o],t=e.history[e.currentSlideId];if(t)try{let r=JSON.parse(JSON.stringify(a));t.past.push(r),t.future=[],t.past.length>20&&t.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),t.past.length>5&&(t.past=t.past.slice(-5)),t.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;}}}),{addSlide:jr,deleteSlide:Xr,duplicateSlide:$r,setCurrentSlide:_r,updateSlideThumbnail:Yr,setBackgroundColor:Jr,reorderSlides:hu,loadSlides:Qr,addLine:Zr,removeLine:jo,addImage:es,updateImage:Ia,deleteImage:ts,duplicateImage:Xo,addVideo:$o,updateVideo:_o,deleteVideo:as,duplicateVideo:Yo,toggleVideoPlaying:Ga,addShape:os,updateShape:wa,duplicateShape:Jo,deleteShape:rs,addText:ss,updateText:st,deleteText:ns,duplicateText:Qo,addFlashcard:is,updateFlashcard:Sa,deleteFlashcard:ls,duplicateFlashcard:Zo,editFlashcard:ja,nextFlashcard:ds,previousFlashcard:us,addPhotoFrame:cs,updatePhotoFrame:la,deletePhotoFrame:fs,duplicatePhotoFrame:er,toggleImageDrawingMode:ms,addImageAnnotation:ps,updateImageAnnotation:gu,clearImageAnnotations:xu,togglePhotoFrameDrawingMode:hs,addPhotoFrameAnnotation:gs,updatePhotoFrameAnnotation:bu,clearPhotoFrameAnnotations:vu,addMultipleChoice:xs,updateMultipleChoice:Ht,editMultipleChoice:Lu,deleteMultipleChoice:bs,duplicateMultipleChoice:tr,addTrueFalse:vs,updateTrueFalse:Ut,deleteTrueFalse:Ls,duplicateTrueFalse:ar,addShortAnswer:ys,updateShortAnswer:Xa,deleteShortAnswer:Is,duplicateShortAnswer:or,addLongAnswer:ws,updateLongAnswer:$a,deleteLongAnswer:Ss,duplicateLongAnswer:rr,addFillInTheBlanks:Cs,updateFillInTheBlanks:_a,deleteFillInTheBlanks:ks,duplicateFillInTheBlanks:sr,setShowMcqForm:Wt,setShowFlashcardForm:da,setActivityType:Ms,setEditingActivity:Ya,bringToFront:As,sendToBack:Ds,toggleLock:Ts,setLink:nr,setAltText:ir,setAudioData:lr,updateLastLine:yu,finalizeDrawing:Fs,setLines:Iu,updateLinePosition:wu,updateLineTransform:dr,deleteLineById:Ps,duplicateLine:Es,updateElementOrder:Ja,clearCanvas:Rs,undo:Bs,redo:Os,saveToHistory:oe,toggleSketchMode:Su,setSketchMode:Xe,setEditingTextId:Qa}=ni.actions,Za=e=>e.canvas.currentSlideId,ce=e=>{let o=e.canvas.currentSlideId,a=e.canvas.slides.findIndex(t=>t.id===o);return a>=0?e.canvas.slides[a]:void 0},eo=e=>e.canvas.slides,qs=e=>e.canvas.slides.length<Gr,Cu=e=>o=>{let a=o.canvas.slides.findIndex(t=>t.id===e);return a>=0?o.canvas.slides[a]:void 0},ii=ni.reducer;var di=e=>{let o=pe(),a=useRef(null),t=useRef(false),r=$(d=>d.toolbar.selectedTool),i=$(d=>d.toolbar.penColor),n=$(d=>d.toolbar.strokeWidth),u=$(d=>d.canvas.isSketchMode),c=$(d=>d.canvas.slides.find(x=>x.id===d.canvas.currentSlideId)?.lines||[]),s=useCallback(d=>{a.current=d;},[]),l=useCallback(d=>{r==="pen"&&a.current&&(o(oe()),a.current.startDrawing(d),t.current=true);},[r,o]),p=useCallback(d=>{!a.current||!t.current||a.current.draw(d);},[]),f=useCallback(()=>{if(!a.current||!t.current)return;let d=a.current.stopDrawing();t.current=false,d&&d.points.length>=4&&o(Zr(d)),o(Fs()),e?.();},[o,e]);return {lines:c,tool:r,color:i,strokeWidth:n,isSketchMode:u,setCanvasRef:s,startDrawing:l,draw:p,stopDrawing:f}};var mi=forwardRef(({width:e,height:o,tool:a,color:t,strokeWidth:r,isSketchMode:i,style:n},u)=>{let c=useRef(null),s=useRef(false),l=useRef([]),p=useRef(null),f=useRef(a),d=useRef(t),m=useRef(r),x=useRef(i);useEffect(()=>{f.current=a,d.current=t,m.current=r,x.current=i;},[a,t,r,i]);let g=useCallback(()=>{let h=c.current;if(!h)return;let b=h.getContext("2d");b&&b.clearRect(0,0,h.width,h.height);},[]),y=useCallback(()=>{let h=c.current,b=l.current;if(!h||b.length<1)return;let L=h.getContext("2d");if(!L)return;if(L.clearRect(0,0,h.width,h.height),f.current==="eraser"?(L.globalCompositeOperation="destination-out",L.fillStyle="rgba(0,0,0,1)"):(L.globalCompositeOperation="source-over",L.fillStyle=d.current),b.length===1){L.beginPath(),L.arc(b[0].x,b[0].y,m.current/2,0,Math.PI*2),L.fill();return}let I=fi(b,{size:m.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:k=>k,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(I.length<2)){L.beginPath(),L.moveTo(I[0][0],I[0][1]);for(let k=1;k<I.length;k++)L.lineTo(I[k][0],I[k][1]);L.closePath(),L.fill();}},[]);return useImperativeHandle(u,()=>({startDrawing:h=>{s.current=true,l.current=[{x:h.x,y:h.y}],p.current=h,y();},draw:h=>{if(!s.current||!p.current)return;let b=h.x-p.current.x,L=h.y-p.current.y;Math.sqrt(b*b+L*L)<2||(l.current.push({x:h.x,y:h.y}),p.current=h,y());},stopDrawing:()=>{if(!s.current)return null;if(s.current=false,l.current.length<2)return l.current=[],p.current=null,g(),null;let b=fi(l.current,{size:m.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:C=>C,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(C=>[C[0],C[1]]),L={tool:f.current,points:b,color:d.current,strokeWidth:m.current,isSketch:true};return l.current=[],p.current=null,g(),L},clear:()=>{g(),l.current=[],p.current=null,s.current=false;},isDrawing:()=>s.current,getCanvasElement:()=>c.current}),[g,y]),useEffect(()=>{let h=c.current;h&&(h.width=e,h.height=o);},[e,o]),jsx("canvas",{ref:c,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});mi.displayName="DirectDrawingCanvas";var pi=mi;var gi=e=>{let o=pe(),t=$(ce)?.images||[],r=useRef(new Map),i=useRef(new Map),n=useRef(new Set);useEffect(()=>{let l=new Set(t.map(p=>p.id));n.current.forEach(p=>{if(!l.has(p)){let f=i.current.get(p);f&&(f.src="",i.current.delete(p)),r.current.delete(p);}}),n.current=l;},[t]),useEffect(()=>()=>{i.current.forEach(l=>{l.src="";}),i.current.clear(),r.current.clear();},[]);let u=useCallback(l=>{if(i.current.has(l.id))return i.current.get(l.id);let p=new window.Image;return p.src=l.src,i.current.set(l.id,p),p},[]),c=useCallback((l,p)=>{let f=l.target,d=f.id();t.find(x=>x.id===d)&&(o(Ia({id:d,x:f.x(),y:f.y(),width:f.width(),height:f.height(),rotation:f.rotation()})),p?.());},[t,o]),s=useCallback((l,p)=>{let f=p.target,d=r.current.get(l);if(!d){console.error("\u274C Image node not found for id:",l);return}let m=f.scaleX(),x=f.scaleY(),g=f.rotation(),y=d.width(),h=d.height(),b=Math.max(5,y*m),L=Math.max(5,h*x);f.scaleX(1),f.scaleY(1),d.width(b),d.height(L),o(Ia({id:l,width:b,height:L,x:f.x(),y:f.y(),rotation:g})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:t,getLoadedImage:u,imageRefs:r,handleDragEnd:c,handleImageTransformEnd:s}};var xi=e=>{let o=useDispatch(),a=useSelector(ce),t=useRef(new Map),r=useMemo(()=>a?.multipleChoices||[],[a?.multipleChoices]),i=useCallback((u,c)=>{let s=c.target,l=s.scaleX(),p=s.scaleY(),f=s.rotation(),d=Math.max(5,s.width()*l),m=Math.max(5,s.height()*p);s.scaleX(1),s.scaleY(1),s.width(d),s.height(m),o(Ht({id:u,width:d,height:m,x:s.x(),y:s.y(),rotation:f})),s.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:i,mcqRefs:t,handleDragEnd:(u,c)=>{o(Ht({id:c,x:u.target.x(),y:u.target.y()})),e?.();}}};var bi=e=>{let o=useDispatch(),a=useSelector(ce),t=useRef(new Map),r=useMemo(()=>a?.trueFalses||[],[a?.trueFalses]),i=useCallback((u,c)=>{let s=c.target,l=s.scaleX(),p=s.scaleY(),f=s.rotation(),d=Math.max(5,s.width()*l),m=Math.max(5,s.height()*p);s.scaleX(1),s.scaleY(1),s.width(d),s.height(m),o(Ut({id:u,width:d,height:m,x:s.x(),y:s.y(),rotation:f})),s.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:i,handleTrueFalseDragEnd:(u,c)=>{o(Ut({id:c,x:u.target.x(),y:u.target.y()})),e?.();},trueFalseRefs:t}};var vi=e=>{let o=pe(),t=$(ce)?.videos||[],r=useRef(new Map),i=useCallback(c=>{o(Ga(c));},[o]),n=useCallback((c,s)=>{let l=s.target;o(_o({id:c,x:l.x(),y:l.y()})),e?.();},[o,e]),u=useCallback((c,s)=>{let l=s.target,p=l.scaleX(),f=l.scaleY(),d=l.rotation(),m=Math.max(5,l.width()*p),x=Math.max(5,l.height()*f);l.scaleX(1),l.scaleY(1),l.width(m),l.height(x),o(_o({id:c,width:m,height:x,x:l.x(),y:l.y(),rotation:d})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:t,videoRefs:r,handleVideoClick:i,handleVideoDragEnd:n,handleVideoTransformEnd:u}};var Ii=e=>{let o=pe(),t=$(ce)?.shapes||[],r=useRef(new Map),i=useRef(new Map),[n,u]=useState(false),c=useCallback((l,p)=>{let f=p.target;o(wa({id:l,x:f.x(),y:f.y()})),e?.();},[o,e]),s=useCallback((l,p)=>{let f=p.target,d=t.find(b=>b.id===l);if(!d)return;let m=f.scaleX(),x=f.scaleY(),g=d.type?.toLowerCase();g==="arrow"||g==="line"||(f.scaleX(1),f.scaleY(1));let h={id:l,x:f.x(),y:f.y(),width:Math.max(5,f.width()*m),height:Math.max(5,f.height()*x),rotation:f.rotation()};switch(g){case "circle":h.radius=f.width()*m/2;break;case "star":h.innerRadius=f.width()*m/4,h.outerRadius=f.width()*m/2;break;case "triangle":h.radius=f.width()*m/2;break;case "ellipse":h.radiusX=f.width()*m/2,h.radiusY=f.height()*x/2;break;case "polygon":h.radius=f.width()*m/2;break;case "ring":let b=m;h.innerRadius=d.innerRadius&&d.innerRadius*b,h.outerRadius=d.outerRadius&&d.outerRadius*b;break;case "wedge":h.radius=d.radius&&d.radius*m;break;case "arc":h.innerRadius=d.innerRadius&&d.innerRadius*m,h.outerRadius=d.outerRadius&&d.outerRadius*m;break;case "arrow":case "line":{h.scaleX=m,h.scaleY=x,delete h.width,delete h.height;break}}o(wa(h)),e?.();},[o,e,t]);return {shapes:t,shapeRefs:r,isDragging:n,loadedShapesRef:i,handleShapeDragEnd:c,handleShapeResizeEnd:s}};var Si=(e,o)=>{let a=yt(),r=$(ce)?.texts||[],i=useRef(new Map),[n,u]=useState(null),[c,s]=useState("");return {texts:r,textRefs:i,handleDragEnd:(g,y)=>{let h=g.target;a(oe()),a(st({id:y,x:h.x(),y:h.y()})),e();},handleTransformEnd:g=>{let y=i.current.get(g);if(!y)return;let h=y.scaleX(),b=y.scaleY(),L=r.find(I=>I.id===g);if(!L)return;let C=(h+b)/2;y.scaleX(1),y.scaleY(1),a(oe()),a(st({id:g,x:y.x(),y:y.y(),width:Math.max(5,(L.width||100)*h),height:Math.max(5,(L.height||50)*b),fontSize:Math.round(Math.max(8,L.fontSize*C)),rotation:y.rotation()})),e();},handleDoubleClick:g=>{let y=r.find(h=>h.id===g);y&&!y.locked&&(u(g),s(y.text));},startEditing:g=>{let y=r.find(h=>h.id===g);y&&!y.locked&&(u(g),s(y.text));},editingTextId:n,editingValue:c,handleEditingChange:g=>{s(g);},finishEditing:()=>{if(n){let g=i.current.get(n),y=r.find(b=>b.id===n);a(oe());let h={id:n,text:c};if(y&&(y.fontWeight!==void 0&&(h.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(h.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(h.textDecoration=y.textDecoration)),o?.current&&c.trim()){let b=o.current,L=b.offsetWidth,C=b.offsetHeight,I=1;if(g){let G=g.getStage();G&&(I=G.scaleX());}let k=14,w=(L-k)/I,q=(C-k)/I,U=c.split(`
3
+ `).length,R=r.find(G=>G.id===n)?.fontSize||24,T=U*R*1.2+10;h.width=Math.max(200,w),h.height=Math.max(50,q,T);}else if(g&&c.trim()){let b=g.text(),L=g.width();g.text(c),g.width(void 0);let C=g.width(),I=g.height();g.text(b),g.width(L),h.width=Math.max(200,C+20),h.height=Math.max(50,I+20);}a(st(h)),u(null),s(""),a(Qa(null)),e();}}}};var Ci=e=>{let o=useDispatch(),t=useSelector(ce)?.shortAnswers||[],r=useRef(new Map),i=useCallback((n,u)=>{let c=n.target;o(Xa({id:u,x:c.x(),y:c.y()})),e?.();},[o,e]);return {shortAnswers:t,saRefs:r,handleShortAnswerDragEnd:i}};var ki=e=>{let o=useDispatch(),a=useSelector(ce),t=useMemo(()=>a?.LongAnswer||[],[a?.LongAnswer]),r=useCallback((i,n)=>{let u=i.target;o($a({id:n,x:u.x(),y:u.y()})),e?.();},[o,e]);return {longAnswers:t,handleLongAnswerDragEnd:r}};var Ai=e=>{let o=pe(),t=$(ce)?.flashcards||[],r=useRef(new Map),i=useRef(new Map),n=useCallback((p,f)=>{if(i.current.has(f))return i.current.get(f);let d=new window.Image;return d.src=p,i.current.set(f,d),d},[]),u=useCallback((p,f)=>{let d=p.target,m=d.id();t.find(g=>g.id===m)&&(o(Sa({id:m,x:d.x(),y:d.y()})),f?.());},[t,o]),c=useCallback((p,f)=>{let d=f.target,m=d.scaleX(),x=d.scaleY(),g=d.rotation(),y=Math.max(50,d.width()*m),h=Math.max(50,d.height()*x);d.scaleX(1),d.scaleY(1),d.width(y),d.height(h),o(Sa({id:p,width:y,height:h,x:d.x(),y:d.y(),rotation:g})),d.getLayer()?.batchDraw(),e?.();},[o,e]),s=useCallback(p=>{o(ds(p)),e?.();},[o,e]),l=useCallback(p=>{o(us(p)),e?.();},[o,e]);return {flashcards:t,getLoadedImage:n,flashcardRefs:r,handleDragEnd:u,handleFlashcardTransformEnd:c,handleNext:s,handlePrevious:l}};var Fi=e=>{let o=pe(),t=$(ce)?.photoFrames||[],r=useRef(new Map),[i,n]=useState(new Map),u=useCallback((d,m)=>{console.log("handleDragEnd"),o(la({id:m,x:d.target.x(),y:d.target.y()})),e?.();},[o,e]),c=useCallback((d,m)=>{let x=m.target,g=x.scaleX(),y=x.scaleY(),h=x.rotation(),b=t.find(I=>I.id===d);if(!b)return;let L=Math.max(100,b.width*g),C=Math.max(100,b.height*y);x.scaleX(1),x.scaleY(1),o(la({id:d,width:L,height:C,x:x.x(),y:x.y(),rotation:h})),x.getLayer()?.batchDraw(),e?.();},[o,e,t]),s=useCallback(async d=>{try{let m=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(x=>{let g=new Map(x);return g.set(d,m),g}),o(la({id:d,isCapturing:!0})),e?.(),m}catch(m){return console.error("Error accessing camera:",m),null}},[o,e]),l=useCallback(d=>{let m=i.get(d);m&&(m.getTracks().forEach(x=>x.stop()),n(x=>{let g=new Map(x);return g.delete(d),g}),o(la({id:d,isCapturing:false})),e?.());},[i,o,e]),p=useCallback((d,m)=>{let x=document.createElement("canvas");x.width=m.videoWidth,x.height=m.videoHeight;let g=x.getContext("2d");if(g){g.drawImage(m,0,0,x.width,x.height);let y=x.toDataURL("image/jpeg",.8);return o(la({id:d,capturedImageUrl:y,isCapturing:false})),l(d),e?.(),y}return null},[o,l,e]),f=useRef(i);return useEffect(()=>{f.current=i;},[i]),useEffect(()=>()=>{f.current.forEach(d=>{d.getTracks().forEach(m=>m.stop());});},[]),{photoFrames:t,photoFrameRefs:r,handleDragEnd:u,handlePhotoFrameTransformEnd:c,startCamera:s,stopCamera:l,capturePhoto:p,cameraStreams:i}};var Pi=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),a=useCallback((i,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),t=useCallback((i,n,u,c,s,l,p=[])=>{if(e.current){if(i&&!p.find(m=>m.id===i)?.isPlaying){let m=n.get(i)||u.get(i)||c.get(i)||s.get(i)||l.get(i);if(m){e.current.boundBoxFunc(a),e.current.nodes([m]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:t,deselectTransformer:r,boundBoxFunc:a}};var Zu=(e,o)=>{let a=useRef(void 0);return useEffect(()=>()=>{a.current&&clearTimeout(a.current);},[]),useCallback((...t)=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{e(...t);},o);},[o])},Oi=(e,o)=>{let a=yt(),t=useRef(e);useEffect(()=>{t.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:.2,mimeType:"image/jpeg",quality:.6});a(Yr({id:t.current,thumbnail:n}));}catch(n){console.error("Error generating thumbnail:",n);}},[o,a]),i=Zu(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:i}};var tc=e=>e.flatMap(o=>[o[0],o[1]]),cr=(e,o)=>{let a=fi(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:t=>t,start:{taper:0,cap:true},end:{taper:0,cap:true}});return tc(a)};var qi=e=>{let o=pe(),a=useRef(false),t=useRef(false),r=useRef([]),[i,n]=useState(null),u=$(b=>b.toolbar.selectedTool),c=$(b=>b.toolbar.penColor),s=$(b=>b.toolbar.strokeWidth),l=$(b=>b.canvas.isSketchMode),p=$(b=>b.canvas.slides.find(C=>C.id===b.canvas.currentSlideId)?.images.find(C=>C.id===e)),f=p?.annotations||[],d=p?.isDrawingMode||false,m=p?.width||1,x=p?.height||1,g=useCallback(b=>{if(u!=="pen"&&u!=="eraser")return;a.current=true,t.current=false,r.current=[{x:b.x,y:b.y}];let L=b.x/m,C=b.y/x;n({tool:u,points:[L,C],color:c,strokeWidth:s/m,isSketch:l});},[u,c,s,l,m,x]),y=useCallback(b=>{if(!a.current||!i)return;t.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-L.x,2)+Math.pow(b.y-L.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(l)I=cr(r.current,{size:s*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,q)=>q%2===0?w/m:w/x);else {let k=b.x/m,w=b.y/x;I=[...i.points,k,w];}n(k=>k?{...k,points:I}:null);},[l,s,i,m,x]),h=useCallback(()=>{a.current&&(i&&i.points.length>0&&o(ps({imageId:e,line:i})),n(null),a.current=false,t.current=false,r.current=[]);},[o,e,i]);return {annotations:f,activeLine:i,isDrawingMode:d,startDrawing:g,draw:y,stopDrawing:h,tool:u}};var Ui=memo(({img:e,loadedImage:o,imageRefs:a,onDragEnd:t,onTransform:r,onSelect:i,onContextMenu:n})=>{let{annotations:u,activeLine:c,stopDrawing:f,tool:d}=qi(e.id);useEffect(()=>{let h=a.current.get(e.id);h&&(h.width()!==e.width||h.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:h.width(),konvaHeight:h.height()}),h.width(e.width),h.height(e.height),h.getLayer()?.batchDraw());},[e.id,e.width,e.height,a]);let m=false;useEffect(()=>{return;},[f,m]);let x=h=>{{i(e.id);return}},g=h=>{return;},y=h=>{};return jsxs(Group,{listening:d!=="pen"&&d!=="eraser",children:[jsx(Image,{id:e.id,ref:h=>{if(h){a.current.set(e.id,h),h.width(e.width),h.height(e.height),h.getLayer()?.batchDraw();let b=h.getStage()?.container();if(b){let L=C=>{let I=h.getStage()?.getPointerPosition();if(I){let k={x:e.x,y:e.y,width:e.width,height:e.height};I.x>=k.x&&I.x<=k.x+k.width&&I.y>=k.y&&I.y<=k.y+k.height&&n(C,e.id,"image");}};b.addEventListener("contextmenu",L),h._contextMenuCleanup=()=>{b.removeEventListener("contextmenu",L);};}}else {let b=a.current.get(e.id);b?._contextMenuCleanup&&b._contextMenuCleanup(),a.current.delete(e.id);}},rotation:e.rotation,draggable:d!=="pen"&&d!=="eraser",onDragEnd:t,onTransformEnd:h=>r(e.id,h),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...d!=="pen"&&d!=="eraser"?{onClick:x,onTap:x,onMouseDown:x,onTouchStart:x,onMouseMove:g,onTouchMove:g,onMouseUp:y,onTouchEnd:y}:{}}),u?.map((h,b)=>{let L=h.points.map((I,k)=>k%2===0?I*e.width+e.x:I*e.height+e.y),C=h.strokeWidth*e.width;return jsx(Line,{points:L,stroke:h.tool==="eraser"?"white":h.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:h.tool==="eraser"?"destination-out":"source-over",fill:h.isSketch?h.color:void 0,closed:h.isSketch,listening:false},b)}),c&&jsx(Line,{points:c.points.map((h,b)=>b%2===0?h*e.width+e.x:h*e.height+e.y),stroke:c.tool==="eraser"?"white":c.color,strokeWidth:c.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:c.tool==="eraser"?"destination-out":"source-over",fill:c.isSketch?c.color:void 0,closed:c.isSketch,listening:false},"active")]})});Ui.displayName="ImageWithDrawing";var zs=memo(({images:e,getLoadedImage:o,imageRefs:a,onDragEnd:t,onTransform:r,onSelect:i,onContextMenu:n})=>jsx(Fragment,{children:e.map(u=>{let c=o(u);return c?jsx(Ui,{img:u,loadedImage:c,imageRefs:a,onDragEnd:t,onTransform:r,onSelect:i,onContextMenu:n},u.id):null})}));zs.displayName="ImageLayer";var cc=({src:e,x:o,id:a,y:t,width:r,height:i,isSelected:n,rotation:u=0,onTransformEnd:c,onDragEnd:s})=>{let l=pe(),p=useRef(null),f=d=>{l(Ga(d));};return jsxs(Group,{draggable:true,x:o,y:t,width:r,height:i,rotation:u,onDragEnd:s,onTransformEnd:c,children:[jsx(Rect,{width:r,height:i,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${i}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:p,src:e,controls:true,autoPlay:true,onClick:()=>f(a),onSeeking:d=>d.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Wi=cc;var vc=({video:e,isSelected:o,onClick:a,onDragEnd:t,onTransformEnd:r,onContextMenu:i,nodeRef:n})=>{let[u,c]=useState(null),s=useSelector(x=>x.toolbar.selectedTool),l=s==="pen"||s==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let x=new window.Image;x.src=e.thumbnailDataUrl,x.onload=()=>{c(x);};}},[e.thumbnailDataUrl]),!u)return null;let p=e.width/2,f=e.height/2,d=Math.min(e.width,e.height)*.08,m=Math.max(40,Math.min(d,80));return jsxs(Group,{draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...l?{}:{onDragEnd:t,onTransformEnd:r},ref:x=>{if(n(x),x){let g=x.getStage()?.container();if(g){let y=h=>{let b=x.getStage()?.getPointerPosition();if(b){let L={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=L.x&&b.x<=L.x+L.width&&b.y>=L.y&&b.y<=L.y+L.height&&i(h);}};g.addEventListener("contextmenu",y),x._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",y);};}}},children:[jsx(Image,{image:u,width:e.width,height:e.height,listening:!l,...l?{}:{onClick:a,onTap:a},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:p,y:f,radius:m,fill:"white",listening:!l,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...l?{}:{onClick:a,onTap:a}}),jsx(Circle,{x:p,y:f,radius:m*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!l,...l?{}:{onClick:a,onTap:a}}),jsx(RegularPolygon,{x:p+m*.1,y:f,sides:3,radius:m*.35,fill:"white",rotation:90,listening:!l,...l?{}:{onClick:a,onTap:a}})]})},zi=vc;var Xs=memo(({videos:e,selectedId:o,videoRefs:a,onVideoClick:t,onDragEnd:r,onTransformEnd:i,onContextMenu:n})=>jsx(Fragment,{children:e.map(u=>jsxs(ut.Fragment,{children:[jsx(zi,{video:u,isSelected:!u.isPlaying&&o===u.id,onClick:()=>t(u.id),onDragEnd:c=>r(u.id,c),onTransformEnd:c=>i(u.id,c),onContextMenu:c=>n(c,u.id,"video"),nodeRef:c=>{c?a.current.set(u.id,c):a.current.delete(u.id);}}),u.isPlaying&&(()=>{let c=u.x,s=u.y;if(u.isRecorded){let l=typeof window<"u"?window.innerWidth:u.width,p=typeof window<"u"?window.innerHeight:u.height;c=(l-u.width)/2,s=(p-u.height)/2;}return jsx(Wi,{id:u.id,src:u.objectUrl,x:c,y:s,width:u.width,height:u.height,isSelected:false,rotation:u.rotation,onTransformEnd:l=>i(u.id,l),onDragEnd:l=>r(u.id,l)})})()]},u.id))}));Xs.displayName="VideoLayer";var $s=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:a,handleShapeResizeEnd:t,onSelect:r,handleShapeDragStart:i,onContextMenu:n})=>{let u=useSelector(s=>s.toolbar.selectedTool),c=u==="pen"||u==="eraser";return jsx(Fragment,{children:e.map((s,l)=>{let p=s.id||l,f={id:s.id,x:s.x,y:s.y,rotation:s.rotation,draggable:!s.locked&&!c,listening:!c,fill:s.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(s.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},radius:s.radius||s.width/2,width:s.width,height:s.width},p);case "star":return jsx(Star,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},numPoints:5,innerRadius:s.innerRadius||s.width/4,outerRadius:s.outerRadius||s.width/2},p);case "triangle":return jsx(RegularPolygon,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},sides:3,radius:s.radius||s.width/2},p);case "polygon":return jsx(RegularPolygon,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},sides:s.sides||6,radius:s.radius||s.width/2},p);case "ellipse":return jsx(Ellipse,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},radiusX:s.radiusX||s.width/2,radiusY:s.radiusY||s.height/2},p);case "ring":return jsx(Ring,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},innerRadius:s.innerRadius||s.width/4,outerRadius:s.outerRadius||s.width/2},p);case "wedge":return jsx(Wedge,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},radius:s.radius||s.width/2,angle:s.angle||60},p);case "arrow":return jsx(Arrow,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,scaleX:s.scaleX||1,scaleY:s.scaleY||1,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},points:s.points||[0,0,s.width,0],pointerLength:s.pointerLength||10,pointerWidth:s.pointerWidth||10,stroke:"#000000",strokeWidth:s.strokeWidth||3,fill:"transparent"},p);case "line":return jsx(Line,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,scaleX:s.scaleX||1,scaleY:s.scaleY||1,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},points:s.points||[0,0,s.width,0],stroke:"#000000",strokeWidth:s.strokeWidth||3,fill:"transparent"},p);case "arc":return jsx(Arc,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},innerRadius:s.innerRadius||s.width/4,outerRadius:s.outerRadius||s.width/2,angle:s.angle||90},p);case "rectangle":default:return jsx(Rect,{ref:d=>{d?o.current.set(s.id,d):o.current.delete(s.id);},...f,draggable:!s.locked&&!c,...c?{}:{onDragStart:d=>{i?.();},onDragEnd:d=>a(s.id,d),onTransformEnd:d=>t(s.id,d),onClick:()=>r(s.id),onContextMenu:d=>{d.evt.preventDefault(),n(d.evt,s.id,"shape");}},width:s.width,height:s.height,cornerRadius:s.type==="rounded-rectangle"?10:0},p)}})})});$s.displayName="ShapeLayer";var Xi=({texts:e,textRefs:o,onDragEnd:a,onTransformEnd:t,onSelect:r,onContextMenu:i,onDoubleClick:n,editingTextId:u})=>{let c=useSelector(l=>l.toolbar.selectedTool),s=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map(l=>{let p=l.id===u,f=l.fontWeight==="bold",d=f?Math.max(1,l.fontSize/25):0;return jsx(Text,{id:l.id,ref:m=>{m?o.current.set(l.id,m):o.current.delete(l.id);},text:l.text,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:!l.locked&&!p&&!s,listening:!s,fontSize:l.fontSize,fontFamily:l.fontFamily,fontStyle:l.fontStyle,fontWeight:l.fontWeight,textDecoration:l.textDecoration,fill:l.fill,stroke:f?l.fill:void 0,strokeWidth:d,align:l.align,wrap:"none",lineHeight:1.2,opacity:p?0:1,visible:!p,...s?{}:{onClick:()=>r(l.id),onTap:()=>r(l.id),onDblClick:()=>n(l.id),onDblTap:()=>n(l.id),onDragEnd:m=>a(m,l.id),onTransformEnd:()=>t(l.id),onContextMenu:m=>{m.evt.preventDefault();let x=m.evt;i(x,l.id,"text");}}},l.id)})})};var zc=({flashcard:e,isSelected:o,onClick:a,onDragEnd:t,onTransformEnd:r,onContextMenu:i,onNext:n,onPrevious:u,nodeRef:c})=>{let[s,l]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let g=new window.Image;g.src=e.images[e.currentIndex],g.onload=()=>{l(g);};}},[e.images,e.currentIndex]),!s||e.images.length===0)return null;let p=8,f=2,d=Math.min(e.width,e.height)*.08,m=Math.max(16,Math.min(d,32)),x=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:t,onTransformEnd:r,ref:g=>{if(c(g),g){let y=g.getStage()?.container();if(y){let h=b=>{let L=g.getStage()?.getPointerPosition();if(L){let C={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=C.x&&L.x<=C.x+C.width&&L.y>=C.y&&L.y<=C.y+C.height&&i(b);}};y.addEventListener("contextmenu",h),g._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",h);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:p,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:a,onTap:a}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:p,stroke:"#E5E7EB",strokeWidth:f,listening:false}),jsx(Image,{x:f+4,y:f+4,image:s,width:e.width-(f+4)*2,height:e.height-(f+4)*2,cornerRadius:p-f,onClick:a,onTap:a}),jsx(Rect,{x:f,y:e.height-50,width:e.width-f*2,height:50,cornerRadius:[0,0,p-f,p-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:x+m,y:e.height/2,onClick:g=>{g.cancelBubble=true,u();},onTap:g=>{g.cancelBubble=true,u();},children:[jsx(Circle,{radius:m,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-x-m,y:e.height/2,onClick:g=>{g.cancelBubble=true,n();},onTap:g=>{g.cancelBubble=true,n();},children:[jsx(Circle,{radius:m,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"})]})},Yi=zc;var Js=memo(({flashcards:e,flashcardRefs:o,selectedId:a,onDragEnd:t,onTransform:r,onSelect:i,onNext:n,onPrevious:u,onContextMenu:c})=>jsx(Fragment,{children:e.map(s=>jsx(Yi,{flashcard:s,isSelected:a===s.id,onClick:()=>i(s.id),onDragEnd:t,onTransformEnd:l=>r(s.id,l),onContextMenu:l=>c(l,s.id,"flashcard"),onNext:()=>n(s.id),onPrevious:()=>u(s.id),nodeRef:l=>{l?o.current.set(s.id,l):o.current.delete(s.id);}},s.id))}));Js.displayName="FlashcardLayer";var Qi=e=>{let o=pe(),a=useRef(false),t=useRef(false),r=useRef([]),[i,n]=useState(null);$(b=>b.toolbar.selectedTool);let c=$(b=>b.toolbar.penColor),s=$(b=>b.toolbar.strokeWidth),l=$(b=>b.canvas.isSketchMode),p=$(b=>b.canvas.slides.find(C=>C.id===b.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),f=p?.annotations||[],d=p?.isDrawingMode||false,m=p?.width||1,x=p?.height||1,g=useCallback(b=>{if(!d)return;a.current=true,t.current=false,r.current=[{x:b.x,y:b.y}];let L=b.x/m,C=b.y/x;n({tool:"pen",points:[L,C],color:c,strokeWidth:s/m,isSketch:l});},[d,c,s,l,m,x]),y=useCallback(b=>{if(!a.current||!i)return;t.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(b.x-L.x,2)+Math.pow(b.y-L.y,2))<2)return;r.current.push({x:b.x,y:b.y});let I;if(l)I=cr(r.current,{size:s*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((w,q)=>q%2===0?w/m:w/x);else {let k=b.x/m,w=b.y/x;I=[...i.points,k,w];}n(k=>k?{...k,points:I}:null);},[l,s,i,m,x]),h=useCallback(()=>{a.current&&(i&&i.points.length>0&&o(gs({frameId:e,line:i})),n(null),a.current=false,t.current=false,r.current=[]);},[o,e,i]);return {annotations:f,activeLine:i,isDrawingMode:d,startDrawing:g,draw:y,stopDrawing:h}};var Qc=({photoFrame:e,isSelected:o,onClick:a,onDragEnd:t,onTransformEnd:r,onContextMenu:i,onStartCamera:n,onCapture:u,cameraStream:c,nodeRef:s})=>{let[l,p]=useState(null),[f,d]=useState(null),m=useRef(null),x=useRef(null),g=useRef(null),y=useRef(null),h=useRef(0),b=33,L=useSelector(D=>D.toolbar.selectedTool),C=L==="pen"||L==="eraser",{annotations:I,activeLine:k,isDrawingMode:w,startDrawing:q,draw:U,stopDrawing:O}=Qi(e.id);useEffect(()=>{if(!w)return;let D=()=>{O();},V=()=>{O();};return window.addEventListener("mouseup",D),window.addEventListener("touchend",V),()=>{window.removeEventListener("mouseup",D),window.removeEventListener("touchend",V);}},[O,w]),useEffect(()=>{if(e.capturedImageUrl){let D=new window.Image;D.src=e.capturedImageUrl,D.onload=()=>{p(D);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&c){m.current||(m.current=document.createElement("video"),m.current.autoplay=true,m.current.playsInline=true),x.current||(x.current=document.createElement("canvas"));let D=m.current,V=x.current;D.srcObject=c;let j=()=>{V.width=D.videoWidth||640,V.height=D.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",V.width,V.height);let te=Z=>{if(Z-h.current<b){g.current=requestAnimationFrame(te);return}h.current=Z;let ae=V.getContext("2d");if(ae&&D.readyState===D.HAVE_ENOUGH_DATA){ae.drawImage(D,0,0,V.width,V.height);let Ce=V.toDataURL("image/jpeg",.6),_=new window.Image;_.onload=()=>{d(_);},_.src=Ce;}g.current=requestAnimationFrame(te);};g.current=requestAnimationFrame(te);};return D.onloadedmetadata=j,D.readyState>=D.HAVE_METADATA&&j(),D.play().catch(te=>console.error("Error playing video:",te)),()=>{g.current&&(cancelAnimationFrame(g.current),g.current=null);}}return ()=>{d(null),y.current&&(y.current.src="");}},[e.isCapturing,c]);let R=()=>{m.current&&e.isCapturing&&u(m.current);},E=D=>{if(e.capturedImageUrl){if(!w){a();return}let V=D.currentTarget,j=V.getAbsoluteTransform().copy(),Z=V.getStage()?.getPointerPosition();if(Z){j.invert();let ae=j.point(Z);q(ae);}D.cancelBubble=true;}else a();},T=D=>{if(!w||!e.capturedImageUrl)return;let V=D.currentTarget,j=V.getAbsoluteTransform().copy(),Z=V.getStage()?.getPointerPosition();if(Z){j.invert();let ae=j.point(Z);U(ae);}},G=()=>{!w||!e.capturedImageUrl||O();},z=e.isCapturing?f:l,me=Math.min(e.width,e.height)*.12,J=Math.max(25,Math.min(me,50)),de=e.width/2,N=e.height/2;return jsxs(Group,{id:e.id,draggable:!w&&!C,listening:true,x:e.x,y:e.y,...C?{}:{onDragEnd:t,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:D=>{if(s(D),D){let V=D.getStage()?.container();if(V){let j=te=>{let Z=D.getStage()?.getPointerPosition();if(Z){let ae={x:e.x,y:e.y,width:e.width,height:e.height};Z.x>=ae.x&&Z.x<=ae.x+ae.width&&Z.y>=ae.y&&Z.y<=ae.y+ae.height&&i(te);}};V.addEventListener("contextmenu",j),D._contextMenuCleanup=()=>{V.removeEventListener("contextmenu",j);};}}},children:[jsx(Rect,{x:0,y:0,width:e.width,height:e.height,fill:z?"transparent":"#f0f0f0",stroke:o?"transparent":"#4A90E2",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:a,onTap:a}),z&&jsx(Image,{image:z,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:E,onTap:E,onMouseDown:E,onTouchStart:E,onMouseMove:T,onTouchMove:T,onMouseUp:G,onTouchEnd:G,...C?{}:{onDragEnd:t,onTransformEnd:r}}),I?.map((D,V)=>{let j=D.points.map((Z,ae)=>ae%2===0?Z*e.width:Z*e.height),te=D.strokeWidth*e.width;return jsx(Line,{points:j,stroke:D.tool==="eraser"?"white":D.color,strokeWidth:te,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:D.tool==="eraser"?"destination-out":"source-over",fill:D.isSketch?D.color:void 0,closed:D.isSketch,listening:false},V)}),k&&jsx(Line,{points:k.points.map((D,V)=>V%2===0?D*e.width:D*e.height),stroke:k.tool==="eraser"?"white":k.color,strokeWidth:k.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:k.tool==="eraser"?"destination-out":"source-over",fill:k.isSketch?k.color:void 0,closed:k.isSketch,listening:false},"active"),!z&&!e.isCapturing&&jsx(Text,{x:0,y:N-20,width:e.width,height:40,text:"Click to start camera",fontSize:16,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Circle,{x:de,y:e.height*.75,radius:J,fill:e.isCapturing?"#E74C3C":"#4A90E2",shadowColor:"black",shadowBlur:5,shadowOpacity:.3,listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?R():n();},onTap:D=>{D.cancelBubble=true,e.isCapturing?R():n();}}),jsx(Text,{x:de-J,y:e.height*.75-8,width:J*2,height:16,text:e.isCapturing?"\u{1F4F8}":"\u{1F4F7}",fontSize:20,fontFamily:"Arial",fill:"white",align:"center",verticalAlign:"middle",listening:true,onClick:D=>{D.cancelBubble=true,e.isCapturing?R():n();},onTap:D=>{D.cancelBubble=true,e.isCapturing?R():n();}})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"})]})]})},ol=Qc;var on=memo(({photoFrames:e,photoFrameRefs:o,selectedId:a,onDragEnd:t,onTransform:r,onSelect:i,onStartCamera:n,onCapture:u,cameraStreams:c,onContextMenu:s})=>jsx(Fragment,{children:e.map(l=>jsx(ol,{photoFrame:l,isSelected:a===l.id,onClick:()=>i(l.id),onDragEnd:p=>t(p,l.id),onTransformEnd:p=>r(l.id,p),onContextMenu:p=>s(p,l.id,"photoFrame"),onStartCamera:()=>n(l.id),onCapture:p=>u(l.id,p),cameraStream:c.get(l.id),nodeRef:p=>{p?o.current.set(l.id,p):o.current.delete(l.id);}},l.id))}));on.displayName="PhotoFrameLayer";var ll=({x:e,y:o,onAction:a,onClose:t,type:r,isDrawingMode:i})=>{let n=useRef(null);useEffect(()=>{let s=p=>{n.current&&!n.current.contains(p.target)&&t();},l=p=>{p.key==="Escape"&&t();};return document.addEventListener("mousedown",s),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",l);}},[t]);let u=[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5"})},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5"})},...r==="mcq"||r==="trueFalse"||r==="shortAnswer"||r==="longAnswer"||r==="fillInTheBlanks"?[{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5"})}]:[],...r==="shape"?[{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5"})}]:[],...r==="image"?[{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5"})},{action:"draw",label:i?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5"})}]:[],...r==="photoFrame"?[{action:"draw",label:i?"Exit Drawing Mode":"Draw on Frame",icon:jsx(PencilSimple,{className:"h-5 w-5"})}]:[],...r==="flashcard"?[{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5"})}]:[],{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5"})},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5"})},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5"}),isDanger:true}],c=(s,l)=>{s==="order"||s==="lock"?a(s,l):(a(s),t());};return jsx("div",{ref:n,className:"fixed z-100 min-w-[200px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:u.map((s,l)=>jsxs("button",{onClick:p=>c(s.action,p),className:`flex w-full items-center justify-between px-4 py-2.5 text-left text-sm transition-colors hover:bg-gray-50 ${s.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"} ${l!==0?"border-t border-gray-100":""}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[s.icon,jsx("span",{className:"font-medium",children:s.label})]}),s.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"})})]},s.action))})})};var dl=({x:e,y:o,items:a,onClose:t})=>{let r=useRef(null);return useEffect(()=>{let i=n=>{r.current&&!r.current.contains(n.target)&&t();};return document.addEventListener("mousedown",i),()=>{document.removeEventListener("mousedown",i);}},[t]),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:a.map((i,n)=>jsx("button",{onClick:()=>{i.onClick(),t();},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:i.label})},n))})})};var ul=({title:e,label:o,placeholder:a,defaultValue:t="",onSave:r,onClose:i})=>{let[n,u]=useState(t),c=useRef(null);useEffect(()=>{c.current?.focus();},[]);let s=()=>{r(n),i();};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:i,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:c,type:"text",value:n,onChange:p=>u(p.target.value),onKeyDown:p=>{p.key==="Enter"?s():p.key==="Escape"&&i();},placeholder:a,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:i,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:s,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 cl=({defaultColor:e="#096B76",onConfirm:o,onCancel:a})=>{let[t,r]=useState(e),i=useRef(null);useEffect(()=>{let l=p=>{p.key==="Escape"&&a();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[a]);let n=l=>{l.preventDefault(),o(t);},u=(l,p,f)=>{f/=100;let d=p*Math.min(f,1-f)/100,m=x=>{let g=(x+l/30)%12,y=f-d*Math.max(Math.min(g-3,9-g,1),-1);return Math.round(255*y).toString(16).padStart(2,"0")};return `#${m(0)}${m(8)}${m(4)}`},s=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{ref:i,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:l=>l.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:a,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:n,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:t}}),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:t,onChange:l=>r(l.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:t,onChange:l=>r(l.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:l=>{let p=parseInt(l.target.value),f=u(p,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(l=>jsx("button",{type:"button",onClick:()=>r(l),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${t.toUpperCase()===l.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:l},title:l},l))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:a,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(s,document.body)};var Rf=({imageSrc:e,onCrop:o})=>{let[a]=pl(e),t=useRef(null),r=useRef(null),i=useRef(null),n=useMemo(()=>{if(!a)return {width:600,height:400};let m=Math.min(600/a.width,400/a.height);return {width:a.width*m,height:a.height*m}},[a]),u=useMemo(()=>{let f=n.width*.5,d=n.height*.5,m=(n.width-f)/2,x=(n.height-d)/2;return {x:m,y:x,width:f,height:d}},[n]),[c,s]=useState(u);useEffect(()=>{s(u);},[u]),useEffect(()=>{i.current&&r.current&&(i.current.nodes([r.current]),i.current.getLayer()?.batchDraw());},[c]),useEffect(()=>{o(c.x,c.y,c.width,c.height);},[c,o]);let l=()=>{let f=r.current;if(!f)return;let d=f.scaleX(),m=f.scaleY();f.scaleX(1),f.scaleY(1),s({x:f.x(),y:f.y(),width:Math.max(20,f.width()*d),height:Math.max(20,f.height()*m)});},p=()=>{let f=r.current;f&&s({x:f.x(),y:f.y(),width:f.width(),height:f.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image,{ref:t,image:a,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:c.x,y:c.y,width:c.width,height:c.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:c.x,y:c.y,width:c.width,height:c.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:p,onTransformEnd:l,dragBoundFunc:f=>{let d=Math.max(0,Math.min(f.x,n.width-c.width)),m=Math.max(0,Math.min(f.y,n.height-c.height));return {x:d,y:m}}}),jsx(Transformer,{ref:i,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,d)=>d.width<20||d.height<20||d.x<0||d.y<0||d.x+d.width>n.width||d.y+d.height>n.height?f:d})]})})},hl=({imageSrc:e,onConfirm:o,onCancel:a})=>{let t=useRef(null),[r,i]=useState({x:0,y:0,width:0,height:0}),[n]=pl(e);return useEffect(()=>{let l=p=>{p.key==="Escape"&&a();};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[a]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:l=>l.stopPropagation(),onMouseUp:l=>l.stopPropagation(),onMouseMove:l=>l.stopPropagation(),onTouchStart:l=>l.stopPropagation(),onTouchMove:l=>l.stopPropagation(),onTouchEnd:l=>l.stopPropagation(),children:jsxs("div",{ref:t,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:l=>l.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:a,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(Rf,{imageSrc:e,onCrop:(l,p,f,d)=>{i({x:l,y:p,width:f,height:d});}})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:a,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:()=>{if(!n)return;let f=Math.min(600/n.width,400/n.height),d=r.x/f,m=r.y/f,x=r.width/f,g=r.height/f,y=document.createElement("canvas");y.width=x,y.height=g;let h=y.getContext("2d");if(!h)return;h.drawImage(n,d,m,x,g,0,0,x,g);let b=y.toDataURL("image/png");o(b);},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),document.body)};var no=({onClose:e,stageRef:o,onRecordingComplete:a,directDrawingCanvasRef:t})=>{let[r,i]=useState(false),[n,u]=useState(null),[c,s]=useState(0),[l,p]=useState(true),f=useRef(null),d=useRef([]),m=useRef(null),x=useRef(null),g=useRef(null),y=useRef(null),h=useRef(null),b=useRef(null);useEffect(()=>()=>{g.current&&cancelAnimationFrame(g.current),m.current&&clearInterval(m.current),x.current&&x.current.getTracks().forEach(w=>w.stop());},[]);let L=async()=>{try{let w,q=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((V,j)=>{let te=V.getChildren();console.log(`Layer ${j} children count:`,te.length);});let G=document.createElement("canvas");G.width=o.current.width(),G.height=o.current.height();let z=G.getContext("2d",{willReadFrequently:!1});if(!z){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",G.width,"x",G.height),h.current=G;let me=()=>{if(z.clearRect(0,0,G.width,G.height),T.forEach(V=>{let j=V.getCanvas()._canvas;j&&z.drawImage(j,0,0);}),t?.current){let V=t.current;z.drawImage(V,0,0);}};b.current=me,o.current.draw(),me(),await new Promise(V=>setTimeout(V,100)),console.log("Creating captureStream..."),w=G.captureStream(30),console.log("Canvas stream created, tracks:",w.getTracks().length);let de=w.getVideoTracks()[0];de&&console.log("Video track:",de.label,"state:",de.readyState);let N=0,D=()=>{me(),o?.current&&(o.current.getLayers().forEach(j=>{j.batchDraw();}),N++,N%60===0&&console.log("Drawing frame:",N)),g.current=requestAnimationFrame(D);};D();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(l)try{q=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(T){console.warn("Microphone access denied:",T);}let U=[...w.getVideoTracks()];q&&U.push(...q.getAudioTracks());let O=new MediaStream(U);x.current=O;let R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8"),console.log("Using mimeType:",R);let E=new MediaRecorder(O,{mimeType:R,videoBitsPerSecond:25e5});f.current=E,d.current=[],E.ondataavailable=T=>{console.log("Data available, size:",T.data.size),T.data.size>0&&d.current.push(T.data);},E.onstop=()=>{console.log("Recording stopped, chunks:",d.current.length);let T=new Blob(d.current,{type:R});console.log("Final blob size:",T.size),o?.current&&b.current&&h.current&&(o.current.draw(),o.current.getLayers().forEach(z=>{z.batchDraw();}),b.current(),y.current=h.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",y.current.length)),O.getTracks().forEach(G=>G.stop()),m.current&&clearInterval(m.current),g.current&&(cancelAnimationFrame(g.current),g.current=null),u(T);},E.onerror=T=>{console.error("MediaRecorder error:",T);},console.log("Starting recording..."),E.start(1e3),i(!0),s(0),m.current=setInterval(()=>{s(T=>T+1);},1e3);}catch(w){console.error("Error starting screen recording:",w),alert("Failed to start recording. Please ensure you granted permission.");}},C=()=>{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)),i(false));},I=()=>{if(n){let w=URL.createObjectURL(n),q=document.createElement("a");q.href=w,q.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(q),q.click(),document.body.removeChild(q),URL.revokeObjectURL(w);}},k=w=>{let q=Math.floor(w/60),U=w%60;return `${q.toString().padStart(2,"0")}:${U.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:k(c)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:C,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-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[!n&&jsxs("div",{className:"text-center",children:[jsx("p",{className:"mb-4 text-sm text-gray-600",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsx("div",{className:"mb-4 flex items-center justify-center gap-2",children:jsx("button",{onClick:()=>p(!l),className:`flex items-center gap-2 rounded-lg border px-4 py-2 text-sm transition-colors ${l?"border-blue-500 bg-blue-50 text-blue-700":"border-gray-300 bg-white text-gray-700 hover:bg-gray-50"}`,children:l?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5"}),"Microphone Off"]})})}),jsxs("button",{onClick:L,className:"flex items-center gap-2 rounded-lg bg-red-600 px-6 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]}),n&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(n),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",k(c)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{a&&n&&y.current&&(a(n,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:I,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{u(null),s(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 bg-blue-50 p-3",children:jsxs("p",{className:"text-xs 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 xl=({elementType:e,existingAudio:o,onSave:a,onDelete:t,onClose:r})=>{let[i,n]=useState(false),[u,c]=useState(null),[s,l]=useState(false),[p,f]=useState(0),d=useRef(null),m=useRef([]),x=useRef(null),g=useRef(null);useEffect(()=>{o&&!u&&fetch(o).then(w=>w.blob()).then(w=>c(w)).catch(w=>console.error("Error loading audio:",w));},[o,u]);let y=async()=>{try{let w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),q=new MediaRecorder(w);d.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:"audio/webm"});c(U),w.getTracks().forEach(O=>O.stop()),x.current&&clearInterval(x.current);},q.start(),n(!0),f(0),x.current=setInterval(()=>{f(U=>U+1);},1e3);}catch(w){console.error("Error starting audio recording:",w),alert("Failed to start recording. Please allow microphone access.");}},h=()=>{d.current&&i&&(d.current.stop(),n(false));},b=()=>{if(u){let w=URL.createObjectURL(u),q=new Audio(w);g.current=q,q.onended=()=>{l(false),URL.revokeObjectURL(w);},q.play(),l(true);}},L=()=>{g.current&&(g.current.pause(),g.current.currentTime=0,l(false));},C=async()=>{if(u){let w=new FileReader;w.onloadend=()=>{let q=w.result;a(q),r();},w.readAsDataURL(u);}},I=()=>{c(null),t();},k=w=>{let q=Math.floor(w/60),U=w%60;return `${q.toString().padStart(2,"0")}:${U.toString().padStart(2,"0")}`};return i?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:k(p)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:h,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-4",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:"mb-6",children:[!u&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:y,className:"flex w-full items-center justify-center gap-2 rounded-lg bg-red-600 px-6 py-3 text-white transition-colors hover:bg-red-700",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),u&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:s?L:b,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),s?"Playing...":"Play Audio"]}),jsx("button",{onClick:I,className:"flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-3 text-red-600 transition-colors hover:bg-red-50",children:jsx(Trash,{className:"h-5 w-5"})})]}),jsx("button",{onClick:C,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]})]}),jsx("div",{className:"flex justify-end",children:jsx("button",{onClick:r,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"})})]})})};var it=({audioData:e,x:o,y:a,width:t})=>{let[r,i]=useState(false),n=useRef(null);return jsx("button",{onClick:c=>{if(c.stopPropagation(),r&&n.current)n.current.pause(),n.current.currentTime=0,i(false);else {let s=new Audio(e);n.current=s,s.onended=()=>{i(false);},s.onerror=()=>{console.error("Error playing audio"),i(false);},s.play(),i(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+t-35}px`,top:`${a+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 Ll=({selectedElementId:e,onClose:o,onSelectElement:a})=>{let t=pe(),r=$(ce),i=useMemo(()=>{if(!r)return [];let x=[];return r.images?.forEach(g=>{x.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),r.videos?.forEach(g=>{x.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),r.shapes?.forEach(g=>{x.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),r.texts?.forEach(g=>{x.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),r.flashcards?.forEach(g=>{x.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),r.photoFrames?.forEach(g=>{x.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),r.multipleChoices?.forEach(g=>{x.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),r.trueFalses?.forEach(g=>{x.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),r.shortAnswers?.forEach(g=>{x.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),r.LongAnswer?.forEach(g=>{x.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),r.fillInTheBlanks?.forEach(g=>{x.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),r.lines?.forEach(g=>{g.id&&x.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),x.sort((g,y)=>y.timestamp-g.timestamp)},[r]),[n,u]=useState(i),[c,s]=useState(false);useEffect(()=>{c||u(i);},[i]);let l=x=>{let g="h-5 w-5";switch(x){case "image":return jsx(Image$2,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes,{className:g});case "text":return jsx(TextT$1,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx("span",{className:g,children:"\u270F\uFE0F"});default:return jsx(Question,{className:g})}},p=x=>{if(x===0)return;let g=n[x],y=n[x-1];t(Ja({id:g.id,type:g.type,newTimestamp:y.timestamp+1}));},f=x=>{if(x===n.length-1)return;let g=n[x],y=n[x+1];t(Ja({id:g.id,type:g.type,newTimestamp:y.timestamp-1}));},d=x=>{s(true),u(x);},m=()=>{s(false);let x=Date.now();n.forEach((g,y)=>{let h=x-y;t(Ja({id:g.id,type:g.type,newTimestamp:h}));});};return jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-gray-200 bg-white shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 p-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Stack$1,{className:"h-5 w-5 text-gray-700",weight:"bold"}),jsx("h3",{className:"font-semibold text-gray-900",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto p-2",children:n.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:n,onReorder:d,className:"space-y-1",children:n.map((x,g)=>{let y=x.id===e;return jsxs(Reorder.Item,{value:x,onDragEnd:m,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:()=>a(x.id,x.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${y?"text-blue-600":"text-gray-600"}`,children:l(x.type)}),jsx("span",{className:`text-sm ${y?"font-medium text-blue-900":"text-gray-700"}`,children:x.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:h=>{h.stopPropagation(),p(g);},disabled:g===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:h=>{h.stopPropagation(),f(g);},disabled:g===n.length-1,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move down (backward)",children:jsx(ArrowDown,{className:"h-4 w-4"})})]})]},x.id)})})}),jsx("div",{className:"border-t border-gray-200 p-3 text-xs text-gray-500",children:jsx("p",{children:"Drag to reorder \u2022 Top layers appear above bottom layers"})})]})]})};var yl=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:a,mcqRefs:t,handleDragEnd:r,onContextMenu:i})=>{let n=useSelector(N=>N.toolbar.selectedTool),u=n==="pen"||n==="eraser",[c,s]=useState(new Set),[l,p]=useState(false),[f,d]=useState(null),m=useRef(null);useEffect(()=>{let N=m.current;if(N)return t.current.set(e.id,N),()=>{t.current.delete(e.id);}},[e.id]);let x=new Set(e.data.responseOptions.correctIndex),g=x.size>1,y=N=>{l||s(g?D=>{let V=new Set(D);return V.has(N)?V.delete(N):V.add(N),V}:new Set([N]));},h=()=>{c.size>0&&p(true);},b=()=>{p(false),s(new Set);},L=c.size===x.size&&Array.from(c).every(N=>x.has(N)),C=Array.from(c).filter(N=>x.has(N)),I=g&&C.length>0&&!L,k=()=>L?"\u2713 Correct! Great job! \u{1F389}":I?`\u26A0 Partially correct (${C.length}/${x.size})`:"\u2717 Try again!",w=()=>L?{bg:"#dcfce7",text:"#166534"}:I?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},q=55,U=8,O=24,R=60,E=60,T=g&&!l?25:0,G=e.data.feedbackMode==="practice"?48:0,z=12,me=R+T+(l?E:0),J=e.data.responseOptions.options.length*(q+U),de=me+J+z+G+O;return jsxs(Group,{ref:m,name:"mcq-element",draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...u?{}:{onDragEnd:r,onClick:N=>a(e.id),onTap:N=>a(e.id),onContextMenu:N=>{let D=m.current?.getStage()?.getPointerPosition();if(D){let V={x:e.x,y:e.y,width:e.width,height:e.height};if(D.x>=V.x&&D.x<=V.x+V.width&&D.y>=V.y&&D.y<=V.y+V.height){let j=N.evt;i(j,e.id,"mcq");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:de,width:e.width,onTransformEnd:N=>o(e.id,N)}),jsx(Text,{x:O,y:O,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-O*2,listening:false}),g&&!l&&e.data.feedbackMode==="practice"?jsx(Text,{x:O,y:O+35,text:`Select ${x.size} answers (${c.size}/${x.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-O*2,listening:false}):null,l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:O,y:R+T,width:e.width-O*2,height:E,fill:w().bg,cornerRadius:8}),jsx(Text,{x:O,y:R+T,width:e.width-O*2,height:E,text:k(),fontSize:16,fontStyle:"bold",fill:w().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((N,D)=>{let V=x.has(D),j=c.has(D),te=me+D*(q+U),Z="#e5e7eb",ae="#ffffff";return l&&V?(Z="#22c55e",ae="#dcfce7"):l&&j&&!V?(Z="#ef4444",ae="#fee2e2"):j&&(Z="#096B76",ae="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:te,width:e.width-O*2,height:q,fill:ae,stroke:Z,strokeWidth:2,cornerRadius:8,onClick:Ce=>{Ce.cancelBubble=true,y(D);},onTap:Ce=>{Ce.cancelBubble=true,y(D);}}),jsx(Rect,{x:O+12,y:te+(q-20)/2,width:20,height:20,fill:j?"#096B76":"white",stroke:j?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:g?4:10,listening:false}),j&&jsx(Text,{x:O+12,y:te+(q-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O+44,y:te,width:e.width-O*2-80,height:q,text:N,fontSize:16,fill:"#111827",verticalAlign:"middle",listening:false}),l&&V&&jsx(Text,{x:e.width-O-30,y:te+(q-24)/2,width:24,height:24,text:"\u2713",fontSize:20,fill:"#22c55e",align:"center",verticalAlign:"middle",listening:false}),l&&j&&!V&&jsx(Text,{x:e.width-O-30,y:te+(q-24)/2,width:24,height:24,text:"\u2717",fontSize:20,fill:"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},D)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:me+e.data.responseOptions.options.length*(q+U)+12,children:[jsxs(Group,{onMouseDown:N=>{N.cancelBubble=true,d("check");},onMouseUp:N=>{N.cancelBubble=true,d(null),h();},onMouseLeave:N=>{N.cancelBubble=true,d(null);},onTouchStart:N=>{N.cancelBubble=true,d("check");},onTouchEnd:N=>{N.cancelBubble=true,d(null),h();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:O,width:(e.width-O*2-8)/(l?2:1),height:48,fill:c.size===0||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:O,width:(e.width-O*2-8)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-O*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),b();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),b();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:O,width:(e.width-O*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:O,width:(e.width-O*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});yl.displayName="MultipleChoice";var Il=yl;var Lm="#FFFFFF",ln=({multipleChoice:e,onContextMenu:o,handleMcqTransform:a})=>{let t=useDispatch(),r=useSelector(D=>D.toolbar.selectedTool),i=r==="pen"||r==="eraser",[n,u]=useState(false),[c,s]=useState(new Set),[l,p]=useState(false),[f,d]=useState(false),[m,x]=useState(0),g=340,y=100,h=window.innerWidth*.5,b=window.innerHeight*.5,L=g+20,C=y+60,I=h-40,k=b-160,w=useRef(null),q=D=>{t(Ht({id:e.id,x:D.target.x(),y:D.target.y()}));},U=D=>{let V=D.target,j=V.x(),te=V.y(),Z=window.innerWidth*.2,Ce=j+Z>L&&j<L+I&&te+50>C&&te<C+k;u(Ce);},O=(D,V)=>{let j=V.target,te=j.x(),Z=j.y(),ae=window.innerWidth*.2,_=te+ae>L&&te<L+I&&Z+50>C&&Z<C+k;s(_?Pe=>new Set(Pe).add(D):Pe=>{let vt=new Set(Pe);return vt.delete(D),vt}),u(false);},R=()=>{p(true);},E=()=>{p(false),s(new Set),x(D=>D+1);},T=new Set(e.data.responseOptions.correctIndex),G=c.size===T.size&&Array.from(c).every(D=>T.has(D)),z=Array.from(c).filter(D=>T.has(D));Array.from(c).filter(D=>!T.has(D));let J=z.length>0&&!G,de=()=>G?"\u2713 Correct! Great job!":J?`\u26A0 Partially correct (${z.length}/${T.size})`:"\u2717 Try again!",N=()=>G?{bg:"#dcfce7",text:"#166534"}:J?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"};return jsxs(Group,{ref:w,name:"mcq-element",width:h,height:b,draggable:!i,listening:!i,...i?{}:{onContextMenu:D=>{D.evt.preventDefault(),o(D.evt,e.id,"mcq");}},children:[jsxs(Group,{x:g,y,rotation:e.rotation,onDragEnd:q,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?b-10:b-50,width:h,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:h-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:I,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:I,height:60,fill:N().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:I,height:60,text:de(),fontSize:18,fontStyle:"bold",fill:N().text,align:"center",verticalAlign:"middle"})]}),c.size===0&&!l&&jsx(Text,{x:20,y:60,width:I,height:k-60,text:T.size>1?`Drop ${T.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),c.size>0&&!l&&jsx(Text,{x:20,y:b-120,width:I,text:`${c.size} of ${T.size} answers selected`,fontSize:16,fill:"#6b7280",align:"center"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:b-90,children:[jsxs(Group,{onMouseDown:()=>{d(true),R();},onMouseUp:()=>d(false),onMouseLeave:()=>d(false),onTouchStart:()=>{d(true),R();},onTouchEnd:()=>d(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((D,V)=>{let j=V%2,te=Math.floor(V/2),Z=window.innerWidth*.2,ae=50,Ce=10,_=c.has(V),Pe=T.has(V),vt=l&&_,B="transparent";return vt?B=Pe?"#4CAF50":"#ef4444":_&&(B="#4CAF50"),jsxs(Group,{x:420+j*(Z+Ce),y:y+b+20+te*(ae+Ce),draggable:!l,onDragMove:U,onDragEnd:se=>O(V,se),opacity:l&&!_?.5:1,children:[jsx(Rect,{width:Z,height:ae,fill:"#075560",stroke:B,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z,height:ae,text:D,fontSize:18,fontStyle:"bold",fill:Lm,align:"center",verticalAlign:"middle",listening:false}),vt&&jsx(Text,{x:Z-30,y:5,width:25,height:25,text:Pe?"\u2713":"\u2717",fontSize:20,fontStyle:"bold",fill:Pe?"#4CAF50":"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},`${V}-${m}`)})]})};ln.displayName="MultipleChoiceDragAndDrop";var wl=({multipleChoice:e,handleMcqTransform:o,handleSelect:a,mcqRefs:t,handleDragEnd:r,onContextMenu:i})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Il,{multipleChoice:n,handleMcqTransform:o,handleSelect:a,mcqRefs:t,handleDragEnd:u=>r(u,n.id),onContextMenu:i},n.id):jsx(ln,{multipleChoice:n,handleMcqTransform:o,handleSelect:a,mcqRefs:t,onContextMenu:i},n.id))});var Sl=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,onContextMenu:r,handleDragEnd:i})=>{let n=useSelector(z=>z.toolbar.selectedTool),u=n==="pen"||n==="eraser",[c,s]=useState(null),[l,p]=useState(false),[f,d]=useState(null),m=useRef(null);useEffect(()=>{let z=m.current;if(z)return t.current.set(e.id,z),()=>{t.current.delete(e.id);}},[e.id]);let x=()=>{c!==null&&p(true);},g=()=>{p(false),s(null);},y=e.data.responseOptions.correctAnswer,h=c===y,b=z=>{l||s(z);},L=()=>h?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},I=70,k=12,w=24,q=60,U=60,O=e.data.feedbackMode==="practice"?48:0,R=12,E=q+(l?U:0),T=2*(I+k),G=E+T+R+O+w;return jsxs(Group,{ref:m,name:"trueFalse-element",draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...u?{}:{onDragEnd:z=>i(z,e.id),onClick:z=>a(e.id),onTap:z=>a(e.id),onContextMenu:z=>{let me=m.current?.getStage()?.getPointerPosition();if(me){let J={x:e.x,y:e.y,width:e.width,height:e.height};if(me.x>=J.x&&me.x<=J.x+J.width&&me.y>=J.y&&me.y<=J.y+J.height){let de=z.evt;r(de,e.id,"trueFalse");}}}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:G,width:e.width,onTransformEnd:z=>o(e.id,z)}),jsx(Text,{x:w,y:w,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-w*2,listening:false}),l&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:w,y:q,width:e.width-w*2,height:U,fill:C().bg,cornerRadius:8}),jsx(Text,{x:w,y:q,width:e.width-w*2,height:U,text:L(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,[{label:"True",value:true},{label:"False",value:false}].map((z,me)=>{let J=y===z.value,de=c===z.value,N=E+me*(I+k),D="#e5e7eb",V="#ffffff";return l&&J?(D="#22c55e",V="#dcfce7"):l&&de&&!J?(D="#ef4444",V="#fee2e2"):de&&(D="#096B76",V="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:w,y:N,width:e.width-w*2,height:I,fill:V,stroke:D,strokeWidth:2,cornerRadius:8,onClick:j=>{j.cancelBubble=true,b(z.value);},onTap:j=>{j.cancelBubble=true,b(z.value);}}),jsx(Rect,{x:w+12,y:N+(I-24)/2,width:24,height:24,fill:de?"#096B76":"white",stroke:de?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:12,listening:false}),de&&jsx(Rect,{x:w+12+6,y:N+(I-24)/2+6,width:12,height:12,fill:"white",cornerRadius:6,listening:false}),jsx(Text,{x:w+48,y:N,width:e.width-w*2-80,height:I,text:z.label,fontSize:18,fontStyle:"bold",fill:"#111827",verticalAlign:"middle",listening:false}),l&&J&&jsx(Text,{x:e.width-w-30,y:N+(I-24)/2,width:24,height:24,text:"\u2713",fontSize:20,fill:"#22c55e",align:"center",verticalAlign:"middle",listening:false}),l&&de&&!J&&jsx(Text,{x:e.width-w-30,y:N+(I-24)/2,width:24,height:24,text:"\u2717",fontSize:20,fill:"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},z.label)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:E+2*(I+k)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,d("check");},onMouseUp:z=>{z.cancelBubble=true,d(null),x();},onMouseLeave:z=>{z.cancelBubble=true,d(null);},onTouchStart:z=>{z.cancelBubble=true,d("check");},onTouchEnd:z=>{z.cancelBubble=true,d(null),x();},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:w,width:(e.width-w*2-8)/(l?2:1),height:48,fill:c===null||l?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:w,width:(e.width-w*2-8)/(l?2:1),height:48,text:l?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{x:(e.width-w*2)/2+8,onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),g();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),g();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:w,width:(e.width-w*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:w,width:(e.width-w*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Sl.displayName="TrueFalse";var Cl=Sl;var Fm="#FFFFFF",cn=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:a})=>{let t=useDispatch(),r=useSelector(J=>J.toolbar.selectedTool),i=r==="pen"||r==="eraser",[n,u]=useState(false),[c,s]=useState(null),[l,p]=useState(false),[f,d]=useState(false),[m,x]=useState(0),g=340,y=100,h=window.innerWidth*.5,b=window.innerHeight*.5,L=g+20,C=y+60,I=h-40,k=b-160,w=useRef(null),q=J=>{t(Ut({id:e.id,x:J.target.x(),y:J.target.y()}));},U=J=>{let de=J.target,N=de.x(),D=de.y(),V=window.innerWidth*.2,te=N+V>L&&N<L+I&&D+50>C&&D<C+k;u(te);},O=(J,de)=>{let N=de.target,D=N.x(),V=N.y(),j=window.innerWidth*.2,Z=D+j>L&&D<L+I&&V+50>C&&V<C+k;s(Z?J:null),u(false);},R=()=>{p(true);},E=()=>{p(false),s(null),x(J=>J+1);},T=e.data.responseOptions.correctAnswer,G=c===T,z=()=>G?"\u2713 Correct! Great job!":"\u2717 Try again!",me=()=>G?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsxs(Group,{ref:w,name:"trueFalse-element",width:h,height:b,draggable:!i,listening:!i,...i?{}:{onContextMenu:J=>{J.evt.preventDefault(),o(J.evt,e.id,"trueFalse");}},children:[jsxs(Group,{x:g,y,rotation:e.rotation,onDragEnd:q,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?b+10:b-50,width:h,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:h-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:I,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:I,height:60,fill:me().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:I,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:me().text,align:"center",verticalAlign:"middle"})]}),c===null&&!l&&jsx(Text,{x:20,y:60,width:I,height:k-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),c!==null&&!l&&jsxs(Fragment,{children:[jsx(Text,{x:20,y:60+(k-60)/2-25,width:I,text:c?"True":"False",fontSize:32,fontStyle:"bold",fill:"#075560",align:"center"}),jsx(Text,{x:20,y:b-120,width:I,text:"Answer selected",fontSize:16,fill:"#6b7280",align:"center"})]}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:b-90,children:[jsxs(Group,{onMouseDown:()=>{c!==null&&(d(true),R());},onMouseUp:()=>d(false),onMouseLeave:()=>d(false),onTouchStart:()=>{c!==null&&(d(true),R());},onTouchEnd:()=>d(false),scaleX:f?.95:1,scaleY:f?.95:1,children:[jsx(Rect,{fill:c===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:E,onTouchStart:E,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:I}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:I,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),[{value:true,label:"True"},{value:false,label:"False"}].map((J,de)=>{let N=window.innerWidth*.2,D=50,V=10,j=c===J.value,te=T===J.value,Z=l&&j,ae="transparent";return Z?ae=te?"#4CAF50":"#ef4444":j&&(ae="#4CAF50"),jsxs(Group,{x:420+de*(N+V),y:y+b+20,draggable:!l,onDragMove:U,onDragEnd:Ce=>O(J.value,Ce),opacity:l&&!j?.5:1,children:[jsx(Rect,{width:N,height:D,fill:"#075560",stroke:ae,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:N,height:D,text:J.label,fontSize:18,fontStyle:"bold",fill:Fm,align:"center",verticalAlign:"middle",listening:false}),Z&&jsx(Text,{x:N-30,y:5,width:25,height:25,text:te?"\u2713":"\u2717",fontSize:20,fontStyle:"bold",fill:te?"#4CAF50":"#ef4444",align:"center",verticalAlign:"middle",listening:false})]},`${J.value}-${m}`)})]})};cn.displayName="TrueFalseDragAndDrop";var Ml=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,handleDragEnd:r,onContextMenu:i})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Cl,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,onContextMenu:i,handleDragEnd:r},n.id):jsx(cn,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:a,trueFalseRefs:t,onContextMenu:i},n.id))});var $t=new WeakMap,Pa=new WeakMap,po={current:[]},mn=false,mo=0,fo=new Set,yr=new Map;function Al(e){let o=Array.from(e).sort((a,t)=>a instanceof ht&&a.options.deps.includes(t)?1:t instanceof ht&&t.options.deps.includes(a)?-1:0);for(let a of o){if(po.current.includes(a))continue;po.current.push(a),a.recompute();let t=Pa.get(a);if(t)for(let r of t){let i=$t.get(r);i&&Al(i);}}}function Em(e){let o={prevVal:e.prevState,currentVal:e.state};for(let a of e.listeners)a(o);}function Rm(e){let o={prevVal:e.prevState,currentVal:e.state};for(let a of e.listeners)a(o);}function Ir(e){if(mo>0&&!yr.has(e)&&yr.set(e,e.prevState),fo.add(e),!(mo>0)&&!mn)try{for(mn=!0;fo.size>0;){let o=Array.from(fo);fo.clear();for(let a of o){let t=yr.get(a)??a.prevState;a.prevState=t,Em(a);}for(let a of o){let t=$t.get(a);t&&(po.current.push(a),Al(t));}for(let a of o){let t=$t.get(a);if(t)for(let r of t)Rm(r);}}}finally{mn=false,po.current=[],yr.clear();}}function $e(e){mo++;try{e();}finally{if(mo--,mo===0){let o=fo.values().next().value;o&&Ir(o);}}}function Dl(e){return typeof e=="function"}var St=class{constructor(o,a){this.listeners=new Set,this.subscribe=t=>{var r,i;this.listeners.add(t);let n=(i=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:i.call(r,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.prevState=o,this.state=o,this.options=a;}setState(o){var a,t,r;this.prevState=this.state,(a=this.options)!=null&&a.updateFn?this.state=this.options.updateFn(this.prevState)(o):Dl(o)?this.state=o(this.prevState):this.state=o,(r=(t=this.options)==null?void 0:t.onUpdate)==null||r.call(t),Ir(this);}};var ht=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let a=this.options.deps.length,t=new Array(a),r=new Array(a);for(let i=0;i<a;i++){let n=this.options.deps[i];t[i]=n.prevState,r[i]=n.state;}return this.lastSeenDepValues=r,{prevDepVals:t,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var a,t;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(t=(a=this.options).onUpdate)==null||t.call(a);},this.checkIfRecalculationNeededDeeply=()=>{for(let i of this.options.deps)i instanceof e&&i.checkIfRecalculationNeededDeeply();let a=false,t=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let i=0;i<r.length;i++)if(r[i]!==t[i]){a=true;break}a&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let a of this._subscriptions)a();}),this.subscribe=a=>{var t,r;this.listeners.add(a);let i=(r=(t=this.options).onSubscribe)==null?void 0:r.call(t,a,this);return ()=>{this.listeners.delete(a),i?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let a of o)if(a instanceof e)a.registerOnGraph(),this.registerOnGraph(a.options.deps);else if(a instanceof St){let t=$t.get(a);t||(t=new Set,$t.set(a,t)),t.add(this);let r=Pa.get(this);r||(r=new Set,Pa.set(this,r)),r.add(a);}}unregisterFromGraph(o=this.options.deps){for(let a of o)if(a instanceof e)this.unregisterFromGraph(a.options.deps);else if(a instanceof St){let t=$t.get(a);t&&t.delete(this);let r=Pa.get(this);r&&r.delete(a);}}};function Bm(e){return typeof e=="function"}function pn(e,...o){return Bm(e)?e(...o):e}function Tl(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var _t,ze,Ue,ho,Yt,pa,Pt,Ea,go,wr,xo,Ra,ha=class{constructor({pluginId:o,debug:a=false,enabled:t=true,reconnectEveryMs:r=1e3}){Se(this,_t,true);Se(this,ze);Se(this,Ue);Se(this,ho);Se(this,Yt);Se(this,pa);Se(this,Pt);Se(this,Ea);Se(this,go,0);Se(this,wr,5);Se(this,xo,()=>{this.debugLog("Connected to event bus"),be(this,pa,true),this.debugLog("Emitting queued events",W(this,Yt)),W(this,Yt).forEach(o=>this.emitEventToBus(o)),be(this,Yt,[]),this.stopConnectLoop(),W(this,Ue).call(this).removeEventListener("tanstack-connect-success",W(this,xo));});Se(this,Ra,()=>{if(W(this,Ue).call(this).addEventListener("tanstack-connect-success",W(this,xo)),W(this,go)<W(this,wr)){ri(this,go)._++,this.dispatchCustomEvent("tanstack-connect",{});return}W(this,Ue).call(this).removeEventListener("tanstack-connect",W(this,Ra)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});be(this,ze,o),be(this,_t,t),be(this,Ue,this.getGlobalTarget),be(this,ho,a),this.debugLog(" Initializing event subscription for plugin",W(this,ze)),be(this,Yt,[]),be(this,pa,false),be(this,Pt,null),be(this,Ea,r);}startConnectLoop(){W(this,Pt)!==null||W(this,pa)||(this.debugLog(`Starting connect loop (every ${W(this,Ea)}ms)`),be(this,Pt,setInterval(W(this,Ra),W(this,Ea))));}stopConnectLoop(){W(this,Pt)!==null&&(clearInterval(W(this,Pt)),be(this,Pt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){W(this,ho)&&console.log(`\u{1F334} [tanstack-devtools:${W(this,ze)}-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 W(this,ze)}dispatchCustomEventShim(o,a){try{let t=new Event(o,{detail:a});W(this,Ue).call(this).dispatchEvent(t);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,a){try{W(this,Ue).call(this).dispatchEvent(new CustomEvent(o,{detail:a}));}catch{this.dispatchCustomEventShim(o,a);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,a){if(!W(this,_t)){this.debugLog("Event bus client is disabled, not emitting event",o,a);return}if(!W(this,pa)){this.debugLog("Bus not available, will be pushed as soon as connected"),W(this,Yt).push({type:`${W(this,ze)}:${o}`,payload:a,pluginId:W(this,ze)}),typeof CustomEvent<"u"&&(W(this,Ra).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${W(this,ze)}:${o}`,payload:a,pluginId:W(this,ze)})}on(o,a){let t=`${W(this,ze)}:${o}`;if(!W(this,_t))return this.debugLog("Event bus client is disabled, not registering event",t),()=>{};let r=i=>{this.debugLog("Received event from bus",i.detail),a(i.detail);};return W(this,Ue).call(this).addEventListener(t,r),this.debugLog("Registered event to bus",t),()=>{W(this,Ue).call(this).removeEventListener(t,r);}}onAll(o){if(!W(this,_t))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let a=t=>{let r=t.detail;o(r);};return W(this,Ue).call(this).addEventListener("tanstack-devtools-global",a),()=>W(this,Ue).call(this).removeEventListener("tanstack-devtools-global",a)}onAllPluginEvents(o){if(!W(this,_t))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let a=t=>{let r=t.detail;W(this,ze)&&r.pluginId!==W(this,ze)||o(r);};return W(this,Ue).call(this).addEventListener("tanstack-devtools-global",a),()=>W(this,Ue).call(this).removeEventListener("tanstack-devtools-global",a)}};_t=new WeakMap,ze=new WeakMap,Ue=new WeakMap,ho=new WeakMap,Yt=new WeakMap,pa=new WeakMap,Pt=new WeakMap,Ea=new WeakMap,go=new WeakMap,wr=new WeakMap,xo=new WeakMap,Ra=new WeakMap;var hn=class extends ha{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Fl=(e,o)=>{gn.emit(e,o);},gn=new hn;function Pl(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Om={enabled:true,leading:true,trailing:true,wait:0},Jt,_e,ga,xa,ba,Ba,Sr=class{constructor(o,a){Se(this,Jt);Se(this,_e);Se(this,ga);Se(this,xa);Se(this,ba);Se(this,Ba);this.fn=o,this.store=new St(Pl()),this.setOptions=t=>{this.options={...this.options,...t},W(this,ga).call(this)||this.cancel();},be(this,_e,t=>{this.store.setState(r=>{let i={...r,...t},{isPending:n}=i;return {...i,status:W(this,ga).call(this)?n?"pending":"idle":"disabled"}}),Fl("Throttler",this);}),be(this,ga,()=>!!pn(this.options.enabled,this)),be(this,xa,()=>pn(this.options.wait,this)),this.maybeExecute=(...t)=>{W(this,_e).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),i=r-this.store.state.lastExecutionTime,n=W(this,xa).call(this);if(this.options.leading&&i>=n)W(this,ba).call(this,...t);else if(W(this,_e).call(this,{lastArgs:t}),!W(this,Jt)&&this.options.trailing){let u=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,c=n-u;W(this,_e).call(this,{isPending:true}),be(this,Jt,setTimeout(()=>{let{lastArgs:s}=this.store.state;s!==void 0&&W(this,ba).call(this,...s);},c));}},be(this,ba,(...t)=>{if(!W(this,ga).call(this))return;this.fn(...t);let r=Date.now(),i=r+W(this,xa).call(this);W(this,Ba).call(this),W(this,_e).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:i,isPending:false,lastArgs:void 0}),this.options.onExecute?.(t,this),setTimeout(()=>{this.store.state.isPending||W(this,_e).call(this,{nextExecutionTime:void 0});},W(this,xa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&W(this,ba).call(this,...this.store.state.lastArgs);},be(this,Ba,()=>{W(this,Jt)&&(clearTimeout(W(this,Jt)),be(this,Jt,void 0));}),this.cancel=()=>{W(this,Ba).call(this),W(this,_e).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{W(this,_e).call(this,Pl());},this.key=Tl(a.key),this.options={...Om,...a},W(this,_e).call(this,this.options.initialState??{}),gn.on("d-Throttler",t=>{t.payload.key===this.key&&(W(this,_e).call(this,t.payload.store.state),this.setOptions(t.payload.options));});}};Jt=new WeakMap,_e=new WeakMap,ga=new WeakMap,xa=new WeakMap,ba=new WeakMap,Ba=new WeakMap;function xn(e,o){return new Sr(e,o).maybeExecute}function Qt(e,o){return typeof e=="function"?e(o):e}function Zt(e,o){return Ar(o).reduce((t,r)=>{if(t===null)return null;if(typeof t<"u")return t[r]},e)}function Oa(e,o,a){let t=Ar(o);function r(i){if(!t.length)return Qt(a,i);let n=t.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(i))return typeof i=="object"?(i===null&&(i={}),{...i,[n]:r(i[n])}):{[n]:r()};if(Array.isArray(i)&&typeof n=="number"){let u=i.slice(0,n);return [...u.length?u:new Array(n),r(i[n]),...i.slice(n+1)]}return [...new Array(n),r()]}return r(e)}function vn(e,o){let a=Ar(o);function t(r){if(!r)return;if(a.length===1){let n=a[0];if(Array.isArray(r)&&typeof n=="number")return r.filter((s,l)=>l!==n);let{[n]:u,...c}=r;return c}let i=a.shift();if(typeof i=="string"&&typeof r=="object")return {...r,[i]:t(r[i])};if(typeof i=="number"&&Array.isArray(r)){if(i>=r.length)return r;let n=r.slice(0,i);return [...n.length?n:new Array(i),t(r[i]),...r.slice(i+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return t(e)}var qm=/^(\d+)$/gm,Nm=/\.(\d+)(?=\.)/gm,Vm=/^(\d+)\./gm,Hm=/\.(\d+$)/gm,Um=/\.{2,}/gm,bn="__int__",Cr=`${bn}$1`;function Ar(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(qm,Cr).replace(Nm,`.${Cr}.`).replace(Vm,`${Cr}.`).replace(Hm,`.${Cr}`).replace(Um,".").split(".").map(o=>{if(o.startsWith(bn)){let a=o.substring(bn.length),t=parseInt(a,10);return String(t)===a?t:a}return o})}function Ln(e){return !(Array.isArray(e)&&e.length===0)}function qa(e,o){let a=t=>t.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:a})}function Na(e,o){let{asyncDebounceMs:a}=o,{onBlurAsyncDebounceMs:t,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:i}=o.validators||{},n=a??0,u=c=>c.validators.filter(Boolean).map(s=>{let l=s?.cause||e,p=n;switch(l){case "change":p=r??n;break;case "blur":p=t??n;break;case "dynamic":p=i??n;break;case "submit":p=0;break}return e==="submit"&&(p=0),{cause:l,validate:s.fn,debounceMs:p}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:u})}var bo=e=>!!e&&typeof e=="object"&&"fields"in e;function ea(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,i]of e)if(!o.has(r)||!Object.is(i,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 a=Object.keys(e),t=Object.keys(o);if(a.length!==t.length)return false;for(let r of a)if(!t.includes(r)||!ea(e[r],o[r]))return false;return true}var Dr=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:a})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:a?{newErrorValue:a,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},Tr=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Te(e,o){return e==null?o:{...e,...o}}var va=256,Mr=[],kr;for(;va--;)Mr[va]=(va+256).toString(16).substring(1);function yn(){let e=0,o,a="";if(!kr||va+16>256){for(kr=new Array(256),e=256;e--;)kr[e]=256*Math.random()|0;e=0,va=0;}for(;e<16;e++)o=kr[va+e],e===6?a+=Mr[o&15|64]:e===8?a+=Mr[o&63|128]:a+=Mr[o],e&1&&e>1&&e<11&&(a+="-");return va++,a}var ta=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,a=o?void 0:{fn:e.validators.onMount,cause:"mount"},t={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},i={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[a],form:e.form});case "submit":return e.runValidation({validators:[t,r,i,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,n],form:e.form});case "change":return e.runValidation({validators:[t,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Wm(e,o){let a=new Map;for(let t of e){let r=t.path??[],i=o,n="";for(let u=0;u<r.length;u++){let c=r[u];if(c===void 0)continue;let s=typeof c=="object"?c.key:c,l=Number(s);Array.isArray(i)&&!Number.isNaN(l)?n+=`[${l}]`:n+=(u>0?".":"")+String(s),typeof i=="object"&&i!==null?i=i[s]:i=void 0;}a.set(n,(a.get(n)??[]).concat(t));}return Object.fromEntries(a)}var El=(e,o)=>{let a=Wm(e,o);return {form:a,fields:a}},aa={validate({value:e,validationSource:o},a){let t=a["~standard"].validate(e);if(t instanceof Promise)throw new Error("async function passed to sync validator");if(t.issues)return o==="field"?t.issues:El(t.issues,e)},async validateAsync({value:e,validationSource:o},a){let t=await a["~standard"].validate(e);if(t.issues)return o==="field"?t.issues:El(t.issues,e)}},Fr=e=>!!e&&"~standard"in e;var Va={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function vo(e){function o(p,f,d,m){let x=t(p,f,d,m);({insert:()=>u(x,p,f),remove:()=>c(x),swap:()=>m!==void 0&&l(x,p,f,m),move:()=>m!==void 0&&s(x,p,f,m)})[d]();}function a(p,f){return `${p}[${f}]`}function t(p,f,d,m){let x=[a(p,f)];if(d==="swap")x.push(a(p,m));else if(d==="move"){let[g,y]=[Math.min(f,m),Math.max(f,m)];for(let h=g;h<=y;h++)x.push(a(p,h));}else {let g=e.getFieldValue(p),y=Array.isArray(g)?g.length:0;for(let h=f+1;h<y;h++)x.push(a(p,h));}return Object.keys(e.fieldInfo).filter(g=>x.some(y=>g.startsWith(y)))}function r(p,f){return p.replace(/\[(\d+)\]/,(d,m)=>{let x=parseInt(m,10);return `[${f==="up"?x+1:Math.max(0,x-1)}]`})}function i(p,f){(f==="up"?p:[...p].reverse()).forEach(m=>{let x=r(m.toString(),f),g=e.getFieldMeta(x);g?e.setFieldMeta(m,g):e.setFieldMeta(m,n());});}let n=()=>Va,u=(p,f,d)=>{i(p,"down"),p.forEach(m=>{m.toString().startsWith(a(f,d))&&e.setFieldMeta(m,n());});},c=p=>{i(p,"up");},s=(p,f,d,m)=>{let x=new Map(Object.keys(e.fieldInfo).filter(g=>g.startsWith(a(f,d))).map(g=>[g,e.getFieldMeta(g)]));i(p,d<m?"up":"down"),Object.keys(e.fieldInfo).filter(g=>g.startsWith(a(f,m))).forEach(g=>{let y=g.replace(a(f,m),a(f,d)),h=x.get(y);h&&e.setFieldMeta(g,h);});},l=(p,f,d,m)=>{p.forEach(x=>{if(!x.toString().startsWith(a(f,d)))return;let g=x.toString().replace(a(f,d),a(f,m)),[y,h]=[e.getFieldMeta(x),e.getFieldMeta(g)];y&&e.setFieldMeta(g,y),h&&e.setFieldMeta(x,h);});};return {handleArrayFieldMetaShift:o}}var In=class extends ha{constructor(){super({pluginId:"form-devtools"});}},Ye=new In;function wn(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 yo=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let t=this.fieldMetaDerived.mount(),r=this.store.mount(),i=()=>{t(),r(),Ye.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return Ye.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),i},this.update=t=>{if(!t)return;let r=this.options;this.options=t;let i=!!t.transform?.deps?.some((c,s)=>c!==this.prevTransformArray[s]),n=t.defaultValues&&!ea(t.defaultValues,r.defaultValues)&&!this.state.isTouched,u=!ea(t.defaultState,r.defaultState)&&!this.state.isTouched;!n&&!u&&!i||($e(()=>{this.baseStore.setState(()=>wn(Object.assign({},this.state,u?t.defaultState:{},n?{values:t.defaultValues}:{},i?{_force_re_eval:!this.state._force_re_eval}:{})));}),Ye.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(t,r)=>{let{fieldMeta:i}=this.state,n=this.resetFieldMeta(i);t&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:t}),this.baseStore.setState(()=>wn({...this.options.defaultState,values:t??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async t=>{let r=[];return $e(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let u=n.instance;r.push(Promise.resolve().then(()=>u.validate(t,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(c=>({...c,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(t,r,i)=>{let n=this.getFieldValue(t),u=Array.isArray(n)?Math.max(n.length-1,0):null,c=[`${t}[${r}]`];for(let f=r+1;f<=(u??0);f++)c.push(`${t}[${f}]`);let s=Object.keys(this.fieldInfo).filter(f=>c.some(d=>f.startsWith(d))),l=[];return $e(()=>{s.forEach(f=>{l.push(Promise.resolve().then(()=>this.validateField(f,i)));});}),(await Promise.all(l)).flat()},this.validateField=(t,r)=>{let i=this.fieldInfo[t]?.instance;return i?(i.state.meta.isTouched||i.setMeta(n=>({...n,isTouched:true})),i.validate(r)):[]},this.validateSync=t=>{let r=qa(t,{...this.options,form:this,validationLogic:this.options.validationLogic||ta}),i=false,n={};return $e(()=>{for(let s of r){if(!s.validate)continue;let l=this.runValidator({validate:s.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:p,fieldErrors:f}=Pr(l),d=Lo(s.cause);for(let m of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[m]===void 0)continue;let x=this.getFieldMeta(m);if(!x)continue;let{errorMap:g,errorSourceMap:y}=x,h=f?.[m],{newErrorValue:b,newSource:L}=Dr({newFormValidatorError:h,isPreviousErrorFromFormValidator:y?.[d]==="form",previousErrorValue:g?.[d]});L==="form"&&(n[m]={...n[m],[d]:h}),g?.[d]!==b&&this.setFieldMeta(m,C=>({...C,errorMap:{...C.errorMap,[d]:b},errorSourceMap:{...C.errorSourceMap,[d]:L}}));}this.state.errorMap?.[d]!==p&&this.baseStore.setState(m=>({...m,errorMap:{...m.errorMap,[d]:p}})),(p||f)&&(i=!0);}let u=Lo("submit");this.state.errorMap?.[u]&&t!=="submit"&&!i&&this.baseStore.setState(s=>({...s,errorMap:{...s.errorMap,[u]:void 0}}));let c=Lo("server");this.state.errorMap?.[c]&&t!=="server"&&!i&&this.baseStore.setState(s=>({...s,errorMap:{...s.errorMap,[c]:void 0}}));}),{hasErrored:i,fieldsErrorMap:n}},this.validateAsync=async t=>{let r=Na(t,{...this.options,form:this,validationLogic:this.options.validationLogic||ta});this.state.isFormValidating||this.baseStore.setState(s=>({...s,isFormValidating:true}));let i=[],n;for(let s of r){if(!s.validate)continue;let l=Lo(s.cause);this.state.validationMetaMap[l]?.lastAbortController.abort();let f=new AbortController;this.state.validationMetaMap[l]={lastAbortController:f},i.push(new Promise(async d=>{let m;try{m=await new Promise((h,b)=>{setTimeout(async()=>{if(f.signal.aborted)return h(void 0);try{h(await this.runValidator({validate:s.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:f.signal},type:"validateAsync"}));}catch(L){b(L);}},s.debounceMs);});}catch(h){m=h;}let{formError:x,fieldErrors:g}=Pr(m);g&&(n=n?{...n,...g}:g);let y=Lo(s.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let b=this.getFieldMeta(h);if(!b)continue;let{errorMap:L,errorSourceMap:C}=b,I=n?.[h],{newErrorValue:k,newSource:w}=Dr({newFormValidatorError:I,isPreviousErrorFromFormValidator:C?.[y]==="form",previousErrorValue:L?.[y]});L?.[y]!==k&&this.setFieldMeta(h,q=>({...q,errorMap:{...q.errorMap,[y]:k},errorSourceMap:{...q.errorSourceMap,[y]:w}}));}this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[y]:x}})),d(n?{fieldErrors:n,errorMapKey:y}:void 0);}));}let u=[],c={};if(i.length){u=await Promise.all(i);for(let s of u)if(s?.fieldErrors){let{errorMapKey:l}=s;for(let[p,f]of Object.entries(s.fieldErrors)){let m={...c[p]||{},[l]:f};c[p]=m;}}}return this.baseStore.setState(s=>({...s,isFormValidating:false})),c},this.validate=t=>{let{hasErrored:r,fieldsErrorMap:i}=this.validateSync(t);return r&&!this.options.asyncAlways?i:this.validateAsync(t)},this.getFieldValue=t=>Zt(this.state.values,t),this.getFieldMeta=t=>this.state.fieldMeta[t],this.getFieldInfo=t=>{var r;return (r=this.fieldInfo)[t]||(r[t]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(t,r)=>{this.baseStore.setState(i=>({...i,fieldMetaBase:{...i.fieldMetaBase,[t]:Qt(r,i.fieldMetaBase[t])}}));},this.resetFieldMeta=t=>Object.keys(t).reduce((r,i)=>{let n=i;return r[n]=Va,r},{}),this.setFieldValue=(t,r,i)=>{let n=i?.dontUpdateMeta??false,u=i?.dontRunListeners??false,c=i?.dontValidate??false;$e(()=>{n||this.setFieldMeta(t,s=>({...s,isTouched:!0,isDirty:!0,errorMap:{...s?.errorMap,onMount:void 0}})),this.baseStore.setState(s=>({...s,values:Oa(s.values,t,r)}));}),u||this.getFieldInfo(t).instance?.triggerOnChangeListener(),c||this.validateField(t,"change");},this.deleteField=t=>{let i=[...Object.keys(this.fieldInfo).filter(n=>{let u=t.toString();return n!==u&&n.startsWith(u)}),t];this.baseStore.setState(n=>{let u={...n};return i.forEach(c=>{u.values=vn(u.values,c),delete this.fieldInfo[c],delete u.fieldMetaBase[c];}),u});},this.pushFieldValue=(t,r,i)=>{this.setFieldValue(t,n=>[...Array.isArray(n)?n:[],r],i);},this.insertFieldValue=async(t,r,i,n)=>{this.setFieldValue(t,c=>[...c.slice(0,r),i,...c.slice(r)],Te(n,{dontValidate:true}));let u=n?.dontValidate??false;u||await this.validateField(t,"change"),vo(this).handleArrayFieldMetaShift(t,r,"insert"),u||await this.validateArrayFieldsStartingFrom(t,r,"change");},this.replaceFieldValue=async(t,r,i,n)=>{this.setFieldValue(t,c=>c.map((s,l)=>l===r?i:s),Te(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(t,"change"),await this.validateArrayFieldsStartingFrom(t,r,"change"));},this.removeFieldValue=async(t,r,i)=>{let n=this.getFieldValue(t),u=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(t,s=>s.filter((l,p)=>p!==r),Te(i,{dontValidate:true})),vo(this).handleArrayFieldMetaShift(t,r,"remove"),u!==null){let s=`${t}[${u}]`;this.deleteField(s);}(i?.dontValidate??false)||(await this.validateField(t,"change"),await this.validateArrayFieldsStartingFrom(t,r,"change"));},this.swapFieldValues=(t,r,i,n)=>{this.setFieldValue(t,c=>{let s=c[r],l=c[i];return Oa(Oa(c,`${r}`,l),`${i}`,s)},Te(n,{dontValidate:true})),vo(this).handleArrayFieldMetaShift(t,r,"swap",i),(n?.dontValidate??false)||(this.validateField(t,"change"),this.validateField(`${t}[${r}]`,"change"),this.validateField(`${t}[${i}]`,"change"));},this.moveFieldValues=(t,r,i,n)=>{this.setFieldValue(t,c=>{let s=[...c];return s.splice(i,0,s.splice(r,1)[0]),s},Te(n,{dontValidate:true})),vo(this).handleArrayFieldMetaShift(t,r,"move",i),(n?.dontValidate??false)||(this.validateField(t,"change"),this.validateField(`${t}[${r}]`,"change"),this.validateField(`${t}[${i}]`,"change"));},this.clearFieldValues=(t,r)=>{let i=this.getFieldValue(t),n=Array.isArray(i)?Math.max(i.length-1,0):null;if(this.setFieldValue(t,[],Te(r,{dontValidate:true})),n!==null)for(let c=0;c<=n;c++){let s=`${t}[${c}]`;this.deleteField(s);}(r?.dontValidate??false)||this.validateField(t,"change");},this.resetField=t=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[t]:Va},values:this.options.defaultValues?Oa(r.values,t,Zt(this.options.defaultValues,t)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((t,[r,i])=>(Object.keys(i).length&&i.errors.length&&(t[r]={errors:i.errors,errorMap:i.errorMap}),t),{})}),this.parseValuesWithSchema=t=>aa.validate({value:this.state.values,validationSource:"form"},t),this.parseValuesWithSchemaAsync=t=>aa.validateAsync({value:this.state.values,validationSource:"form"},t),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??yn(),this._devtoolsSubmissionOverride=false,this.baseStore=new St(wn({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new ht({deps:[this.baseStore],fn:({prevDepVals:t,currDepVals:r,prevVal:i})=>{let n=i,u=t?.[0],c=r[0],s=0,l={};for(let p of Object.keys(c.fieldMetaBase)){let f=c.fieldMetaBase[p],d=u?.fieldMetaBase[p],m=n?.[p],x=Zt(c.values,p),g=m?.errors;if(!d||f.errorMap!==d.errorMap){g=Object.values(f.errorMap??{}).filter(C=>C!==void 0);let L=this.getFieldInfo(p)?.instance;L&&!L.options.disableErrorFlat&&(g=g?.flat(1));}let y=!Ln(g??[]),h=!f.isDirty,b=ea(x,Zt(this.options.defaultValues,p))||ea(x,this.getFieldInfo(p)?.instance?.options.defaultValue);if(m&&m.isPristine===h&&m.isValid===y&&m.isDefaultValue===b&&m.errors===g&&f===d){l[p]=m,s++;continue}l[p]={...f,errors:g,isPristine:h,isValid:y,isDefaultValue:b};}return Object.keys(c.fieldMetaBase).length&&n&&s===Object.keys(c.fieldMetaBase).length?n:l}}),this.store=new ht({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:t,currDepVals:r,prevVal:i})=>{let n=i,u=t?.[0],c=r[0],s=r[1],l=Object.values(s).filter(Boolean),p=l.some(T=>T.isValidating),f=l.every(T=>T.isValid),d=l.some(T=>T.isTouched),m=l.some(T=>T.isBlurred),x=l.every(T=>T.isDefaultValue),g=d&&c.errorMap?.onMount,y=l.some(T=>T.isDirty),h=!y,b=!!(c.errorMap?.onMount||l.some(T=>T?.errorMap?.onMount)),L=!!p,C=n?.errors??[];(!u||c.errorMap!==u.errorMap)&&(C=Object.values(c.errorMap).reduce((T,G)=>G===void 0?T:G&&bo(G)?(T.push(G.form),T):(T.push(G),T),[]));let I=C.length===0,k=f&&I,w=this.options.canSubmitWhenInvalid??false,q=c.submissionAttempts===0&&!d&&!b||!L&&!c.isSubmitting&&k||w,U=c.errorMap;if(g&&(C=C.filter(T=>T!==c.errorMap.onMount),U=Object.assign(U,{onMount:void 0})),n&&u&&n.errorMap===U&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===p&&n.isFieldsValid===f&&n.isFormValid===I&&n.isValid===k&&n.canSubmit===q&&n.isTouched===d&&n.isBlurred===m&&n.isPristine===h&&n.isDefaultValue===x&&n.isDirty===y&&ea(u,c))return n;let O={...c,errorMap:U,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:p,isFieldsValid:f,isFormValid:I,isValid:k,canSubmit:q,isTouched:d,isBlurred:m,isPristine:h,isDefaultValue:x,isDirty:y},R=this.options.transform?.deps??[];if(R.length!==this.prevTransformArray.length||R.some((T,G)=>T!==this.prevTransformArray[G])){let T=Object.assign({},this,{state:O});this.options.transform?.fn(T),O=T.state,this.prevTransformArray=R;}return O}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let a=xn(t=>Ye.emit("form-state",{id:this._formId,state:t}),{wait:300});this.store.subscribe(()=>{a(this.store.state);}),Ye.on("request-form-state",t=>{t.payload.id===this._formId&&Ye.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),Ye.on("request-form-reset",t=>{t.payload.id===this._formId&&this.reset();}),Ye.on("request-form-force-submit",t=>{t.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 Fr(o.validate)?aa[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})),$e(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(i=>({...i,isTouched:!0})));});});let a=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:a});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let t=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){t(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:a}),Ye.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){t(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:a}),Ye.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}$e(()=>{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:a});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:a}),$e(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),Ye.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),t();});}catch(r){throw this.baseStore.setState(i=>({...i,isSubmitSuccessful:false})),Ye.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),t(),r}}setErrorMap(o){$e(()=>{Object.entries(o).forEach(([a,t])=>{let r=a;if(bo(t)){let{formError:i,fieldErrors:n}=Pr(t);for(let u of Object.keys(this.fieldInfo))this.getFieldMeta(u)&&this.setFieldMeta(u,s=>({...s,errorMap:{...s.errorMap,[r]:n?.[u]},errorSourceMap:{...s.errorSourceMap,[r]:"form"}}));this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[r]:i}}));}else this.baseStore.setState(i=>({...i,errorMap:{...i.errorMap,[r]:t}}));});});}};function Pr(e){if(e){if(bo(e)){let o=Pr(e.form).formError,a=e.fields;return {formError:o,fieldErrors:a}}return {formError:e}}return {formError:void 0}}function Lo(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 Io=class{constructor(o){this.options={},this.mount=()=>{let a=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let t=this.getInfo();t.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let i=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});i&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:i},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),a},this.update=a=>{this.options=a;let t=this.name!==a.name;if(this.name=a.name,this.state.value===void 0){let r=Zt(a.form.options.defaultValues,a.name),i=a.defaultValue??r;t?this.setValue(n=>n||i,{dontUpdateMeta:true}):i!==void 0&&this.setValue(i,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(a,t)=>{this.form.setFieldValue(this.name,a,Te(t,{dontRunListeners:true,dontValidate:true})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=a=>this.form.setFieldMeta(this.name,a),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(a,t)=>{this.form.pushFieldValue(this.name,a,Te(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(a,t,r)=>{this.form.insertFieldValue(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(a,t,r)=>{this.form.replaceFieldValue(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(a,t)=>{this.form.removeFieldValue(this.name,a,Te(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(a,t,r)=>{this.form.swapFieldValues(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(a,t,r)=>{this.form.moveFieldValues(this.name,a,t,Te(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=a=>{this.form.clearFieldValues(this.name,Te(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=a=>{let t=Object.values(this.form.fieldInfo),r=[];for(let i of t){if(!i.instance)continue;let{onChangeListenTo:n,onBlurListenTo:u}=i.instance.options.validators||{};a==="change"&&n?.includes(this.name)&&r.push(i.instance),a==="blur"&&u?.includes(this.name)&&r.push(i.instance);}return r},this.validateSync=(a,t)=>{let r=qa(a,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ta}),n=this.getLinkedFields(a).reduce((s,l)=>{let p=qa(a,{...l.options,form:l.form,validationLogic:l.form.options.validationLogic||ta});return p.forEach(f=>{f.field=l;}),s.concat(p)},[]),u=false;$e(()=>{let s=(l,p)=>{let f=Er(p.cause),d=p.validate?Rl(l.runValidator({validate:p.validate,value:{value:l.store.state.value,validationSource:"field",fieldApi:l},type:"validate"})):void 0,m=t[f],{newErrorValue:x,newSource:g}=Tr({formLevelError:m,fieldLevelError:d});l.state.meta.errorMap?.[f]!==x&&l.setMeta(y=>({...y,errorMap:{...y.errorMap,[f]:x},errorSourceMap:{...y.errorSourceMap,[f]:g}})),x&&(u=!0);};for(let l of r)s(this,l);for(let l of n)l.validate&&s(l.field,l);});let c=Er("submit");return this.state.meta.errorMap?.[c]&&a!=="submit"&&!u&&this.setMeta(s=>({...s,errorMap:{...s.errorMap,[c]:void 0},errorSourceMap:{...s.errorSourceMap,[c]:void 0}})),{hasErrored:u}},this.validateAsync=async(a,t)=>{let r=Na(a,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||ta}),i=await t,n=this.getLinkedFields(a),u=n.reduce((f,d)=>{let m=Na(a,{...d.options,form:d.form,validationLogic:d.form.options.validationLogic||ta});return m.forEach(x=>{x.field=d;}),f.concat(m)},[]);this.state.meta.isValidating||this.setMeta(f=>({...f,isValidating:true}));for(let f of n)f.setMeta(d=>({...d,isValidating:true}));let c=[],s=[],l=(f,d,m)=>{let x=Er(d.cause);f.getInfo().validationMetaMap[x]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[x]={lastAbortController:y},m.push(new Promise(async h=>{let b;try{b=await new Promise((w,q)=>{this.timeoutIds.validations[d.cause]&&clearTimeout(this.timeoutIds.validations[d.cause]),this.timeoutIds.validations[d.cause]=setTimeout(async()=>{if(y.signal.aborted)return w(void 0);try{w(await this.runValidator({validate:d.validate,value:{value:f.store.state.value,fieldApi:f,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(U){q(U);}},d.debounceMs);});}catch(w){b=w;}if(y.signal.aborted)return h(void 0);let L=Rl(b),C=i[this.name]?.[x],{newErrorValue:I,newSource:k}=Tr({formLevelError:C,fieldLevelError:L});f.setMeta(w=>({...w,errorMap:{...w?.errorMap,[x]:I},errorSourceMap:{...w.errorSourceMap,[x]:k}})),h(I);}));};for(let f of r)f.validate&&l(this,f,c);for(let f of u)f.validate&&l(f.field,f,s);let p=[];(c.length||s.length)&&(p=await Promise.all(c),await Promise.all(s)),this.setMeta(f=>({...f,isValidating:false}));for(let f of n)f.setMeta(d=>({...d,isValidating:false}));return p.filter(Boolean)},this.validate=(a,t)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(a),{hasErrored:i}=this.validateSync(a,r[this.name]??{});if(i&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Er(a)]?.lastAbortController.abort(),this.state.meta.errors;let n=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(a);return this.validateAsync(a,n)},this.handleChange=a=>{this.setValue(a);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(t=>({...t,isTouched:true})),this.state.meta.isBlurred||this.setMeta(t=>({...t,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=a=>aa.validate({value:this.state.value,validationSource:"field"},a),this.parseValueWithSchemaAsync=a=>aa.validateAsync({value:this.state.value,validationSource:"field"},a),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new ht({deps:[this.form.store],fn:()=>{let a=this.form.getFieldValue(this.name),t=this.form.getFieldMeta(this.name)??{...Va,...o.defaultMeta};return {value:a,meta:t}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Fr(o.validate)?aa[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(a=>({...a,errorMap:{...a.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 a=this.options.listeners?.onBlurDebounceMs;a&&a>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});},a)):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 a=this.options.listeners?.onChangeDebounceMs;a&&a>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});},a)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function Rl(e){if(e)return e}function Er(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 Rr(e,o=a=>a){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,zm)}function zm(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[t,r]of e)if(!o.has(t)||!Object.is(r,o.get(t)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let t of e)if(!o.has(t))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let a=Bl(e);if(a.length!==Bl(o).length)return false;for(let t=0;t<a.length;t++)if(!Object.prototype.hasOwnProperty.call(o,a[t])||!Object.is(e[a[t]],o[a[t]]))return false;return true}function Bl(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Ha=typeof window<"u"?useLayoutEffect:useEffect;function Jm(e){let[o]=useState(()=>{let t=new Io({...e,form:e.form,name:e.name});return t.Field=Sn,t});return Ha(o.mount,[o]),Ha(()=>{o.update(e);}),Rr(o.store,e.mode==="array"?a=>[a.meta,Object.keys(a.value??[]).length]:void 0),o}var Sn=(({children:e,...o})=>{let a=Jm(o),t=useMemo(()=>Qt(e,a),[e,a,a.state.value,a.state.meta]);return jsx(Fragment,{children:t})});function ep({form:e,selector:o,children:a}){let t=Rr(e.store,o);return Qt(a,t)}function Cn(e){let o=useId(),[a]=useState(()=>{let t=new yo({...e,formId:o}),r=t;return r.Field=function(n){return jsx(Sn,{...n,form:t})},r.Subscribe=function(n){return jsx(ep,{form:t,selector:n.selector,children:n.children})},r});return Ha(a.mount,[]),Ha(()=>{a.update(e);}),a}function kn({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 rp=({editElement:e})=>{let o=useDispatch(),a=useSelector(ce),t=!!e,r=e?.data.questionType||a?.activityType||"multiple-choice",[i,n]=useState(r),u=Cn({defaultValues:{questionType:r,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:s})=>{if(s.questionType==="true-false"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctAnswer:s.responseOptions.correctAnswer??false}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:300,rotation:t?e.rotation:0};o(t?Ut(l):vs(l));}else if(s.questionType==="multiple-choice"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctIndex:s.responseOptions.correctIndex??[]}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?Ht(l):xs(l));}else if(s.questionType==="short-answer"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctShortAnswer:s.responseOptions.correctShortAnswer??""}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?Xa(l):ys(l));}else if(s.questionType==="fill-in-the-blank"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctShortAnswer:s.responseOptions.correctShortAnswer??""}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?_a(l):Cs(l));}else if(s.questionType==="long-answer"){let l={id:t?e.id:v4(),data:{questionType:s.questionType,responseType:s.responseType,feedbackMode:s.feedbackMode,question:s.question,responseOptions:{options:s.responseOptions.options,correctLongAnswer:s.responseOptions.correctLongAnswer??""}},x:t?e.x:500,y:t?e.y:200,width:t?e.width:400,height:t?e.height:400,rotation:t?e.rotation:0};o(t?$a(l):ws(l));}o(Wt(false));}}),c=()=>{o(Wt(false));};return 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",{className:"h-fit max-h-[calc(100vh-300px)] w-full max-w-2xl overflow-y-auto rounded-lg bg-white p-6",children:jsxs("form",{className:"relative h-full max-h-[calc(100vh-300px)] w-full max-w-2xl rounded-lg bg-white p-6",onSubmit:s=>{s.preventDefault(),s.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-4",children:[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:()=>{c();},children:jsx("span",{className:"text-xl",children:"\u2715"})}),jsx("h2",{className:"text-xl font-bold text-gray-900",children:t?"Edit Question":"Add Question"}),jsx("div",{className:"w-8"})]}),jsx(u.Field,{name:"questionType",children:s=>jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:s.name,name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:l=>{s.handleChange(l.target.value),n(l.target.value);},disabled:t,className:`w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none ${t?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"\u2630 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"})})})]}),t&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Question type cannot be changed when editing"}),jsx(kn,{field:s})]})}),i&&!["short-answer","fill-in-the-blank","long-answer"].includes(i)&&jsx(u.Field,{name:"responseType",children:s=>jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:s.name,name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:l=>s.handleChange(l.target.value),className:"w-full appearance-none rounded-lg border border-gray-300 bg-white px-4 py-3 pr-10 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none",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(kn,{field:s})]})}),jsx(u.Field,{name:"feedbackMode",children:s=>jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Feedback Mode"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:s.name,name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:l=>s.handleChange(l.target.value),disabled:i==="long-answer",className:`w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none ${i==="long-answer"?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"practice",children:"Practice Mode"}),jsx("option",{value:"test",children:"Assessment Mode"})]}),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"})})})]}),i==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(kn,{field:s})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:s})=>s?void 0:"A question is required"},children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"w-full resize-none rounded-lg border border-gray-300 bg-white px-4 py-3 text-gray-900 outline-none focus:border-[#096B76] focus:ring-2 focus:ring-[#096B76]/20 focus:outline-none",value:s.state.value,onChange:l=>s.handleChange(l.target.value),onBlur:s.handleBlur})}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}),jsxs("button",{type:"button",className:"flex w-full items-center justify-center gap-2 rounded-lg border-2 border-gray-300 bg-white px-4 py-3 font-medium text-gray-900 transition-colors hover:border-gray-400 hover:bg-gray-50",children:[jsx("span",{children:"\u{1F50D}"}),jsx("span",{children:"Find Questions"})]}),i==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{className:"text-sm font-semibold text-gray-900",children:"Correct Answer"}),jsxs("div",{className:"flex gap-4",children:[jsxs("button",{type:"button",onClick:()=>s.handleChange(true),className:`flex flex-1 items-center justify-center gap-3 rounded-lg border-2 px-6 py-4 transition-colors ${s.state.value===true?"border-green-500 bg-green-50":"border-gray-300 bg-white hover:border-gray-400"}`,children:[jsx("div",{className:`flex h-6 w-6 items-center justify-center rounded-full border-2 ${s.state.value===true?"border-green-500 bg-green-500":"border-gray-300"}`,children:s.state.value===true&&jsx("div",{className:"h-3 w-3 rounded-full bg-white"})}),jsx("span",{className:"text-lg font-semibold text-black",children:"True"})]}),jsxs("button",{type:"button",onClick:()=>s.handleChange(false),className:`flex flex-1 items-center justify-center gap-3 rounded-lg border-2 px-6 py-4 transition-colors ${s.state.value===false?"border-green-500 bg-green-50":"border-gray-300 bg-white hover:border-gray-400"}`,children:[jsx("div",{className:`flex h-6 w-6 items-center justify-center rounded-full border-2 ${s.state.value===false?"border-green-500 bg-green-500":"border-gray-300"}`,children:s.state.value===false&&jsx("div",{className:"h-3 w-3 rounded-full bg-white"})}),jsx("span",{className:"text-lg font-semibold text-black",children:"False"})]})]}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Select the correct answer for this true/false question"})]})}),i==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:s})=>{if(s.options.filter(p=>!p.trim()).length>0)return "All options must have text";if(!s.correctIndex||s.correctIndex.length===0)return "Please select at least one correct answer"}},children:s=>{let l=(m,x)=>{let g=[...s.state.value.options];g[m]=x,s.handleChange({...s.state.value,options:g});},p=()=>{if(s.state.value.options.length>=6){alert("Maximum 6 options allowed");return}s.handleChange({...s.state.value,options:[...s.state.value.options,""]});},f=m=>{if(s.state.value.options.length<=2){alert("Minimum 2 options required");return}let x=s.state.value.options.filter((y,h)=>h!==m),g=s.state.value.correctIndex?.filter(y=>y!==m).map(y=>y>m?y-1:y);s.handleChange({...s.state.value,options:x,correctIndex:g});},d=m=>{let x=s.state.value.correctIndex||[];if(x.includes(m))s.handleChange({...s.state.value,correctIndex:x.filter(y=>y!==m)});else {if(x.length>=6){alert("Maximum 6 correct answers allowed");return}s.handleChange({...s.state.value,correctIndex:[...x,m]});}};return jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:["Response Options (",s.state.value.options.length,"/6)"]}),jsx("button",{type:"button",onClick:p,disabled:s.state.value.options.length>=6,className:"rounded-lg bg-[#096B76] px-3 py-1 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50",children:"+ Add Option"})]}),jsx("div",{className:"flex flex-col gap-3",children:s.state.value.options.map((m,x)=>{let g=!m.trim(),y=s.state.value.correctIndex?.includes(x),h=s.state.meta.isTouched&&g;return jsxs("div",{className:`flex items-center gap-3 rounded-lg border-2 px-4 py-3 transition-colors ${h?"border-red-500 bg-red-50":y?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:[jsx("button",{type:"button",onClick:()=>d(x),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors ${y?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:y&&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("input",{type:"text",placeholder:`Option ${x+1}`,value:m,onChange:b=>l(x,b.target.value),onBlur:s.handleBlur,className:"flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"}),s.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>f(x),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded bg-red-500 text-white transition-colors hover:bg-red-600",children:jsx("span",{className:"text-sm",children:"\u2715"})})]},x)})}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Click the box to mark the correct answer"}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}}),(i==="short-answer"||i==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:s.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:s.state.value,onChange:l=>{s.handleChange(l.target.value);},className:"w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors focus:border-[#096B76] focus:outline-none"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Learners must write this answer exactly (case-insensitive)."}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}),i==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:s=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:s.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:s.state.value,onChange:l=>{s.handleChange(l.target.value);},rows:6,className:"w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors focus:border-[#096B76] focus:outline-none"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"This will be used as a reference answer for manual grading."}),s.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:s.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:s=>[s.canSubmit,s.isSubmitting],children:([s,l])=>jsx("button",{type:"submit",disabled:!s,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:l?"Saving...":t?"Update Question":"Save Question"})})]})})})},ql=rp;var Nl=({text:e,position:o})=>{let a=pe(),t=s=>{a(oe()),a(st({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+s))}));},r=s=>{a(oe()),a(st({id:e.id,fill:s}));},i=()=>{a(oe()),a(st({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{a(oe()),a(st({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},u=()=>{a(oe()),a(st({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},c=s=>{a(oe()),a(st({id:e.id,fontFamily:s}));};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:s=>s.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:s=>c(s.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:()=>t(-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:()=>t(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:i,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:jsx(TextB,{size:16,weight:"bold"})}),jsx("button",{onClick:n,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:jsx(TextItalic,{size:16,weight:"bold"})}),jsx("button",{onClick:u,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:s=>r(s.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var Hl=({text:e,editingValue:o,onEditingChange:a,onFinish:t,position:r,scale:i,textareaRef:n})=>{let u=useRef(null),c=useMemo(()=>({fontSize:`${e.fontSize*i}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,i]),s=useCallback(l=>{l.style.height="auto",l.style.height=`${l.scrollHeight}px`;let p=document.createElement("span");p.style.font=window.getComputedStyle(l).font,p.style.fontSize=l.style.fontSize,p.style.fontFamily=l.style.fontFamily,p.style.fontWeight=l.style.fontWeight,p.style.fontStyle=l.style.fontStyle,p.style.visibility="hidden",p.style.position="absolute",p.style.whiteSpace="pre";let f=l.value.split(`
4
+ `),d=0;document.body.appendChild(p);for(let x of f){p.textContent=x||" ";let g=p.offsetWidth;g>d&&(d=g);}document.body.removeChild(p);let m=10;l.style.width=`${Math.max(200,d+m+20)}px`;},[]);return useEffect(()=>{let l=u.current;l&&(l.style.fontSize=`${e.fontSize*i}px`,l.style.fontFamily=e.fontFamily,l.style.fontStyle=e.fontStyle,l.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",l.style.textDecoration=e.textDecoration,l.style.color=e.fill,s(l));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,i,s]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:l=>{if(u.current=l,n.current=l,l){l.focus();let p=l.value.length;l.setSelectionRange(p,p),s(l);}},value:o,onChange:l=>{a(l.target.value);},onKeyDown:l=>{l.key==="Escape"&&t();},style:c},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Ul=memo(({shortAnswer:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>{let n=useSelector(E=>E.toolbar.selectedTool),u=n==="pen"||n==="eraser",c=useRef(null),[s,l]=useState(""),[p,f]=useState(false),[d,m]=useState(null);useEffect(()=>{let E=c.current;if(E)return t.current.set(e.id,E),()=>{t.current.delete(e.id);}},[e.id,t]);let x=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",g=p&&s.trim().toLowerCase()===x,y=()=>{f(false),l("");},h=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",b=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,C=60,I=p?50:0,k=50,w=12,q=e.data.feedbackMode==="practice"?48:0,U=12,O=30,R=C+I+O+k+w+U+q+L;return jsxs(Group,{ref:c,draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"sa-element",...u?{}:{onDragEnd:i,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let T=c.current?.getStage()?.getPointerPosition();if(!T)return;let G={x:e.x,y:e.y,width:e.width,height:e.height};T.x>=G.x&&T.x<=G.x+G.width&&T.y>=G.y&&T.y<=G.y+G.height&&r(E.evt,e.id,"shortAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:R,onTransformEnd:E=>a(e.id,E)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:I,text:h(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer:",x:L,y:C+I+w,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+I+O,width:e.width-L*2,height:k,fill:"#ffffff",stroke:g?"#22c55e":p?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${C+I+O}px`,left:`${L}px`,width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:p?"none":"auto"}},children:jsx("input",{type:"text",value:s,onChange:E=>l(E.target.value),disabled:p,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:p?"none":"auto"}})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C+I+O+k+w+U,children:[!p&&jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,m("check");},onMouseUp:E=>{E.cancelBubble=true,m(null),s.length>0&&f(true);},onMouseLeave:E=>{E.cancelBubble=true,m(null);},onTouchStart:E=>{E.cancelBubble=true,m("check");},onTouchEnd:E=>{E.cancelBubble=true,m(null),s.length>0&&f(true);},scaleX:d==="check"?.95:1,scaleY:d==="check"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:s.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),p&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),y();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),y();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.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})]})]})]})});Ul.displayName="ShortAnswer";var Wl=Ul;var zl=({shortAnswers:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>jsx(Fragment,{children:e.map(n=>jsx(Wl,{shortAnswer:n,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:u=>i(u,n.id)},n.id))});var Gl=e=>{let o=useDispatch(),t=useSelector(ce)?.fillInTheBlanks||[],r=useRef(new Map),i=useCallback((n,u)=>{let c=n.target;o(_a({id:u,x:c.x(),y:c.y()})),e?.();},[o,e]);return {fillInTheBlanks:t,fibRefs:r,handleFillInTheBlanksDragEnd:i}};var jl=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:a,handleDragEnd:t,onContextMenu:r})=>{let i=useSelector(R=>R.toolbar.selectedTool),n=i==="pen"||i==="eraser",u=useRef(null),[c,s]=useState(""),[l,p]=useState(false),[f,d]=useState(null);useEffect(()=>{if(u.current)return ()=>{}},[e.id]);let m=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",x=l&&c.trim().toLowerCase()===m,g=()=>{p(false),s("");},y=()=>x?"\u2713 Correct! \u{1F389}":"\u2717 Try again!",h=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=24,L=80,C=l?50:0,I=45,k=8,w=20,q=e.data.feedbackMode==="practice"?48:0,U=12,O=L+C+k+w+k+U+q+b;return jsxs(Group,{ref:u,draggable:!n,listening:!n,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...n?{}:{onDragEnd:R=>t(R,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:R=>{let E=u.current?.getStage()?.getPointerPosition();if(!E||!r)return;let T={x:e.x,y:e.y,width:e.width,height:e.height};E.x>=T.x&&E.x<=T.x+T.width&&E.y>=T.y&&E.y<=T.y+T.height&&r(R.evt,e.id,"fillInTheBlanks");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:O,onTransformEnd:R=>a(e.id,R)}),jsx(Text,{text:e.data.question,x:b,y:b,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2-200,listening:false}),jsx(Rect,{x:e.width-b-180,y:b+10,width:180,height:I,fill:"#ffffff",stroke:x?"#22c55e":l?"#ef4444":"#096B76",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${b+10}px`,left:`${e.width-b-180}px`,width:"180px",height:`${I}px`,pointerEvents:l?"none":"auto"}},children:jsx("input",{type:"text",value:c,onChange:R=>s(R.target.value),disabled:l,placeholder:"__________",className:"h-full w-full border-0 bg-white px-2 text-center text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:l?"none":"auto"}})}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:b,y:L,width:e.width-b*2,height:C,fill:h().bg,cornerRadius:8}),jsx(Text,{x:b,y:L,width:e.width-b*2,height:C,text:y(),fontSize:16,fontStyle:"bold",fill:h().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"\u26A0\uFE0F Answer is case sensitive",x:b,y:L+C+k,fontSize:10,fontStyle:"italic",fill:"#6b7280",width:e.width-b*2,listening:false}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:L+C+k+w+k+U,children:[!l&&jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,d("check");},onMouseUp:R=>{R.cancelBubble=true,d(null),c.length>0&&p(true);},onMouseLeave:R=>{R.cancelBubble=true,d(null);},onTouchStart:R=>{R.cancelBubble=true,d("check");},onTouchEnd:R=>{R.cancelBubble=true,d(null),c.length>0&&p(true);},scaleX:f==="check"?.95:1,scaleY:f==="check"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:c.length===0?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Check",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{onMouseDown:()=>d("reset"),onMouseUp:()=>{d(null),g();},onMouseLeave:()=>d(null),onTouchStart:()=>d("reset"),onTouchEnd:()=>{d(null),g();},scaleX:f==="reset"?.95:1,scaleY:f==="reset"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*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,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});jl.displayName="FillInTheBlanks";var Xl=jl;var _l=({fillInTheBlanks:e,handleSelect:o,handleTransform:a,onContextMenu:t,handleDragEnd:r})=>jsx(Fragment,{children:e.map(i=>jsx(Xl,{fillInTheBlank:i,handleSelect:o,handleTransform:a,onContextMenu:t,handleDragEnd:r},i.id))});var Pn=memo(({longAnswer:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>{let n=useSelector(E=>E.toolbar.selectedTool),u=n==="pen"||n==="eraser",c=useRef(null),[s,l]=useState(""),[p,f]=useState(false),[d,m]=useState(null);useEffect(()=>{let E=c.current;if(E)return t.current.set(e.id,E),()=>{t.current.delete(e.id);}},[e.id,t]);let x=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",g=p&&s.trim().toLowerCase()===x,y=()=>{f(false),l("");},h=()=>g?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",b=()=>g?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,C=60,I=p?60:0,k=120,w=12,q=48,U=12,O=30,R=C+I+O+k+w+U+q+L;return jsxs(Group,{ref:c,draggable:!u,listening:!u,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...u?{}:{onDragEnd:i,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:E=>{let T=c.current?.getStage()?.getPointerPosition();if(!T||!r)return;let G={x:e.x,y:e.y,width:e.width,height:e.height};T.x>=G.x&&T.x<=G.x+G.width&&T.y>=G.y&&T.y<=G.y+G.height&&r(E.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:R,onTransformEnd:E=>a(e.id,E)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),p&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:I,fill:b().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:I,text:h(),fontSize:14,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:C+I+w,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+I+O,width:e.width-L*2,height:k,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{divProps:{style:{position:"absolute",top:`${C+I+O}px`,left:`${L}px`,width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:p?"none":"auto"}},children:jsx("textarea",{value:s,onChange:E=>l(E.target.value),disabled:p,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:p?"none":"auto"}})}),jsx(Group,{y:C+I+O+k+w+U,children:p&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),y();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),y();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.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})]})})]})});Pn.displayName="LongAnswer";var Yl=({longAnswer:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>jsx(Fragment,{children:e.map(n=>jsx(Pn,{longAnswer:n,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:u=>i(u,n.id)},n.id))});var qp=({onStageReady:e,onSelectionChange:o,onTextEditingReady:a,onDirectDrawingCanvasReady:t}={})=>{let r=yt(),i=$(v=>v.toolbar.selectedTool);$(v=>v.canvas.isSketchMode);let u=$(ce),c=$(Za),s=u?.editingActivity,l=u?.showMcqForm,p=u?.lines||[],f=useRef(null),d=useRef(null),[m,x]=useState(null),[g,y]=useState(""),[h,b]=useState({width:1280,height:1200}),[L,C]=useState(null),[I,k]=useState(null),[w,q]=useState(null),[U,O]=useState(null),[R,E]=useState(null),[T,G]=useState(null),[z,me]=useState(null),[J,de]=useState(false),[N,D]=useState(null),[V,j]=useState(false),te=useRef(null),Z=useRef(null),ae=useRef(null),{debouncedGenerateThumbnail:Ce}=Bi(c,f);useEffect(()=>{let v=()=>{if(d.current){let A=d.current.getBoundingClientRect();b({width:A.width,height:A.height});}};v();let M=new ResizeObserver(v);return d.current&&M.observe(d.current),window.addEventListener("resize",v),()=>{M.disconnect(),window.removeEventListener("resize",v);}},[]),useEffect(()=>{if(f.current){let v=f.current.container();v&&(v.style.cursor="");}},[i]);let _=useCallback(()=>{f.current&&requestAnimationFrame(()=>{if(!f.current)return;f.current.getLayers().forEach(P=>P.batchDraw());let M=1/6,A=f.current.toDataURL({pixelRatio:M});y(A),Ce();});},[Ce]),Pe=useRef(c);useEffect(()=>{Pe.current!==c&&(Pe.current=c,_());},[c,_]);let vt=useRef(null),B=useRef(true);useEffect(()=>{if(!u)return;let v=(u.lines?.length||0)+(u.images?.length||0)+(u.videos?.length||0)+(u.shapes?.length||0)+(u.texts?.length||0)+(u.flashcards?.length||0)+(u.photoFrames?.length||0)+(u.multipleChoices?.length||0)+(u.trueFalses?.length||0)+(u.shortAnswers?.length||0)+(u.LongAnswer?.length||0)+(u.fillInTheBlanks?.length||0),M=vt.current?.count!==v;!B.current&&M&&setTimeout(()=>{_();},100),vt.current={slideId:c,count:v},B.current=false;},[u,c,_]),useEffect(()=>{f.current&&e&&e(f);},[e]),useEffect(()=>{ae.current&&t&&t(ae);},[t]);let{startDrawing:se,draw:ie,stopDrawing:le,setCanvasRef:Q,tool:ee,color:Le,strokeWidth:Ze,isSketchMode:kt}=li(_),Ae=useRef(new Map),{images:we,getLoadedImage:Be,imageRefs:et,handleDragEnd:Ot,handleImageTransformEnd:ya}=hi(_),{videos:Mt,videoRefs:na,handleVideoClick:tt,handleVideoDragEnd:qt,handleVideoTransformEnd:ia}=bi(_),{multipleChoice:Sd,handleMcqTransform:No,mcqRefs:Vo,handleDragEnd:Cd}=gi(_),{trueFalse:kd,handleTrueFalseTransform:Md,trueFalseRefs:jn,handleTrueFalseDragEnd:Ad}=xi(_),{shortAnswers:Dd,saRefs:Ka,handleShortAnswerDragEnd:Td}=Si(_),{longAnswers:Fd,handleLongAnswerDragEnd:Pd}=Ci(_),{fillInTheBlanks:Ed,handleFillInTheBlanksDragEnd:Rd}=zl(_),{transformerRef:re,boundBoxFunc:at}=Fi(),{shapes:Bd,shapeRefs:Ho,isDragging:Xn,handleShapeDragEnd:Od,handleShapeResizeEnd:qd}=yi(_),{texts:za,textRefs:Nt,handleDragEnd:Nd,handleTransformEnd:Vd,handleDoubleClick:Hd,startEditing:Uo,editingTextId:ue,editingValue:$n,handleEditingChange:_n,finishEditing:Wr}=wi(_,te);useEffect(()=>{a&&a(Uo);},[a,Uo]);let Wo=$(v=>v.canvas.editingTextId);useEffect(()=>{Wo&&Wo!==ue&&Uo(Wo);},[Wo,ue,Uo]);let{flashcards:Ud,flashcardRefs:Ko,handleDragEnd:Wd,handleFlashcardTransformEnd:Kd,handleNext:zd,handlePrevious:Gd}=Mi(_),{photoFrames:Yn,photoFrameRefs:zo,handleDragEnd:jd,handlePhotoFrameTransformEnd:Xd,startCamera:$d,capturePhoto:_d,cameraStreams:Yd}=Ti(_);useEffect(()=>{if(re.current){if(ue){re.current.nodes([]),re.current.getLayer()?.batchDraw();return}if(m&&!Mt.find(A=>A.id===m)?.isPlaying){let A=Ae.current.get(m)||et.current.get(m)||na.current.get(m)||Ho.current.get(m)||Nt.current.get(m)||Vo.current.get(m)||Ko.current.get(m)||zo.current.get(m);if(A){let P=A.attrs?.locked;if(A.visible()&&P!==true){re.current.nodes([A]),re.current.getLayer()?.batchDraw();return}}}re.current.nodes([]),re.current.getLayer()?.batchDraw();}},[m,ue,Mt,Ae,et,na,Ho,Nt,Ko,zo,Yn,Vo,re]);let De=useCallback(v=>{x(v),o?.(v);},[o]),Go=useCallback(()=>{x(null),o?.(null),re.current&&(re.current.nodes([]),re.current.getLayer()?.batchDraw());},[re,o]);useEffect(()=>{let v=re.current;return ()=>{v&&v.nodes([]);}},[c]),useEffect(()=>{let v=M=>{ue&&M.target.tagName!=="TEXTAREA"&&Wr();};return document.addEventListener("mousedown",v),()=>{document.removeEventListener("mousedown",v);}},[ue,Wr]),useEffect(()=>{let v=ue||m;if(!v||m&&ue){k(null);return}let M=Nt.current.get(v),A=f.current;if(!M||!A){k(null);return}let P=A.container().getBoundingClientRect(),Oe=M.absolutePosition(),ye=A.scaleX();k({x:P.left+(Oe.x+M.width()*ye/2)*ye,y:P.top+Oe.y*ye});},[m,ue,za,Nt]),useEffect(()=>{if(!ue){q(null);return}let v=Nt.current.get(ue),M=f.current;if(!v||!M){q(null);return}let A=M.container().getBoundingClientRect(),P=v.absolutePosition(),Oe=M.scaleX();q({top:A.top+P.y*Oe,left:A.left+P.x*Oe,scale:Oe});},[ue,za,Nt]);let Jn=useCallback(v=>{let M=v.target.getClassName(),A=v.target===v.target.getStage(),P=M==="Transformer"||v.target.getParent()?.getClassName()==="Transformer",Oe=M==="Image",ye=M==="Text",Y=M==="Group"||v.target.getParent()?.getClassName()==="Group",At=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&v.target.attrs.id,Lt=M==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:M,clickedOnImage:Oe,clickedOnGroup:Y,tool:i,targetId:v.target.attrs?.id}),A&&!P&&!Oe&&!ye&&!Y&&!At&&!Lt&&Go(),!(i==="pen"||i==="eraser")&&(Oe||ye||P||Y||At||Lt))return;let je=v.target.getStage()?.getPointerPosition();if(!je)return;["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(i)||se(je);},[i,se,Go]),Qn=useCallback(v=>{if(Xn)return;let M=v.target.getStage()?.getPointerPosition();M&&ie(M);},[ie,Xn]),Zn=useCallback(()=>{le();},[le]),Jd=useCallback(v=>{Ot(v,_);},[Ot,_]),Qd=useCallback(v=>{tt(v),De(v);},[tt,De]),ot=useCallback((v,M,A)=>{v.preventDefault(),C({x:v.clientX,y:v.clientY,elementId:M,elementType:A}),De(M);},[De]),ei=useCallback(v=>{r(Ya(v)),r(Wt(true));},[r]),Zd=useCallback(v=>{r(ja(v)),r(da(true));},[r]),eu=useCallback((v,M)=>{if(!L)return;let{elementId:A,elementType:P}=L;switch(v){case "order":if(M){let S=M.target.getBoundingClientRect();O({x:S.right+5,y:S.top,type:"order"});}break;case "lock":if(M){let S=M.target.getBoundingClientRect();O({x:S.right+5,y:S.top,type:"lock"});}break;case "link":if(C(null),P==="line")break;let Oe=u?P==="image"?u.images.find(S=>S.id===A):u.videos.find(S=>S.id===A):null;E({type:"link",defaultValue:Oe?.link||""});break;case "voice":if(C(null),P==="line")break;let ye=u?P==="image"?u.images.find(S=>S.id===A):P==="video"?u.videos.find(S=>S.id===A):P==="text"?u.texts.find(S=>S.id===A):P==="flashcard"?u.flashcards.find(S=>S.id===A):P==="photoFrame"?u.photoFrames.find(S=>S.id===A):P==="mcq"?u.multipleChoices.find(S=>S.id===A):P==="fillInTheBlanks"?u.fillInTheBlanks.find(S=>S.id===A):P==="longAnswer"?u.LongAnswer.find(S=>S.id===A):P==="shortAnswer"?u.shortAnswers.find(S=>S.id===A):P==="trueFalse"?u.trueFalses.find(S=>S.id===A):P==="shape"?u.shapes.find(S=>S.id===A):null:null;D({elementId:A,elementType:P,existingAudio:ye?.audioData});break;case "edit":C(null);let Y=null;P==="mcq"?Y=u?.multipleChoices.find(S=>S.id===A):P==="trueFalse"?Y=u?.trueFalses.find(S=>S.id===A):P==="shortAnswer"?Y=u?.shortAnswers.find(S=>S.id===A):P==="longAnswer"?Y=u?.LongAnswer.find(S=>S.id===A):P==="fillInTheBlanks"&&(Y=u?.fillInTheBlanks.find(S=>S.id===A)),Y&&ei(Y);break;case "editFlashcard":C(null);let At=u?.flashcards.find(S=>S.id===A);At&&Zd(At);break;case "color":C(null);let Lt=u?.shapes.find(S=>S.id===A);G({elementId:A,elementType:"shape",defaultColor:Lt?.color||"#096B76"});break;case "crop":if(C(null),P==="image"){let S=u?.images.find(iu=>iu.id===A);S&&me({elementId:A,imageSrc:S.src});}break;case "draw":C(null),P==="image"?r(ms(A)):P==="photoFrame"&&r(hs(A));break;case "duplicate":r(oe()),P==="line"?r(Es(A)):P==="image"?r(Xo(A)):P==="video"?r(Yo(A)):P==="shape"?r(Jo(A)):P==="text"?r(Qo(A)):P==="flashcard"?r(Zo(A)):P==="photoFrame"?r(er(A)):P==="mcq"?r(tr(A)):P==="trueFalse"?r(ar(A)):P==="shortAnswer"?r(or(A)):P==="fillInTheBlanks"?r(sr(A)):P==="longAnswer"&&r(rr(A)),_();break;case "infinite-clone":r(oe());let mt=5;for(let S=0;S<mt;S++)P==="image"?r(Xo(A)):P==="video"?r(Yo(A)):P==="shape"?r(Jo(A)):P==="text"?r(Qo(A)):P==="flashcard"?r(Zo(A)):P==="photoFrame"?r(er(A)):P==="mcq"?r(tr(A)):P==="trueFalse"?r(ar(A)):P==="shortAnswer"?r(or(A)):P==="fillInTheBlanks"?r(sr(A)):P==="longAnswer"&&r(rr(A));_();break;case "make-response":if(C(null),P==="line")break;let je=`#response-${A}`;r(oe()),r(nr({id:A,type:P,link:je})),(u?P==="image"?u.images.find(S=>S.id===A):P==="video"?u.videos.find(S=>S.id===A):P==="shape"?u.shapes.find(S=>S.id===A):P==="flashcard"?u.flashcards.find(S=>S.id===A):P==="photoFrame"?u.photoFrames.find(S=>S.id===A):u.multipleChoices.find(S=>S.id===A):null)?.altText||r(ir({id:A,type:P,altText:"Interactive response area"})),_(),console.log(`Element ${A} marked as interactive response area`);break;case "accessibility":if(C(null),P==="line")break;let F=u?P==="image"?u.images.find(S=>S.id===A):P==="video"?u.videos.find(S=>S.id===A):P==="shape"?u.shapes.find(S=>S.id===A):null:null;E({type:"altText",defaultValue:F?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),C(null),j(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(oe()),P==="line"?r(Ps(A)):P==="image"?r(ts(A)):P==="video"?r(as(A)):P==="shape"?r(rs(A)):P==="text"?r(ns(A)):P==="flashcard"?r(ls(A)):P==="photoFrame"?r(fs(A)):P==="mcq"?r(bs(A)):P==="trueFalse"?r(Ls(A)):P==="shortAnswer"?r(Is(A)):P==="longAnswer"?r(Ss(A)):P==="fillInTheBlanks"&&r(ks(A)),Go(),_();break}},[L,r,_,Go,u,ei]),tu=useCallback(()=>{C(null),O(null);},[]),Kr=useCallback(v=>{if(!L)return;let{elementId:M,elementType:A}=L;switch(r(oe()),v){case "bring-to-front":A!=="line"&&r(As({id:M,type:A}));break;case "send-to-back":A!=="line"&&r(Ds({id:M,type:A}));break;case "lock":case "unlock":A!=="line"&&r(Ts({id:M,type:A}));break}_(),C(null),O(null);},[L,r,_]),au=useCallback(v=>{if(!L||!R)return;let{elementId:M,elementType:A}=L;r(oe()),R.type==="link"&&A!=="line"?r(nr({id:M,type:A,link:v})):R.type==="altText"&&A!=="line"&&r(ir({id:M,type:A,altText:v})),_(),E(null);},[L,R,r,_]),ou=useCallback(v=>{if(!N)return;let{elementId:M,elementType:A}=N;r(oe()),r(lr({id:M,type:A,audioData:v})),_(),D(null);},[N,r,_]),ru=useCallback(()=>{if(!N)return;let{elementId:v,elementType:M}=N;r(oe()),r(lr({id:v,type:M,audioData:""})),_();},[N,r,_]),su=useCallback(v=>{if(!T)return;let{elementId:M}=T;r(oe()),r(wa({id:M,color:v})),_(),G(null);},[T,r,_]),nu=useCallback(v=>{if(!z)return;let{elementId:M}=z;r(oe()),r(Ia({id:M,src:v})),_(),me(null);},[z,r,_]);return jsxs("div",{ref:d,className:"fixed inset-0",style:{cursor:i==="pen"?"crosshair":i==="eraser"?"":"default"},children:[i==="pen"&&jsx(mi,{ref:v=>{if(Z.current=v,Q(v),v){let M=v.getCanvasElement();M&&(ae.current=M,t&&t(ae));}},width:h.width,height:h.height,tool:ee,color:Le,strokeWidth:Ze,isSketchMode:kt}),jsxs(Stage,{ref:f,width:h.width,height:h.height,onMouseDown:Jn,onMouseMove:Qn,onMouseUp:Zn,onTouchStart:Jn,onTouchMove:Qn,onTouchEnd:Zn,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:h.width,height:h.height,fill:u?.backgroundColor||"white"})}),jsx(Layer,{children:(()=>{let v=[];return p.forEach((M,A)=>{v.push({type:"line",timestamp:M.timestamp||A,element:{...M,id:M.id??`line-${A}`},index:A});}),Bd.forEach(M=>{v.push({type:"shape",timestamp:M.timestamp||0,element:M});}),we.forEach(M=>{v.push({type:"image",timestamp:M.timestamp||0,element:M});}),Mt.forEach(M=>{v.push({type:"video",timestamp:M.timestamp||0,element:M});}),za.forEach(M=>{v.push({type:"text",timestamp:M.timestamp||0,element:M});}),Ud.forEach(M=>{v.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Yn.forEach(M=>{v.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),Sd.forEach(M=>{v.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),kd.forEach(M=>{v.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Dd.forEach(M=>{v.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),Fd.forEach(M=>{v.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),Ed.forEach(M=>{v.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),v.sort((M,A)=>M.timestamp-A.timestamp),v.map((M,A)=>{let P=`${M.type}-${"id"in M.element&&M.element.id||M.index||A}`,Oe="id"in M.element?M.element.id:void 0,ye=Oe&&m===Oe;switch(M.type){case "line":let Y=M.element,At=M.index||0,Lt=Y.tool==="eraser",mt=Y.isSketch&&Y.tool==="pen",je=Y.isSketch&&Lt,rt=Y.id||`line-${At}`;return Y.x===void 0&&(Y.x=0),Y.y===void 0&&(Y.y=0),Y.scaleX===void 0&&(Y.scaleX=1),Y.scaleY===void 0&&(Y.scaleY=1),Y.rotation===void 0&&(Y.rotation=0),i==="eraser"?jsx(Group,{x:Y.x||0,y:Y.y||0,scaleX:Y.scaleX||1,scaleY:Y.scaleY||1,rotation:Y.rotation||0,children:jsx(Line,{points:Y.points||[],stroke:mt||je?void 0:Y.color,strokeWidth:mt||je?0:Y.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:mt||je?Lt?"black":Y.color:void 0,closed:mt||je,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,onClick:()=>{r(oe()),r(jo(At));},onTap:()=>{r(oe()),r(jo(At));},hitStrokeWidth:Math.max(20,(Y.strokeWidth??0)*2),onMouseEnter:F=>{let S=F.target.getStage();S&&(S.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:F=>{let S=F.target.getStage();S&&(S.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`);}})},P):jsxs(ut.Fragment,{children:[jsx(Group,{id:rt,ref:F=>{F?Ae.current.set(rt,F):Ae.current.delete(rt);},x:Y.x||0,y:Y.y||0,scaleX:Y.scaleX||1,scaleY:Y.scaleY||1,rotation:Y.rotation||0,draggable:i==="select",listening:i==="select",onClick:()=>{i==="select"&&(console.log("Line clicked:",rt),De(rt));},onTap:()=>{i==="select"&&(console.log("Line tapped:",rt),De(rt));},onDragEnd:F=>{r(oe()),r(dr({id:rt,x:F.target.x(),y:F.target.y(),scaleX:F.target.scaleX(),scaleY:F.target.scaleY(),rotation:F.target.rotation()})),_();},onTransformEnd:F=>{r(oe()),r(dr({id:rt,x:F.target.x(),y:F.target.y(),scaleX:F.target.scaleX(),scaleY:F.target.scaleY(),rotation:F.target.rotation()})),_();},onMouseEnter:F=>{if(i==="select"){let S=F.target.getStage();S&&(S.container().style.cursor="move");}},onMouseLeave:F=>{if(i==="select"){let S=F.target.getStage();S&&(S.container().style.cursor="default");}},onContextMenu:F=>{let S=F.evt;S.preventDefault(),ot(S,rt,"line");},children:jsx(Line,{points:Y.points||[],stroke:mt||je?void 0:Y.color,strokeWidth:mt||je?0:Y.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:mt||je?Lt?"black":Y.color:void 0,closed:mt||je,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ae.current.get(m);console.log("Line Transformer - selectedId:",m,"node found:",!!S),S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:at,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"]})]},P);case "shape":return jsxs(ut.Fragment,{children:[jsx($s,{onSelect:De,shapes:[M.element],shapeRefs:Ho,handleShapeDragEnd:Od,handleShapeResizeEnd:qd,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ho.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "image":return jsxs(ut.Fragment,{children:[jsx(zs,{images:[M.element],getLoadedImage:Be,imageRefs:et,onDragEnd:Jd,onTransform:ya,onSelect:De,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=et.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "video":return jsxs(ut.Fragment,{children:[jsx(Xs,{videos:[M.element],selectedId:m,videoRefs:na,onVideoClick:Qd,onDragEnd:qt,onTransformEnd:ia,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=na.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "text":return jsxs(ut.Fragment,{children:[jsx(ji,{texts:[M.element],textRefs:Nt,onDragEnd:Nd,onTransformEnd:Vd,onSelect:De,onContextMenu:ot,onDoubleClick:Hd,editingTextId:ue,editingValue:$n,onEditingChange:_n}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Nt.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "flashcard":return jsxs(ut.Fragment,{children:[jsx(Js,{flashcards:[M.element],flashcardRefs:Ko,selectedId:m,onDragEnd:Wd,onTransform:Kd,onSelect:De,onNext:zd,onPrevious:Gd,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ko.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "photoFrame":return jsxs(ut.Fragment,{children:[jsx(on,{photoFrames:[M.element],photoFrameRefs:zo,selectedId:m,onDragEnd:jd,onTransform:Xd,onSelect:De,onStartCamera:$d,onCapture:_d,cameraStreams:Yd,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=zo.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "mcq":return jsxs(ut.Fragment,{children:[jsx(Il,{handleMcqTransform:No,multipleChoice:[M.element],handleSelect:De,mcqRefs:Vo,handleDragEnd:Cd,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Vo.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "trueFalse":return jsxs(ut.Fragment,{children:[jsx(kl,{trueFalses:[M.element],handleTrueFalseTransform:Md,handleSelect:De,trueFalseRefs:jn,onContextMenu:ot,handleDragEnd:Ad}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=jn.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "shortAnswer":return jsxs(ut.Fragment,{children:[jsx(Kl,{shortAnswers:[M.element],handleSelect:De,handleTransform:No,saRefs:Ka,onContextMenu:ot,handleDragEnd:Td}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ka.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "longAnswer":return jsxs(ut.Fragment,{children:[jsx(Yl,{longAnswer:[M.element],handleSelect:De,handleTransform:No,saRefs:Ka,onContextMenu:ot,handleDragEnd:Pd}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ka.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "fillInTheBlanks":return jsxs(ut.Fragment,{children:[jsx($l,{fillInTheBlanks:[M.element],handleSelect:De,handleTransform:No,onContextMenu:ot,handleDragEnd:Rd}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ka.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);default:return null}})})()})]}),g&&!Mt.some(v=>v.isRecorded&&v.isPlaying)&&jsx("img",{src:g,alt:"Canvas Preview",className:"fixed top-4 right-4 z-50 rounded-lg border-2 border-gray-300 p-1 shadow-lg",style:{maxWidth:"250px",maxHeight:"250px"}}),L&&jsx(il,{x:L.x,y:L.y,type:L.elementType,onAction:eu,onClose:tu,isDrawingMode:L.elementType==="image"?u?.images.find(v=>v.id===L.elementId)?.isDrawingMode:L.elementType==="photoFrame"?u?.photoFrames.find(v=>v.id===L.elementId)?.isDrawingMode:false}),U&&L&&jsx(ll,{x:U.x,y:U.y,items:U.type==="order"?[{label:"Bring to Front",onClick:()=>Kr("bring-to-front")},{label:"Send to Back",onClick:()=>Kr("send-to-back")}]:[{label:u&&(L.elementType==="image"?u.images.find(v=>v.id===L.elementId)?.locked:u.videos.find(v=>v.id===L.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Kr(u&&(L.elementType==="image"?u.images.find(v=>v.id===L.elementId)?.locked:u.videos.find(v=>v.id===L.elementId)?.locked)?"unlock":"lock")}],onClose:()=>O(null)}),R&&jsx(dl,{title:R.type==="link"?"Add Link":"Add Alt Text",label:R.type==="link"?"URL":"Alternative Text",placeholder:R.type==="link"?"https://example.com":"Describe this image/video",defaultValue:R.defaultValue,onSave:au,onClose:()=>E(null)}),T&&jsx(ul,{defaultColor:T.defaultColor,onConfirm:su,onCancel:()=>G(null)}),z&&jsx(pl,{imageSrc:z.imageSrc,onConfirm:nu,onCancel:()=>me(null)}),J&&jsx(no,{onClose:()=>de(false),stageRef:f}),N&&jsx(gl,{elementId:N.elementId,elementType:N.elementType,existingAudio:N.existingAudio,onSave:ou,onDelete:ru,onClose:()=>D(null)}),V&&jsx(vl,{selectedElementId:m||void 0,onClose:()=>j(false),onSelectElement:v=>{De(v),j(false);}}),u?.images.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.videos.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.shapes?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.texts?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.flashcards?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.photoFrames?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.multipleChoices?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.trueFalses?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.shortAnswers?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.LongAnswer?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.fillInTheBlanks?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),l&&jsx(Ol,{editElement:s}),I&&(()=>{let v=ue||m;if(!v)return null;let M=za.find(A=>A.id===v);return M?jsx(ql,{text:M,position:I}):null})(),w&&ue&&(()=>{let v=za.find(M=>M.id===ue);return v?jsx(Vl,{text:v,editingValue:$n,onEditingChange:_n,onFinish:Wr,position:{top:w.top,left:w.left},scale:w.scale,textareaRef:te},ue):null})()]})},Np=qp;var Vp="SchooplaVideoStorage";var oa="videos",En=()=>new Promise((e,o)=>{let a=indexedDB.open(Vp,1);a.onerror=()=>o(a.error),a.onsuccess=()=>e(a.result),a.onupgradeneeded=t=>{let r=t.target.result;r.objectStoreNames.contains(oa)||r.createObjectStore(oa,{keyPath:"id"});};}),To=async(e,o,a)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let t=await En(),i=t.transaction([oa],"readwrite").objectStore(oa),n={id:e,blob:o,thumbnailDataUrl:a,timestamp:Date.now()};await new Promise((u,c)=>{let s=i.put(n);s.onsuccess=()=>u(!0),s.onerror=()=>c(s.error);}),t.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(t){throw console.error("Error saving video blob to IndexedDB:",t),t}};var ed=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await En(),a=e.transaction([oa],"readonly").objectStore(oa);return new Promise((t,r)=>{let i=a.getAll();i.onsuccess=()=>{e.close();let n=i.result,u=new Map;n.forEach(c=>{u.set(c.id,{blob:c.blob,thumbnailDataUrl:c.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),t(u);},i.onerror=()=>{e.close(),r(i.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Rn=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await En(),t=o.transaction([oa],"readwrite").objectStore(oa);await new Promise((r,i)=>{let n=t.delete(e);n.onsuccess=()=>r(!0),n.onerror=()=>i(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}};var td=e=>URL.createObjectURL(e);var Up={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},ad=createSlice({name:"toolbar",initialState:Up,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:xt,setPenColor:Hr,setStrokeWidth:Bn,setFontSize:Bw,setFontFamily:Ow,setFontStyle:qw,setFontWeight:Nw,setTextDecoration:Vw,setTextColor:Hw}=ad.actions,od=ad.reducer;var rd=({onClose:e,onRecordingComplete:o})=>{let[a,t]=useState(false),[r,i]=useState(null),[n,u]=useState(0),[c,s]=useState(null),[l,p]=useState(false),f=useRef(null),d=useRef([]),m=useRef(null),x=useRef(null),g=useRef(null);useEffect(()=>((async()=>{try{let k=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});s(k),p(!0),g.current&&(g.current.srcObject=k);}catch(k){console.error("Error accessing camera:",k),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{m.current&&clearInterval(m.current),c&&c.getTracks().forEach(k=>k.stop());}),[]);let y=()=>{c&&(c.getTracks().forEach(I=>I.stop()),s(null),p(false));},h=async()=>{try{let I=null,k=null;try{I=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(R){console.error("Error accessing camera for recording:",R),alert("Failed to access camera for recording.");return}try{k=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(R){console.warn("Microphone access denied:",R);}let w=[...I.getVideoTracks()];k&&w.push(...k.getAudioTracks());let q=new MediaStream(w),U="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?U="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?U="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?U="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(U="video/webm;codecs=vp8");let O=new MediaRecorder(q,{mimeType:U,videoBitsPerSecond:25e5});f.current=O,d.current=[],O.ondataavailable=R=>{R.data.size>0&&d.current.push(R.data);},O.onstop=()=>{let R=new Blob(d.current,{type:U}),E=document.createElement("video");E.src=URL.createObjectURL(R),E.muted=!0,E.currentTime=.1,E.onseeked=()=>{let T=document.createElement("canvas");T.width=E.videoWidth,T.height=E.videoHeight;let G=T.getContext("2d");G&&(G.drawImage(E,0,0),x.current=T.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(E.src);},q.getTracks().forEach(T=>T.stop()),I&&I.getTracks().forEach(T=>T.stop()),k&&k.getTracks().forEach(T=>T.stop()),m.current&&clearInterval(m.current),i(R),y();},O.onerror=R=>{console.error("MediaRecorder error:",R);},O.start(1e3),t(!0),u(0),m.current=setInterval(()=>{u(R=>R+1);},1e3);}catch(I){console.error("Error starting camera recording:",I),alert("Failed to start recording. Please check permissions.");}},b=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),t(false));},L=()=>{if(r){let I=URL.createObjectURL(r),k=document.createElement("a");k.href=I,k.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(k),k.click(),document.body.removeChild(k),URL.revokeObjectURL(I);}},C=I=>{let k=Math.floor(I/60),w=I%60;return `${k.toString().padStart(2,"0")}:${w.toString().padStart(2,"0")}`};return jsx("div",{className:"fixed inset-0 flex items-center justify-center",children:jsxs("div",{className:"relative w-full max-w-2xl overflow-hidden rounded-2xl shadow-2xl",children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:g,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:h,disabled:!l,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"})})}),!l&&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"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:b,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:C(n)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",C(n)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{i(null),u(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&&x.current&&(o(r,x.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})})};var Rt=40,ld=({onConfirm:e,onCancel:o,editingFlashcard:a})=>{let[t,r]=useState(a?.images||[]),[i,n]=useState(a?.order||"sequential"),[u,c]=useState(false),s=useRef(null),l=useRef(null);useEffect(()=>{let h=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[o]);let p=h=>{let b=h.target.files;if(!b||b.length===0)return;let L=Rt-t.length;if(L<=0){alert(`You can only upload a maximum of ${Rt} images`);return}let C=Array.from(b).slice(0,L);C.length<b.length&&alert(`Only ${L} more images can be added (max ${Rt} total)`);let I=C.map(k=>new Promise((w,q)=>{let U=new FileReader;U.onload=O=>{O.target?.result?w(O.target.result):q(new Error("Failed to read file"));},U.onerror=q,U.readAsDataURL(k);}));Promise.all(I).then(k=>{r(w=>[...w,...k]),l.current&&(l.current.value="");});},f=h=>{h.preventDefault(),c(false);let b=Array.from(h.dataTransfer.files).filter(k=>k.type.startsWith("image/"));if(b.length===0)return;let L=Rt-t.length;if(L<=0){alert(`You can only upload a maximum of ${Rt} images`);return}let C=b.slice(0,L);C.length<b.length&&alert(`Only ${L} more images can be added (max ${Rt} total)`);let I=C.map(k=>new Promise((w,q)=>{let U=new FileReader;U.onload=O=>{O.target?.result?w(O.target.result):q(new Error("Failed to read file"));},U.onerror=q,U.readAsDataURL(k);}));Promise.all(I).then(k=>{r(w=>[...w,...k]);});},d=h=>{h.preventDefault(),c(true);},m=()=>{c(false);},x=h=>{r(b=>b.filter((L,C)=>C!==h));},y=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:h=>{h.target===h.currentTarget&&o(),h.stopPropagation();},onMouseUp:h=>h.stopPropagation(),onMouseMove:h=>h.stopPropagation(),onTouchStart:h=>h.stopPropagation(),onTouchMove:h=>h.stopPropagation(),onTouchEnd:h=>h.stopPropagation(),children:jsxs("div",{ref:s,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white shadow-xl",onClick:h=>h.stopPropagation(),children:[jsx("div",{className:"border-b border-gray-200 px-6 py-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-black",children:a?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-black",children:jsx(X,{size:20,weight:"bold"})})]})}),jsxs("form",{onSubmit:h=>{if(h.preventDefault(),t.length<2){alert("Please upload at least 2 images for the flashcard");return}e(t,i,a?.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-gray-900",children:[jsxs("span",{className:"flex items-center gap-2",children:[jsx(Image$1,{size:16,className:"text-gray-900"}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-600",children:t.length>=Rt?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",Rt," images"]}):jsxs("span",{children:[t.length,"/",Rt," images"]})})]}),jsx("input",{ref:l,type:"file",accept:"image/*",multiple:true,onChange:p,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:d,onDragLeave:m,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full border border-gray-300 bg-gray-100",children:jsx(Image$1,{size:24,className:"text-gray-600"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF up to 10MB each"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center gap-2 text-sm font-medium text-gray-900",children:[jsx(ArrowsDownUp,{size:16,className:"text-gray-900"}),"Display Order"]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${i==="sequential"?"border-black text-black":"border-gray-300 bg-white text-gray-900 hover:border-gray-400"}`,children:jsxs("div",{className:"flex flex-col items-center gap-2",children:[jsx(ArrowsDownUp,{size:20}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Navigate in order"})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${i==="random"?"border-black text-black":"border-gray-300 bg-white text-gray-900 hover:border-gray-400"}`,children:jsxs("div",{className:"flex flex-col items-center gap-2",children:[jsx(Shuffle,{size:20}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Shuffle cards"})]})]})})]})]}),t.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-gray-900",children:[jsx("span",{children:"Your Cards"}),jsxs("span",{className:"rounded bg-black px-2 py-0.5 text-xs text-white",children:[t.length," card",t.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg border border-gray-200 bg-gray-50 p-3",children:t.map((h,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded border border-gray-300 bg-white",children:[jsx("img",{src:h,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>x(b),className:"absolute top-1 right-1 rounded bg-black p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-gray-800",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded bg-black text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:b+1})]},b))})]}),t.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 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:t.length<2,className:"flex-1 rounded-lg bg-black px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:a?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(y,document.body)};var Sh=({isOpen:e,onClose:o,onScreenRecord:a,stageRef:t,onTextAdded:r,showToggleButton:i=true}={})=>{let n=pe(),u=$(B=>B.canvas.slides.find(se=>se.id===B.canvas.currentSlideId)),c=u?.videos||[],s=u?.editingFlashcard,l=$(B=>B.toolbar.selectedTool),p=$(B=>B.toolbar.penColor),f=$(B=>B.toolbar.strokeWidth),d=u?.showMcqForm,m=u?.showFlashcardForm,x=u?.backgroundColor||"#ffffff",g=c.some(B=>B.isRecorded&&B.isPlaying),y=$(B=>B.toolbar.fontSize),h=$(B=>B.toolbar.fontFamily),b=$(B=>B.toolbar.fontStyle),L=$(B=>B.toolbar.fontWeight),C=$(B=>B.toolbar.textDecoration),I=$(B=>B.toolbar.textColor),[k,w]=useState(false),[q,U]=useState(false),[O,R]=useState(true),E=e!==void 0?e:O,T=()=>{o&&E?o():e===void 0&&R(!O);},G=(B,se,ie)=>{ie/=100;let le=se*Math.min(ie,1-ie)/100,Q=ee=>{let Le=(ee+B/30)%12,Ze=ie-le*Math.max(Math.min(Le-3,9-Le,1),-1);return Math.round(255*Ze).toString(16).padStart(2,"0")};return `#${Q(0)}${Q(8)}${Q(4)}`},z=[{name:"select",icon:jsx(Selection,{size:20,weight:"bold"}),label:"Select"},{name:"pen",icon:jsx(Pen,{size:20,weight:"bold"}),label:"Pen"},{name:"eraser",icon:jsx(Eraser,{size:20,weight:"bold"}),label:"Eraser"},{name:"text",icon:jsx(TextT,{size:20,weight:"bold"}),label:"Text"}],me=[{name:"rectangle",icon:jsx(Square,{size:20,weight:"bold"}),label:"Rect"},{name:"circle",icon:jsx(Circle$1,{size:20,weight:"bold"}),label:"Circle"},{name:"ellipse",icon:jsx(Circle$1,{size:20,weight:"bold",style:{transform:"scaleX(0.6)"}}),label:"Ellipse"},{name:"triangle",icon:jsx(Triangle,{size:20,weight:"bold"}),label:"Tri"},{name:"polygon",icon:jsx(Hexagon,{size:20,weight:"bold"}),label:"Hex"},{name:"star",icon:jsx(Star$1,{size:20,weight:"bold"}),label:"Star"},{name:"ring",icon:jsx(Circle$1,{size:20,weight:"bold"}),label:"Ring"},{name:"wedge",icon:jsx(Pizza,{size:20,weight:"bold"}),label:"Wedge"},{name:"arrow",icon:jsx(ArrowRight,{size:20,weight:"bold"}),label:"Arrow"},{name:"line",icon:jsx(LineSegment,{size:20,weight:"bold"}),label:"Line"},{name:"arc",icon:jsx(Circuitry,{size:20,weight:"bold"}),label:"Arc"}],J=B=>{let se=B.target.files;!se||se.length===0||(n(xt("select")),n(Xe(false)),Array.from(se).forEach(ie=>{let le=new FileReader;le.onload=Q=>{let ee=new window.Image;ee.src=Q.target?.result,ee.onload=()=>{let Le=ee.width/ee.height,Ze=300,kt=300,Ae=ee.width,we=ee.height;Ae>Ze&&(Ae=Ze,we=Ae/Le),we>kt&&(we=kt,Ae=we*Le),n(oe());let Be=(window.innerWidth-Ae)/2,et=(window.innerHeight-we)/2;n(es({id:v4(),src:ee.src,x:Be,y:et,width:Ae,height:we,draggable:true,rotation:0}));};},le.readAsDataURL(ie);}),B.target.value="");},de=async B=>{let se=B.target.files;if(!(!se||se.length===0)){console.log("files",B),n(xt("select")),n(Xe(false));for(let ie of Array.from(se))try{let le=URL.createObjectURL(ie),Q=document.createElement("video");console.log("video",Q),Q.src=le,Q.muted=!0,Q.playsInline=!0,Q.preload="auto",await new Promise((tt,qt)=>{let ia=setTimeout(()=>qt(new Error("Metadata load timeout")),1e4);Q.onloadedmetadata=()=>{clearTimeout(ia),tt();},Q.onerror=()=>{clearTimeout(ia),qt(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:Q.duration,width:Q.videoWidth,height:Q.videoHeight}),await new Promise((tt,qt)=>{let ia=setTimeout(()=>qt(new Error("Video load timeout")),1e4);Q.readyState>=2?(clearTimeout(ia),tt()):Q.onloadeddata=()=>{clearTimeout(ia),tt();};});let ee=Math.min(.8,Q.duration/2);console.log("Seeking to:",ee),Q.currentTime=ee,await new Promise(tt=>{let qt=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),tt();},5e3);Q.onseeked=()=>{clearTimeout(qt),console.log("Seek completed"),tt();};});let Le=document.createElement("canvas"),Ze=Q.videoWidth/Q.videoHeight,kt=400,Ae=400,we=Q.videoWidth,Be=Q.videoHeight;we>kt&&(we=kt,Be=we/Ze),Be>Ae&&(Be=Ae,we=Be*Ze),Le.width=we,Le.height=Be;let et=Le.getContext("2d",{willReadFrequently:!1});if(!et)throw new Error("Failed to get canvas context");if(await new Promise(tt=>setTimeout(tt,100)),Q.videoWidth===0||Q.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:we,height:Be}),et.drawImage(Q,0,0,we,Be);let Ot=Le.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ot.length),n(oe());let ya=(window.innerWidth-we)/2,Mt=(window.innerHeight-Be)/2,na=v4();await To(na,ie,Ot),n($o({id:na,objectUrl:le,thumbnailDataUrl:Ot,videoBlob:ie,x:ya,y:Mt,width:we,height:Be,draggable:!0,isPlaying:!1,rotation:0})),Q.src="",Q.load(),console.log(`Video uploaded: ${ie.name}`);}catch(le){console.error("Error processing video:",le),alert(`Failed to process video: ${ie.name}`);}B.target.value="";}},N=(B,se,ie)=>{n(oe()),n(xt("select")),n(Xe(false));let le=300,Q=300,ee=(window.innerWidth-le)/2,Le=(window.innerHeight-Q)/2;n(ie?Sa({id:ie,images:B,order:se,x:ee,y:Le,width:le,height:Q,rotation:0,draggable:true}):is({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:B,currentIndex:0,order:se,x:ee,y:Le,width:le,height:Q,rotation:0,draggable:true})),n(da(false));},D=()=>{n(oe()),n(xt("select")),n(Xe(false));let B=400,se=300,ie=(window.innerWidth-B)/2,le=(window.innerHeight-se)/2;n(cs({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ie,y:le,width:B,height:se,rotation:0,draggable:true,isCapturing:false}));},V=B=>{let le=(window.innerWidth-100)/2,Q=(window.innerHeight-100)/2,ee={};switch(B.name){case "circle":case "ring":case "wedge":case "arc":ee.radius=50,(B.name==="ring"||B.name==="arc")&&(ee.innerRadius=25,ee.outerRadius=50),(B.name==="wedge"||B.name==="arc")&&(ee.angle=B.name==="wedge"?60:90);break;case "ellipse":ee.radiusX=60,ee.radiusY=40;break;case "triangle":ee.radius=50,ee.sides=3;break;case "polygon":ee.radius=50,ee.sides=6;break;case "star":ee.innerRadius=25,ee.outerRadius=50,ee.numPoints=5;break;case "arrow":case "line":ee.points=[0,0,100,0],B.name==="arrow"&&(ee.pointerLength=10,ee.pointerWidth=10);break}let Le={id:`shape-${Date.now()}`,type:B.name,x:le,y:Q,width:100,height:100,rotation:0,color:p,...ee};n(oe()),n(Xe(false)),n(xt(B.name)),n(os(Le));},j=B=>{if(n(xt(B)),B==="select")n(Xe(false));else if(B==="text"){n(Xe(false)),n(oe());let se=200,ie=50,le=(window.innerWidth-se)/2,Q=(window.innerHeight-ie)/2,ee=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(ss({id:ee,text:"",x:le,y:Q,width:se,height:ie,rotation:0,draggable:true,fontSize:y,fontFamily:h,fontStyle:b,fontWeight:L,textDecoration:C,fill:I,align:"left"})),setTimeout(()=>{n(Qa(ee));},100),r&&r(ee);}else n(Xe(true));},te=()=>{n(Rs()),n(xt("select")),n(Xe(false));},Z=B=>{n(oe()),n(Jr(B));},ae=()=>{a?a():t?w(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Ce=()=>{U(true);},_=async(B,se)=>{try{n(xt("select")),n(Xe(!1));let ie=URL.createObjectURL(B),le=document.createElement("video");le.src=ie,le.muted=!0,le.playsInline=!0,le.preload="auto",await new Promise((Ot,ya)=>{let Mt=setTimeout(()=>ya(new Error("Metadata load timeout")),1e4);le.onloadedmetadata=()=>{clearTimeout(Mt),Ot();},le.onerror=()=>{clearTimeout(Mt),ya(new Error("Failed to load video"));};});let Q=640,ee=le.videoWidth/le.videoHeight,Le=Q,Ze=Le/ee,kt=window.innerWidth,Ae=window.innerHeight;n(oe());let we=(kt-Le)/2,Be=(Ae-Ze)/2,et=v4();await To(et,B,se),n($o({id:et,objectUrl:ie,thumbnailDataUrl:se,videoBlob:B,x:we,y:Be,width:Le,height:Ze,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),w(!1),U(!1);}catch(ie){console.error("Error adding recorded video to canvas:",ie),alert("Failed to add video to canvas. Please try again.");}},Pe=B=>{n(xt("select")),n(Xe(false)),n(Ya(null)),B&&n(Ms(B)),n(Wt(!d));},vt=()=>{n(ja(null)),n(da(true));};return g?null:jsxs(Fragment,{children:[i&&jsx("div",{className:"fixed top-4 left-4 z-50 flex h-10 w-10 cursor-pointer flex-col items-center justify-center gap-1 rounded-lg transition-all","aria-label":"Toggle toolbar",onClick:T,children:jsx(List,{size:32})}),E&&jsxs("div",{className:"fixed top-16 left-4 z-50 h-[calc(100vh-6rem)] w-56 overflow-y-auto rounded-xl border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"TOOLS"}),jsx("div",{className:"grid grid-cols-4 gap-2",children:z.map((B,se)=>jsxs("button",{onClick:()=>j(B.name),className:`flex flex-col items-center justify-center rounded-lg p-2 transition-all ${l===B.name?"bg-blue-500 text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,title:B.label,children:[B.icon,jsx("span",{className:"mt-1 text-[10px]",children:B.label})]},se))})]}),jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"SIZE"}),jsx("input",{type:"range",name:"size",id:"size",value:f,className:"h-2 w-full cursor-pointer rounded-full",min:6,max:24,onChange:B=>n(Bn(parseInt(B.target.value)))})]}),jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"SHAPES"}),jsx("div",{className:"grid grid-cols-4 gap-2",children:me.map(B=>jsxs("button",{onClick:()=>V(B),className:`flex flex-col items-center justify-center rounded-lg p-1.5 transition-all ${l===B.name?"bg-blue-500 text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,title:B.label,children:[B.icon,jsx("span",{className:"mt-0.5 text-[9px]",children:B.label})]},B.name))})]}),jsxs("div",{className:"space-y-1",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"PEN COLOR"}),jsx("div",{className:"h-8 w-full cursor-pointer rounded-md border-2 border-gray-300 transition-transform hover:scale-[1.02]",style:{backgroundColor:p},onClick:()=>document.getElementById("color-input")?.click()}),jsx("div",{className:"relative",children:jsx("input",{type:"range",min:"0",max:"360",defaultValue:"0",onChange:B=>{let se=parseInt(B.target.value),ie=G(se,100,50);n(Hr(ie));},className:"h-2 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%)"}})}),jsx("input",{id:"color-input",type:"color",value:p,onChange:B=>n(Hr(B.target.value)),className:"hidden"})]}),jsxs("div",{className:"space-y-1 border-t border-gray-200 pt-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsx("div",{className:"h-8 w-full cursor-pointer rounded-md border-2 border-gray-300 transition-transform hover:scale-[1.02]",style:{backgroundColor:x},onClick:()=>document.getElementById("bg-color-input")?.click()}),jsx("input",{id:"bg-color-input",type:"color",value:x,onChange:B=>Z(B.target.value),className:"hidden"})]}),jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"MEDIA"}),jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxs("label",{className:"flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 text-gray-700 transition-colors hover:bg-gray-200",children:[jsx(Image$1,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Image"}),jsx("input",{type:"file",accept:"image/*",multiple:true,onChange:J,className:"hidden"})]}),jsxs("label",{className:`flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg transition-colors ${c.length>=1?"cursor-not-allowed bg-gray-50 text-gray-400":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:[jsx(Video,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Video"}),jsx("input",{type:"file",accept:"video/*",disabled:c.length>=1,multiple:true,onChange:de,className:"hidden"})]})]})]}),!a&&k&&t&&jsx(no,{onClose:()=>w(false),stageRef:t,onRecordingComplete:_}),q&&jsx(rd,{onClose:()=>U(false),onRecordingComplete:_}),m&&jsx(ld,{editingFlashcard:s,onConfirm:N,onCancel:()=>n(da(false))}),jsxs("div",{className:"mb-3 border-t border-gray-200 pt-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"ACTIVITIES"}),jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxs("button",{onClick:()=>vt(),className:"flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 text-gray-700 transition-colors hover:bg-gray-200",children:[jsx(Cards,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Flashcard"})]}),jsxs("button",{onClick:D,className:"flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 text-gray-700 transition-colors hover:bg-gray-200",children:[jsx(Camera,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Frame"})]}),jsxs("button",{onClick:()=>Pe("multiple-choice"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"MCQ",children:[jsx(ListChecksIcon,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"MCQ"})]}),jsxs("button",{onClick:()=>Pe("true-false"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"True False",children:[jsx(ToggleRight,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"True False"})]}),jsxs("button",{onClick:()=>Pe("short-answer"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Short Answer",children:[jsx(Textbox,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Short Answer"})]}),jsxs("button",{onClick:()=>Pe("long-answer"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Long Answer",children:[jsx(Article,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Long Answer"})]}),jsxs("button",{onClick:()=>Pe("fill-in-the-blank"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Fill in the blank",children:[jsx(TextUnderline,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Fill in the blank"})]})]})]}),jsxs("div",{className:"mb-3 border-t border-gray-200 pt-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"ACTIONS"}),jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxs("button",{onClick:()=>n(Bs()),className:"flex flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Undo",children:[jsx(ArrowUUpLeft,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Undo"})]}),jsxs("button",{onClick:()=>n(Os()),className:"flex flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Redo",children:[jsx(ArrowUDownRight,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Redo"})]}),jsxs("button",{onClick:ae,className:"flex flex-col items-center justify-center rounded-lg bg-blue-50 p-2 text-blue-600 transition-colors hover:bg-blue-100",title:"Screen Record",children:[jsx(Record,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Record"})]}),jsxs("button",{onClick:Ce,className:"flex flex-col items-center justify-center rounded-lg bg-purple-50 p-2 text-purple-600 transition-colors hover:bg-purple-100",title:"Camera Record",children:[jsx(Camera,{size:18,weight:"fill"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Camera"})]}),jsxs("button",{onClick:()=>te(),className:"flex flex-col items-center justify-center rounded-lg bg-red-50 p-2 text-red-600 transition-colors hover:bg-red-100",title:"Clear",children:[jsx(Trash,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Clear"})]})]})]})]})]})},Ch=Sh;var ud=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Mh=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,a,t)=>t?t.toUpperCase():a.toLowerCase()),Un=e=>{let o=Mh(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ur=(...e)=>e.filter((o,a,t)=>!!o&&o.trim()!==""&&t.indexOf(o)===a).join(" ").trim(),cd=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var fd={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 pd=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:a=2,absoluteStrokeWidth:t,className:r="",children:i,iconNode:n,...u},c)=>createElement("svg",{ref:c,...fd,width:o,height:o,stroke:e,strokeWidth:t?Number(a)*24/Number(o):a,className:Ur("lucide",r),...!i&&!cd(u)&&{"aria-hidden":"true"},...u},[...n.map(([s,l])=>createElement(s,l)),...Array.isArray(i)?i:[i]]));var ft=(e,o)=>{let a=forwardRef(({className:t,...r},i)=>createElement(pd,{ref:i,iconNode:o,className:Ur(`lucide-${ud(Un(e))}`,`lucide-${e}`,t),...r}));return a.displayName=Un(e),a};var Fh=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],ra=ft("circle-check-big",Fh);var Ph=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],sa=ft("circle-x",Ph);var Eh=[["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"}]],Eo=ft("copy",Eh);var Rh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ro=ft("plus",Rh);var Bh=[["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"}]],Bo=ft("trash-2",Bh);var Oh=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Oo=ft("upload",Oh);var gd=({slide:e,index:o,isSelected:a,isSingleSlide:t,onSelect:r,onDuplicate:i,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${a?"border-blue-500 bg-blue-50 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:u=>{u.stopPropagation(),i();},className:"rounded bg-blue-500 p-1.5 text-white shadow-md transition-colors hover:bg-blue-600",title:"Duplicate slide",children:jsx(Eo,{size:14})}),!t&&jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Bo,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Slide ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var qh=()=>{let e=yt(),o=Vt(eo),a=Vt(Za),t=Vt(qs),n=(Vt(p=>p.canvas.slides.find(f=>f.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),u=()=>{t&&e(jr());},c=p=>{e(_r(p));},s=p=>{e($r(p));},l=p=>{o.length>1&&e(Xr(p));};return n?null:jsxs("div",{className:"fixed top-0 right-0 z-50 flex h-screen w-80 flex-col border-l border-gray-300 bg-gray-50 shadow-lg",children:[jsxs("div",{className:"border-b border-gray-300 bg-white p-4",children:[jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsx("h2",{className:"text-lg font-semibold text-gray-800",children:"Slides"}),jsxs("span",{className:"text-sm text-gray-600",children:[o.length,"/20"]})]}),jsxs("button",{onClick:u,disabled:!t,className:`flex w-full items-center justify-center gap-2 rounded-lg px-4 py-2 font-medium transition-colors ${t?"bg-blue-500 text-white hover:bg-blue-600":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Ro,{size:18}),"Add Slide"]})]}),jsx("div",{className:"flex-1 overflow-y-auto p-4",children:jsx("div",{className:"space-y-3",children:o.map((p,f)=>jsx(gd,{slide:p,index:f,isSelected:p.id===a,isSingleSlide:o.length===1,onSelect:()=>c(p.id),onDuplicate:()=>s(p.id),onDelete:()=>l(p.id)},p.id))})}),jsx("div",{className:"border-t border-gray-300 bg-white p-3 text-center text-xs text-gray-500",children:"Click a slide to edit \u2022 Use buttons to manage slides"})]})};var Nh=({onPublish:e,label:o="Publish Slides",className:a})=>{let t=Vt(eo),n=(Vt(m=>m.canvas.slides.find(x=>x.id===m.canvas.currentSlideId))?.videos||[]).some(m=>m.isRecorded&&m.isPlaying),[u,c]=useState(false),[s,l]=useState(null),[p,f]=useState(null),d=async()=>{if(t.length===0){f({type:"error",message:"No slides to publish"});return}if(!e){f({type:"error",message:"No publish handler provided"});return}c(true),f(null);try{let m=await e(t,x=>{l(x);});m.success?f({type:"success",message:m.message}):f({type:"error",message:m.message});}catch(m){f({type:"error",message:m instanceof Error?m.message:"An unexpected error occurred"});}finally{c(false),setTimeout(()=>{l(null),f(null);},3e3);}};return n?null:jsx("div",{className:a||"fixed bottom-6 left-1/2 z-50 -translate-x-1/2 transform",children:jsxs("div",{className:"flex min-w-[280px] flex-col items-center gap-3 rounded-lg bg-white p-4 shadow-lg",children:[jsx("button",{onClick:d,disabled:u||t.length===0||!e,className:`flex items-center justify-center gap-2 rounded-lg px-6 py-3 font-medium transition-all ${u||t.length===0||!e?"cursor-not-allowed bg-gray-300 text-gray-500":"bg-green-500 text-white shadow-md hover:bg-green-600 hover:shadow-lg"}`,children:u?jsxs(Fragment,{children:[jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Publishing..."]}):jsxs(Fragment,{children:[jsx(Oo,{size:20}),o]})}),s&&jsxs("div",{className:"w-full",children:[jsx("div",{className:"mb-1 text-xs text-gray-600",children:s.status}),jsx("div",{className:"h-2 w-full rounded-full bg-gray-200",children:jsx("div",{className:"h-2 rounded-full bg-green-500 transition-all duration-300",style:{width:`${s.current/s.total*100}%`}})}),jsxs("div",{className:"mt-1 text-xs text-gray-500",children:[s.current," / ",s.total]})]}),p&&jsxs("div",{className:`flex items-center gap-2 rounded-lg px-4 py-2 ${p.type==="success"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[p.type==="success"?jsx(ra,{size:18}):jsx(sa,{size:18}),jsx("span",{className:"text-sm font-medium",children:p.message})]}),jsxs("div",{className:"text-xs text-gray-500",children:[t.length," slide",t.length!==1?"s":""," ready"]})]})})};function Vh({children:e,className:o="",style:a}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:a,children:e})}var Uh="SchooplaEditorDB",Wh=1,Wa="slides",bd="schoopla_current_slide_id",vd=()=>new Promise((e,o)=>{let a=indexedDB.open(Uh,Wh);a.onerror=()=>o(a.error),a.onsuccess=()=>e(a.result),a.onupgradeneeded=t=>{let r=t.target.result;r.objectStoreNames.contains(Wa)||r.createObjectStore(Wa,{keyPath:"id"});};}),Kn=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await vd(),t=o.transaction([Wa],"readwrite").objectStore(Wa);await new Promise((r,i)=>{let n=t.clear();n.onsuccess=()=>r(!0),n.onerror=()=>i(n.error);});for(let r of e)await new Promise((i,n)=>{let u=t.add(r);u.onsuccess=()=>i(!0),u.onerror=()=>n(u.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(a){console.error("localStorage fallback failed:",a);}}},Ld=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await vd(),a=e.transaction([Wa],"readonly").objectStore(Wa);return new Promise((t,r)=>{let i=a.getAll();i.onsuccess=()=>{e.close();let n=i.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),t(n.length>0?n:null);},i.onerror=()=>{e.close(),r(i.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var zn=e=>{try{localStorage.setItem(bd,e);}catch(o){console.error("Error saving current slide ID:",o);}},yd=()=>{try{return localStorage.getItem(bd)}catch(e){return console.error("Error loading current slide ID:",e),null}},Id=(e,o)=>{let a=null;return (...t)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...t),o);}};var Kh=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/setCurrentSlide","canvas/updateSlideThumbnail","canvas/reorderSlides"],zh=["canvas/clearCanvas"],Gh=Id((e,o)=>{Kn(e),zn(o);},500),jh=(e,o)=>{Kn(e),zn(o);},Gn=false,wd=(e=>o=>a=>{if(a.type==="canvas/deleteVideo"&&a.payload){let r=a.payload;Rn(r).catch(i=>{console.error("Error deleting video blob:",i);});}if(a.type==="canvas/deleteSlide"&&a.payload){let r=a.payload,n=e.getState().canvas.slides.find(u=>u.id===r);n&&n.videos&&n.videos.length>0&&n.videos.forEach(u=>{Rn(u.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(a.type==="canvas/duplicateVideo"&&a.payload){let r=a.payload,i=e.getState(),u=i.canvas.slides.find(c=>c.id===i.canvas.currentSlideId)?.videos.find(c=>c.id===r);u&&u.videoBlob&&setTimeout(()=>{let c=e.getState(),l=c.canvas.slides.find(p=>p.id===c.canvas.currentSlideId)?.videos.find(p=>p.id!==r&&p.x===u.x+20&&p.y===u.y+20);l&&u.videoBlob&&To(l.id,u.videoBlob,l.thumbnailDataUrl).catch(p=>{console.error("Error saving duplicated video blob:",p);});},0);}let t=o(a);if(a.type&&zh.includes(a.type)){if(!Gn){Gn=true;try{let r=e.getState(),{slides:i,currentSlideId:n}=r.canvas;jh(i,n);}finally{setTimeout(()=>{Gn=false;},0);}}}else if(a.type&&Kh.includes(a.type)){let r=e.getState(),{slides:i,currentSlideId:n}=r.canvas;Gh(i,n);}return t});new QueryClient;var _h=configureStore({reducer:{toolbar:od,canvas:ni},middleware:e=>e({serializableCheck:false}).concat(wd)});var Yh=(e,o={})=>{let{format:a="png",quality:t=1,pixelRatio:r=2,fileName:i=`slide-${Date.now()}`}=o;try{let n=a==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:n,quality:t,pixelRatio:r}),c=document.createElement("a");c.download=`${i}.${a}`,c.href=u,document.body.appendChild(c),c.click(),document.body.removeChild(c);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},Jh=async(e,o={})=>{let{format:a="png",quality:t=1,pixelRatio:r=2}=o;return new Promise((i,n)=>{try{let u=a==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:u,quality:t,pixelRatio:r});fetch(c).then(s=>s.blob()).then(s=>i(s)).catch(s=>n(s));}catch(u){n(u);}})},Qh=(e,o={})=>{let{format:a="png",quality:t=1,pixelRatio:r=2}=o,i=a==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:i,quality:t,pixelRatio:r})};var eg=()=>{let e=yt();useEffect(()=>{(async()=>{try{let a=await Ld(),t=yd();if(a&&a.length>0){let r=await ed(),i=a.map(u=>{if(u.videos&&u.videos.length>0){let c=u.videos.map(s=>{let l=r.get(s.id);if(l){let p=td(l.blob);return {...s,objectUrl:p,thumbnailDataUrl:l.thumbnailDataUrl,videoBlob:l.blob}}else return s});return {...u,videos:c}}return u}),n=t&&i.find(u=>u.id===t)?t:i[0].id;e(Qr({slides:i,currentSlideId:n}));}}catch(a){console.error("Error loading persisted slides:",a);}})();},[e]);};/*! Bundled license information:
6
+ This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:p?"none":"auto"}})}),jsx(Group,{y:C+I+O+k+w+U,children:p&&jsxs(Group,{onMouseDown:()=>m("reset"),onMouseUp:()=>{m(null),y();},onMouseLeave:()=>m(null),onTouchStart:()=>m("reset"),onTouchEnd:()=>{m(null),y();},scaleX:d==="reset"?.95:1,scaleY:d==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.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})]})})]})});Pn.displayName="LongAnswer";var Jl=({longAnswer:e,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:i})=>jsx(Fragment,{children:e.map(n=>jsx(Pn,{longAnswer:n,handleSelect:o,handleTransform:a,saRefs:t,onContextMenu:r,handleDragEnd:u=>i(u,n.id)},n.id))});var Hp=({onStageReady:e,onSelectionChange:o,onTextEditingReady:a,onDirectDrawingCanvasReady:t}={})=>{let r=yt(),i=$(v=>v.toolbar.selectedTool);$(v=>v.canvas.isSketchMode);let u=$(ce),c=$(Za),s=u?.editingActivity,l=u?.showMcqForm,p=u?.lines||[],f=useRef(null),d=useRef(null),[m,x]=useState(null),[g,y]=useState(""),[h,b]=useState({width:1280,height:1200}),[L,C]=useState(null),[I,k]=useState(null),[w,q]=useState(null),[U,O]=useState(null),[R,E]=useState(null),[T,G]=useState(null),[z,me]=useState(null),[J,de]=useState(false),[N,D]=useState(null),[V,j]=useState(false),te=useRef(null),Z=useRef(null),ae=useRef(null),{debouncedGenerateThumbnail:Ce}=Oi(c,f);useEffect(()=>{let v=()=>{if(d.current){let A=d.current.getBoundingClientRect();b({width:A.width,height:A.height});}};v();let M=new ResizeObserver(v);return d.current&&M.observe(d.current),window.addEventListener("resize",v),()=>{M.disconnect(),window.removeEventListener("resize",v);}},[]),useEffect(()=>{if(f.current){let v=f.current.container();v&&(v.style.cursor="");}},[i]);let _=useCallback(()=>{f.current&&requestAnimationFrame(()=>{if(!f.current)return;f.current.getLayers().forEach(P=>P.batchDraw());let M=1/6,A=f.current.toDataURL({pixelRatio:M});y(A),Ce();});},[Ce]),Pe=useRef(c);useEffect(()=>{Pe.current!==c&&(Pe.current=c,_());},[c,_]);let vt=useRef(null),B=useRef(true);useEffect(()=>{if(!u)return;let v=(u.lines?.length||0)+(u.images?.length||0)+(u.videos?.length||0)+(u.shapes?.length||0)+(u.texts?.length||0)+(u.flashcards?.length||0)+(u.photoFrames?.length||0)+(u.multipleChoices?.length||0)+(u.trueFalses?.length||0)+(u.shortAnswers?.length||0)+(u.LongAnswer?.length||0)+(u.fillInTheBlanks?.length||0),M=vt.current?.count!==v;!B.current&&M&&setTimeout(()=>{_();},100),vt.current={slideId:c,count:v},B.current=false;},[u,c,_]),useEffect(()=>{f.current&&e&&e(f);},[e]),useEffect(()=>{ae.current&&t&&t(ae);},[t]);let{startDrawing:se,draw:ie,stopDrawing:le,setCanvasRef:Q,tool:ee,color:Le,strokeWidth:Ze,isSketchMode:kt}=di(_),Ae=useRef(new Map),{images:we,getLoadedImage:Be,imageRefs:et,handleDragEnd:Ot,handleImageTransformEnd:ya}=gi(_),{videos:Mt,videoRefs:na,handleVideoClick:tt,handleVideoDragEnd:qt,handleVideoTransformEnd:ia}=vi(_),{multipleChoice:Md,handleMcqTransform:No,mcqRefs:Vo,handleDragEnd:Ad}=xi(_),{trueFalse:Dd,handleTrueFalseTransform:Td,trueFalseRefs:Xn,handleTrueFalseDragEnd:Fd}=bi(_),{shortAnswers:Pd,saRefs:Ka,handleShortAnswerDragEnd:Ed}=Ci(_),{longAnswers:Rd,handleLongAnswerDragEnd:Bd}=ki(_),{fillInTheBlanks:Od,handleFillInTheBlanksDragEnd:qd}=Gl(_),{transformerRef:re,boundBoxFunc:at}=Pi(),{shapes:Nd,shapeRefs:Ho,isDragging:$n,handleShapeDragEnd:Vd,handleShapeResizeEnd:Hd}=Ii(_),{texts:za,textRefs:Nt,handleDragEnd:Ud,handleTransformEnd:Wd,handleDoubleClick:Kd,startEditing:Uo,editingTextId:ue,editingValue:_n,handleEditingChange:Yn,finishEditing:Wr}=Si(_,te);useEffect(()=>{a&&a(Uo);},[a,Uo]);let Wo=$(v=>v.canvas.editingTextId);useEffect(()=>{Wo&&Wo!==ue&&Uo(Wo);},[Wo,ue,Uo]);let{flashcards:zd,flashcardRefs:Ko,handleDragEnd:Gd,handleFlashcardTransformEnd:jd,handleNext:Xd,handlePrevious:$d}=Ai(_),{photoFrames:Jn,photoFrameRefs:zo,handleDragEnd:_d,handlePhotoFrameTransformEnd:Yd,startCamera:Jd,capturePhoto:Qd,cameraStreams:Zd}=Fi(_);useEffect(()=>{if(re.current){if(ue){re.current.nodes([]),re.current.getLayer()?.batchDraw();return}if(m&&!Mt.find(A=>A.id===m)?.isPlaying){let A=Ae.current.get(m)||et.current.get(m)||na.current.get(m)||Ho.current.get(m)||Nt.current.get(m)||Vo.current.get(m)||Ko.current.get(m)||zo.current.get(m);if(A){let P=A.attrs?.locked;if(A.visible()&&P!==true){re.current.nodes([A]),re.current.getLayer()?.batchDraw();return}}}re.current.nodes([]),re.current.getLayer()?.batchDraw();}},[m,ue,Mt,Ae,et,na,Ho,Nt,Ko,zo,Jn,Vo,re]);let De=useCallback(v=>{x(v),o?.(v);},[o]),Go=useCallback(()=>{x(null),o?.(null),re.current&&(re.current.nodes([]),re.current.getLayer()?.batchDraw());},[re,o]);useEffect(()=>{let v=re.current;return ()=>{v&&v.nodes([]);}},[c]),useEffect(()=>{let v=M=>{ue&&M.target.tagName!=="TEXTAREA"&&Wr();};return document.addEventListener("mousedown",v),()=>{document.removeEventListener("mousedown",v);}},[ue,Wr]),useEffect(()=>{let v=ue||m;if(!v||m&&ue){k(null);return}let M=Nt.current.get(v),A=f.current;if(!M||!A){k(null);return}let P=A.container().getBoundingClientRect(),Oe=M.absolutePosition(),ye=A.scaleX();k({x:P.left+(Oe.x+M.width()*ye/2)*ye,y:P.top+Oe.y*ye});},[m,ue,za,Nt]),useEffect(()=>{if(!ue){q(null);return}let v=Nt.current.get(ue),M=f.current;if(!v||!M){q(null);return}let A=M.container().getBoundingClientRect(),P=v.absolutePosition(),Oe=M.scaleX();q({top:A.top+P.y*Oe,left:A.left+P.x*Oe,scale:Oe});},[ue,za,Nt]);let Qn=useCallback(v=>{let M=v.target.getClassName(),A=v.target===v.target.getStage(),P=M==="Transformer"||v.target.getParent()?.getClassName()==="Transformer",Oe=M==="Image",ye=M==="Text",Y=M==="Group"||v.target.getParent()?.getClassName()==="Group",At=M==="Circle"||M==="Star"||M==="RegularPolygon"||M==="Ellipse"||M==="Ring"||M==="Wedge"||M==="Arrow"||M==="Line"||M==="Arc"||M==="Rect"&&v.target.attrs.id,Lt=M==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:M,clickedOnImage:Oe,clickedOnGroup:Y,tool:i,targetId:v.target.attrs?.id}),A&&!P&&!Oe&&!ye&&!Y&&!At&&!Lt&&Go(),!(i==="pen"||i==="eraser")&&(Oe||ye||P||Y||At||Lt))return;let je=v.target.getStage()?.getPointerPosition();if(!je)return;["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(i)||se(je);},[i,se,Go]),Zn=useCallback(v=>{if($n)return;let M=v.target.getStage()?.getPointerPosition();M&&ie(M);},[ie,$n]),ei=useCallback(()=>{le();},[le]),eu=useCallback(v=>{Ot(v,_);},[Ot,_]),tu=useCallback(v=>{tt(v),De(v);},[tt,De]),ot=useCallback((v,M,A)=>{v.preventDefault(),C({x:v.clientX,y:v.clientY,elementId:M,elementType:A}),De(M);},[De]),ti=useCallback(v=>{r(Ya(v)),r(Wt(true));},[r]),au=useCallback(v=>{r(ja(v)),r(da(true));},[r]),ou=useCallback((v,M)=>{if(!L)return;let{elementId:A,elementType:P}=L;switch(v){case "order":if(M){let S=M.target.getBoundingClientRect();O({x:S.right+5,y:S.top,type:"order"});}break;case "lock":if(M){let S=M.target.getBoundingClientRect();O({x:S.right+5,y:S.top,type:"lock"});}break;case "link":if(C(null),P==="line")break;let Oe=u?P==="image"?u.images.find(S=>S.id===A):u.videos.find(S=>S.id===A):null;E({type:"link",defaultValue:Oe?.link||""});break;case "voice":if(C(null),P==="line")break;let ye=u?P==="image"?u.images.find(S=>S.id===A):P==="video"?u.videos.find(S=>S.id===A):P==="text"?u.texts.find(S=>S.id===A):P==="flashcard"?u.flashcards.find(S=>S.id===A):P==="photoFrame"?u.photoFrames.find(S=>S.id===A):P==="mcq"?u.multipleChoices.find(S=>S.id===A):P==="fillInTheBlanks"?u.fillInTheBlanks.find(S=>S.id===A):P==="longAnswer"?u.LongAnswer.find(S=>S.id===A):P==="shortAnswer"?u.shortAnswers.find(S=>S.id===A):P==="trueFalse"?u.trueFalses.find(S=>S.id===A):P==="shape"?u.shapes.find(S=>S.id===A):null:null;D({elementId:A,elementType:P,existingAudio:ye?.audioData});break;case "edit":C(null);let Y=null;P==="mcq"?Y=u?.multipleChoices.find(S=>S.id===A):P==="trueFalse"?Y=u?.trueFalses.find(S=>S.id===A):P==="shortAnswer"?Y=u?.shortAnswers.find(S=>S.id===A):P==="longAnswer"?Y=u?.LongAnswer.find(S=>S.id===A):P==="fillInTheBlanks"&&(Y=u?.fillInTheBlanks.find(S=>S.id===A)),Y&&ti(Y);break;case "editFlashcard":C(null);let At=u?.flashcards.find(S=>S.id===A);At&&au(At);break;case "color":C(null);let Lt=u?.shapes.find(S=>S.id===A);G({elementId:A,elementType:"shape",defaultColor:Lt?.color||"#096B76"});break;case "crop":if(C(null),P==="image"){let S=u?.images.find(uu=>uu.id===A);S&&me({elementId:A,imageSrc:S.src});}break;case "draw":C(null),P==="image"?r(ms(A)):P==="photoFrame"&&r(hs(A));break;case "duplicate":r(oe()),P==="line"?r(Es(A)):P==="image"?r(Xo(A)):P==="video"?r(Yo(A)):P==="shape"?r(Jo(A)):P==="text"?r(Qo(A)):P==="flashcard"?r(Zo(A)):P==="photoFrame"?r(er(A)):P==="mcq"?r(tr(A)):P==="trueFalse"?r(ar(A)):P==="shortAnswer"?r(or(A)):P==="fillInTheBlanks"?r(sr(A)):P==="longAnswer"&&r(rr(A)),_();break;case "infinite-clone":r(oe());let mt=5;for(let S=0;S<mt;S++)P==="image"?r(Xo(A)):P==="video"?r(Yo(A)):P==="shape"?r(Jo(A)):P==="text"?r(Qo(A)):P==="flashcard"?r(Zo(A)):P==="photoFrame"?r(er(A)):P==="mcq"?r(tr(A)):P==="trueFalse"?r(ar(A)):P==="shortAnswer"?r(or(A)):P==="fillInTheBlanks"?r(sr(A)):P==="longAnswer"&&r(rr(A));_();break;case "make-response":if(C(null),P==="line")break;let je=`#response-${A}`;r(oe()),r(nr({id:A,type:P,link:je})),(u?P==="image"?u.images.find(S=>S.id===A):P==="video"?u.videos.find(S=>S.id===A):P==="shape"?u.shapes.find(S=>S.id===A):P==="flashcard"?u.flashcards.find(S=>S.id===A):P==="photoFrame"?u.photoFrames.find(S=>S.id===A):u.multipleChoices.find(S=>S.id===A):null)?.altText||r(ir({id:A,type:P,altText:"Interactive response area"})),_(),console.log(`Element ${A} marked as interactive response area`);break;case "accessibility":if(C(null),P==="line")break;let F=u?P==="image"?u.images.find(S=>S.id===A):P==="video"?u.videos.find(S=>S.id===A):P==="shape"?u.shapes.find(S=>S.id===A):null:null;E({type:"altText",defaultValue:F?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),C(null),j(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(oe()),P==="line"?r(Ps(A)):P==="image"?r(ts(A)):P==="video"?r(as(A)):P==="shape"?r(rs(A)):P==="text"?r(ns(A)):P==="flashcard"?r(ls(A)):P==="photoFrame"?r(fs(A)):P==="mcq"?r(bs(A)):P==="trueFalse"?r(Ls(A)):P==="shortAnswer"?r(Is(A)):P==="longAnswer"?r(Ss(A)):P==="fillInTheBlanks"&&r(ks(A)),Go(),_();break}},[L,r,_,Go,u,ti]),ru=useCallback(()=>{C(null),O(null);},[]),Kr=useCallback(v=>{if(!L)return;let{elementId:M,elementType:A}=L;switch(r(oe()),v){case "bring-to-front":A!=="line"&&r(As({id:M,type:A}));break;case "send-to-back":A!=="line"&&r(Ds({id:M,type:A}));break;case "lock":case "unlock":A!=="line"&&r(Ts({id:M,type:A}));break}_(),C(null),O(null);},[L,r,_]),su=useCallback(v=>{if(!L||!R)return;let{elementId:M,elementType:A}=L;r(oe()),R.type==="link"&&A!=="line"?r(nr({id:M,type:A,link:v})):R.type==="altText"&&A!=="line"&&r(ir({id:M,type:A,altText:v})),_(),E(null);},[L,R,r,_]),nu=useCallback(v=>{if(!N)return;let{elementId:M,elementType:A}=N;r(oe()),r(lr({id:M,type:A,audioData:v})),_(),D(null);},[N,r,_]),iu=useCallback(()=>{if(!N)return;let{elementId:v,elementType:M}=N;r(oe()),r(lr({id:v,type:M,audioData:""})),_();},[N,r,_]),lu=useCallback(v=>{if(!T)return;let{elementId:M}=T;r(oe()),r(wa({id:M,color:v})),_(),G(null);},[T,r,_]),du=useCallback(v=>{if(!z)return;let{elementId:M}=z;r(oe()),r(Ia({id:M,src:v})),_(),me(null);},[z,r,_]);return jsxs("div",{ref:d,className:"fixed inset-0",style:{cursor:i==="pen"?"crosshair":i==="eraser"?"":"default"},children:[i==="pen"&&jsx(pi,{ref:v=>{if(Z.current=v,Q(v),v){let M=v.getCanvasElement();M&&(ae.current=M,t&&t(ae));}},width:h.width,height:h.height,tool:ee,color:Le,strokeWidth:Ze,isSketchMode:kt}),jsxs(Stage,{ref:f,width:h.width,height:h.height,onMouseDown:Qn,onMouseMove:Zn,onMouseUp:ei,onTouchStart:Qn,onTouchMove:Zn,onTouchEnd:ei,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:h.width,height:h.height,fill:u?.backgroundColor||"white"})}),jsx(Layer,{children:(()=>{let v=[];return p.forEach((M,A)=>{v.push({type:"line",timestamp:M.timestamp||A,element:{...M,id:M.id??`line-${A}`},index:A});}),Nd.forEach(M=>{v.push({type:"shape",timestamp:M.timestamp||0,element:M});}),we.forEach(M=>{v.push({type:"image",timestamp:M.timestamp||0,element:M});}),Mt.forEach(M=>{v.push({type:"video",timestamp:M.timestamp||0,element:M});}),za.forEach(M=>{v.push({type:"text",timestamp:M.timestamp||0,element:M});}),zd.forEach(M=>{v.push({type:"flashcard",timestamp:M.timestamp||0,element:M});}),Jn.forEach(M=>{v.push({type:"photoFrame",timestamp:M.timestamp||0,element:M});}),Md.forEach(M=>{v.push({type:"mcq",timestamp:M.timestamp||0,element:M});}),Dd.forEach(M=>{v.push({type:"trueFalse",timestamp:M.timestamp||0,element:M});}),Pd.forEach(M=>{v.push({type:"shortAnswer",timestamp:M.timestamp||0,element:M});}),Rd.forEach(M=>{v.push({type:"longAnswer",timestamp:M.timestamp||0,element:M});}),Od.forEach(M=>{v.push({type:"fillInTheBlanks",timestamp:M.timestamp||0,element:M});}),v.sort((M,A)=>M.timestamp-A.timestamp),v.map((M,A)=>{let P=`${M.type}-${"id"in M.element&&M.element.id||M.index||A}`,Oe="id"in M.element?M.element.id:void 0,ye=Oe&&m===Oe;switch(M.type){case "line":let Y=M.element,At=M.index||0,Lt=Y.tool==="eraser",mt=Y.isSketch&&Y.tool==="pen",je=Y.isSketch&&Lt,rt=Y.id||`line-${At}`;return Y.x===void 0&&(Y.x=0),Y.y===void 0&&(Y.y=0),Y.scaleX===void 0&&(Y.scaleX=1),Y.scaleY===void 0&&(Y.scaleY=1),Y.rotation===void 0&&(Y.rotation=0),i==="eraser"?jsx(Group,{x:Y.x||0,y:Y.y||0,scaleX:Y.scaleX||1,scaleY:Y.scaleY||1,rotation:Y.rotation||0,children:jsx(Line,{points:Y.points||[],stroke:mt||je?void 0:Y.color,strokeWidth:mt||je?0:Y.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:mt||je?Lt?"black":Y.color:void 0,closed:mt||je,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,onClick:()=>{r(oe()),r(jo(At));},onTap:()=>{r(oe()),r(jo(At));},hitStrokeWidth:Math.max(20,(Y.strokeWidth??0)*2),onMouseEnter:F=>{let S=F.target.getStage();S&&(S.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:F=>{let S=F.target.getStage();S&&(S.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`);}})},P):jsxs(ut.Fragment,{children:[jsx(Group,{id:rt,ref:F=>{F?Ae.current.set(rt,F):Ae.current.delete(rt);},x:Y.x||0,y:Y.y||0,scaleX:Y.scaleX||1,scaleY:Y.scaleY||1,rotation:Y.rotation||0,draggable:i==="select",listening:i==="select",onClick:()=>{i==="select"&&(console.log("Line clicked:",rt),De(rt));},onTap:()=>{i==="select"&&(console.log("Line tapped:",rt),De(rt));},onDragEnd:F=>{r(oe()),r(dr({id:rt,x:F.target.x(),y:F.target.y(),scaleX:F.target.scaleX(),scaleY:F.target.scaleY(),rotation:F.target.rotation()})),_();},onTransformEnd:F=>{r(oe()),r(dr({id:rt,x:F.target.x(),y:F.target.y(),scaleX:F.target.scaleX(),scaleY:F.target.scaleY(),rotation:F.target.rotation()})),_();},onMouseEnter:F=>{if(i==="select"){let S=F.target.getStage();S&&(S.container().style.cursor="move");}},onMouseLeave:F=>{if(i==="select"){let S=F.target.getStage();S&&(S.container().style.cursor="default");}},onContextMenu:F=>{let S=F.evt;S.preventDefault(),ot(S,rt,"line");},children:jsx(Line,{points:Y.points||[],stroke:mt||je?void 0:Y.color,strokeWidth:mt||je?0:Y.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:mt||je?Lt?"black":Y.color:void 0,closed:mt||je,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ae.current.get(m);console.log("Line Transformer - selectedId:",m,"node found:",!!S),S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:at,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"]})]},P);case "shape":return jsxs(ut.Fragment,{children:[jsx($s,{onSelect:De,shapes:[M.element],shapeRefs:Ho,handleShapeDragEnd:Vd,handleShapeResizeEnd:Hd,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ho.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "image":return jsxs(ut.Fragment,{children:[jsx(zs,{images:[M.element],getLoadedImage:Be,imageRefs:et,onDragEnd:eu,onTransform:ya,onSelect:De,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=et.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "video":return jsxs(ut.Fragment,{children:[jsx(Xs,{videos:[M.element],selectedId:m,videoRefs:na,onVideoClick:tu,onDragEnd:qt,onTransformEnd:ia,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=na.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "text":return jsxs(ut.Fragment,{children:[jsx(Xi,{texts:[M.element],textRefs:Nt,onDragEnd:Ud,onTransformEnd:Wd,onSelect:De,onContextMenu:ot,onDoubleClick:Kd,editingTextId:ue,editingValue:_n,onEditingChange:Yn}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Nt.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "flashcard":return jsxs(ut.Fragment,{children:[jsx(Js,{flashcards:[M.element],flashcardRefs:Ko,selectedId:m,onDragEnd:Gd,onTransform:jd,onSelect:De,onNext:Xd,onPrevious:$d,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ko.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "photoFrame":return jsxs(ut.Fragment,{children:[jsx(on,{photoFrames:[M.element],photoFrameRefs:zo,selectedId:m,onDragEnd:_d,onTransform:Yd,onSelect:De,onStartCamera:Jd,onCapture:Qd,cameraStreams:Zd,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=zo.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "mcq":return jsxs(ut.Fragment,{children:[jsx(wl,{handleMcqTransform:No,multipleChoice:[M.element],handleSelect:De,mcqRefs:Vo,handleDragEnd:Ad,onContextMenu:ot}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Vo.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "trueFalse":return jsxs(ut.Fragment,{children:[jsx(Ml,{trueFalses:[M.element],handleTrueFalseTransform:Td,handleSelect:De,trueFalseRefs:Xn,onContextMenu:ot,handleDragEnd:Fd}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Xn.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "shortAnswer":return jsxs(ut.Fragment,{children:[jsx(zl,{shortAnswers:[M.element],handleSelect:De,handleTransform:No,saRefs:Ka,onContextMenu:ot,handleDragEnd:Ed}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ka.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "longAnswer":return jsxs(ut.Fragment,{children:[jsx(Jl,{longAnswer:[M.element],handleSelect:De,handleTransform:No,saRefs:Ka,onContextMenu:ot,handleDragEnd:Bd}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ka.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);case "fillInTheBlanks":return jsxs(ut.Fragment,{children:[jsx(_l,{fillInTheBlanks:[M.element],handleSelect:De,handleTransform:No,onContextMenu:ot,handleDragEnd:qd}),ye&&!ue&&m&&jsx(Transformer,{ref:F=>{if(F&&re.current!==F){re.current=F;let S=Ka.current.get(m);S&&S.visible()&&(F.nodes([S]),F.getLayer()?.batchDraw());}},boundBoxFunc:at,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"]})]},P);default:return null}})})()})]}),g&&!Mt.some(v=>v.isRecorded&&v.isPlaying)&&jsx("img",{src:g,alt:"Canvas Preview",className:"fixed top-4 right-4 z-50 rounded-lg border-2 border-gray-300 p-1 shadow-lg",style:{maxWidth:"250px",maxHeight:"250px"}}),L&&jsx(ll,{x:L.x,y:L.y,type:L.elementType,onAction:ou,onClose:ru,isDrawingMode:L.elementType==="image"?u?.images.find(v=>v.id===L.elementId)?.isDrawingMode:L.elementType==="photoFrame"?u?.photoFrames.find(v=>v.id===L.elementId)?.isDrawingMode:false}),U&&L&&jsx(dl,{x:U.x,y:U.y,items:U.type==="order"?[{label:"Bring to Front",onClick:()=>Kr("bring-to-front")},{label:"Send to Back",onClick:()=>Kr("send-to-back")}]:[{label:u&&(L.elementType==="image"?u.images.find(v=>v.id===L.elementId)?.locked:u.videos.find(v=>v.id===L.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Kr(u&&(L.elementType==="image"?u.images.find(v=>v.id===L.elementId)?.locked:u.videos.find(v=>v.id===L.elementId)?.locked)?"unlock":"lock")}],onClose:()=>O(null)}),R&&jsx(ul,{title:R.type==="link"?"Add Link":"Add Alt Text",label:R.type==="link"?"URL":"Alternative Text",placeholder:R.type==="link"?"https://example.com":"Describe this image/video",defaultValue:R.defaultValue,onSave:su,onClose:()=>E(null)}),T&&jsx(cl,{defaultColor:T.defaultColor,onConfirm:lu,onCancel:()=>G(null)}),z&&jsx(hl,{imageSrc:z.imageSrc,onConfirm:du,onCancel:()=>me(null)}),J&&jsx(no,{onClose:()=>de(false),stageRef:f}),N&&jsx(xl,{elementId:N.elementId,elementType:N.elementType,existingAudio:N.existingAudio,onSave:nu,onDelete:iu,onClose:()=>D(null)}),V&&jsx(Ll,{selectedElementId:m||void 0,onClose:()=>j(false),onSelectElement:v=>{De(v),j(false);}}),u?.images.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.videos.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.shapes?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.texts?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.flashcards?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.photoFrames?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.multipleChoices?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.trueFalses?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.shortAnswers?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.LongAnswer?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),u?.fillInTheBlanks?.filter(v=>v.audioData).map(v=>jsx(it,{audioData:v.audioData,x:v.x,y:v.y,width:v.width},`audio-${v.id}`)),l&&jsx(ql,{editElement:s}),I&&(()=>{let v=ue||m;if(!v)return null;let M=za.find(A=>A.id===v);return M?jsx(Nl,{text:M,position:I}):null})(),w&&ue&&(()=>{let v=za.find(M=>M.id===ue);return v?jsx(Hl,{text:v,editingValue:_n,onEditingChange:Yn,onFinish:Wr,position:{top:w.top,left:w.left},scale:w.scale,textareaRef:te},ue):null})()]})},Up=Hp;var Wp="SchooplaVideoStorage";var oa="videos",En=()=>new Promise((e,o)=>{let a=indexedDB.open(Wp,1);a.onerror=()=>o(a.error),a.onsuccess=()=>e(a.result),a.onupgradeneeded=t=>{let r=t.target.result;r.objectStoreNames.contains(oa)||r.createObjectStore(oa,{keyPath:"id"});};}),To=async(e,o,a)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let t=await En(),i=t.transaction([oa],"readwrite").objectStore(oa),n={id:e,blob:o,thumbnailDataUrl:a,timestamp:Date.now()};await new Promise((u,c)=>{let s=i.put(n);s.onsuccess=()=>u(!0),s.onerror=()=>c(s.error);}),t.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(t){throw console.error("Error saving video blob to IndexedDB:",t),t}};var td=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await En(),a=e.transaction([oa],"readonly").objectStore(oa);return new Promise((t,r)=>{let i=a.getAll();i.onsuccess=()=>{e.close();let n=i.result,u=new Map;n.forEach(c=>{u.set(c.id,{blob:c.blob,thumbnailDataUrl:c.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${u.size} video blobs from IndexedDB`),t(u);},i.onerror=()=>{e.close(),r(i.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Rn=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await En(),t=o.transaction([oa],"readwrite").objectStore(oa);await new Promise((r,i)=>{let n=t.delete(e);n.onsuccess=()=>r(!0),n.onerror=()=>i(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}};var ad=e=>URL.createObjectURL(e);var zp={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},od=createSlice({name:"toolbar",initialState:zp,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:xt,setPenColor:Hr,setStrokeWidth:Bn,setFontSize:Kw,setFontFamily:zw,setFontStyle:Gw,setFontWeight:jw,setTextDecoration:Xw,setTextColor:$w}=od.actions,rd=od.reducer;var sd=({onClose:e,onRecordingComplete:o})=>{let[a,t]=useState(false),[r,i]=useState(null),[n,u]=useState(0),[c,s]=useState(null),[l,p]=useState(false),f=useRef(null),d=useRef([]),m=useRef(null),x=useRef(null),g=useRef(null);useEffect(()=>((async()=>{try{let k=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});s(k),p(!0),g.current&&(g.current.srcObject=k);}catch(k){console.error("Error accessing camera:",k),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{m.current&&clearInterval(m.current),c&&c.getTracks().forEach(k=>k.stop());}),[]);let y=()=>{c&&(c.getTracks().forEach(I=>I.stop()),s(null),p(false));},h=async()=>{try{let I=null,k=null;try{I=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(R){console.error("Error accessing camera for recording:",R),alert("Failed to access camera for recording.");return}try{k=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(R){console.warn("Microphone access denied:",R);}let w=[...I.getVideoTracks()];k&&w.push(...k.getAudioTracks());let q=new MediaStream(w),U="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?U="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?U="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?U="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(U="video/webm;codecs=vp8");let O=new MediaRecorder(q,{mimeType:U,videoBitsPerSecond:25e5});f.current=O,d.current=[],O.ondataavailable=R=>{R.data.size>0&&d.current.push(R.data);},O.onstop=()=>{let R=new Blob(d.current,{type:U}),E=document.createElement("video");E.src=URL.createObjectURL(R),E.muted=!0,E.currentTime=.1,E.onseeked=()=>{let T=document.createElement("canvas");T.width=E.videoWidth,T.height=E.videoHeight;let G=T.getContext("2d");G&&(G.drawImage(E,0,0),x.current=T.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(E.src);},q.getTracks().forEach(T=>T.stop()),I&&I.getTracks().forEach(T=>T.stop()),k&&k.getTracks().forEach(T=>T.stop()),m.current&&clearInterval(m.current),i(R),y();},O.onerror=R=>{console.error("MediaRecorder error:",R);},O.start(1e3),t(!0),u(0),m.current=setInterval(()=>{u(R=>R+1);},1e3);}catch(I){console.error("Error starting camera recording:",I),alert("Failed to start recording. Please check permissions.");}},b=()=>{f.current&&a&&(f.current.state!=="inactive"&&(f.current.requestData(),setTimeout(()=>{f.current&&f.current.state!=="inactive"&&f.current.stop();},100)),t(false));},L=()=>{if(r){let I=URL.createObjectURL(r),k=document.createElement("a");k.href=I,k.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(k),k.click(),document.body.removeChild(k),URL.revokeObjectURL(I);}},C=I=>{let k=Math.floor(I/60),w=I%60;return `${k.toString().padStart(2,"0")}:${w.toString().padStart(2,"0")}`};return jsx("div",{className:"fixed inset-0 flex items-center justify-center",children:jsxs("div",{className:"relative w-full max-w-2xl overflow-hidden rounded-2xl shadow-2xl",children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:g,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:h,disabled:!l,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"})})}),!l&&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"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:b,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:C(n)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",C(n)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{i(null),u(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&&x.current&&(o(r,x.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})})};var Rt=40,dd=({onConfirm:e,onCancel:o,editingFlashcard:a})=>{let[t,r]=useState(a?.images||[]),[i,n]=useState(a?.order||"sequential"),[u,c]=useState(false),s=useRef(null),l=useRef(null);useEffect(()=>{let h=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[o]);let p=h=>{let b=h.target.files;if(!b||b.length===0)return;let L=Rt-t.length;if(L<=0){alert(`You can only upload a maximum of ${Rt} images`);return}let C=Array.from(b).slice(0,L);C.length<b.length&&alert(`Only ${L} more images can be added (max ${Rt} total)`);let I=C.map(k=>new Promise((w,q)=>{let U=new FileReader;U.onload=O=>{O.target?.result?w(O.target.result):q(new Error("Failed to read file"));},U.onerror=q,U.readAsDataURL(k);}));Promise.all(I).then(k=>{r(w=>[...w,...k]),l.current&&(l.current.value="");});},f=h=>{h.preventDefault(),c(false);let b=Array.from(h.dataTransfer.files).filter(k=>k.type.startsWith("image/"));if(b.length===0)return;let L=Rt-t.length;if(L<=0){alert(`You can only upload a maximum of ${Rt} images`);return}let C=b.slice(0,L);C.length<b.length&&alert(`Only ${L} more images can be added (max ${Rt} total)`);let I=C.map(k=>new Promise((w,q)=>{let U=new FileReader;U.onload=O=>{O.target?.result?w(O.target.result):q(new Error("Failed to read file"));},U.onerror=q,U.readAsDataURL(k);}));Promise.all(I).then(k=>{r(w=>[...w,...k]);});},d=h=>{h.preventDefault(),c(true);},m=()=>{c(false);},x=h=>{r(b=>b.filter((L,C)=>C!==h));},y=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:h=>{h.target===h.currentTarget&&o(),h.stopPropagation();},onMouseUp:h=>h.stopPropagation(),onMouseMove:h=>h.stopPropagation(),onTouchStart:h=>h.stopPropagation(),onTouchMove:h=>h.stopPropagation(),onTouchEnd:h=>h.stopPropagation(),children:jsxs("div",{ref:s,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white shadow-xl",onClick:h=>h.stopPropagation(),children:[jsx("div",{className:"border-b border-gray-200 px-6 py-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-black",children:a?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-black",children:jsx(X,{size:20,weight:"bold"})})]})}),jsxs("form",{onSubmit:h=>{if(h.preventDefault(),t.length<2){alert("Please upload at least 2 images for the flashcard");return}e(t,i,a?.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-gray-900",children:[jsxs("span",{className:"flex items-center gap-2",children:[jsx(Image$1,{size:16,className:"text-gray-900"}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-600",children:t.length>=Rt?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",Rt," images"]}):jsxs("span",{children:[t.length,"/",Rt," images"]})})]}),jsx("input",{ref:l,type:"file",accept:"image/*",multiple:true,onChange:p,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:f,onDragOver:d,onDragLeave:m,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${u?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full border border-gray-300 bg-gray-100",children:jsx(Image$1,{size:24,className:"text-gray-600"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:u?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF up to 10MB each"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center gap-2 text-sm font-medium text-gray-900",children:[jsx(ArrowsDownUp,{size:16,className:"text-gray-900"}),"Display Order"]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${i==="sequential"?"border-black text-black":"border-gray-300 bg-white text-gray-900 hover:border-gray-400"}`,children:jsxs("div",{className:"flex flex-col items-center gap-2",children:[jsx(ArrowsDownUp,{size:20}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Navigate in order"})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${i==="random"?"border-black text-black":"border-gray-300 bg-white text-gray-900 hover:border-gray-400"}`,children:jsxs("div",{className:"flex flex-col items-center gap-2",children:[jsx(Shuffle,{size:20}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Shuffle cards"})]})]})})]})]}),t.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-gray-900",children:[jsx("span",{children:"Your Cards"}),jsxs("span",{className:"rounded bg-black px-2 py-0.5 text-xs text-white",children:[t.length," card",t.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg border border-gray-200 bg-gray-50 p-3",children:t.map((h,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded border border-gray-300 bg-white",children:[jsx("img",{src:h,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>x(b),className:"absolute top-1 right-1 rounded bg-black p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-gray-800",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded bg-black text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:b+1})]},b))})]}),t.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 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:t.length<2,className:"flex-1 rounded-lg bg-black px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:a?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(y,document.body)};var Mh=({isOpen:e,onClose:o,onScreenRecord:a,stageRef:t,onTextAdded:r,showToggleButton:i=true}={})=>{let n=pe(),u=$(B=>B.canvas.slides.find(se=>se.id===B.canvas.currentSlideId)),c=u?.videos||[],s=u?.editingFlashcard,l=$(B=>B.toolbar.selectedTool),p=$(B=>B.toolbar.penColor),f=$(B=>B.toolbar.strokeWidth),d=u?.showMcqForm,m=u?.showFlashcardForm,x=u?.backgroundColor||"#ffffff",g=c.some(B=>B.isRecorded&&B.isPlaying),y=$(B=>B.toolbar.fontSize),h=$(B=>B.toolbar.fontFamily),b=$(B=>B.toolbar.fontStyle),L=$(B=>B.toolbar.fontWeight),C=$(B=>B.toolbar.textDecoration),I=$(B=>B.toolbar.textColor),[k,w]=useState(false),[q,U]=useState(false),[O,R]=useState(true),E=e!==void 0?e:O,T=()=>{o&&E?o():e===void 0&&R(!O);},G=(B,se,ie)=>{ie/=100;let le=se*Math.min(ie,1-ie)/100,Q=ee=>{let Le=(ee+B/30)%12,Ze=ie-le*Math.max(Math.min(Le-3,9-Le,1),-1);return Math.round(255*Ze).toString(16).padStart(2,"0")};return `#${Q(0)}${Q(8)}${Q(4)}`},z=[{name:"select",icon:jsx(Selection,{size:20,weight:"bold"}),label:"Select"},{name:"pen",icon:jsx(Pen,{size:20,weight:"bold"}),label:"Pen"},{name:"eraser",icon:jsx(Eraser,{size:20,weight:"bold"}),label:"Eraser"},{name:"text",icon:jsx(TextT,{size:20,weight:"bold"}),label:"Text"}],me=[{name:"rectangle",icon:jsx(Square,{size:20,weight:"bold"}),label:"Rect"},{name:"circle",icon:jsx(Circle$1,{size:20,weight:"bold"}),label:"Circle"},{name:"ellipse",icon:jsx(Circle$1,{size:20,weight:"bold",style:{transform:"scaleX(0.6)"}}),label:"Ellipse"},{name:"triangle",icon:jsx(Triangle,{size:20,weight:"bold"}),label:"Tri"},{name:"polygon",icon:jsx(Hexagon,{size:20,weight:"bold"}),label:"Hex"},{name:"star",icon:jsx(Star$1,{size:20,weight:"bold"}),label:"Star"},{name:"ring",icon:jsx(Circle$1,{size:20,weight:"bold"}),label:"Ring"},{name:"wedge",icon:jsx(Pizza,{size:20,weight:"bold"}),label:"Wedge"},{name:"arrow",icon:jsx(ArrowRight,{size:20,weight:"bold"}),label:"Arrow"},{name:"line",icon:jsx(LineSegment,{size:20,weight:"bold"}),label:"Line"},{name:"arc",icon:jsx(Circuitry,{size:20,weight:"bold"}),label:"Arc"}],J=B=>{let se=B.target.files;!se||se.length===0||(n(xt("select")),n(Xe(false)),Array.from(se).forEach(ie=>{let le=new FileReader;le.onload=Q=>{let ee=new window.Image;ee.src=Q.target?.result,ee.onload=()=>{let Le=ee.width/ee.height,Ze=300,kt=300,Ae=ee.width,we=ee.height;Ae>Ze&&(Ae=Ze,we=Ae/Le),we>kt&&(we=kt,Ae=we*Le),n(oe());let Be=(window.innerWidth-Ae)/2,et=(window.innerHeight-we)/2;n(es({id:v4(),src:ee.src,x:Be,y:et,width:Ae,height:we,draggable:true,rotation:0}));};},le.readAsDataURL(ie);}),B.target.value="");},de=async B=>{let se=B.target.files;if(!(!se||se.length===0)){console.log("files",B),n(xt("select")),n(Xe(false));for(let ie of Array.from(se))try{let le=URL.createObjectURL(ie),Q=document.createElement("video");console.log("video",Q),Q.src=le,Q.muted=!0,Q.playsInline=!0,Q.preload="auto",await new Promise((tt,qt)=>{let ia=setTimeout(()=>qt(new Error("Metadata load timeout")),1e4);Q.onloadedmetadata=()=>{clearTimeout(ia),tt();},Q.onerror=()=>{clearTimeout(ia),qt(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:Q.duration,width:Q.videoWidth,height:Q.videoHeight}),await new Promise((tt,qt)=>{let ia=setTimeout(()=>qt(new Error("Video load timeout")),1e4);Q.readyState>=2?(clearTimeout(ia),tt()):Q.onloadeddata=()=>{clearTimeout(ia),tt();};});let ee=Math.min(.8,Q.duration/2);console.log("Seeking to:",ee),Q.currentTime=ee,await new Promise(tt=>{let qt=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),tt();},5e3);Q.onseeked=()=>{clearTimeout(qt),console.log("Seek completed"),tt();};});let Le=document.createElement("canvas"),Ze=Q.videoWidth/Q.videoHeight,kt=400,Ae=400,we=Q.videoWidth,Be=Q.videoHeight;we>kt&&(we=kt,Be=we/Ze),Be>Ae&&(Be=Ae,we=Be*Ze),Le.width=we,Le.height=Be;let et=Le.getContext("2d",{willReadFrequently:!1});if(!et)throw new Error("Failed to get canvas context");if(await new Promise(tt=>setTimeout(tt,100)),Q.videoWidth===0||Q.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:we,height:Be}),et.drawImage(Q,0,0,we,Be);let Ot=Le.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ot.length),n(oe());let ya=(window.innerWidth-we)/2,Mt=(window.innerHeight-Be)/2,na=v4();await To(na,ie,Ot),n($o({id:na,objectUrl:le,thumbnailDataUrl:Ot,videoBlob:ie,x:ya,y:Mt,width:we,height:Be,draggable:!0,isPlaying:!1,rotation:0})),Q.src="",Q.load(),console.log(`Video uploaded: ${ie.name}`);}catch(le){console.error("Error processing video:",le),alert(`Failed to process video: ${ie.name}`);}B.target.value="";}},N=(B,se,ie)=>{n(oe()),n(xt("select")),n(Xe(false));let le=300,Q=300,ee=(window.innerWidth-le)/2,Le=(window.innerHeight-Q)/2;n(ie?Sa({id:ie,images:B,order:se,x:ee,y:Le,width:le,height:Q,rotation:0,draggable:true}):is({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:B,currentIndex:0,order:se,x:ee,y:Le,width:le,height:Q,rotation:0,draggable:true})),n(da(false));},D=()=>{n(oe()),n(xt("select")),n(Xe(false));let B=400,se=300,ie=(window.innerWidth-B)/2,le=(window.innerHeight-se)/2;n(cs({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ie,y:le,width:B,height:se,rotation:0,draggable:true,isCapturing:false}));},V=B=>{let le=(window.innerWidth-100)/2,Q=(window.innerHeight-100)/2,ee={};switch(B.name){case "circle":case "ring":case "wedge":case "arc":ee.radius=50,(B.name==="ring"||B.name==="arc")&&(ee.innerRadius=25,ee.outerRadius=50),(B.name==="wedge"||B.name==="arc")&&(ee.angle=B.name==="wedge"?60:90);break;case "ellipse":ee.radiusX=60,ee.radiusY=40;break;case "triangle":ee.radius=50,ee.sides=3;break;case "polygon":ee.radius=50,ee.sides=6;break;case "star":ee.innerRadius=25,ee.outerRadius=50,ee.numPoints=5;break;case "arrow":case "line":ee.points=[0,0,100,0],B.name==="arrow"&&(ee.pointerLength=10,ee.pointerWidth=10);break}let Le={id:`shape-${Date.now()}`,type:B.name,x:le,y:Q,width:100,height:100,rotation:0,color:p,...ee};n(oe()),n(Xe(false)),n(xt(B.name)),n(os(Le));},j=B=>{if(n(xt(B)),B==="select")n(Xe(false));else if(B==="text"){n(Xe(false)),n(oe());let se=200,ie=50,le=(window.innerWidth-se)/2,Q=(window.innerHeight-ie)/2,ee=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(ss({id:ee,text:"",x:le,y:Q,width:se,height:ie,rotation:0,draggable:true,fontSize:y,fontFamily:h,fontStyle:b,fontWeight:L,textDecoration:C,fill:I,align:"left"})),setTimeout(()=>{n(Qa(ee));},100),r&&r(ee);}else n(Xe(true));},te=()=>{n(Rs()),n(xt("select")),n(Xe(false));},Z=B=>{n(oe()),n(Jr(B));},ae=()=>{a?a():t?w(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Ce=()=>{U(true);},_=async(B,se)=>{try{n(xt("select")),n(Xe(!1));let ie=URL.createObjectURL(B),le=document.createElement("video");le.src=ie,le.muted=!0,le.playsInline=!0,le.preload="auto",await new Promise((Ot,ya)=>{let Mt=setTimeout(()=>ya(new Error("Metadata load timeout")),1e4);le.onloadedmetadata=()=>{clearTimeout(Mt),Ot();},le.onerror=()=>{clearTimeout(Mt),ya(new Error("Failed to load video"));};});let Q=640,ee=le.videoWidth/le.videoHeight,Le=Q,Ze=Le/ee,kt=window.innerWidth,Ae=window.innerHeight;n(oe());let we=(kt-Le)/2,Be=(Ae-Ze)/2,et=v4();await To(et,B,se),n($o({id:et,objectUrl:ie,thumbnailDataUrl:se,videoBlob:B,x:we,y:Be,width:Le,height:Ze,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),w(!1),U(!1);}catch(ie){console.error("Error adding recorded video to canvas:",ie),alert("Failed to add video to canvas. Please try again.");}},Pe=B=>{n(xt("select")),n(Xe(false)),n(Ya(null)),B&&n(Ms(B)),n(Wt(!d));},vt=()=>{n(ja(null)),n(da(true));};return g?null:jsxs(Fragment,{children:[i&&jsx("div",{className:"fixed top-4 left-4 z-50 flex h-10 w-10 cursor-pointer flex-col items-center justify-center gap-1 rounded-lg transition-all","aria-label":"Toggle toolbar",onClick:T,children:jsx(List,{size:32})}),E&&jsxs("div",{className:"fixed top-16 left-4 z-50 h-[calc(100vh-6rem)] w-56 overflow-y-auto rounded-xl border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"TOOLS"}),jsx("div",{className:"grid grid-cols-4 gap-2",children:z.map((B,se)=>jsxs("button",{onClick:()=>j(B.name),className:`flex flex-col items-center justify-center rounded-lg p-2 transition-all ${l===B.name?"bg-blue-500 text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,title:B.label,children:[B.icon,jsx("span",{className:"mt-1 text-[10px]",children:B.label})]},se))})]}),jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"SIZE"}),jsx("input",{type:"range",name:"size",id:"size",value:f,className:"h-2 w-full cursor-pointer rounded-full",min:6,max:24,onChange:B=>n(Bn(parseInt(B.target.value)))})]}),jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"SHAPES"}),jsx("div",{className:"grid grid-cols-4 gap-2",children:me.map(B=>jsxs("button",{onClick:()=>V(B),className:`flex flex-col items-center justify-center rounded-lg p-1.5 transition-all ${l===B.name?"bg-blue-500 text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,title:B.label,children:[B.icon,jsx("span",{className:"mt-0.5 text-[9px]",children:B.label})]},B.name))})]}),jsxs("div",{className:"space-y-1",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"PEN COLOR"}),jsx("div",{className:"h-8 w-full cursor-pointer rounded-md border-2 border-gray-300 transition-transform hover:scale-[1.02]",style:{backgroundColor:p},onClick:()=>document.getElementById("color-input")?.click()}),jsx("div",{className:"relative",children:jsx("input",{type:"range",min:"0",max:"360",defaultValue:"0",onChange:B=>{let se=parseInt(B.target.value),ie=G(se,100,50);n(Hr(ie));},className:"h-2 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%)"}})}),jsx("input",{id:"color-input",type:"color",value:p,onChange:B=>n(Hr(B.target.value)),className:"hidden"})]}),jsxs("div",{className:"space-y-1 border-t border-gray-200 pt-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"BACKGROUND"}),jsx("div",{className:"h-8 w-full cursor-pointer rounded-md border-2 border-gray-300 transition-transform hover:scale-[1.02]",style:{backgroundColor:x},onClick:()=>document.getElementById("bg-color-input")?.click()}),jsx("input",{id:"bg-color-input",type:"color",value:x,onChange:B=>Z(B.target.value),className:"hidden"})]}),jsxs("div",{className:"mb-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"MEDIA"}),jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxs("label",{className:"flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 text-gray-700 transition-colors hover:bg-gray-200",children:[jsx(Image$1,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Image"}),jsx("input",{type:"file",accept:"image/*",multiple:true,onChange:J,className:"hidden"})]}),jsxs("label",{className:`flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg transition-colors ${c.length>=1?"cursor-not-allowed bg-gray-50 text-gray-400":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:[jsx(Video,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Video"}),jsx("input",{type:"file",accept:"video/*",disabled:c.length>=1,multiple:true,onChange:de,className:"hidden"})]})]})]}),!a&&k&&t&&jsx(no,{onClose:()=>w(false),stageRef:t,onRecordingComplete:_}),q&&jsx(sd,{onClose:()=>U(false),onRecordingComplete:_}),m&&jsx(dd,{editingFlashcard:s,onConfirm:N,onCancel:()=>n(da(false))}),jsxs("div",{className:"mb-3 border-t border-gray-200 pt-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"ACTIVITIES"}),jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxs("button",{onClick:()=>vt(),className:"flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 text-gray-700 transition-colors hover:bg-gray-200",children:[jsx(Cards,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Flashcard"})]}),jsxs("button",{onClick:D,className:"flex h-12 cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 text-gray-700 transition-colors hover:bg-gray-200",children:[jsx(Camera,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Frame"})]}),jsxs("button",{onClick:()=>Pe("multiple-choice"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"MCQ",children:[jsx(ListChecksIcon,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"MCQ"})]}),jsxs("button",{onClick:()=>Pe("true-false"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"True False",children:[jsx(ToggleRight,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"True False"})]}),jsxs("button",{onClick:()=>Pe("short-answer"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Short Answer",children:[jsx(Textbox,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Short Answer"})]}),jsxs("button",{onClick:()=>Pe("long-answer"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Long Answer",children:[jsx(Article,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Long Answer"})]}),jsxs("button",{onClick:()=>Pe("fill-in-the-blank"),className:"flex cursor-pointer flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Fill in the blank",children:[jsx(TextUnderline,{size:20,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Fill in the blank"})]})]})]}),jsxs("div",{className:"mb-3 border-t border-gray-200 pt-3",children:[jsx("div",{className:"mb-2 text-xs font-semibold text-gray-500",children:"ACTIONS"}),jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxs("button",{onClick:()=>n(Bs()),className:"flex flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Undo",children:[jsx(ArrowUUpLeft,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Undo"})]}),jsxs("button",{onClick:()=>n(Os()),className:"flex flex-col items-center justify-center rounded-lg bg-gray-100 p-2 text-gray-700 transition-colors hover:bg-gray-200",title:"Redo",children:[jsx(ArrowUDownRight,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Redo"})]}),jsxs("button",{onClick:ae,className:"flex flex-col items-center justify-center rounded-lg bg-blue-50 p-2 text-blue-600 transition-colors hover:bg-blue-100",title:"Screen Record",children:[jsx(Record,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Record"})]}),jsxs("button",{onClick:Ce,className:"flex flex-col items-center justify-center rounded-lg bg-purple-50 p-2 text-purple-600 transition-colors hover:bg-purple-100",title:"Camera Record",children:[jsx(Camera,{size:18,weight:"fill"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Camera"})]}),jsxs("button",{onClick:()=>te(),className:"flex flex-col items-center justify-center rounded-lg bg-red-50 p-2 text-red-600 transition-colors hover:bg-red-100",title:"Clear",children:[jsx(Trash,{size:18,weight:"bold"}),jsx("span",{className:"mt-0.5 text-[10px]",children:"Clear"})]})]})]})]})]})},Ah=Mh;var cd=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Th=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,a,t)=>t?t.toUpperCase():a.toLowerCase()),Un=e=>{let o=Th(e);return o.charAt(0).toUpperCase()+o.slice(1)},Ur=(...e)=>e.filter((o,a,t)=>!!o&&o.trim()!==""&&t.indexOf(o)===a).join(" ").trim(),fd=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var md={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 hd=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:a=2,absoluteStrokeWidth:t,className:r="",children:i,iconNode:n,...u},c)=>createElement("svg",{ref:c,...md,width:o,height:o,stroke:e,strokeWidth:t?Number(a)*24/Number(o):a,className:Ur("lucide",r),...!i&&!fd(u)&&{"aria-hidden":"true"},...u},[...n.map(([s,l])=>createElement(s,l)),...Array.isArray(i)?i:[i]]));var ft=(e,o)=>{let a=forwardRef(({className:t,...r},i)=>createElement(hd,{ref:i,iconNode:o,className:Ur(`lucide-${cd(Un(e))}`,`lucide-${e}`,t),...r}));return a.displayName=Un(e),a};var Rh=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],ra=ft("circle-check-big",Rh);var Bh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],sa=ft("circle-x",Bh);var Oh=[["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"}]],Eo=ft("copy",Oh);var qh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ro=ft("plus",qh);var Nh=[["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"}]],Bo=ft("trash-2",Nh);var Vh=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Oo=ft("upload",Vh);var xd=({slide:e,index:o,isSelected:a,isSingleSlide:t,onSelect:r,onDuplicate:i,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${a?"border-blue-500 bg-blue-50 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:u=>{u.stopPropagation(),i();},className:"rounded bg-blue-500 p-1.5 text-white shadow-md transition-colors hover:bg-blue-600",title:"Duplicate slide",children:jsx(Eo,{size:14})}),!t&&jsx("button",{onClick:u=>{u.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Bo,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Slide ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var Hh=()=>{let e=yt(),o=Vt(eo),a=Vt(Za),t=Vt(qs),n=(Vt(p=>p.canvas.slides.find(f=>f.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),u=()=>{t&&e(jr());},c=p=>{e(_r(p));},s=p=>{e($r(p));},l=p=>{o.length>1&&e(Xr(p));};return n?null:jsxs("div",{className:"fixed top-0 right-0 z-50 flex h-screen w-80 flex-col border-l border-gray-300 bg-gray-50 shadow-lg",children:[jsxs("div",{className:"border-b border-gray-300 bg-white p-4",children:[jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsx("h2",{className:"text-lg font-semibold text-gray-800",children:"Slides"}),jsxs("span",{className:"text-sm text-gray-600",children:[o.length,"/20"]})]}),jsxs("button",{onClick:u,disabled:!t,className:`flex w-full items-center justify-center gap-2 rounded-lg px-4 py-2 font-medium transition-colors ${t?"bg-blue-500 text-white hover:bg-blue-600":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Ro,{size:18}),"Add Slide"]})]}),jsx("div",{className:"flex-1 overflow-y-auto p-4",children:jsx("div",{className:"space-y-3",children:o.map((p,f)=>jsx(xd,{slide:p,index:f,isSelected:p.id===a,isSingleSlide:o.length===1,onSelect:()=>c(p.id),onDuplicate:()=>s(p.id),onDelete:()=>l(p.id)},p.id))})}),jsx("div",{className:"border-t border-gray-300 bg-white p-3 text-center text-xs text-gray-500",children:"Click a slide to edit \u2022 Use buttons to manage slides"})]})};var Uh=({onPublish:e,label:o="Publish Slides",className:a})=>{let t=Vt(eo),n=(Vt(m=>m.canvas.slides.find(x=>x.id===m.canvas.currentSlideId))?.videos||[]).some(m=>m.isRecorded&&m.isPlaying),[u,c]=useState(false),[s,l]=useState(null),[p,f]=useState(null),d=async()=>{if(t.length===0){f({type:"error",message:"No slides to publish"});return}if(!e){f({type:"error",message:"No publish handler provided"});return}c(true),f(null);try{let m=await e(t,x=>{l(x);});m.success?f({type:"success",message:m.message}):f({type:"error",message:m.message});}catch(m){f({type:"error",message:m instanceof Error?m.message:"An unexpected error occurred"});}finally{c(false),setTimeout(()=>{l(null),f(null);},3e3);}};return n?null:jsx("div",{className:a||"fixed bottom-6 left-1/2 z-50 -translate-x-1/2 transform",children:jsxs("div",{className:"flex min-w-[280px] flex-col items-center gap-3 rounded-lg bg-white p-4 shadow-lg",children:[jsx("button",{onClick:d,disabled:u||t.length===0||!e,className:`flex items-center justify-center gap-2 rounded-lg px-6 py-3 font-medium transition-all ${u||t.length===0||!e?"cursor-not-allowed bg-gray-300 text-gray-500":"bg-green-500 text-white shadow-md hover:bg-green-600 hover:shadow-lg"}`,children:u?jsxs(Fragment,{children:[jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Publishing..."]}):jsxs(Fragment,{children:[jsx(Oo,{size:20}),o]})}),s&&jsxs("div",{className:"w-full",children:[jsx("div",{className:"mb-1 text-xs text-gray-600",children:s.status}),jsx("div",{className:"h-2 w-full rounded-full bg-gray-200",children:jsx("div",{className:"h-2 rounded-full bg-green-500 transition-all duration-300",style:{width:`${s.current/s.total*100}%`}})}),jsxs("div",{className:"mt-1 text-xs text-gray-500",children:[s.current," / ",s.total]})]}),p&&jsxs("div",{className:`flex items-center gap-2 rounded-lg px-4 py-2 ${p.type==="success"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[p.type==="success"?jsx(ra,{size:18}):jsx(sa,{size:18}),jsx("span",{className:"text-sm font-medium",children:p.message})]}),jsxs("div",{className:"text-xs text-gray-500",children:[t.length," slide",t.length!==1?"s":""," ready"]})]})})};function Wh({children:e,className:o="",style:a}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:a,children:e})}var zh="SchooplaEditorDB",Gh=1,Wa="slides",vd="schoopla_current_slide_id",Ld=()=>new Promise((e,o)=>{let a=indexedDB.open(zh,Gh);a.onerror=()=>o(a.error),a.onsuccess=()=>e(a.result),a.onupgradeneeded=t=>{let r=t.target.result;r.objectStoreNames.contains(Wa)||r.createObjectStore(Wa,{keyPath:"id"});};}),Kn=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Ld(),t=o.transaction([Wa],"readwrite").objectStore(Wa);await new Promise((r,i)=>{let n=t.clear();n.onsuccess=()=>r(!0),n.onerror=()=>i(n.error);});for(let r of e)await new Promise((i,n)=>{let u=t.add(r);u.onsuccess=()=>i(!0),u.onerror=()=>n(u.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(a){console.error("localStorage fallback failed:",a);}}},yd=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Ld(),a=e.transaction([Wa],"readonly").objectStore(Wa);return new Promise((t,r)=>{let i=a.getAll();i.onsuccess=()=>{e.close();let n=i.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(u=>({id:u.id,width:u.width,height:u.height,x:u.x,y:u.y}))),t(n.length>0?n:null);},i.onerror=()=>{e.close(),r(i.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var zn=e=>{try{localStorage.setItem(vd,e);}catch(o){console.error("Error saving current slide ID:",o);}},Id=()=>{try{return localStorage.getItem(vd)}catch(e){return console.error("Error loading current slide ID:",e),null}},wd=(e,o)=>{let a=null;return (...t)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...t),o);}};var jh=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/setCurrentSlide","canvas/updateSlideThumbnail","canvas/reorderSlides"],Xh=["canvas/clearCanvas"],$h=wd((e,o)=>{Kn(e),zn(o);},500),_h=(e,o)=>{Kn(e),zn(o);},Gn=false,Sd=(e=>o=>a=>{if(a.type==="canvas/deleteVideo"&&a.payload){let r=a.payload;Rn(r).catch(i=>{console.error("Error deleting video blob:",i);});}if(a.type==="canvas/deleteSlide"&&a.payload){let r=a.payload,n=e.getState().canvas.slides.find(u=>u.id===r);n&&n.videos&&n.videos.length>0&&n.videos.forEach(u=>{Rn(u.id).catch(c=>{console.error("Error deleting video blob:",c);});});}if(a.type==="canvas/duplicateVideo"&&a.payload){let r=a.payload,i=e.getState(),u=i.canvas.slides.find(c=>c.id===i.canvas.currentSlideId)?.videos.find(c=>c.id===r);u&&u.videoBlob&&setTimeout(()=>{let c=e.getState(),l=c.canvas.slides.find(p=>p.id===c.canvas.currentSlideId)?.videos.find(p=>p.id!==r&&p.x===u.x+20&&p.y===u.y+20);l&&u.videoBlob&&To(l.id,u.videoBlob,l.thumbnailDataUrl).catch(p=>{console.error("Error saving duplicated video blob:",p);});},0);}let t=o(a);if(a.type&&Xh.includes(a.type)){if(!Gn){Gn=true;try{let r=e.getState(),{slides:i,currentSlideId:n}=r.canvas;_h(i,n);}finally{setTimeout(()=>{Gn=false;},0);}}}else if(a.type&&jh.includes(a.type)){let r=e.getState(),{slides:i,currentSlideId:n}=r.canvas;$h(i,n);}return t});new QueryClient;var Qh=configureStore({reducer:{toolbar:rd,canvas:ii},middleware:e=>e({serializableCheck:false}).concat(Sd)});var Zh=(e,o={})=>{let{format:a="png",quality:t=1,pixelRatio:r=2,fileName:i=`slide-${Date.now()}`}=o;try{let n=a==="png"?"image/png":"image/jpeg",u=e.toDataURL({mimeType:n,quality:t,pixelRatio:r}),c=document.createElement("a");c.download=`${i}.${a}`,c.href=u,document.body.appendChild(c),c.click(),document.body.removeChild(c);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},eg=async(e,o={})=>{let{format:a="png",quality:t=1,pixelRatio:r=2}=o;return new Promise((i,n)=>{try{let u=a==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:u,quality:t,pixelRatio:r});fetch(c).then(s=>s.blob()).then(s=>i(s)).catch(s=>n(s));}catch(u){n(u);}})},tg=(e,o={})=>{let{format:a="png",quality:t=1,pixelRatio:r=2}=o,i=a==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:i,quality:t,pixelRatio:r})};var ag=(e,o,a)=>{let t=a.x-o.x,r=a.y-o.y;if(t===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let i=t*t+r*r,n=Math.max(0,Math.min(1,((e.x-o.x)*t+(e.y-o.y)*r)/i)),u=o.x+n*t,c=o.y+n*r;return Math.sqrt(Math.pow(e.x-u,2)+Math.pow(e.y-c,2))},jn=(e,o)=>{if(e.length<=2)return e;let a=0,t=0,r=e[0],i=e[e.length-1];for(let n=1;n<e.length-1;n++){let u=ag(e[n],r,i);u>a&&(a=u,t=n);}if(a>o){let n=jn(e.slice(0,t+1),o),u=jn(e.slice(t),o);return [...n.slice(0,-1),...u]}return [r,i]},og=e=>{let o=[];for(let a=0;a<e.length;a+=2)o.push({x:e[a],y:e[a+1]});return o},rg=e=>{let o=[];for(let a of e)o.push(a.x,a.y);return o},Cd=(e,o=1.5)=>{if(e.length<=4)return e;let a=og(e),t=jn(a,o);return rg(t)},kd=(e,o=1.5)=>({...e,points:Cd(e.points,o)}),sg=(e,o=1.5)=>e.map(a=>kd(a,o)),ng=(e,o)=>{let a=e.length/2,t=o.length/2,r=((1-t/a)*100).toFixed(1);return {originalPoints:a,simplifiedPoints:t,reduction:`${r}%`}};var lg=()=>{let e=yt();useEffect(()=>{(async()=>{try{let a=await yd(),t=Id();if(a&&a.length>0){let r=await td(),i=a.map(u=>{if(u.videos&&u.videos.length>0){let c=u.videos.map(s=>{let l=r.get(s.id);if(l){let p=ad(l.blob);return {...s,objectUrl:p,thumbnailDataUrl:l.thumbnailDataUrl,videoBlob:l.blob}}else return s});return {...u,videos:c}}return u}),n=t&&i.find(u=>u.id===t)?t:i[0].id;e(Qr({slides:i,currentSlideId:n}));}}catch(a){console.error("Error loading persisted slides:",a);}})();},[e]);};/*! Bundled license information:
7
7
 
8
8
  lucide-react/dist/esm/shared/src/utils.js:
9
9
  lucide-react/dist/esm/defaultAttributes.js:
@@ -22,5 +22,5 @@ lucide-react/dist/esm/lucide-react.js:
22
22
  * This source code is licensed under the ISC license.
23
23
  * See the LICENSE file in the root directory of this source tree.
24
24
  *)
25
- */export{Np as Canvas,Vh as EditorRoot,Nh as PublishButton,no as ScreenRecorder,qh as SlideNavigation,Ch as Toolbar,Cs as addFillInTheBlanks,is as addFlashcard,es as addImage,ps as addImageAnnotation,Zr as addLine,ws as addLongAnswer,xs as addMultipleChoice,cs as addPhotoFrame,gs as addPhotoFrameAnnotation,os as addShape,ys as addShortAnswer,jr as addSlide,ss as addText,vs as addTrueFalse,$o as addVideo,As as bringToFront,Rs as clearCanvas,pu as clearImageAnnotations,gu as clearPhotoFrameAnnotations,ks as deleteFillInTheBlanks,ls as deleteFlashcard,ts as deleteImage,Ps as deleteLineById,Ss as deleteLongAnswer,bs as deleteMultipleChoice,fs as deletePhotoFrame,rs as deleteShape,Is as deleteShortAnswer,Xr as deleteSlide,ns as deleteText,Ls as deleteTrueFalse,as as deleteVideo,sr as duplicateFillInTheBlanks,Zo as duplicateFlashcard,Xo as duplicateImage,Es as duplicateLine,rr as duplicateLongAnswer,tr as duplicateMultipleChoice,er as duplicatePhotoFrame,Jo as duplicateShape,or as duplicateShortAnswer,$r as duplicateSlide,Qo as duplicateText,ar as duplicateTrueFalse,Yo as duplicateVideo,ja as editFlashcard,xu as editMultipleChoice,Jh as exportSlideAsBlob,Yh as exportSlideAsImage,Fs as finalizeDrawing,Qh as getSlideDataURL,Qr as loadSlides,ds as nextFlashcard,us as previousFlashcard,Os as redo,jo as removeLine,fu as reorderSlides,oe as saveToHistory,eo as selectAllSlides,qs as selectCanAddSlide,ce as selectCurrentSlide,Za as selectCurrentSlideId,Iu as selectSlideById,Ds as sendToBack,Ms as setActivityType,ir as setAltText,lr as setAudioData,Jr as setBackgroundColor,_r as setCurrentSlide,Ya as setEditingActivity,Qa as setEditingTextId,vu as setLines,nr as setLink,Hr as setPenColor,da as setShowFlashcardForm,Wt as setShowMcqForm,Xe as setSketchMode,Bn as setStrokeWidth,xt as setTool,_h as store,ms as toggleImageDrawingMode,Ts as toggleLock,hs as togglePhotoFrameDrawingMode,yu as toggleSketchMode,Ga as toggleVideoPlaying,Bs as undo,Ja as updateElementOrder,_a as updateFillInTheBlanks,Sa as updateFlashcard,Ia as updateImage,mu as updateImageAnnotation,bu as updateLastLine,Lu as updateLinePosition,dr as updateLineTransform,$a as updateLongAnswer,Ht as updateMultipleChoice,la as updatePhotoFrame,hu as updatePhotoFrameAnnotation,wa as updateShape,Xa as updateShortAnswer,Yr as updateSlideThumbnail,st as updateText,Ut as updateTrueFalse,_o as updateVideo,pe as useDispatch,$ as useSelector,eg as useSlidesPersistence};//# sourceMappingURL=index.js.map
25
+ */export{Up as Canvas,Wh as EditorRoot,Uh as PublishButton,no as ScreenRecorder,Hh as SlideNavigation,Ah as Toolbar,Cs as addFillInTheBlanks,is as addFlashcard,es as addImage,ps as addImageAnnotation,Zr as addLine,ws as addLongAnswer,xs as addMultipleChoice,cs as addPhotoFrame,gs as addPhotoFrameAnnotation,os as addShape,ys as addShortAnswer,jr as addSlide,ss as addText,vs as addTrueFalse,$o as addVideo,As as bringToFront,Rs as clearCanvas,xu as clearImageAnnotations,vu as clearPhotoFrameAnnotations,ks as deleteFillInTheBlanks,ls as deleteFlashcard,ts as deleteImage,Ps as deleteLineById,Ss as deleteLongAnswer,bs as deleteMultipleChoice,fs as deletePhotoFrame,rs as deleteShape,Is as deleteShortAnswer,Xr as deleteSlide,ns as deleteText,Ls as deleteTrueFalse,as as deleteVideo,sr as duplicateFillInTheBlanks,Zo as duplicateFlashcard,Xo as duplicateImage,Es as duplicateLine,rr as duplicateLongAnswer,tr as duplicateMultipleChoice,er as duplicatePhotoFrame,Jo as duplicateShape,or as duplicateShortAnswer,$r as duplicateSlide,Qo as duplicateText,ar as duplicateTrueFalse,Yo as duplicateVideo,ja as editFlashcard,Lu as editMultipleChoice,eg as exportSlideAsBlob,Zh as exportSlideAsImage,Fs as finalizeDrawing,ng as getCompressionStats,tg as getSlideDataURL,Qr as loadSlides,ds as nextFlashcard,us as previousFlashcard,Os as redo,jo as removeLine,hu as reorderSlides,oe as saveToHistory,eo as selectAllSlides,qs as selectCanAddSlide,ce as selectCurrentSlide,Za as selectCurrentSlideId,Cu as selectSlideById,Ds as sendToBack,Ms as setActivityType,ir as setAltText,lr as setAudioData,Jr as setBackgroundColor,_r as setCurrentSlide,Ya as setEditingActivity,Qa as setEditingTextId,Iu as setLines,nr as setLink,Hr as setPenColor,da as setShowFlashcardForm,Wt as setShowMcqForm,Xe as setSketchMode,Bn as setStrokeWidth,xt as setTool,Cd as simplifyFlatPoints,kd as simplifyLine,sg as simplifyLines,Qh as store,ms as toggleImageDrawingMode,Ts as toggleLock,hs as togglePhotoFrameDrawingMode,Su as toggleSketchMode,Ga as toggleVideoPlaying,Bs as undo,Ja as updateElementOrder,_a as updateFillInTheBlanks,Sa as updateFlashcard,Ia as updateImage,gu as updateImageAnnotation,yu as updateLastLine,wu as updateLinePosition,dr as updateLineTransform,$a as updateLongAnswer,Ht as updateMultipleChoice,la as updatePhotoFrame,bu as updatePhotoFrameAnnotation,wa as updateShape,Xa as updateShortAnswer,Yr as updateSlideThumbnail,st as updateText,Ut as updateTrueFalse,_o as updateVideo,pe as useDispatch,$ as useSelector,lg as useSlidesPersistence};//# sourceMappingURL=index.js.map
26
26
  //# sourceMappingURL=index.js.map