@turnix-co/konva-editor 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- export{default as Konva}from'konva';import*as be from'react';import be__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,useMemo,createElement,useId,useLayoutEffect}from'react';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,configureStore}from'@reduxjs/toolkit';import Xl from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,Plus,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp as CloudArrowUp$1,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {CaretLeft,CloudArrowUp,EyeIcon,Stack as Stack$1,X as X$1,DotsSixVertical,ArrowUp,ArrowDown,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {createPortal}from'react-dom';import Xd from'use-image';import {motion,AnimatePresence,Reorder}from'framer-motion';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var Hl=e=>{throw TypeError(e)};var Ul=(e,o,t)=>o.has(e)||Hl("Cannot "+t);var _=(e,o,t)=>(Ul(e,o,"read from private field"),t?t.call(e):o.get(e)),Ae=(e,o,t)=>o.has(e)?Hl("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Ce=(e,o,t,a)=>(Ul(e,o,"write to private field"),o.set(e,t),t);var Wl=(e,o,t,a)=>({set _(r){Ce(e,o,r);},get _(){return _(e,o,a)}});var xe=()=>useDispatch(),ee=e=>useSelector(e),yt=xe,sa=ee;var vs=20,ys=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()}),bs=ys("Slide 1"),mm={slides:[bs],currentSlideId:bs.id,history:{[bs.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null},zl=createSlice({name:"canvas",initialState:mm,reducers:{addSlide:e=>{if(e.slides.length>=vs)return;let o=ys(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{if(e.slides.length<=1)return;let t=e.slides.findIndex(a=>a.id===o.payload);if(t!==-1&&(e.slides.splice(t,1),delete e.history[o.payload],e.currentSlideId===o.payload)){let a=Math.max(0,t-1);e.currentSlideId=e.slides[a].id;}},duplicateSlide:(e,o)=>{if(e.slides.length>=vs)return;let t=e.slides.findIndex(n=>n.id===o.payload);if(t===-1)return;let a=e.slides[t],r={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[r]=e.slides.splice(t,1);e.slides.splice(a,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(r=>r.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload);if(a){let r={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(r),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,newTimestamp:n}=o.payload;switch(r){case "image":let s=t.images.find(x=>x.id===a);s&&(s.timestamp=n);break;case "video":let c=t.videos.find(x=>x.id===a);c&&(c.timestamp=n);break;case "shape":let i=t.shapes.find(x=>x.id===a);i&&(i.timestamp=n);break;case "text":let d=t.texts.find(x=>x.id===a);d&&(d.timestamp=n);break;case "flashcard":let f=t.flashcards.find(x=>x.id===a);f&&(f.timestamp=n);break;case "photoFrame":let u=t.photoFrames.find(x=>x.id===a);u&&(u.timestamp=n);break;case "mcq":let m=t.multipleChoices.find(x=>x.id===a);m&&(m.timestamp=n);break;case "trueFalse":let l=t.trueFalses.find(x=>x.id===a);l&&(l.timestamp=n);break;case "shortAnswer":let h=t.shortAnswers.find(x=>x.id===a);h&&(h.timestamp=n);break;case "longAnswer":let g=t.LongAnswer.find(x=>x.id===a);g&&(g.timestamp=n);break;case "fillInTheBlanks":let p=t.fillInTheBlanks.find(x=>x.id===a);p&&(p.timestamp=n);break;case "line":let w=t.lines.find(x=>x.id===a);w&&(w.timestamp=n);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);if(a){let r={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(r),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);if(a){let r={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(r),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(r),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let r=t.multipleChoices[t.multipleChoices.length-1];a.x=r.x+20,a.y=r.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(r=>r.id===o.payload);if(a){let r={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(r),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let r=t.trueFalses[t.trueFalses.length-1];a.x=r.x+20,a.y=r.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(r),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let r=t.shortAnswers[t.shortAnswers.length-1];a.x=r.x+20,a.y=r.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(r=>r.id===o.payload);if(a){let r={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(r),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let r=t.LongAnswer[t.LongAnswer.length-1];a.x=r.x+20,a.y=r.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload);if(a){let r={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(r),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let r=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=r.x+20,a.y=r.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(r=>r.id===o.payload);if(a){let r={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(r),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.push(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.push(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.push(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.push(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.push(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.push(s);}}else if(r==="trueFalse"){let n=t.trueFalses.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.trueFalses.splice(n,1);t.trueFalses.push(s);}}else if(r==="shortAnswer"){let n=t.shortAnswers.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shortAnswers.splice(n,1);t.shortAnswers.push(s);}}else if(r==="fillInTheBlanks"){let n=t.fillInTheBlanks.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.fillInTheBlanks.splice(n,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.unshift(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.unshift(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.unshift(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.unshift(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.unshift(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.unshift(s);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload,s=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(c=>c.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,link:n}=o.payload,c=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="mcq"?t.multipleChoices:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);c&&(c.link=n,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,altText:n}=o.payload,c=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);c&&(c.altText=n,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,audioData:n}=o.payload,c=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);c&&(c.audioData=n,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(r=>r.id===o.payload);if(a){let r={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(r),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a){let r={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(r),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let r=a.images.map((n,s)=>s).filter(n=>n!==a.currentIndex);if(r.length>0){let n=r[Math.floor(Math.random()*r.length)];a.navigationHistory.push(n),a.currentIndex=n;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);if(a){let r={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(r),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let r=o.past.pop();e.slides[t]=r;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let r=o.future.shift();e.slides[t]=r;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let r=JSON.parse(JSON.stringify(t));a.past.push(r),a.future=[],a.past.length>20&&a.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;}}}),{addSlide:ws,deleteSlide:Ls,duplicateSlide:Is,setCurrentSlide:Ss,updateSlideThumbnail:Cs,setBackgroundColor:ks,reorderSlides:pm,loadSlides:to,addLine:Ms,removeLine:Ur,addImage:Ts,updateImage:ao,deleteImage:Wr,duplicateImage:zr,addVideo:Gr,updateVideo:Kr,deleteVideo:_r,duplicateVideo:jr,toggleVideoPlaying:Ho,addShape:As,updateShape:oo,duplicateShape:$r,deleteShape:Xr,addText:Ps,updateText:wt,deleteText:Yr,duplicateText:Jr,addFlashcard:Rs,updateFlashcard:ro,deleteFlashcard:Zr,duplicateFlashcard:Qr,editFlashcard:Uo,nextFlashcard:Ds,previousFlashcard:Es,addPhotoFrame:Fs,updatePhotoFrame:Pa,deletePhotoFrame:en,duplicatePhotoFrame:tn,toggleImageDrawingMode:Bs,addImageAnnotation:Os,updateImageAnnotation:hm,clearImageAnnotations:gm,togglePhotoFrameDrawingMode:Ns,addPhotoFrameAnnotation:Vs,updatePhotoFrameAnnotation:xm,clearPhotoFrameAnnotations:bm,addMultipleChoice:qs,updateMultipleChoice:ia,editMultipleChoice:vm,deleteMultipleChoice:an,duplicateMultipleChoice:on,addTrueFalse:Hs,updateTrueFalse:la,deleteTrueFalse:rn,duplicateTrueFalse:nn,addShortAnswer:Us,updateShortAnswer:Wo,deleteShortAnswer:sn,duplicateShortAnswer:ln,addLongAnswer:Ws,updateLongAnswer:zo,deleteLongAnswer:dn,duplicateLongAnswer:un,addFillInTheBlanks:zs,updateFillInTheBlanks:Go,deleteFillInTheBlanks:cn,duplicateFillInTheBlanks:fn,setShowMcqForm:da,setShowFlashcardForm:Ra,setActivityType:Gs,setEditingActivity:Ko,bringToFront:Ks,sendToBack:_s,toggleLock:js,setLink:mn,setAltText:pn,setAudioData:hn,updateLastLine:ym,finalizeDrawing:$s,setLines:wm,updateLinePosition:Lm,updateLineTransform:gn,deleteLineById:xn,duplicateLine:Xs,updateElementOrder:_o,clearCanvas:Ys,undo:Js,redo:Zs,saveToHistory:le,toggleSketchMode:Im,setSketchMode:it,setEditingTextId:jo}=zl.actions;var $o=e=>e.canvas.currentSlideId,ge=e=>{let o=e.canvas.currentSlideId,t=e.canvas.slides.findIndex(a=>a.id===o);return t>=0?e.canvas.slides[t]:void 0},Xo=e=>e.canvas.slides,Qs=e=>e.canvas.slides.length<vs,Sm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},Gl=zl.reducer;var _l=e=>{let o=xe(),t=useRef(null),a=useRef(false),r=ee(l=>l.toolbar.selectedTool),n=ee(l=>l.toolbar.penColor),s=ee(l=>l.toolbar.strokeWidth),c=ee(l=>l.canvas.isSketchMode),i=ee(l=>l.canvas.slides.find(g=>g.id===l.canvas.currentSlideId)?.lines||[]),d=useCallback(l=>{t.current=l;},[]),f=useCallback(l=>{r==="pen"&&t.current&&(o(le()),t.current.startDrawing(l),a.current=true);},[r,o]),u=useCallback(l=>{!t.current||!a.current||t.current.draw(l);},[]),m=useCallback(()=>{if(!t.current||!a.current)return;let l=t.current.stopDrawing();a.current=false,l&&l.points.length>=4&&o(Ms(l)),o($s()),e?.();},[o,e]);return {lines:i,tool:r,color:n,strokeWidth:s,isSketchMode:c,setCanvasRef:d,startDrawing:f,draw:u,stopDrawing:m}};var Yl=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:n,style:s,xOffset:c=0,yOffset:i=0},d)=>{let f=useRef(null),u=useRef(false),m=useRef([]),l=useRef([]),h=useRef(null),g=useRef(t),p=useRef(a),w=useRef(r),x=useRef(n),v=useRef(c),L=useRef(i);useEffect(()=>{g.current=t,p.current=a,w.current=r,x.current=n,v.current=c,L.current=i;},[t,a,r,n,c,i]);let I=useCallback(()=>{let S=f.current;if(!S)return;let b=S.getContext("2d");b&&b.clearRect(0,0,S.width,S.height);},[]),k=useCallback(()=>{let S=f.current,b=l.current;if(!S||b.length<1)return;let A=S.getContext("2d");if(!A)return;if(A.clearRect(0,0,S.width,S.height),g.current==="eraser"?(A.globalCompositeOperation="destination-out",A.fillStyle="rgba(0,0,0,1)"):(A.globalCompositeOperation="source-over",A.fillStyle=p.current),b.length===1){A.beginPath(),A.arc(b[0].x,b[0].y,w.current/2,0,Math.PI*2),A.fill();return}let R=Xl(b,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:H=>H,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(R.length<2)){A.beginPath(),A.moveTo(R[0][0],R[0][1]);for(let H=1;H<R.length;H++)A.lineTo(R[H][0],R[H][1]);A.closePath(),A.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:S=>{u.current=true;let b={x:S.x-v.current,y:S.y-L.current};m.current=[{x:S.x,y:S.y}],l.current=[b],h.current=S,k();},draw:S=>{if(!u.current||!h.current)return;let b=S.x-h.current.x,A=S.y-h.current.y;if(Math.sqrt(b*b+A*A)<2)return;let R={x:S.x-v.current,y:S.y-L.current};m.current.push({x:S.x,y:S.y}),l.current.push(R),h.current=S,k();},stopDrawing:()=>{if(!u.current)return null;if(u.current=false,m.current.length<2)return m.current=[],l.current=[],h.current=null,I(),null;let b=Xl(m.current,{size:w.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:V=>V,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(V=>[V[0],V[1]]),A={tool:g.current,points:b,color:p.current,strokeWidth:w.current,isSketch:true};return m.current=[],l.current=[],h.current=null,I(),A},clear:()=>{I(),m.current=[],l.current=[],h.current=null,u.current=false;},isDrawing:()=>u.current,getCanvasElement:()=>f.current}),[I,k]),useEffect(()=>{let S=f.current;S&&(S.width=e,S.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});Yl.displayName="DirectDrawingCanvas";var Jl=Yl;var Ql=e=>{let o=xe(),a=ee(ge)?.images||[],r=useRef(new Map),n=useRef(new Map),s=useRef(new Set);useEffect(()=>{let f=new Set(a.map(u=>u.id));s.current.forEach(u=>{if(!f.has(u)){let m=n.current.get(u);m&&(m.src="",n.current.delete(u)),r.current.delete(u);}}),s.current=f;},[a]),useEffect(()=>()=>{n.current.forEach(f=>{f.src="";}),n.current.clear(),r.current.clear();},[]);let c=useCallback(f=>{if(n.current.has(f.id))return n.current.get(f.id);let u=new window.Image;return (f.src.startsWith("http://")||f.src.startsWith("https://"))&&(u.crossOrigin="anonymous"),u.src=f.src,n.current.set(f.id,u),u},[]),i=useCallback((f,u)=>{let m=f.target,l=m.id();a.find(g=>g.id===l)&&(o(ao({id:l,x:m.x(),y:m.y(),width:m.width(),height:m.height(),rotation:m.rotation()})),u?.());},[a,o]),d=useCallback((f,u)=>{let m=u.target,l=r.current.get(f);if(!l){console.error("\u274C Image node not found for id:",f);return}let h=m.scaleX(),g=m.scaleY(),p=m.rotation(),w=l.width(),x=l.height(),v=Math.max(5,w*h),L=Math.max(5,x*g);m.scaleX(1),m.scaleY(1),l.width(v),l.height(L),o(ao({id:f,width:v,height:L,x:m.x(),y:m.y(),rotation:p})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:c,imageRefs:r,handleDragEnd:i,handleImageTransformEnd:d}};var ed=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),n=useCallback((c,i)=>{let d=i.target,f=d.scaleX(),u=d.scaleY(),m=d.rotation(),l=Math.max(5,d.width()*f),h=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(l),d.height(h),o(ia({id:c,width:l,height:h,x:d.x(),y:d.y(),rotation:m})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:n,mcqRefs:a,handleDragEnd:(c,i)=>{o(ia({id:i,x:c.target.x(),y:c.target.y()})),e?.();}}};var td=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),n=useCallback((c,i)=>{let d=i.target,f=d.scaleX(),u=d.scaleY(),m=d.rotation(),l=Math.max(5,d.width()*f),h=Math.max(5,d.height()*u);d.scaleX(1),d.scaleY(1),d.width(l),d.height(h),o(la({id:c,width:l,height:h,x:d.x(),y:d.y(),rotation:m})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:n,handleTrueFalseDragEnd:(c,i)=>{o(la({id:i,x:c.target.x(),y:c.target.y()})),e?.();},trueFalseRefs:a}};var ad=e=>{let o=xe(),a=ee(ge)?.videos||[],r=useRef(new Map),n=useCallback(i=>{o(Ho(i));},[o]),s=useCallback((i,d)=>{let f=d.target;o(Kr({id:i,x:f.x(),y:f.y()})),e?.();},[o,e]),c=useCallback((i,d)=>{let f=d.target,u=f.scaleX(),m=f.scaleY(),l=f.rotation(),h=Math.max(5,f.width()*u),g=Math.max(5,f.height()*m);f.scaleX(1),f.scaleY(1),f.width(h),f.height(g),o(Kr({id:i,width:h,height:g,x:f.x(),y:f.y(),rotation:l})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:n,handleVideoDragEnd:s,handleVideoTransformEnd:c}};var nd=e=>{let o=xe(),a=ee(ge)?.shapes||[],r=useRef(new Map),n=useRef(new Map),[s,c]=useState(false),i=useCallback((f,u)=>{let m=u.target;o(oo({id:f,x:m.x(),y:m.y()})),e?.();},[o,e]),d=useCallback((f,u)=>{let m=u.target,l=a.find(v=>v.id===f);if(!l)return;let h=m.scaleX(),g=m.scaleY(),p=l.type?.toLowerCase();p==="arrow"||p==="line"||(m.scaleX(1),m.scaleY(1));let x={id:f,x:m.x(),y:m.y(),width:Math.max(5,m.width()*h),height:Math.max(5,m.height()*g),rotation:m.rotation()};switch(p){case "circle":x.radius=m.width()*h/2;break;case "star":x.innerRadius=m.width()*h/4,x.outerRadius=m.width()*h/2;break;case "triangle":x.radius=m.width()*h/2;break;case "ellipse":x.radiusX=m.width()*h/2,x.radiusY=m.height()*g/2;break;case "polygon":x.radius=m.width()*h/2;break;case "ring":let v=h;x.innerRadius=l.innerRadius&&l.innerRadius*v,x.outerRadius=l.outerRadius&&l.outerRadius*v;break;case "wedge":x.radius=l.radius&&l.radius*h;break;case "arc":x.innerRadius=l.innerRadius&&l.innerRadius*h,x.outerRadius=l.outerRadius&&l.outerRadius*h;break;case "arrow":case "line":{x.scaleX=h,x.scaleY=g,delete x.width,delete x.height;break}}o(oo(x)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:s,loadedShapesRef:n,handleShapeDragEnd:i,handleShapeResizeEnd:d}};var id=(e,o)=>{let t=yt(),r=ee(ge)?.texts||[],n=useRef(new Map),[s,c]=useState(null),[i,d]=useState("");return {texts:r,textRefs:n,handleDragEnd:(p,w)=>{let x=p.target;t(le()),t(wt({id:w,x:x.x(),y:x.y()})),e();},handleTransformEnd:p=>{let w=n.current.get(p);if(!w)return;let x=w.scaleX(),v=w.scaleY(),L=r.find(k=>k.id===p);if(!L)return;let I=(x+v)/2;w.scaleX(1),w.scaleY(1),t(le()),t(wt({id:p,x:w.x(),y:w.y(),width:Math.max(5,(L.width||100)*x),height:Math.max(5,(L.height||50)*v),fontSize:Math.round(Math.max(8,L.fontSize*I)),rotation:w.rotation()})),e();},handleDoubleClick:p=>{let w=r.find(x=>x.id===p);w&&!w.locked&&(c(p),d(w.text));},startEditing:p=>{let w=r.find(x=>x.id===p);w&&!w.locked&&(c(p),d(w.text));},editingTextId:s,editingValue:i,handleEditingChange:p=>{d(p);},finishEditing:()=>{if(s){let p=n.current.get(s),w=r.find(v=>v.id===s);t(le());let x={id:s,text:i};if(w&&(w.fontWeight!==void 0&&(x.fontWeight=w.fontWeight),w.fontStyle!==void 0&&(x.fontStyle=w.fontStyle),w.textDecoration!==void 0&&(x.textDecoration=w.textDecoration)),o?.current&&i.trim()){let v=o.current,L=v.offsetWidth,I=v.offsetHeight,k=1;if(p){let W=p.getStage();W&&(k=W.scaleX());}let S=14,b=(L-S)/k,A=(I-S)/k,V=i.split(`
3
- `).length,H=r.find(W=>W.id===s)?.fontSize||24,P=V*H*1.2+10;x.width=Math.max(200,b),x.height=Math.max(50,A,P);}else if(p&&i.trim()){let v=p.text(),L=p.width();p.text(i),p.width(void 0);let I=p.width(),k=p.height();p.text(v),p.width(L),x.width=Math.max(200,I+20),x.height=Math.max(50,k+20);}t(wt(x)),c(null),d(""),t(jo(null)),e();}}}};var ld=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),n=useCallback((s,c)=>{let i=s.target;o(Wo({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var dd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,s)=>{let c=n.target;o(zo({id:s,x:c.x(),y:c.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var cd=e=>{let o=xe(),a=ee(ge)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),s=useCallback((u,m)=>{if(n.current.has(m))return n.current.get(m);let l=new window.Image;return l.src=u,n.current.set(m,l),l},[]),c=useCallback((u,m)=>{let l=u.target,h=l.id();a.find(p=>p.id===h)&&(o(ro({id:h,x:l.x(),y:l.y()})),m?.());},[a,o]),i=useCallback((u,m)=>{let l=m.target,h=l.scaleX(),g=l.scaleY(),p=l.rotation(),w=Math.max(50,l.width()*h),x=Math.max(50,l.height()*g);l.scaleX(1),l.scaleY(1),l.width(w),l.height(x),o(ro({id:u,width:w,height:x,x:l.x(),y:l.y(),rotation:p})),l.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(u=>{o(Ds(u)),e?.();},[o,e]),f=useCallback(u=>{o(Es(u)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:r,handleDragEnd:c,handleFlashcardTransformEnd:i,handleNext:d,handlePrevious:f}};var pd=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],r=useRef(new Map),[n,s]=useState(new Map),c=useCallback((l,h)=>{console.log("handleDragEnd"),o(Pa({id:h,x:l.target.x(),y:l.target.y()})),e?.();},[o,e]),i=useCallback((l,h)=>{let g=h.target,p=g.scaleX(),w=g.scaleY(),x=g.rotation(),v=a.find(k=>k.id===l);if(!v)return;let L=Math.max(100,v.width*p),I=Math.max(100,v.height*w);g.scaleX(1),g.scaleY(1),o(Pa({id:l,width:L,height:I,x:g.x(),y:g.y(),rotation:x})),g.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async l=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(g=>{let p=new Map(g);return p.set(l,h),p}),o(Pa({id:l,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),f=useCallback(l=>{let h=n.get(l);h&&(h.getTracks().forEach(g=>g.stop()),s(g=>{let p=new Map(g);return p.delete(l),p}),o(Pa({id:l,isCapturing:false})),e?.());},[n,o,e]),u=useCallback((l,h)=>{let g=document.createElement("canvas");g.width=h.videoWidth,g.height=h.videoHeight;let p=g.getContext("2d");if(p){p.drawImage(h,0,0,g.width,g.height);let w=g.toDataURL("image/jpeg",.8);return o(Pa({id:l,capturedImageUrl:w,isCapturing:false})),f(l),e?.(),w}return null},[o,f,e]),m=useRef(n);return useEffect(()=>{m.current=n;},[n]),useEffect(()=>()=>{m.current.forEach(l=>{l.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:c,handlePhotoFrameTransformEnd:i,startCamera:d,stopCamera:f,capturePhoto:u,cameraStreams:n}};var hd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((n,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((n,s,c,i,d,f,u,m=[])=>{if(e.current){if(n&&!m.find(g=>g.id===n)?.isPlaying){let g=s.get(n)||c.get(n)||i.get(n)||d.get(n)||f.get(n)||(u?u.get(n):null);if(g){e.current.boundBoxFunc(t),e.current.nodes([g]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var Zm=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},vd=(e,o)=>{let t=yt(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let s=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});s&&s.startsWith("data:")&&t(Cs({id:a.current,thumbnail:s}));}catch(s){console.warn("Could not generate thumbnail (likely CORS issue with images):",s);}},[o,t]),n=Zm(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var ep=e=>e.flatMap(o=>[o[0],o[1]]),vn=(e,o)=>{let t=Xl(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return ep(t)};var yd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null),c=ee(v=>v.toolbar.selectedTool),i=ee(v=>v.toolbar.penColor),d=ee(v=>v.toolbar.strokeWidth),f=ee(v=>v.canvas.isSketchMode),u=ee(v=>v.canvas.slides.find(I=>I.id===v.canvas.currentSlideId)?.images.find(I=>I.id===e)),m=u?.annotations||[],l=u?.isDrawingMode||false,h=u?.width||1,g=u?.height||1,p=useCallback(v=>{if(c!=="pen"&&c!=="eraser")return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/h,I=v.y/g;s({tool:c,points:[L,I],color:i,strokeWidth:d/h,isSketch:f});},[c,i,d,f,h,g]),w=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let k;if(f)k=vn(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,A)=>A%2===0?b/h:b/g);else {let S=v.x/h,b=v.y/g;k=[...n.points,S,b];}s(S=>S?{...S,points:k}:null);},[f,d,n,h,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Os({imageId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:m,activeLine:n,isDrawingMode:l,startDrawing:p,draw:w,stopDrawing:x,tool:c}};var Sd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>{let{annotations:c,activeLine:i,stopDrawing:m,tool:l}=yd(e.id);useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let h=false;useEffect(()=>{return;},[m,h]);let g=x=>{{n(e.id);return}},p=x=>{return;},w=x=>{};return jsxs(Group,{listening:l!=="pen"&&l!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x){t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();let v=x.getStage()?.container();if(v){let L=I=>{let k=x.getStage()?.getPointerPosition();if(k){let S={x:e.x,y:e.y,width:e.width,height:e.height};k.x>=S.x&&k.x<=S.x+S.width&&k.y>=S.y&&k.y<=S.y+S.height&&s(I,e.id,"image");}};v.addEventListener("contextmenu",L),x._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",L);};}}else {let v=t.current.get(e.id);v?._contextMenuCleanup&&v._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:l!=="pen"&&l!=="eraser",onDragEnd:a,onTransformEnd:x=>r(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...l!=="pen"&&l!=="eraser"?{onClick:g,onTap:g,onMouseDown:g,onTouchStart:g,onMouseMove:p,onTouchMove:p,onMouseUp:w,onTouchEnd:w}:{}}),c?.map((x,v)=>{let L=x.points.map((k,S)=>S%2===0?k*e.width+e.x:k*e.height+e.y),I=x.strokeWidth*e.width;return jsx(Line,{points:L,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:I,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},v)}),i&&jsx(Line,{points:i.points.map((x,v)=>v%2===0?x*e.width+e.x:x*e.height+e.y),stroke:i.tool==="eraser"?"white":i.color,strokeWidth:i.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:i.tool==="eraser"?"destination-out":"source-over",fill:i.isSketch?i.color:void 0,closed:i.isSketch,listening:false},"active")]})});Sd.displayName="ImageWithDrawing";var si=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(c=>{let i=o(c);return i?jsx(Sd,{img:c,loadedImage:i,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s},c.id):null})}));si.displayName="ImageLayer";var up=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:s,rotation:c=0,onTransformEnd:i,onDragEnd:d})=>{let f=xe(),u=useRef(null),m=l=>{f(Ho(l));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:c,onDragEnd:d,onTransformEnd:i,children:[jsx(Rect,{width:r,height:n,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${n}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:u,src:e,controls:true,autoPlay:true,onClick:()=>m(t),onSeeking:l=>l.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Cd=up;var bp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:s})=>{let[c,i]=useState(null),d=useSelector(g=>g.toolbar.selectedTool),f=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let g=new window.Image;g.src=e.thumbnailDataUrl,g.onload=()=>{i(g);};}},[e.thumbnailDataUrl]),!c)return null;let u=e.width/2,m=e.height/2,l=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(l,80));return jsxs(Group,{draggable:!f,listening:!f,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...f?{}:{onDragEnd:a,onTransformEnd:r},ref:g=>{if(s(g),g){let p=g.getStage()?.container();if(p){let w=x=>{let v=g.getStage()?.getPointerPosition();if(v){let L={x:e.x,y:e.y,width:e.width,height:e.height};v.x>=L.x&&v.x<=L.x+L.width&&v.y>=L.y&&v.y<=L.y+L.height&&n(x);}};p.addEventListener("contextmenu",w),g._contextMenuCleanup=()=>{p.removeEventListener("contextmenu",w);};}}},children:[jsx(Image$1,{image:c,width:e.width,height:e.height,listening:!f,...f?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:u,y:m,radius:h,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:u,y:m,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:u+h*.1,y:m,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},Md=bp;var di=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(c=>jsxs(be__default.Fragment,{children:[jsx(Md,{video:c,isSelected:!c.isPlaying&&o===c.id,onClick:()=>a(c.id),onDragEnd:i=>r(c.id,i),onTransformEnd:i=>n(c.id,i),onContextMenu:i=>s(i,c.id,"video"),nodeRef:i=>{i?t.current.set(c.id,i):t.current.delete(c.id);}}),c.isPlaying&&(()=>{let i=c.x,d=c.y;if(c.isRecorded){let f=typeof window<"u"?window.innerWidth:c.width,u=typeof window<"u"?window.innerHeight:c.height;i=(f-c.width)/2,d=(u-c.height)/2;}return jsx(Cd,{id:c.id,src:c.objectUrl,x:i,y:d,width:c.width,height:c.height,isSelected:false,rotation:c.rotation,onTransformEnd:f=>n(c.id,f),onDragEnd:f=>r(c.id,f)})})()]},c.id))}));di.displayName="VideoLayer";var ui=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:s})=>{let c=useSelector(d=>d.toolbar.selectedTool),i=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map((d,f)=>{let u=d.id||f,m={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!i,listening:!i,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},u);case "star":return jsx(Star,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "triangle":return jsx(RegularPolygon,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},u);case "polygon":return jsx(RegularPolygon,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},u);case "ellipse":return jsx(Ellipse,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},u);case "ring":return jsx(Ring,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},u);case "wedge":return jsx(Wedge,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},u);case "arrow":return jsx(Arrow,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "line":return jsx(Line,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},u);case "arc":return jsx(Arc,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},u);case "rectangle":default:return jsx(Rect,{ref:l=>{l?o.current.set(d.id,l):o.current.delete(d.id);},...m,draggable:!d.locked&&!i,...i?{}:{onDragStart:l=>{n?.();},onDragEnd:l=>t(d.id,l),onTransformEnd:l=>a(d.id,l),onClick:()=>r(d.id),onContextMenu:l=>{l.evt.preventDefault(),s(l.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},u)}})})});ui.displayName="ShapeLayer";var Pd=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:s,editingTextId:c})=>{let i=useSelector(f=>f.toolbar.selectedTool),d=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map(f=>{let u=f.id===c,m=f.fontWeight==="bold",l=m?Math.max(1,f.fontSize/25):0;return jsx(Text,{id:f.id,ref:h=>{h?o.current.set(f.id,h):o.current.delete(f.id);},text:f.text,x:f.x,y:f.y,width:f.width,height:f.height,rotation:f.rotation,draggable:!f.locked&&!u&&!d,listening:!d,fontSize:f.fontSize,fontFamily:f.fontFamily,fontStyle:f.fontStyle,fontWeight:f.fontWeight,textDecoration:f.textDecoration,fill:f.fill,stroke:m?f.fill:void 0,strokeWidth:l,align:f.align,wrap:"none",lineHeight:1.2,opacity:u?0:1,visible:!u,...d?{}:{onClick:()=>r(f.id),onTap:()=>r(f.id),onDblClick:()=>s(f.id),onDblTap:()=>s(f.id),onDragEnd:h=>t(h,f.id),onTransformEnd:()=>a(f.id),onContextMenu:h=>{h.evt.preventDefault();let g=h.evt;n(g,f.id,"text");}}},f.id)})})};var zp=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:s,onPrevious:c,nodeRef:i})=>{let[d,f]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let p=new window.Image;p.src=e.images[e.currentIndex],p.onload=()=>{f(p);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let u=8,m=2,l=Math.min(e.width,e.height)*.08,h=Math.max(16,Math.min(l,32)),g=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,ref:p=>{if(i(p),p){let w=p.getStage()?.container();if(w){let x=v=>{let L=p.getStage()?.getPointerPosition();if(L){let I={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=I.x&&L.x<=I.x+I.width&&L.y>=I.y&&L.y<=I.y+I.height&&n(v);}};w.addEventListener("contextmenu",x),p._contextMenuCleanup=()=>{w.removeEventListener("contextmenu",x);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:u,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:u,stroke:"#E5E7EB",strokeWidth:m,listening:false}),jsx(Image$1,{x:m+4,y:m+4,image:d,width:e.width-(m+4)*2,height:e.height-(m+4)*2,cornerRadius:u-m,onClick:t,onTap:t}),jsx(Rect,{x:m,y:e.height-50,width:e.width-m*2,height:50,cornerRadius:[0,0,u-m,u-m],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:g+h,y:e.height/2,onClick:p=>{p.cancelBubble=true,c();},onTap:p=>{p.cancelBubble=true,c();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-g-h,y:e.height/2,onClick:p=>{p.cancelBubble=true,s();},onTap:p=>{p.cancelBubble=true,s();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Ed=zp;var mi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:s,onPrevious:c,onContextMenu:i})=>jsx(Fragment,{children:e.map(d=>jsx(Ed,{flashcard:d,isSelected:t===d.id,onClick:()=>n(d.id),onDragEnd:a,onTransformEnd:f=>r(d.id,f),onContextMenu:f=>i(f,d.id,"flashcard"),onNext:()=>s(d.id),onPrevious:()=>c(d.id),nodeRef:f=>{f?o.current.set(d.id,f):o.current.delete(d.id);}},d.id))}));mi.displayName="FlashcardLayer";var Bd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null);ee(v=>v.toolbar.selectedTool);let i=ee(v=>v.toolbar.penColor),d=ee(v=>v.toolbar.strokeWidth),f=ee(v=>v.canvas.isSketchMode),u=ee(v=>v.canvas.slides.find(I=>I.id===v.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),m=u?.annotations||[],l=u?.isDrawingMode||false,h=u?.width||1,g=u?.height||1,p=useCallback(v=>{if(!l)return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/h,I=v.y/g;s({tool:"pen",points:[L,I],color:i,strokeWidth:d/h,isSketch:f});},[l,i,d,f,h,g]),w=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let k;if(f)k=vn(r.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,A)=>A%2===0?b/h:b/g);else {let S=v.x/h,b=v.y/g;k=[...n.points,S,b];}s(S=>S?{...S,points:k}:null);},[f,d,n,h,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Vs({frameId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:m,activeLine:n,isDrawingMode:l,startDrawing:p,draw:w,stopDrawing:x}};var Zp=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:s,onCapture:c,cameraStream:i,nodeRef:d})=>{let[f,u]=useState(null),[m,l]=useState(null),h=useRef(null),g=useRef(null),p=useRef(null),w=useRef(null),x=useRef(0),v=33,L=useSelector(O=>O.toolbar.selectedTool),I=L==="pen"||L==="eraser",{annotations:k,activeLine:S,isDrawingMode:b,startDrawing:A,draw:V,stopDrawing:R}=Bd(e.id);useEffect(()=>{if(!b)return;let O=()=>{R();},X=()=>{R();};return window.addEventListener("mouseup",O),window.addEventListener("touchend",X),()=>{window.removeEventListener("mouseup",O),window.removeEventListener("touchend",X);}},[R,b]),useEffect(()=>{if(e.capturedImageUrl){let O=new window.Image;O.src=e.capturedImageUrl,O.onload=()=>{u(O);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){h.current||(h.current=document.createElement("video"),h.current.autoplay=true,h.current.playsInline=true),g.current||(g.current=document.createElement("canvas"));let O=h.current,X=g.current;O.srcObject=i;let U=()=>{X.width=O.videoWidth||640,X.height=O.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",X.width,X.height);let K=Q=>{if(Q-x.current<v){p.current=requestAnimationFrame(K);return}x.current=Q;let te=X.getContext("2d");if(te&&O.readyState===O.HAVE_ENOUGH_DATA){te.drawImage(O,0,0,X.width,X.height);let J=X.toDataURL("image/jpeg",.6),de=new window.Image;de.onload=()=>{l(de);},de.src=J;}p.current=requestAnimationFrame(K);};p.current=requestAnimationFrame(K);};return O.onloadedmetadata=U,O.readyState>=O.HAVE_METADATA&&U(),O.play().catch(K=>console.error("Error playing video:",K)),()=>{p.current&&(cancelAnimationFrame(p.current),p.current=null);}}return ()=>{l(null),w.current&&(w.current.src="");}},[e.isCapturing,i]);let H=()=>{h.current&&e.isCapturing&&c(h.current);},q=O=>{if(e.capturedImageUrl){if(!b){t();return}let X=O.currentTarget,U=X.getAbsoluteTransform().copy(),Q=X.getStage()?.getPointerPosition();if(Q){U.invert();let te=U.point(Q);A(te);}O.cancelBubble=true;}else t();},P=O=>{if(!b||!e.capturedImageUrl)return;let X=O.currentTarget,U=X.getAbsoluteTransform().copy(),Q=X.getStage()?.getPointerPosition();if(Q){U.invert();let te=U.point(Q);V(te);}},W=()=>{!b||!e.capturedImageUrl||R();},E=e.isCapturing?m:f,oe=Math.min(e.width,e.height)*.12,N=Math.max(25,Math.min(oe,50)),fe=e.width/2,z=e.height/2;return jsxs(Group,{id:e.id,draggable:!b&&!I,listening:true,x:e.x,y:e.y,...I?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:O=>{if(d(O),O){let X=O.getStage()?.container();if(X){let U=K=>{let Q=O.getStage()?.getPointerPosition();if(Q){let te={x:e.x,y:e.y,width:e.width,height:e.height};Q.x>=te.x&&Q.x<=te.x+te.width&&Q.y>=te.y&&Q.y<=te.y+te.height&&n(K);}};X.addEventListener("contextmenu",U),O._contextMenuCleanup=()=>{X.removeEventListener("contextmenu",U);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:E?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),E&&jsx(Image$1,{image:E,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:q,onTap:q,onMouseDown:q,onTouchStart:q,onMouseMove:P,onTouchMove:P,onMouseUp:W,onTouchEnd:W,...I?{}:{onDragEnd:a,onTransformEnd:r}}),k?.map((O,X)=>{let U=O.points.map((Q,te)=>te%2===0?Q*e.width:Q*e.height),K=O.strokeWidth*e.width;return jsx(Line,{points:U,stroke:O.tool==="eraser"?"white":O.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:O.tool==="eraser"?"destination-out":"source-over",fill:O.isSketch?O.color:void 0,closed:O.isSketch,listening:false},X)}),S&&jsx(Line,{points:S.points.map((O,X)=>X%2===0?O*e.width:O*e.height),stroke:S.tool==="eraser"?"white":S.color,strokeWidth:S.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:S.tool==="eraser"?"destination-out":"source-over",fill:S.isSketch?S.color:void 0,closed:S.isSketch,listening:false},"active"),!E&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:z-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:fe-N+6,y:z-60,width:N*1.6,height:N*1.6,radius:N,fill:"white",cornerRadius:8,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?H():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:fe-12,y:z-40,width:N*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?H():s();}})})]}),jsx(Text,{x:0,y:z,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:z+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:fe-24,y:z+104,width:N*1.6,height:N*1.6,radius:N,fill:"#096B76",cornerRadius:N,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?H():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:fe-8,y:z+120,width:N*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?H():s();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"})]})]})},qd=Zp;var bi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:s,onCapture:c,cameraStreams:i,onContextMenu:d})=>jsx(Fragment,{children:e.map(f=>jsx(qd,{photoFrame:f,isSelected:t===f.id,onClick:()=>n(f.id),onDragEnd:u=>a(u,f.id),onTransformEnd:u=>r(f.id,u),onContextMenu:u=>d(u,f.id,"photoFrame"),onStartCamera:()=>s(f.id),onCapture:u=>c(f.id,u),cameraStream:i.get(f.id),nodeRef:u=>{u?o.current.set(f.id,u):o.current.delete(f.id);}},f.id))}));bi.displayName="PhotoFrameLayer";var zd=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:s,menuRef:c})=>{useEffect(()=>{let u=l=>{c?.current&&!c.current.contains(l.target)&&a();},m=l=>{l.key==="Escape"&&a();};return document.addEventListener("mousedown",u),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",m);}},[a]);let i=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:s?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(m=>!(m.showForTypes&&!m.showForTypes.includes(r)||m.hideForTypes&&m.hideForTypes.includes(r))),[r,s]),d=(u,m)=>{u==="order"||u==="lock"?t(u,m):(t(u),a());},f=jsx("div",{ref:c,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:i.map((u,m)=>jsxs("button",{onClick:l=>d(u.action,l),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${u.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[u.icon,jsx("span",{className:`font-medium ${u.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:u.label})]}),u.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},m))})});return createPortal(f,document.body)};var Gd=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let n=s=>{r.current&&!r.current.contains(s.target)&&a();};return document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n);}},[a]),jsx("div",{ref:r,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((n,s)=>jsx("button",{onClick:()=>{n.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:n.label})},s))})})};var Kd=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[s,c]=useState(a),i=useRef(null);useEffect(()=>{i.current?.focus();},[]);let d=()=>{r(s),n();};return jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:n,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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:i,type:"text",value:s,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"?d():u.key==="Escape"&&n();},placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:n,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:d,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})})};var _d=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null);useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let s=f=>{f.preventDefault(),o(a);},c=(f,u,m)=>{m/=100;let l=u*Math.min(m,1-m)/100,h=g=>{let p=(g+f/30)%12,w=m-l*Math.max(Math.min(p-3,9-p,1),-1);return Math.round(255*w).toString(16).padStart(2,"0")};return `#${h(0)}${h(8)}${h(4)}`},d=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:n,className:"pointer-events-auto max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Shape Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:s,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:f=>r(f.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:f=>r(f.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:f=>{let u=parseInt(f.target.value),m=c(u,100,50);r(m);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"].map(f=>jsx("button",{type:"button",onClick:()=>r(f),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===f.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:f},title:f},f))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(d,document.body)};var Bh=({imageSrc:e,onCrop:o})=>{let[t]=Xd(e),a=useRef(null),r=useRef(null),n=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),c=useMemo(()=>{let m=s.width*.5,l=s.height*.5,h=(s.width-m)/2,g=(s.height-l)/2;return {x:h,y:g,width:m,height:l}},[s]),[i,d]=useState(c);useEffect(()=>{d(c);},[c]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let f=()=>{let m=r.current;if(!m)return;let l=m.scaleX(),h=m.scaleY();m.scaleX(1),m.scaleY(1),d({x:m.x(),y:m.y(),width:Math.max(20,m.width()*l),height:Math.max(20,m.height()*h)});},u=()=>{let m=r.current;m&&d({x:m.x(),y:m.y(),width:m.width(),height:m.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:u,onTransformEnd:f,dragBoundFunc:m=>{let l=Math.max(0,Math.min(m.x,s.width-i.width)),h=Math.max(0,Math.min(m.y,s.height-i.height));return {x:l,y:h}}}),jsx(Transformer,{ref:n,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(m,l)=>l.width<20||l.height<20||l.x<0||l.y<0||l.x+l.width>s.width||l.y+l.height>s.height?m:l})]})})},Yd=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[s]=Xd(e);return useEffect(()=>{let f=u=>{u.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"pointer-events-auto max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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(Bh,{imageSrc:e,onCrop:(f,u,m,l)=>{n({x:f,y:u,width:m,height:l});}})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:()=>{if(!s)return;let m=Math.min(600/s.width,400/s.height),l=r.x/m,h=r.y/m,g=r.width/m,p=r.height/m,w=document.createElement("canvas");w.width=g,w.height=p;let x=w.getContext("2d");if(!x)return;x.drawImage(s,l,h,g,p,0,0,g,p);let v=w.toDataURL("image/png");o(v);},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),document.body)};var or=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,n]=useState(false),[s,c]=useState(null),[i,d]=useState(0),[f,u]=useState(true),m=useRef(null),l=useRef([]),h=useRef(null),g=useRef(null),p=useRef(null),w=useRef(null),x=useRef(null),v=useRef(null);useEffect(()=>()=>{p.current&&cancelAnimationFrame(p.current),h.current&&clearInterval(h.current),g.current&&g.current.getTracks().forEach(b=>b.stop());},[]);let L=async()=>{try{let b,A=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let P=o.current.getLayers();console.log("Konva layers:",P.length),P.forEach((X,U)=>{let K=X.getChildren();console.log(`Layer ${U} children count:`,K.length);});let W=document.createElement("canvas");W.width=o.current.width(),W.height=o.current.height();let E=W.getContext("2d",{willReadFrequently:!1});if(!E){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",W.width,"x",W.height),x.current=W;let oe=()=>{if(E.clearRect(0,0,W.width,W.height),P.forEach(X=>{let U=X.getCanvas()._canvas;U&&E.drawImage(U,0,0);}),a?.current){let X=a.current;E.drawImage(X,0,0);}};v.current=oe,o.current.draw(),oe(),await new Promise(X=>setTimeout(X,100)),console.log("Creating captureStream..."),b=W.captureStream(30),console.log("Canvas stream created, tracks:",b.getTracks().length);let fe=b.getVideoTracks()[0];fe&&console.log("Video track:",fe.label,"state:",fe.readyState);let z=0,O=()=>{oe(),o?.current&&(o.current.getLayers().forEach(U=>{U.batchDraw();}),z++,z%60===0&&console.log("Drawing frame:",z)),p.current=requestAnimationFrame(O);};O();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{A=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(P){console.warn("Microphone access denied:",P);}let V=[...b.getVideoTracks()];A&&V.push(...A.getAudioTracks());let R=new MediaStream(V);g.current=R;let H="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?H="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?H="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?H="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(H="video/webm;codecs=vp8"),console.log("Using mimeType:",H);let q=new MediaRecorder(R,{mimeType:H,videoBitsPerSecond:25e5});m.current=q,l.current=[],q.ondataavailable=P=>{console.log("Data available, size:",P.data.size),P.data.size>0&&l.current.push(P.data);},q.onstop=()=>{console.log("Recording stopped, chunks:",l.current.length);let P=new Blob(l.current,{type:H});console.log("Final blob size:",P.size),o?.current&&v.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(E=>{E.batchDraw();}),v.current(),w.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",w.current.length)),R.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current),p.current&&(cancelAnimationFrame(p.current),p.current=null),c(P);},q.onerror=P=>{console.error("MediaRecorder error:",P);},console.log("Starting recording..."),q.start(1e3),n(!0),d(0),h.current=setInterval(()=>{d(P=>P+1);},1e3);}catch(b){console.error("Error starting screen recording:",b),alert("Failed to start recording. Please ensure you granted permission.");}},I=()=>{m.current&&r&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),n(false));},k=()=>{if(s){let b=URL.createObjectURL(s),A=document.createElement("a");A.href=b,A.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(b);}},S=b=>{let A=Math.floor(b/60),V=b%60;return `${A.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(i)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:I,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!s&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>u(!f),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${f?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:f?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:L,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),s&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(s),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",S(i)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&s&&w.current&&(t(s,w.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:k,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:()=>{c(null),d(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})})};var Zd=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[n,s]=useState(false),[c,i]=useState(null),[d,f]=useState(false),[u,m]=useState(0),l=useRef(null),h=useRef([]),g=useRef(null),p=useRef(null);useEffect(()=>{o&&!c&&fetch(o).then(b=>b.blob()).then(b=>i(b)).catch(b=>console.error("Error loading audio:",b));},[o,c]);let w=async()=>{try{let b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),A=new MediaRecorder(b);l.current=A,h.current=[],A.ondataavailable=V=>{V.data.size>0&&h.current.push(V.data);},A.onstop=()=>{let V=new Blob(h.current,{type:"audio/webm"});i(V),b.getTracks().forEach(R=>R.stop()),g.current&&clearInterval(g.current);},A.start(),s(!0),m(0),g.current=setInterval(()=>{m(V=>V+1);},1e3);}catch(b){console.error("Error starting audio recording:",b),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{l.current&&n&&(l.current.stop(),s(false));},v=()=>{if(c){let b=URL.createObjectURL(c),A=new Audio(b);p.current=A,A.onended=()=>{f(false),URL.revokeObjectURL(b);},A.play(),f(true);}},L=()=>{p.current&&(p.current.pause(),p.current.currentTime=0,f(false));},I=async()=>{if(c){let b=new FileReader;b.onloadend=()=>{let A=b.result;t(A),r();},b.readAsDataURL(c);}},k=()=>{i(null),a();},S=b=>{let A=Math.floor(b/60),V=b%60;return `${A.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return n?jsxs("div",{className:"fixed top-4 left-1/2 z-103 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:x,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-103 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!c&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:w,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),c&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:d?L:v,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),d?"Playing...":"Play Audio"]}),jsx("button",{onClick:k,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:I,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})})};var It=({audioData:e,x:o,y:t,width:a})=>{let[r,n]=useState(false),s=useRef(null);return jsx("button",{onClick:i=>{if(i.stopPropagation(),r&&s.current)s.current.pause(),s.current.currentTime=0,n(false);else {let d=new Audio(e);s.current=d,d.onended=()=>{n(false);},d.onerror=()=>{console.error("Error playing audio"),n(false);},d.play(),n(true);}},className:`absolute flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${r?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${o+a-35}px`,top:`${t+5}px`,width:"30px",height:"30px",zIndex:99},title:r?"Stop Audio":"Play Audio",children:r?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var tu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=ee(ge),n=useMemo(()=>{if(!r)return [];let g=[];return r.images?.forEach(p=>{g.push({id:p.id,type:"image",name:"Image",timestamp:p.timestamp||0});}),r.videos?.forEach(p=>{g.push({id:p.id,type:"video",name:"Video",timestamp:p.timestamp||0});}),r.shapes?.forEach(p=>{g.push({id:p.id,type:"shape",name:`${p.type} Shape`,timestamp:p.timestamp||0});}),r.texts?.forEach(p=>{g.push({id:p.id,type:"text",name:p.text.substring(0,20)+(p.text.length>20?"...":""),timestamp:p.timestamp||0});}),r.flashcards?.forEach(p=>{g.push({id:p.id,type:"flashcard",name:`Flashcard (${p.images.length} images)`,timestamp:p.timestamp||0});}),r.photoFrames?.forEach(p=>{g.push({id:p.id,type:"photoFrame",name:"Photo Frame",timestamp:p.timestamp||0});}),r.multipleChoices?.forEach(p=>{g.push({id:p.id,type:"mcq",name:"Multiple Choice",timestamp:p.timestamp||0});}),r.trueFalses?.forEach(p=>{g.push({id:p.id,type:"trueFalse",name:"True/False",timestamp:p.timestamp||0});}),r.shortAnswers?.forEach(p=>{g.push({id:p.id,type:"shortAnswer",name:"Short Answer",timestamp:p.timestamp||0});}),r.LongAnswer?.forEach(p=>{g.push({id:p.id,type:"longAnswer",name:"Long Answer",timestamp:p.timestamp||0});}),r.fillInTheBlanks?.forEach(p=>{g.push({id:p.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:p.timestamp||0});}),r.lines?.forEach(p=>{p.id&&g.push({id:p.id,type:"line",name:"Drawn Line",timestamp:p.timestamp||0});}),g.sort((p,w)=>w.timestamp-p.timestamp)},[r]),[s,c]=useState(n),[i,d]=useState(false);useEffect(()=>{i||c(n);},[n]);let f=g=>{let p="h-5 w-5";switch(g){case "image":return jsx(Image$3,{className:p});case "video":return jsx(VideoCamera,{className:p});case "shape":return jsx(Shapes$1,{className:p});case "text":return jsx(TextT,{className:p});case "flashcard":return jsx(Cards$1,{className:p});case "photoFrame":return jsx(FrameCorners,{className:p});case "line":return jsx("span",{className:p,children:"\u270F\uFE0F"});default:return jsx(Question,{className:p})}},u=g=>{if(g===0)return;let p=s[g],w=s[g-1];a(_o({id:p.id,type:p.type,newTimestamp:w.timestamp+1}));},m=g=>{if(g===s.length-1)return;let p=s[g],w=s[g+1];a(_o({id:p.id,type:p.type,newTimestamp:w.timestamp-1}));},l=g=>{d(true),c(g);},h=()=>{d(false);let g=Date.now();s.forEach((p,w)=>{let x=g-w;a(_o({id:p.id,type:p.type,newTimestamp:x}));});};return jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-gray-200 bg-white shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 p-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Stack$1,{className:"h-5 w-5 text-gray-700",weight:"bold"}),jsx("h3",{className:"font-semibold text-gray-900",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto p-2",children:s.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:s,onReorder:l,className:"space-y-1",children:s.map((g,p)=>{let w=g.id===e;return jsxs(Reorder.Item,{value:g,onDragEnd:h,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${w?"border border-blue-200 bg-blue-50":"border border-transparent hover:bg-gray-50"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-4 w-4",weight:"bold"})}),jsxs("div",{onClick:()=>t(g.id,g.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${w?"text-blue-600":"text-gray-600"}`,children:f(g.type)}),jsx("span",{className:`text-sm ${w?"font-medium text-blue-900":"text-gray-700"}`,children:g.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:x=>{x.stopPropagation(),u(p);},disabled:p===0,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move up (forward)",children:jsx(ArrowUp,{className:"h-4 w-4"})}),jsx("button",{onClick:x=>{x.stopPropagation(),m(p);},disabled:p===s.length-1,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move down (backward)",children:jsx(ArrowDown,{className:"h-4 w-4"})})]})]},g.id)})})}),jsx("div",{className:"border-t border-gray-200 p-3 text-xs text-gray-500",children:jsx("p",{children:"Drag to reorder \u2022 Top layers appear above bottom layers"})})]})]})};var au=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>{let s=useSelector(z=>z.toolbar.selectedTool),c=s==="pen"||s==="eraser",[i,d]=useState(new Set),[f,u]=useState(false),[m,l]=useState(null),h=useRef(null);useEffect(()=>{let z=h.current;if(z)return a.current.set(e.id,z),()=>{a.current.delete(e.id);}},[e.id]);let g=new Set(e.data.responseOptions.correctIndex),p=g.size>1,w=z=>{f||d(p?O=>{let X=new Set(O);return X.has(z)?X.delete(z):X.add(z),X}:new Set([z]));},x=()=>{i.size>0&&u(true);},v=()=>{u(false),d(new Set);},L=i.size===g.size&&Array.from(i).every(z=>g.has(z)),I=Array.from(i).filter(z=>g.has(z)),k=p&&I.length>0&&!L,S=()=>L?"\u2713 Correct! Great job! \u{1F389}":k?`\u26A0 Partially correct (${I.length}/${g.size})`:"\u2717 Try again!",b=()=>L?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},A=55,V=8,R=24,H=60,q=60,P=p&&!f?25:0,W=e.data.feedbackMode==="practice"?48:0,E=12,oe=H+P+(f?q:0),N=e.data.responseOptions.options.length*(A+V),fe=oe+N+E+W+R;return jsxs(Group,{ref:h,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:r,onClick:z=>t(e.id),onTap:z=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:fe,width:e.width,onTransformEnd:z=>o(e.id,z),onContextMenu:z=>{z.cancelBubble=true,n(z.evt,e.id,"mcq");}}),jsx(Text,{x:R+8,y:R,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-R*2,listening:false}),p&&!f&&e.data.feedbackMode==="practice"?jsx(Text,{x:R,y:R+35,text:`Select ${g.size} answers (${i.size}/${g.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-R*2,listening:false}):null,f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:R+24,y:H+P,width:e.width-R*2-40,height:q-20,fill:b().bg,cornerRadius:8}),jsx(Text,{x:R,y:H+P,width:e.width-R*2,height:q-20,text:S(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((z,O)=>{let X=g.has(O),U=i.has(O),K=oe+O*(A+V),Q="#e5e7eb",te="#ffffff",J="#111827";return f&&X?(Q="#22c55e",te="#dcfce7",J="#1B9D2C"):f&&U&&!X?(Q="#ef4444",te="#fee2e2",J="#ef4444"):U&&(Q="#096B76",te="#ECFFF8",J="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:R+12,y:K+(A-20)/2,width:20,height:20,fill:U?"#096B76":"white",stroke:U?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:p?4:10,onClick:de=>{de.cancelBubble=true,w(O);},onTap:de=>{de.cancelBubble=true,w(O);}}),U&&jsx(Text,{x:R+12,y:K+(A-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:R+44,y:K,width:e.width-R*2-60,height:A,fill:te,stroke:Q,strokeWidth:2,cornerRadius:8,onClick:de=>{de.cancelBubble=true,w(O);},onTap:de=>{de.cancelBubble=true,w(O);}}),jsx(Text,{x:R+60,y:K,width:e.width-R*2-80,height:A,text:z,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},O)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:oe+e.data.responseOptions.options.length*(A+V)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,l("check");},onMouseUp:z=>{z.cancelBubble=true,l(null),x();},onMouseLeave:z=>{z.cancelBubble=true,l(null);},onTouchStart:z=>{z.cancelBubble=true,l("check");},onTouchEnd:z=>{z.cancelBubble=true,l(null),x();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:R+14,width:(e.width-R*2-24)/(f?2:1),height:48,fill:i.size===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:R+14,width:(e.width-R*2-24)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-R*2)/2+8,onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),v();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),v();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:R,width:(e.width-R*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:R,width:(e.width-R*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});au.displayName="MultipleChoice";var ou=au;var Li=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r})=>{let n=useDispatch(),s=useSelector(U=>U.toolbar.selectedTool),c=s==="pen"||s==="eraser",[i,d]=useState(false),[f,u]=useState(new Set),[m,l]=useState(false),[h,g]=useState(false),[p,w]=useState(0),x=340,v=100,L=window.innerWidth*.4,I=window.innerHeight*.5,k=x+20,S=v+60,b=L-40,A=I-300,V=useRef(null);useEffect(()=>{let U=V.current;if(U)return r.current.set(e.id,U),()=>{r.current.delete(e.id);}},[e.id]);let R=U=>{n(ia({id:e.id,x:U.target.x(),y:U.target.y()}));},H=U=>{let K=U.target,Q=K.x(),te=K.y(),J=window.innerWidth*.2,Y=Q+J>k&&Q<k+b&&te+50>S&&te<S+A;d(Y);},q=(U,K)=>{let Q=K.target,te=Q.x(),J=Q.y(),de=window.innerWidth*.2,Me=te+de>k&&te<k+b&&J+50>S&&J<S+A;u(Me?De=>new Set(De).add(U):De=>{let Se=new Set(De);return Se.delete(U),Se}),d(false);},P=()=>{l(true);},W=()=>{l(false),u(new Set),w(U=>U+1);},E=new Set(e.data.responseOptions.correctIndex),oe=f.size===E.size&&Array.from(f).every(U=>E.has(U)),N=Array.from(f).filter(U=>E.has(U)),fe=N.length>0&&!oe,z=()=>oe?"\u2713 Correct! Great job!":fe?`\u26A0 Partially correct (${N.length}/${E.size})`:"\u2717 Try again!",O=()=>oe?{bg:"#dcfce7",text:"#166534"}:fe?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},X=()=>m?oe?"#4CAF50":fe?"#f59e0b":"#ef4444":i?"#4CAF50":"#075560";return jsxs(Group,{ref:V,name:"mcq-element",width:L,height:I,draggable:!c,listening:!c,...c?{}:{onClick:U=>a(e.id),onTap:U=>a(e.id),onContextMenu:U=>{U.evt.preventDefault(),o(U.evt,e.id,"mcq");}},children:[jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:R,children:[jsx(Rect,{fill:"white",stroke:i?"#4CAF50":"#e5e7eb",strokeWidth:i?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?I-100:I-50,width:L,shadowColor:i?"#4CAF50":"transparent",shadowBlur:i?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:b,height:A,fill:"#EBF6F7",stroke:X(),strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:A+18,width:b-5,height:60,fill:O().bg,cornerRadius:8}),jsx(Text,{x:20,y:A+20,width:b,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:O().text,align:"center",verticalAlign:"middle"})]}),f.size===0&&!m&&jsx(Text,{x:20,y:60,width:b,height:A-60,text:E.size>1?`Drop ${E.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:m?I-200:I-160,children:[jsxs(Group,{onMouseDown:()=>{g(true),P();},onMouseUp:()=>g(false),onMouseLeave:()=>g(false),onTouchStart:()=>{g(true),P();},onTouchEnd:()=>g(false),scaleX:h?.95:1,scaleY:h?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((U,K)=>{let Q=K%2,te=Math.floor(K/2),J=window.innerWidth*.2,de=50,Y=10,Me=f.has(K),De=E.has(K),Se=m&&Me,Rt="transparent";return Se?Rt=De?"#4CAF50":"#ef4444":Me&&(Rt="#4CAF50"),jsxs(Group,{x:340+Q*(J+Y),y:v+I-80+te*(de+Y),draggable:!m,onDragMove:H,onDragEnd:Ja=>q(K,Ja),opacity:m&&!Me?.5:1,children:[jsx(Rect,{width:J-20,height:de,fill:"white",stroke:Rt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:J-20,height:de,text:U,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${p}`)})]})};Li.displayName="MultipleChoiceDragAndDrop";var ru=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(ou,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:c=>r(c,s.id),onContextMenu:n},s.id):jsx(Li,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:n},s.id))});var nu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(E=>E.toolbar.selectedTool),c=s==="pen"||s==="eraser",[i,d]=useState(null),[f,u]=useState(false),[m,l]=useState(null),h=useRef(null);useEffect(()=>{let E=h.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{i!==null&&u(true);},p=()=>{u(false),d(null);},w=e.data.responseOptions.correctAnswer,x=i===w,v=E=>{f||d(E);},L=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",I=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},k=70,S=12,b=24,A=60,V=60,R=e.data.feedbackMode==="practice"?48:0,H=12,q=A+(f?V:0),P=2*(k+S),W=q+P+H+R+b;return jsxs(Group,{ref:h,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:E=>n(E,e.id),onClick:E=>t(e.id),onTap:E=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:W-20,width:e.width,onTransformEnd:E=>o(e.id,E),onContextMenu:E=>{E.cancelBubble=true,r(E.evt,e.id,"trueFalse");}}),jsx(Text,{x:b,y:b,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:b,y:A,width:e.width-b*2,height:V-10,fill:I().bg,cornerRadius:8}),jsx(Text,{x:b,y:A,width:e.width-b*2,height:V-10,text:L(),fontSize:16,fontStyle:"bold",fill:I().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((E,oe)=>{let N=w===E.value,fe=i===E.value,z=(e.width-b*3)/2,O=b+oe*(z+b),X=q,U=E.value===true,K=U?"#10b981":"#ef4444",Q="#ffffff",te="#ffffff",J="#e5e7eb";return f&&(N?(te=U?"#f0fdf4":"#fef2f2",J=U?"#86efac":"#fecaca"):fe&&!N&&(te="#fee2e2",J="#ef4444")),fe&&!f&&(J="#096B76",te="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:X,width:z,height:k+50,fill:te,stroke:J,strokeWidth:2,cornerRadius:12,onClick:de=>{de.cancelBubble=true,v(E.value);},onTap:de=>{de.cancelBubble=true,v(E.value);}}),jsx(Circle,{x:O+z/2,y:X+40,radius:28,fill:K,listening:false}),U?jsx(Text,{x:O+z/2-14,y:X+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Q,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:O+z/2-14,y:X+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:Q,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O,y:X+85,width:z,height:30,text:E.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},E.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:q+2*(k+S),children:[jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,l("check");},onMouseUp:E=>{E.cancelBubble=true,l(null),g();},onMouseLeave:E=>{E.cancelBubble=true,l(null);},onTouchStart:E=>{E.cancelBubble=true,l("check");},onTouchEnd:E=>{E.cancelBubble=true,l(null),g();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,fill:i===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-b*2)/2+8,onMouseDown:()=>l("reset"),onMouseUp:()=>{l(null),p();},onMouseLeave:()=>l(null),onTouchStart:()=>l("reset"),onTouchEnd:()=>{l(null),p();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});nu.displayName="TrueFalse";var su=nu;var Eg="#FFFFFF",Ci=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(K=>K.toolbar.selectedTool),n=r==="pen"||r==="eraser",[s,c]=useState(false),[i,d]=useState(null),[f,u]=useState(false),[m,l]=useState(false),[h,g]=useState(0),[p,w]=useState(false),x=340,v=100,L=window.innerWidth*.4,I=window.innerHeight*.5,k=L-40,S=I-300,b=20,A=60,V=k,R=S,H=L*.2-40,q=50,P=useRef(null),W=K=>{a(la({id:e.id,x:K.target.x(),y:K.target.y()}));},E=K=>{let Q=K.target,te=Q.x(),J=Q.y(),de=Math.max(0,Math.min(te+H,b+V)-Math.max(te,b)),Y=Math.max(0,Math.min(J+q,A+R)-Math.max(J,A)),Me=de*Y,De=H*q;c(Me/De>=.5);},oe=(K,Q)=>{let te=Q.target,J=te.x(),de=te.y(),Y=Math.max(0,Math.min(J+H,b+V)-Math.max(J,b)),Me=Math.max(0,Math.min(de+q,A+R)-Math.max(de,A)),De=Y*Me,Se=H*q;if(De/Se>=.5)d(K);else return;c(false);},N=()=>{u(true);},fe=()=>{u(false),d(null),g(K=>K+1);},z=e.data.responseOptions.correctAnswer,O=i===z,X=()=>O?"\u2713 Correct! Great job!":"\u2717 Try again!",U=()=>O?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:P,name:"trueFalse-element",width:L,height:I,draggable:!n,listening:!n,...n?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:W,children:[jsx(Rect,{fill:"white",stroke:s?"#4CAF50":"#e5e7eb",strokeWidth:s?4:2,cornerRadius:12,height:f?I:e.data.feedbackMode==="practice"?I-50:I-100,width:L,shadowColor:s?"#4CAF50":"transparent",shadowBlur:s?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:k,height:S,fill:"transparent",stroke:s?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:k,height:60,fill:U().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:k,height:60,text:X(),fontSize:18,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle"})]}),i===null&&!f&&jsx(Text,{x:20,y:60,width:k,height:S-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:I-100,children:[jsxs(Group,{onMouseDown:()=>{i!==null&&(l(true),N());},onMouseUp:()=>l(false),onMouseLeave:()=>l(false),onTouchStart:()=>{i!==null&&(l(true),N());},onTouchEnd:()=>l(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:i===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:fe,onTouchStart:fe,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,Q)=>{let te=window.innerWidth*.2,J=50,de=10,Y=i===K.value,Me=z===K.value,De=f&&Y,Se="transparent";return De?Se=Me?"#4CAF50":"#ef4444":Y&&(Se="#4CAF50"),jsxs(Group,{x:16+Q*(te+de),y:v+I-300,draggable:!f,onDragMove:E,onDragEnd:Rt=>oe(K.value,Rt),opacity:f&&!Y?.5:1,children:[jsx(Rect,{width:te-40,height:J,fill:"#075560",stroke:Se,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:te-40,height:J,text:K.label,fontSize:18,fontStyle:"bold",fill:Eg,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${h}`)})]})})};Ci.displayName="TrueFalseDragAndDrop";var iu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(su,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r},s.id):jsx(Ci,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n},s.id))});var fa=new WeakMap,bo=new WeakMap,dr={current:[]},Mi=false,lr=0,ir=new Set,Pn=new Map;function lu(e){let o=Array.from(e).sort((t,a)=>t instanceof Vt&&t.options.deps.includes(a)?1:a instanceof Vt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(dr.current.includes(t))continue;dr.current.push(t),t.recompute();let a=bo.get(t);if(a)for(let r of a){let n=fa.get(r);n&&lu(n);}}}function Og(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Ng(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Rn(e){if(lr>0&&!Pn.has(e)&&Pn.set(e,e.prevState),ir.add(e),!(lr>0)&&!Mi)try{for(Mi=!0;ir.size>0;){let o=Array.from(ir);ir.clear();for(let t of o){let a=Pn.get(t)??t.prevState;t.prevState=a,Og(t);}for(let t of o){let a=fa.get(t);a&&(dr.current.push(t),lu(a));}for(let t of o){let a=fa.get(t);if(a)for(let r of a)Ng(r);}}}finally{Mi=false,dr.current=[],Pn.clear();}}function ut(e){lr++;try{e();}finally{if(lr--,lr===0){let o=ir.values().next().value;o&&Rn(o);}}}function du(e){return typeof e=="function"}var _t=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,n;this.listeners.add(a);let s=(n=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:n.call(r,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,r;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):du(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),Rn(this);}};var Vt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let n=0;n<t;n++){let s=this.options.deps[n];a[n]=s.prevState,r[n]=s.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let n of this.options.deps)n instanceof e&&n.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let n=0;n<r.length;n++)if(r[n]!==a[n]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,r;this.listeners.add(t);let n=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof _t){let a=fa.get(t);a||(a=new Set,fa.set(t,a)),a.add(this);let r=bo.get(this);r||(r=new Set,bo.set(this,r)),r.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof _t){let a=fa.get(t);a&&a.delete(this);let r=bo.get(this);r&&r.delete(t);}}};function Vg(e){return typeof e=="function"}function Ti(e,...o){return Vg(e)?e(...o):e}function uu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ma,tt,Je,ur,pa,Oa,Jt,vo,cr,Dn,fr,yo,Na=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Ae(this,ma,true);Ae(this,tt);Ae(this,Je);Ae(this,ur);Ae(this,pa);Ae(this,Oa);Ae(this,Jt);Ae(this,vo);Ae(this,cr,0);Ae(this,Dn,5);Ae(this,fr,()=>{this.debugLog("Connected to event bus"),Ce(this,Oa,true),this.debugLog("Emitting queued events",_(this,pa)),_(this,pa).forEach(o=>this.emitEventToBus(o)),Ce(this,pa,[]),this.stopConnectLoop(),_(this,Je).call(this).removeEventListener("tanstack-connect-success",_(this,fr));});Ae(this,yo,()=>{if(_(this,Je).call(this).addEventListener("tanstack-connect-success",_(this,fr)),_(this,cr)<_(this,Dn)){Wl(this,cr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,Je).call(this).removeEventListener("tanstack-connect",_(this,yo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ce(this,tt,o),Ce(this,ma,a),Ce(this,Je,this.getGlobalTarget),Ce(this,ur,t),this.debugLog(" Initializing event subscription for plugin",_(this,tt)),Ce(this,pa,[]),Ce(this,Oa,false),Ce(this,Jt,null),Ce(this,vo,r);}startConnectLoop(){_(this,Jt)!==null||_(this,Oa)||(this.debugLog(`Starting connect loop (every ${_(this,vo)}ms)`),Ce(this,Jt,setInterval(_(this,yo),_(this,vo))));}stopConnectLoop(){_(this,Jt)!==null&&(clearInterval(_(this,Jt)),Ce(this,Jt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,ur)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,tt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return _(this,tt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,Je).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,Je).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!_(this,ma)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!_(this,Oa)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,pa).push({type:`${_(this,tt)}:${o}`,payload:t,pluginId:_(this,tt)}),typeof CustomEvent<"u"&&(_(this,yo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,tt)}:${o}`,payload:t,pluginId:_(this,tt)})}on(o,t){let a=`${_(this,tt)}:${o}`;if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=n=>{this.debugLog("Received event from bus",n.detail),t(n.detail);};return _(this,Je).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{_(this,Je).call(this).removeEventListener(a,r);}}onAll(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;_(this,tt)&&r.pluginId!==_(this,tt)||o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}};ma=new WeakMap,tt=new WeakMap,Je=new WeakMap,ur=new WeakMap,pa=new WeakMap,Oa=new WeakMap,Jt=new WeakMap,vo=new WeakMap,cr=new WeakMap,Dn=new WeakMap,fr=new WeakMap,yo=new WeakMap;var Ai=class extends Na{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},cu=(e,o)=>{Pi.emit(e,o);},Pi=new Ai;function fu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var qg={enabled:true,leading:true,trailing:true,wait:0},ha,ct,Va,qa,Ha,wo,En=class{constructor(o,t){Ae(this,ha);Ae(this,ct);Ae(this,Va);Ae(this,qa);Ae(this,Ha);Ae(this,wo);this.fn=o,this.store=new _t(fu()),this.setOptions=a=>{this.options={...this.options,...a},_(this,Va).call(this)||this.cancel();},Ce(this,ct,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:s}=n;return {...n,status:_(this,Va).call(this)?s?"pending":"idle":"disabled"}}),cu("Throttler",this);}),Ce(this,Va,()=>!!Ti(this.options.enabled,this)),Ce(this,qa,()=>Ti(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,ct).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,s=_(this,qa).call(this);if(this.options.leading&&n>=s)_(this,Ha).call(this,...a);else if(_(this,ct).call(this,{lastArgs:a}),!_(this,ha)&&this.options.trailing){let c=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,i=s-c;_(this,ct).call(this,{isPending:true}),Ce(this,ha,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&_(this,Ha).call(this,...d);},i));}},Ce(this,Ha,(...a)=>{if(!_(this,Va).call(this))return;this.fn(...a);let r=Date.now(),n=r+_(this,qa).call(this);_(this,wo).call(this),_(this,ct).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:n,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||_(this,ct).call(this,{nextExecutionTime:void 0});},_(this,qa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,Ha).call(this,...this.store.state.lastArgs);},Ce(this,wo,()=>{_(this,ha)&&(clearTimeout(_(this,ha)),Ce(this,ha,void 0));}),this.cancel=()=>{_(this,wo).call(this),_(this,ct).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,ct).call(this,fu());},this.key=uu(t.key),this.options={...qg,...t},_(this,ct).call(this,this.options.initialState??{}),Pi.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,ct).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ha=new WeakMap,ct=new WeakMap,Va=new WeakMap,qa=new WeakMap,Ha=new WeakMap,wo=new WeakMap;function Ri(e,o){return new En(e,o).maybeExecute}function ga(e,o){return typeof e=="function"?e(o):e}function xa(e,o){return Nn(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Lo(e,o,t){let a=Nn(o);function r(n){if(!a.length)return ga(t,n);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(n))return typeof n=="object"?(n===null&&(n={}),{...n,[s]:r(n[s])}):{[s]:r()};if(Array.isArray(n)&&typeof s=="number"){let c=n.slice(0,s);return [...c.length?c:new Array(s),r(n[s]),...n.slice(s+1)]}return [...new Array(s),r()]}return r(e)}function Ei(e,o){let t=Nn(o);function a(r){if(!r)return;if(t.length===1){let s=t[0];if(Array.isArray(r)&&typeof s=="number")return r.filter((d,f)=>f!==s);let{[s]:c,...i}=r;return i}let n=t.shift();if(typeof n=="string"&&typeof r=="object")return {...r,[n]:a(r[n])};if(typeof n=="number"&&Array.isArray(r)){if(n>=r.length)return r;let s=r.slice(0,n);return [...s.length?s:new Array(n),a(r[n]),...r.slice(n+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Hg=/^(\d+)$/gm,Ug=/\.(\d+)(?=\.)/gm,Wg=/^(\d+)\./gm,zg=/\.(\d+$)/gm,Gg=/\.{2,}/gm,Di="__int__",Fn=`${Di}$1`;function Nn(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(Hg,Fn).replace(Ug,`.${Fn}.`).replace(Wg,`${Fn}.`).replace(zg,`.${Fn}`).replace(Gg,".").split(".").map(o=>{if(o.startsWith(Di)){let t=o.substring(Di.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function Fi(e){return !(Array.isArray(e)&&e.length===0)}function Io(e,o){let t=a=>a.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function So(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},s=t??0,c=i=>i.validators.filter(Boolean).map(d=>{let f=d?.cause||e,u=s;switch(f){case "change":u=r??s;break;case "blur":u=a??s;break;case "dynamic":u=n??s;break;case "submit":u=0;break}return e==="submit"&&(u=0),{cause:f,validate:d.fn,debounceMs:u}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:c})}var mr=e=>!!e&&typeof e=="object"&&"fields"in e;function ba(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,n]of e)if(!o.has(r)||!Object.is(n,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!ba(e[r],o[r]))return false;return true}var Vn=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},qn=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Ge(e,o){return e==null?o:{...e,...o}}var Ua=256,On=[],Bn;for(;Ua--;)On[Ua]=(Ua+256).toString(16).substring(1);function Bi(){let e=0,o,t="";if(!Bn||Ua+16>256){for(Bn=new Array(256),e=256;e--;)Bn[e]=256*Math.random()|0;e=0,Ua=0;}for(;e<16;e++)o=Bn[Ua+e],e===6?t+=On[o&15|64]:e===8?t+=On[o&63|128]:t+=On[o],e&1&&e>1&&e<11&&(t+="-");return Ua++,t}var va=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},n={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,n,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Kg(e,o){let t=new Map;for(let a of e){let r=a.path??[],n=o,s="";for(let c=0;c<r.length;c++){let i=r[c];if(i===void 0)continue;let d=typeof i=="object"?i.key:i,f=Number(d);Array.isArray(n)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(c>0?".":"")+String(d),typeof n=="object"&&n!==null?n=n[d]:n=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var mu=(e,o)=>{let t=Kg(e,o);return {form:t,fields:t}},ya={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:mu(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:mu(a.issues,e)}},Hn=e=>!!e&&"~standard"in e;var Co={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function pr(e){function o(u,m,l,h){let g=a(u,m,l,h);({insert:()=>c(g,u,m),remove:()=>i(g),swap:()=>h!==void 0&&f(g,u,m,h),move:()=>h!==void 0&&d(g,u,m,h)})[l]();}function t(u,m){return `${u}[${m}]`}function a(u,m,l,h){let g=[t(u,m)];if(l==="swap")g.push(t(u,h));else if(l==="move"){let[p,w]=[Math.min(m,h),Math.max(m,h)];for(let x=p;x<=w;x++)g.push(t(u,x));}else {let p=e.getFieldValue(u),w=Array.isArray(p)?p.length:0;for(let x=m+1;x<w;x++)g.push(t(u,x));}return Object.keys(e.fieldInfo).filter(p=>g.some(w=>p.startsWith(w)))}function r(u,m){return u.replace(/\[(\d+)\]/,(l,h)=>{let g=parseInt(h,10);return `[${m==="up"?g+1:Math.max(0,g-1)}]`})}function n(u,m){(m==="up"?u:[...u].reverse()).forEach(h=>{let g=r(h.toString(),m),p=e.getFieldMeta(g);p?e.setFieldMeta(h,p):e.setFieldMeta(h,s());});}let s=()=>Co,c=(u,m,l)=>{n(u,"down"),u.forEach(h=>{h.toString().startsWith(t(m,l))&&e.setFieldMeta(h,s());});},i=u=>{n(u,"up");},d=(u,m,l,h)=>{let g=new Map(Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,l))).map(p=>[p,e.getFieldMeta(p)]));n(u,l<h?"up":"down"),Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,h))).forEach(p=>{let w=p.replace(t(m,h),t(m,l)),x=g.get(w);x&&e.setFieldMeta(p,x);});},f=(u,m,l,h)=>{u.forEach(g=>{if(!g.toString().startsWith(t(m,l)))return;let p=g.toString().replace(t(m,l),t(m,h)),[w,x]=[e.getFieldMeta(g),e.getFieldMeta(p)];w&&e.setFieldMeta(p,w),x&&e.setFieldMeta(g,x);});};return {handleArrayFieldMetaShift:o}}var Oi=class extends Na{constructor(){super({pluginId:"form-devtools"});}},ft=new Oi;function Ni(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 gr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),ft.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),n},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let n=!!a.transform?.deps?.some((i,d)=>i!==this.prevTransformArray[d]),s=a.defaultValues&&!ba(a.defaultValues,r.defaultValues)&&!this.state.isTouched,c=!ba(a.defaultState,r.defaultState)&&!this.state.isTouched;!s&&!c&&!n||(ut(()=>{this.baseStore.setState(()=>Ni(Object.assign({},this.state,c?a.defaultState:{},s?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:n}=this.state,s=this.resetFieldMeta(n);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Ni({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let r=[];return ut(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let c=s.instance;r.push(Promise.resolve().then(()=>c.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null,i=[`${a}[${r}]`];for(let m=r+1;m<=(c??0);m++)i.push(`${a}[${m}]`);let d=Object.keys(this.fieldInfo).filter(m=>i.some(l=>m.startsWith(l))),f=[];return ut(()=>{d.forEach(m=>{f.push(Promise.resolve().then(()=>this.validateField(m,n)));});}),(await Promise.all(f)).flat()},this.validateField=(a,r)=>{let n=this.fieldInfo[a]?.instance;return n?(n.state.meta.isTouched||n.setMeta(s=>({...s,isTouched:true})),n.validate(r)):[]},this.validateSync=a=>{let r=Io(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va}),n=false,s={};return ut(()=>{for(let d of r){if(!d.validate)continue;let f=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:u,fieldErrors:m}=Un(f),l=hr(d.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let g=this.getFieldMeta(h);if(!g)continue;let{errorMap:p,errorSourceMap:w}=g,x=m?.[h],{newErrorValue:v,newSource:L}=Vn({newFormValidatorError:x,isPreviousErrorFromFormValidator:w?.[l]==="form",previousErrorValue:p?.[l]});L==="form"&&(s[h]={...s[h],[l]:x}),p?.[l]!==v&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[l]:v},errorSourceMap:{...I.errorSourceMap,[l]:L}}));}this.state.errorMap?.[l]!==u&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[l]:u}})),(u||m)&&(n=!0);}let c=hr("submit");this.state.errorMap?.[c]&&a!=="submit"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[c]:void 0}}));let i=hr("server");this.state.errorMap?.[i]&&a!=="server"&&!n&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));}),{hasErrored:n,fieldsErrorMap:s}},this.validateAsync=async a=>{let r=So(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let n=[],s;for(let d of r){if(!d.validate)continue;let f=hr(d.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let m=new AbortController;this.state.validationMetaMap[f]={lastAbortController:m},n.push(new Promise(async l=>{let h;try{h=await new Promise((x,v)=>{setTimeout(async()=>{if(m.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:m.signal},type:"validateAsync"}));}catch(L){v(L);}},d.debounceMs);});}catch(x){h=x;}let{formError:g,fieldErrors:p}=Un(h);p&&(s=s?{...s,...p}:p);let w=hr(d.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let v=this.getFieldMeta(x);if(!v)continue;let{errorMap:L,errorSourceMap:I}=v,k=s?.[x],{newErrorValue:S,newSource:b}=Vn({newFormValidatorError:k,isPreviousErrorFromFormValidator:I?.[w]==="form",previousErrorValue:L?.[w]});L?.[w]!==S&&this.setFieldMeta(x,A=>({...A,errorMap:{...A.errorMap,[w]:S},errorSourceMap:{...A.errorSourceMap,[w]:b}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[w]:g}})),l(s?{fieldErrors:s,errorMapKey:w}:void 0);}));}let c=[],i={};if(n.length){c=await Promise.all(n);for(let d of c)if(d?.fieldErrors){let{errorMapKey:f}=d;for(let[u,m]of Object.entries(d.fieldErrors)){let h={...i[u]||{},[f]:m};i[u]=h;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>xa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,r)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:ga(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let s=n;return r[s]=Co,r},{}),this.setFieldValue=(a,r,n)=>{let s=n?.dontUpdateMeta??false,c=n?.dontRunListeners??false,i=n?.dontValidate??false;ut(()=>{s||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Lo(d.values,a,r)}));}),c||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let n=[...Object.keys(this.fieldInfo).filter(s=>{let c=a.toString();return s!==c&&s.startsWith(c)}),a];this.baseStore.setState(s=>{let c={...s};return n.forEach(i=>{c.values=Ei(c.values,i),delete this.fieldInfo[i],delete c.fieldMetaBase[i];}),c});},this.pushFieldValue=(a,r,n)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],r],n);},this.insertFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,i=>[...i.slice(0,r),n,...i.slice(r)],Ge(s,{dontValidate:true}));let c=s?.dontValidate??false;c||await this.validateField(a,"change"),pr(this).handleArrayFieldMetaShift(a,r,"insert"),c||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,i=>i.map((d,f)=>f===r?n:d),Ge(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,d=>d.filter((f,u)=>u!==r),Ge(n,{dontValidate:true})),pr(this).handleArrayFieldMetaShift(a,r,"remove"),c!==null){let d=`${a}[${c}]`;this.deleteField(d);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,s)=>{this.setFieldValue(a,i=>{let d=i[r],f=i[n];return Lo(Lo(i,`${r}`,f),`${n}`,d)},Ge(s,{dontValidate:true})),pr(this).handleArrayFieldMetaShift(a,r,"swap",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.moveFieldValues=(a,r,n,s)=>{this.setFieldValue(a,i=>{let d=[...i];return d.splice(n,0,d.splice(r,1)[0]),d},Ge(s,{dontValidate:true})),pr(this).handleArrayFieldMetaShift(a,r,"move",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.clearFieldValues=(a,r)=>{let n=this.getFieldValue(a),s=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,[],Ge(r,{dontValidate:true})),s!==null)for(let i=0;i<=s;i++){let d=`${a}[${i}]`;this.deleteField(d);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:Co},values:this.options.defaultValues?Lo(r.values,a,xa(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,n])=>(Object.keys(n).length&&n.errors.length&&(a[r]={errors:n.errors,errorMap:n.errorMap}),a),{})}),this.parseValuesWithSchema=a=>ya.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ya.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Bi(),this._devtoolsSubmissionOverride=false,this.baseStore=new _t(Ni({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Vt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],i=r[0],d=0,f={};for(let u of Object.keys(i.fieldMetaBase)){let m=i.fieldMetaBase[u],l=c?.fieldMetaBase[u],h=s?.[u],g=xa(i.values,u),p=h?.errors;if(!l||m.errorMap!==l.errorMap){p=Object.values(m.errorMap??{}).filter(I=>I!==void 0);let L=this.getFieldInfo(u)?.instance;L&&!L.options.disableErrorFlat&&(p=p?.flat(1));}let w=!Fi(p??[]),x=!m.isDirty,v=ba(g,xa(this.options.defaultValues,u))||ba(g,this.getFieldInfo(u)?.instance?.options.defaultValue);if(h&&h.isPristine===x&&h.isValid===w&&h.isDefaultValue===v&&h.errors===p&&m===l){f[u]=h,d++;continue}f[u]={...m,errors:p,isPristine:x,isValid:w,isDefaultValue:v};}return Object.keys(i.fieldMetaBase).length&&s&&d===Object.keys(i.fieldMetaBase).length?s:f}}),this.store=new Vt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],i=r[0],d=r[1],f=Object.values(d).filter(Boolean),u=f.some(P=>P.isValidating),m=f.every(P=>P.isValid),l=f.some(P=>P.isTouched),h=f.some(P=>P.isBlurred),g=f.every(P=>P.isDefaultValue),p=l&&i.errorMap?.onMount,w=f.some(P=>P.isDirty),x=!w,v=!!(i.errorMap?.onMount||f.some(P=>P?.errorMap?.onMount)),L=!!u,I=s?.errors??[];(!c||i.errorMap!==c.errorMap)&&(I=Object.values(i.errorMap).reduce((P,W)=>W===void 0?P:W&&mr(W)?(P.push(W.form),P):(P.push(W),P),[]));let k=I.length===0,S=m&&k,b=this.options.canSubmitWhenInvalid??false,A=i.submissionAttempts===0&&!l&&!v||!L&&!i.isSubmitting&&S||b,V=i.errorMap;if(p&&(I=I.filter(P=>P!==i.errorMap.onMount),V=Object.assign(V,{onMount:void 0})),s&&c&&s.errorMap===V&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===I&&s.isFieldsValidating===u&&s.isFieldsValid===m&&s.isFormValid===k&&s.isValid===S&&s.canSubmit===A&&s.isTouched===l&&s.isBlurred===h&&s.isPristine===x&&s.isDefaultValue===g&&s.isDirty===w&&ba(c,i))return s;let R={...i,errorMap:V,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:u,isFieldsValid:m,isFormValid:k,isValid:S,canSubmit:A,isTouched:l,isBlurred:h,isPristine:x,isDefaultValue:g,isDirty:w},H=this.options.transform?.deps??[];if(H.length!==this.prevTransformArray.length||H.some((P,W)=>P!==this.prevTransformArray[W])){let P=Object.assign({},this,{state:R});this.options.transform?.fn(P),R=P.state,this.prevTransformArray=H;}return R}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Ri(a=>ft.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),ft.on("request-form-state",a=>{a.payload.id===this._formId&&ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),ft.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),ft.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return Hn(o.validate)?ya[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(r=>({...r,isSubmitted:false,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:false})),ut(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(n=>({...n,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ut(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ut(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){ut(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(mr(a)){let{formError:n,fieldErrors:s}=Un(a);for(let c of Object.keys(this.fieldInfo))this.getFieldMeta(c)&&this.setFieldMeta(c,d=>({...d,errorMap:{...d.errorMap,[r]:s?.[c]},errorSourceMap:{...d.errorSourceMap,[r]:"form"}}));this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[r]:n}}));}else this.baseStore.setState(n=>({...n,errorMap:{...n.errorMap,[r]:a}}));});});}};function Un(e){if(e){if(mr(e)){let o=Un(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function hr(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 xr=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let n=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});n&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:n},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=xa(t.form.options.defaultValues,t.name),n=t.defaultValue??r;a?this.setValue(s=>s||n,{dontUpdateMeta:true}):n!==void 0&&this.setValue(n,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Ge(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Ge(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let n of a){if(!n.instance)continue;let{onChangeListenTo:s,onBlurListenTo:c}=n.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&r.push(n.instance),t==="blur"&&c?.includes(this.name)&&r.push(n.instance);}return r},this.validateSync=(t,a)=>{let r=Io(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),s=this.getLinkedFields(t).reduce((d,f)=>{let u=Io(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||va});return u.forEach(m=>{m.field=f;}),d.concat(u)},[]),c=false;ut(()=>{let d=(f,u)=>{let m=Wn(u.cause),l=u.validate?pu(f.runValidator({validate:u.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,h=a[m],{newErrorValue:g,newSource:p}=qn({formLevelError:h,fieldLevelError:l});f.state.meta.errorMap?.[m]!==g&&f.setMeta(w=>({...w,errorMap:{...w.errorMap,[m]:g},errorSourceMap:{...w.errorSourceMap,[m]:p}})),g&&(c=!0);};for(let f of r)d(this,f);for(let f of s)f.validate&&d(f.field,f);});let i=Wn("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!c&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[i]:void 0},errorSourceMap:{...d.errorSourceMap,[i]:void 0}})),{hasErrored:c}},this.validateAsync=async(t,a)=>{let r=So(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),n=await a,s=this.getLinkedFields(t),c=s.reduce((m,l)=>{let h=So(t,{...l.options,form:l.form,validationLogic:l.form.options.validationLogic||va});return h.forEach(g=>{g.field=l;}),m.concat(h)},[]);this.state.meta.isValidating||this.setMeta(m=>({...m,isValidating:true}));for(let m of s)m.setMeta(l=>({...l,isValidating:true}));let i=[],d=[],f=(m,l,h)=>{let g=Wn(l.cause);m.getInfo().validationMetaMap[g]?.lastAbortController.abort();let w=new AbortController;this.getInfo().validationMetaMap[g]={lastAbortController:w},h.push(new Promise(async x=>{let v;try{v=await new Promise((b,A)=>{this.timeoutIds.validations[l.cause]&&clearTimeout(this.timeoutIds.validations[l.cause]),this.timeoutIds.validations[l.cause]=setTimeout(async()=>{if(w.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:l.validate,value:{value:m.store.state.value,fieldApi:m,signal:w.signal,validationSource:"field"},type:"validateAsync"}));}catch(V){A(V);}},l.debounceMs);});}catch(b){v=b;}if(w.signal.aborted)return x(void 0);let L=pu(v),I=n[this.name]?.[g],{newErrorValue:k,newSource:S}=qn({formLevelError:I,fieldLevelError:L});m.setMeta(b=>({...b,errorMap:{...b?.errorMap,[g]:k},errorSourceMap:{...b.errorSourceMap,[g]:S}})),x(k);}));};for(let m of r)m.validate&&f(this,m,i);for(let m of c)m.validate&&f(m.field,m,d);let u=[];(i.length||d.length)&&(u=await Promise.all(i),await Promise.all(d)),this.setMeta(m=>({...m,isValidating:false}));for(let m of s)m.setMeta(l=>({...l,isValidating:false}));return u.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:n}=this.validateSync(t,r[this.name]??{});if(n&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Wn(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>ya.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ya.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Vt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Co,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Hn(o.validate)?ya[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function pu(e){if(e)return e}function Wn(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 zn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,jg)}function jg(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,r]of e)if(!o.has(a)||!Object.is(r,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=hu(e);if(t.length!==hu(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function hu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var ko=typeof window<"u"?useLayoutEffect:useEffect;function ex(e){let[o]=useState(()=>{let a=new xr({...e,form:e.form,name:e.name});return a.Field=Vi,a});return ko(o.mount,[o]),ko(()=>{o.update(e);}),zn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var Vi=(({children:e,...o})=>{let t=ex(o),a=useMemo(()=>ga(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function ox({form:e,selector:o,children:t}){let a=zn(e.store,o);return ga(t,a)}function qi(e){let o=useId(),[t]=useState(()=>{let a=new gr({...e,formId:o}),r=a;return r.Field=function(s){return jsx(Vi,{...s,form:a})},r.Subscribe=function(s){return jsx(ox,{form:a,selector:s.selector,children:s.children})},r});return ko(t.mount,[]),ko(()=>{t.update(e);}),t}function Hi({field:e}){return jsxs(Fragment,{children:[e.state.meta.isTouched&&!e.state.meta.isValid?jsx("em",{children:e.state.meta.errors.join(", ")}):null,e.state.meta.isValidating?"Validating...":null]})}var mx=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[s,c]=useState(n),i=qi({defaultValues:{questionType:n,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:u})=>{if(u.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctAnswer:u.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?la(m):Hs(m));}else if(u.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctIndex:u.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?ia(m):qs(m));}else if(u.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Wo(m):Us(m));}else if(u.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctShortAnswer:u.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Go(m):zs(m));}else if(u.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:u.questionType,responseType:u.responseType,feedbackMode:u.feedbackMode,question:u.question,responseOptions:{options:u.responseOptions.options,correctLongAnswer:u.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?zo(m):Ws(m));}o(da(false));}}),d=()=>{o(da(false));},f=jsx("div",{className:"fixed inset-0 z-106 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-6 shadow-lg",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-240px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-100px)] w-full flex-col gap-1 rounded-lg bg-white p-4",onSubmit:u=>{u.preventDefault(),u.stopPropagation(),i.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-4",children:[jsxs("div",{className:"flex flex-col gap-1",children:[jsx("h2",{className:"text-2xl font-bold text-[#000000CC]",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"font-semibold text-[#00000099]",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-8 w-8 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600",onClick:()=>{d();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(i.Field,{name:"questionType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:m=>{u.handleChange(m.target.value),c(m.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 font-semibold text-[#000000CC] ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Question type cannot be changed when editing"}),jsx(Hi,{field:u})]})}),s&&!["short-answer","fill-in-the-blank","long-answer"].includes(s)&&jsx(i.Field,{name:"responseType",children:u=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:u.name,name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:m=>u.handleChange(m.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-4 py-3 pr-10 font-semibold text-[#000000CC]",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Hi,{field:u})]})})]}),jsx(i.Field,{name:"feedbackMode",children:u=>jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-2 rounded-lg bg-gray-100 p-1.5 ${s==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>u.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",size:16}),"Practice Mode"]}),jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>u.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${u.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",size:16}),"Assessment Mode"]})]}),s==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(Hi,{field:u})]})}),jsx(i.Field,{name:"question",validators:{onChange:({value:u})=>u?void 0:"A question is required"},children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-4 py-3 text-gray-900",value:u.state.value,onChange:m=>u.handleChange(m.target.value),onBlur:u.handleBlur,placeholder:"Enter Your Question"})}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="true-false"&&jsx(i.Field,{name:"responseOptions.correctAnswer",children:u=>{let m=u.state.value;return jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{className:"text-base font-semibold text-[#00000066] uppercase",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-4",children:[jsxs("button",{type:"button",onClick:()=>u.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"True"}),m===true&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>u.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"False"}),m===false&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]})]}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Select the correct answer for this true/false question"})]})}}),s==="multiple-choice"&&jsx(i.Field,{name:"responseOptions",validators:{onChange:({value:u})=>{if(u.options.filter(l=>!l.trim()).length>0)return "All options must have text";if(!u.correctIndex||u.correctIndex.length===0)return "Please select at least one correct answer"}},children:u=>{let m=(p,w)=>{let x=[...u.state.value.options];x[p]=w,u.handleChange({...u.state.value,options:x});},l=()=>{if(u.state.value.options.length>=6){alert("Maximum 6 options allowed");return}u.handleChange({...u.state.value,options:[...u.state.value.options,""]});},h=p=>{if(u.state.value.options.length<=2){alert("Minimum 2 options required");return}let w=u.state.value.options.filter((v,L)=>L!==p),x=u.state.value.correctIndex?.filter(v=>v!==p).map(v=>v>p?v-1:v);u.handleChange({...u.state.value,options:w,correctIndex:x});},g=p=>{let w=u.state.value.correctIndex||[];if(w.includes(p))u.handleChange({...u.state.value,correctIndex:w.filter(v=>v!==p)});else {if(w.length>=6){alert("Maximum 6 correct answers allowed");return}u.handleChange({...u.state.value,correctIndex:[...w,p]});}};return jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:u.name,className:"mb-2 text-base font-semibold text-gray-900",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-4 flex flex-col gap-3",children:u.state.value.options.map((p,w)=>{let x=!p.trim(),v=u.state.value.correctIndex?.includes(w),L=u.state.meta.isTouched&&x;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>g(w),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${v?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:v&&jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-4 py-3 transition-colors ${L?"border-red-500 bg-red-50":v?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${w+1}`,value:p,onChange:I=>m(w,I.target.value),onBlur:u.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),u.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>h(w),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},w)})}),jsx("button",{type:"button",onClick:l,disabled:u.state.value.options.length>=6,className:"mx-2 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-3 text-lg font-semibold text-[#00000066] disabled:cursor-not-allowed",children:"+ Add Option"}),u.state.value.correctIndex.length===0||u.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:u.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill"}),jsx("p",{className:"",children:"Correct answer selected"})]})]})}}),(s==="short-answer"||s==="fill-in-the-blank")&&jsx(i.Field,{name:"responseOptions.correctShortAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:u.state.value,onChange:m=>{u.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Learners must write this answer exactly (case-insensitive)."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),s==="long-answer"&&jsx(i.Field,{name:"responseOptions.correctLongAnswer",children:u=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:u.name,className:"text-sm font-semibold text-gray-900",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:u.state.value,onChange:m=>{u.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"This will be used as a reference answer for manual grading."}),u.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:u.state.meta.errors.join(", ")})]})}),jsx(i.Subscribe,{selector:u=>[u.canSubmit,u.isSubmitting],children:([u,m])=>jsx("button",{type:"submit",disabled:!u,className:"mt-2 mb-4 w-full rounded-lg bg-[#096B76] px-6 py-3 font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50",children:m?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,document.body)},bu=mx;var vu=({text:e,position:o})=>{let t=xe(),a=d=>{t(le()),t(wt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},r=d=>{t(le()),t(wt({id:e.id,fill:d}));},n=()=>{t(le()),t(wt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},s=()=>{t(le()),t(wt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},c=()=>{t(le()),t(wt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},i=d=>{t(le()),t(wt({id:e.id,fontFamily:d}));};return jsxs("div",{className:"fixed z-1001 flex items-center gap-1 rounded-lg border border-gray-200 bg-white p-2 shadow-2xl",style:{left:`${o.x}px`,top:`${o.y-60}px`,transform:"translateX(-50%)"},onClick:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>i(d.target.value),className:"rounded border border-gray-300 bg-white px-2 py-1 text-xs hover:bg-gray-50",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-8 text-center text-xs font-medium",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:n,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:jsx(TextB,{size:16,weight:"bold"})}),jsx("button",{onClick:s,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:jsx(TextItalic,{size:16,weight:"bold"})}),jsx("button",{onClick:c,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:jsx(TextUnderline,{size:16,weight:"bold"})})]}),jsx("div",{className:"ml-1 border-l border-gray-200 pl-1",children:jsx("div",{className:"relative",children:jsx("input",{type:"color",value:e.fill,onChange:d=>r(d.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var wu=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:s})=>{let c=useRef(null),i=useMemo(()=>({fontSize:`${e.fontSize*n}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,n]),d=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let u=document.createElement("span");u.style.font=window.getComputedStyle(f).font,u.style.fontSize=f.style.fontSize,u.style.fontFamily=f.style.fontFamily,u.style.fontWeight=f.style.fontWeight,u.style.fontStyle=f.style.fontStyle,u.style.visibility="hidden",u.style.position="absolute",u.style.whiteSpace="pre";let m=f.value.split(`
4
- `),l=0;document.body.appendChild(u);for(let g of m){u.textContent=g||" ";let p=u.offsetWidth;p>l&&(l=p);}document.body.removeChild(u);let h=10;f.style.width=`${Math.max(200,l+h+20)}px`;},[]);return useEffect(()=>{let f=c.current;f&&(f.style.fontSize=`${e.fontSize*n}px`,f.style.fontFamily=e.fontFamily,f.style.fontStyle=e.fontStyle,f.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",f.style.textDecoration=e.textDecoration,f.style.color=e.fill,d(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,d]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(c.current=f,s.current=f,f){f.focus();let u=f.value.length;f.setSelectionRange(u,u),d(f);}},value:o,onChange:f=>{t(f.target.value);},onKeyDown:f=>{f.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Lu=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(P=>P.toolbar.selectedTool),c=s==="pen"||s==="eraser",i=useRef(null),[d,f]=useState(""),[u,m]=useState(false),[l,h]=useState(null);useEffect(()=>{let P=i.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=u&&d.trim().toLowerCase()===g,w=()=>{m(false),f("");},x=()=>p?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",v=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,I=60,k=u?40:0,S=u?54:20,b=50,A=12,V=e.data.feedbackMode==="practice"?48:0,R=12,H=30,q=I+k+H+b+A+R+V+L;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:q,name:"sa-element",...c?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:q,onTransformEnd:P=>t(e.id,P),onContextMenu:P=>{P.cancelBubble=true,r(P.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:I+k+H-S,width:e.width-L*2+4,height:b+6,fill:"#ffffff",stroke:p?"#22c55e":u?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:I+k+H-S},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${b}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:P=>f(P.target.value),disabled:u,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:u?"none":"auto"}})}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:I+80,width:e.width/2+24,height:k,fill:v().bg,cornerRadius:8}),jsx(Text,{x:36,y:I+80,width:e.width-L*2,height:k,text:x(),fontSize:12,fontStyle:"bold",fill:v().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:I+k+H+b+A+R,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,h("check");},onMouseUp:P=>{P.cancelBubble=true,h(null),d.length>0&&m(true);},onMouseLeave:P=>{P.cancelBubble=true,h(null);},onTouchStart:P=>{P.cancelBubble=true,h("check");},onTouchEnd:P=>{P.cancelBubble=true,h(null),d.length>0&&m(true);},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,fill:d.length===0||u?"#9ca3af":"#096B76",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(u?2:1),height:48,text:u?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),u&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Lu.displayName="ShortAnswer";var Iu=Lu;var Cu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(Iu,{shortAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id)},s.id))});var ku=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((s,c)=>{let i=s.target;o(Go({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var Ct=24,zi=51,Ir=64,Mu=15,jn=32,Tu=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n})=>{let s=useSelector(b=>b.toolbar.selectedTool),c=s==="pen"||s==="eraser",i=useRef(null),[d,f]=useState(""),[u,m]=useState(false),[l,h]=useState(null);useEffect(()=>{let b=i.current;if(b)return n.current.set(e.id,b),()=>{n.current.delete(e.id);}},[e.id,n]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=u&&d.trim().toLowerCase()===g,w=()=>{m(false),f("");},x=()=>{d.length>0&&m(true);},v=e.width-Ct*2,L=(v-Mu)/2,I=e.data.feedbackMode==="practice",k=useMemo(()=>{let b=Ct,A=b;b+=60;let V=b;b+=35;let R=b;b+=zi+16;let H=b;u&&(b+=jn+16);let q=b;return I&&(b+=Ir),b+=Ct,{questionY:A,helperTextY:V,inputY:R,feedbackY:H,buttonsY:q,totalHeight:b}},[u,I]),S=()=>u?p?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...c?{}:{onDragEnd:b=>a(b,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:k.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:b=>t(e.id,b),onContextMenu:b=>{b.cancelBubble=true,r?.(b.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Ct,y:k.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:v,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Ct,y:k.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:v,listening:false}),jsx(Rect,{x:Ct,y:k.inputY,width:v,height:zi,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Ct,y:k.inputY},divProps:{style:{width:`${v}px`,height:`${zi}px`,pointerEvents:u?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:b=>f(b.target.value),disabled:u,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),u&&jsxs(Group,{y:k.feedbackY,children:[jsx(Rect,{x:Ct,width:p?206:140,height:jn,fill:p?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:p?"\u2713":"\u2717",x:Ct+10,y:0,width:16,height:jn,fontSize:14,fill:p?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:p?"Right Answer, Great Job!":"Wrong Answer",x:Ct+30,y:0,height:jn,fontSize:14,fontStyle:"600",fill:p?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),I&&jsxs(Group,{y:k.buttonsY,children:[jsxs(Group,{x:Ct,onMouseDown:b=>{b.cancelBubble=true,h("reset");},onMouseUp:b=>{b.cancelBubble=true,h(null),w();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("reset");},onTouchEnd:b=>{b.cancelBubble=true,h(null),w();},scaleX:l==="reset"?.98:1,scaleY:l==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Ir,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Ir,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Ct+L+Mu,onMouseDown:b=>{b.cancelBubble=true,h("submit");},onMouseUp:b=>{b.cancelBubble=true,h(null),x();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("submit");},onTouchEnd:b=>{b.cancelBubble=true,h(null),x();},scaleX:l==="submit"?.98:1,scaleY:l==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Ir,fill:d.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Ir,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Tu.displayName="FillInTheBlanks";var Au=Tu;var Ru=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n})=>jsx(Fragment,{children:e.map(s=>jsx(Au,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n},s.id))});var ji=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(q=>q.toolbar.selectedTool),c=s==="pen"||s==="eraser",i=useRef(null),[d,f]=useState(""),[u,m]=useState(false),[l,h]=useState(null);useEffect(()=>{let q=i.current;if(q)return a.current.set(e.id,q),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",p=u&&d.trim().toLowerCase()===g,w=()=>{m(false),f("");},x=()=>p?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",v=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,I=60,k=u?60:0,S=120,b=12,A=48,V=12,R=30,H=I+k+R+S+b+V+A+L;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...c?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:q=>{let P=i.current?.getStage()?.getPointerPosition();if(!P||!r)return;let W={x:e.x,y:e.y,width:e.width,height:e.height};P.x>=W.x&&P.x<=W.x+W.width&&P.y>=W.y&&P.y<=W.y+W.height&&r(q.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:H,onTransformEnd:q=>t(e.id,q)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),u&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:I,width:e.width-L*2,height:k,fill:v().bg,cornerRadius:8}),jsx(Text,{x:L,y:I,width:e.width-L*2,height:k,text:x(),fontSize:14,fontStyle:"bold",fill:v().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:I+k+b,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:I+k+R,width:e.width-L*2,height:S,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:I+k+R},divProps:{style:{width:`${e.width-L*2}px`,height:`${S}px`,pointerEvents:u?"none":"auto"}},children:jsx("textarea",{value:d,onChange:q=>f(q.target.value),disabled:u,placeholder:`Type your extended answer here...\r
2
+ export{default as Konva}from'konva';import*as be from'react';import be__default,{forwardRef,useRef,useEffect,useCallback,useImperativeHandle,memo,useState,useMemo,createElement,useId,useLayoutEffect}from'react';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';import {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,configureStore}from'@reduxjs/toolkit';import od from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,CaretLeft,Plus,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp,ArrowsDownUp,Shuffle}from'@phosphor-icons/react/dist/ssr';import {EyeIcon,Stack as Stack$1,X as X$1,DotsSixVertical,ArrowUp,ArrowDown,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import {createPortal}from'react-dom';import ou from'use-image';import {motion,AnimatePresence,Reorder}from'framer-motion';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {v4}from'uuid';import {QueryClient}from'@tanstack/react-query';var $l=e=>{throw TypeError(e)};var Xl=(e,o,t)=>o.has(e)||$l("Cannot "+t);var _=(e,o,t)=>(Xl(e,o,"read from private field"),t?t.call(e):o.get(e)),Ae=(e,o,t)=>o.has(e)?$l("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Ce=(e,o,t,a)=>(Xl(e,o,"write to private field"),o.set(e,t),t);var Yl=(e,o,t,a)=>({set _(r){Ce(e,o,r);},get _(){return _(e,o,a)}});var xe=()=>useDispatch(),ee=e=>useSelector(e),yt=xe,Jt=ee;var Ls=20,Is=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()}),ws=Is("Slide 1"),Lm={slides:[ws],currentSlideId:ws.id,history:{[ws.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:""}},Jl=createSlice({name:"canvas",initialState:Lm,reducers:{addSlide:e=>{if(e.slides.length>=Ls)return;let o=Is(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{if(e.slides.length<=1)return;let t=e.slides.findIndex(a=>a.id===o.payload);if(t!==-1&&(e.slides.splice(t,1),delete e.history[o.payload],e.currentSlideId===o.payload)){let a=Math.max(0,t-1);e.currentSlideId=e.slides[a].id;}},duplicateSlide:(e,o)=>{if(e.slides.length>=Ls)return;let t=e.slides.findIndex(n=>n.id===o.payload);if(t===-1)return;let a=e.slides[t],r={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,r),e.currentSlideId=r.id,e.history[r.id]={past:[],future:[]};},setCurrentSlide:(e,o)=>{e.slides.find(a=>a.id===o.payload)&&(e.currentSlideId=o.payload);},updateSlideThumbnail:(e,o)=>{let t=e.slides.find(a=>a.id===o.payload.id);t&&(t.thumbnail=o.payload.thumbnail,t.updatedAt=Date.now());},setBackgroundColor:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.backgroundColor=o.payload,t.updatedAt=Date.now());},reorderSlides:(e,o)=>{let{fromIndex:t,toIndex:a}=o.payload;if(t<0||t>=e.slides.length||a<0||a>=e.slides.length)return;let[r]=e.slides.splice(t,1);e.slides.splice(a,0,r);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,t.updatedAt=Date.now());}},updateLineTransform:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload.id);a&&(a.x=o.payload.x,a.y=o.payload.y,a.scaleX=o.payload.scaleX,a.scaleY=o.payload.scaleY,a.rotation=o.payload.rotation,t.updatedAt=Date.now());}},deleteLineById:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.findIndex(r=>r.id===o.payload);a!==-1&&(t.lines.splice(a,1),t.updatedAt=Date.now());}},duplicateLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(r=>r.id===o.payload);if(a){let r={...a,id:`line-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,x:(a.x||0)+20,y:(a.y||0)+20,timestamp:Date.now()};t.lines.push(r),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,newTimestamp:n}=o.payload;switch(r){case "image":let s=t.images.find(x=>x.id===a);s&&(s.timestamp=n);break;case "video":let c=t.videos.find(x=>x.id===a);c&&(c.timestamp=n);break;case "shape":let l=t.shapes.find(x=>x.id===a);l&&(l.timestamp=n);break;case "text":let u=t.texts.find(x=>x.id===a);u&&(u.timestamp=n);break;case "flashcard":let f=t.flashcards.find(x=>x.id===a);f&&(f.timestamp=n);break;case "photoFrame":let d=t.photoFrames.find(x=>x.id===a);d&&(d.timestamp=n);break;case "mcq":let m=t.multipleChoices.find(x=>x.id===a);m&&(m.timestamp=n);break;case "trueFalse":let i=t.trueFalses.find(x=>x.id===a);i&&(i.timestamp=n);break;case "shortAnswer":let h=t.shortAnswers.find(x=>x.id===a);h&&(h.timestamp=n);break;case "longAnswer":let g=t.LongAnswer.find(x=>x.id===a);g&&(g.timestamp=n);break;case "fillInTheBlanks":let p=t.fillInTheBlanks.find(x=>x.id===a);p&&(p.timestamp=n);break;case "line":let y=t.lines.find(x=>x.id===a);y&&(y.timestamp=n);break}t.updatedAt=Date.now();}},addImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.images.push(a),t.updatedAt=Date.now();}},updateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.images[a]={...t.images[a],...o.payload},t.updatedAt=Date.now());}},deleteImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.images=t.images.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateImage(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);if(a){let r={...a,id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.images.push(r),t.updatedAt=Date.now();}}},addVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.videos.push(a),t.updatedAt=Date.now();}},updateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.videos[a]={...t.videos[a],...o.payload},t.updatedAt=Date.now());}},toggleVideoPlaying(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);a&&(a.isPlaying=!a.isPlaying,t.updatedAt=Date.now());}},deleteVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.videos=t.videos.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateVideo(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.videos.find(r=>r.id===o.payload);if(a){let r={...a,id:`vid-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isPlaying:false,timestamp:Date.now()};t.videos.push(r),t.updatedAt=Date.now();}}},addShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.shapes?.push(a),t.updatedAt=Date.now();}},updateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shapes[a]={...t.shapes[a],...o.payload},t.updatedAt=Date.now());}},duplicateShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shapes.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shapes.push(r),t.updatedAt=Date.now();}}},deleteShape(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shapes=t.shapes.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.multipleChoices||(t.multipleChoices=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.multipleChoices.length>0){let r=t.multipleChoices[t.multipleChoices.length-1];a.x=r.x+20,a.y=r.y+20;}t.multipleChoices.push(a),t.updatedAt=Date.now();}},updateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},editMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t&&t.multipleChoices){let a=t.multipleChoices.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.multipleChoices[a]={...t.multipleChoices[a],...o.payload},t.updatedAt=Date.now());}},duplicateMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.multipleChoices.find(r=>r.id===o.payload);if(a){let r={...a,id:`mcq-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.multipleChoices.push(r),t.updatedAt=Date.now();}}},deleteMultipleChoice(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.multipleChoices=t.multipleChoices.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.trueFalses||(t.trueFalses=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.trueFalses.length>0){let r=t.trueFalses[t.trueFalses.length-1];a.x=r.x+20,a.y=r.y+20;}t.trueFalses.push(a),t.updatedAt=Date.now();}},updateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.trueFalses[a]={...t.trueFalses[a],...o.payload},t.updatedAt=Date.now());}},deleteTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.trueFalses=t.trueFalses.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateTrueFalse(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.trueFalses.find(r=>r.id===o.payload);if(a){let r={...a,id:`shape-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.trueFalses.push(r),t.updatedAt=Date.now();}}},addShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.shortAnswers||(t.shortAnswers=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.shortAnswers.length>0){let r=t.shortAnswers[t.shortAnswers.length-1];a.x=r.x+20,a.y=r.y+20;}t.shortAnswers.push(a),t.updatedAt=Date.now();}},updateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.shortAnswers[a]={...t.shortAnswers[a],...o.payload},t.updatedAt=Date.now());}},duplicateShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.shortAnswers.find(r=>r.id===o.payload);if(a){let r={...a,id:`shortAnswer-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.shortAnswers.push(r),t.updatedAt=Date.now();}}},deleteShortAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.shortAnswers=t.shortAnswers.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},addLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.LongAnswer||(t.LongAnswer=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.LongAnswer.length>0){let r=t.LongAnswer[t.LongAnswer.length-1];a.x=r.x+20,a.y=r.y+20;}t.LongAnswer.push(a),t.updatedAt=Date.now();}},updateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload.id);a&&(Object.assign(a,o.payload),t.updatedAt=Date.now());}},deleteLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.LongAnswer=t.LongAnswer.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateLongAnswer(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.LongAnswer.find(r=>r.id===o.payload);if(a){let r={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(r),t.updatedAt=Date.now();}}},setShowMcqForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showMcqForm=o.payload,t.updatedAt=Date.now());},setShowFlashcardForm(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.showFlashcardForm=o.payload,t.updatedAt=Date.now());},addFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){t.fillInTheBlanks||(t.fillInTheBlanks=[]);let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.fillInTheBlanks.length>0){let r=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=r.x+20,a.y=r.y+20;}t.fillInTheBlanks.push(a),t.updatedAt=Date.now();}},updateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.fillInTheBlanks[a]={...t.fillInTheBlanks[a],...o.payload},t.updatedAt=Date.now());}},deleteFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.fillInTheBlanks=t.fillInTheBlanks.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFillInTheBlanks(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.fillInTheBlanks.find(r=>r.id===o.payload);if(a){let r={...a,id:`fillInTheBlank-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.fillInTheBlanks.push(r),t.updatedAt=Date.now();}}},setActivityType(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.activityType=o.payload,t.updatedAt=Date.now());},setEditingActivity(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingActivity=o.payload,t.updatedAt=Date.now());},bringToFront(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.push(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.push(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.push(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.push(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.push(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.push(s);}}else if(r==="trueFalse"){let n=t.trueFalses.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.trueFalses.splice(n,1);t.trueFalses.push(s);}}else if(r==="shortAnswer"){let n=t.shortAnswers.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shortAnswers.splice(n,1);t.shortAnswers.push(s);}}else if(r==="fillInTheBlanks"){let n=t.fillInTheBlanks.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.fillInTheBlanks.splice(n,1);t.fillInTheBlanks.push(s);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload;if(r==="image"){let n=t.images.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.images.splice(n,1);t.images.unshift(s);}}else if(r==="video"){let n=t.videos.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.videos.splice(n,1);t.videos.unshift(s);}}else if(r==="shape"){let n=t.shapes.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.shapes.splice(n,1);t.shapes.unshift(s);}}else if(r==="flashcard"){let n=t.flashcards.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.flashcards.splice(n,1);t.flashcards.unshift(s);}}else if(r==="photoFrame"){let n=t.photoFrames.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.photoFrames.splice(n,1);t.photoFrames.unshift(s);}}else if(r==="text"){let n=t.texts.findIndex(s=>s.id===a);if(n!==-1){let[s]=t.texts.splice(n,1);t.texts.unshift(s);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r}=o.payload,s=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(c=>c.id===a);s&&(s.locked=!s.locked,"draggable"in s&&(s.draggable=!s.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,link:n}=o.payload,c=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="mcq"?t.multipleChoices:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(l=>l.id===a);c&&(c.link=n,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,altText:n}=o.payload,c=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(l=>l.id===a);c&&(c.altText=n,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:r,audioData:n}=o.payload,c=(r==="image"?t.images:r==="video"?t.videos:r==="shape"?t.shapes:r==="flashcard"?t.flashcards:r==="photoFrame"?t.photoFrames:r==="trueFalse"?t.trueFalses:r==="shortAnswer"?t.shortAnswers:r==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(l=>l.id===a);c&&(c.audioData=n,t.updatedAt=Date.now());}},clearCanvas:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.lines=[],o.images=[],o.videos=[],o.shapes=[],o.flashcards=[],o.photoFrames=[],o.texts=[],o.multipleChoices=[],o.trueFalses=[],o.shortAnswers=[],o.LongAnswer=[],o.fillInTheBlanks=[],o.backgroundColor="#fff",o.updatedAt=Date.now());},addText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.texts.push(a),t.updatedAt=Date.now();}},updateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.texts[a]={...t.texts[a],...o.payload},t.updatedAt=Date.now());}},deleteText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.texts=t.texts.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.texts.find(r=>r.id===o.payload);if(a){let r={...a,id:`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,timestamp:Date.now()};t.texts.push(r),t.updatedAt=Date.now();}}},addFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};if(t.flashcards.length>=40){alert("You can add maximum 40 flashcards");return}t.flashcards.push(a),t.updatedAt=Date.now();}},updateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.flashcards[a]={...t.flashcards[a],...o.payload},t.updatedAt=Date.now());}},deleteFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.flashcards=t.flashcards.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicateFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a){let r={...a,id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,currentIndex:0,timestamp:Date.now()};t.flashcards.push(r),t.updatedAt=Date.now();}}},editFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.editingFlashcard=o.payload);},nextFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);if(a&&a.images.length>0){if(a.order==="sequential")a.currentIndex=(a.currentIndex+1)%a.images.length;else {a.navigationHistory||(a.navigationHistory=[a.currentIndex]);let r=a.images.map((n,s)=>s).filter(n=>n!==a.currentIndex);if(r.length>0){let n=r[Math.floor(Math.random()*r.length)];a.navigationHistory.push(n),a.currentIndex=n;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(r=>r.id===o.payload);a&&a.images.length>0&&(a.order==="sequential"?a.currentIndex=(a.currentIndex-1+a.images.length)%a.images.length:a.navigationHistory&&a.navigationHistory.length>1&&(a.navigationHistory.pop(),a.currentIndex=a.navigationHistory[a.navigationHistory.length-1]),t.updatedAt=Date.now());}},addPhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,timestamp:o.payload.timestamp||Date.now()};t.photoFrames.push(a),t.updatedAt=Date.now();}},updatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.findIndex(r=>r.id===o.payload.id);a!==-1&&(t.photoFrames[a]={...t.photoFrames[a],...o.payload},t.updatedAt=Date.now());}},deletePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.photoFrames=t.photoFrames.filter(a=>a.id!==o.payload),t.updatedAt=Date.now());},duplicatePhotoFrame(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);if(a){let r={...a,id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:a.x+20,y:a.y+20,isCapturing:false,timestamp:Date.now()};t.photoFrames.push(r),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updateImageAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload.imageId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearImageAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},togglePhotoFrameDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.isDrawingMode=!a.isDrawingMode,a.annotations||(a.annotations=[]),t.updatedAt=Date.now());}},addPhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&(a.annotations||(a.annotations=[]),a.annotations.push(o.payload.line),t.updatedAt=Date.now());}},updatePhotoFrameAnnotation(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload.frameId);a&&a.annotations&&a.annotations.length>0&&(a.annotations[a.annotations.length-1].points=o.payload.points,t.updatedAt=Date.now());}},clearPhotoFrameAnnotations(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.photoFrames.find(r=>r.id===o.payload);a&&(a.annotations=[],t.updatedAt=Date.now());}},undo:e=>{let o=e.history[e.currentSlideId];if(o&&o.past.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.future.unshift(JSON.parse(JSON.stringify(a)));let r=o.past.pop();e.slides[t]=r;}catch(a){console.warn("Failed to undo - data too large:",a),o.past=[],o.future=[];}}},redo:e=>{let o=e.history[e.currentSlideId];if(o&&o.future.length>0){let t=e.slides.findIndex(a=>a.id===e.currentSlideId);if(t>=0)try{let a=e.slides[t];o.past.push(JSON.parse(JSON.stringify(a)));let r=o.future.shift();e.slides[t]=r;}catch(a){console.warn("Failed to redo - data too large:",a),o.past=[],o.future=[];}}},saveToHistory:e=>{let o=e.slides.findIndex(t=>t.id===e.currentSlideId);if(o>=0){let t=e.slides[o],a=e.history[e.currentSlideId];if(a)try{let r=JSON.parse(JSON.stringify(t));a.past.push(r),a.future=[],a.past.length>20&&a.past.shift();}catch(r){console.warn("Failed to save to history - data too large:",r),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description;}}}),{addSlide:Ss,deleteSlide:Cs,duplicateSlide:ks,setCurrentSlide:Ms,updateSlideThumbnail:Ts,setBackgroundColor:As,reorderSlides:Im,loadSlides:ao,addLine:Ps,removeLine:zr,addImage:Ds,updateImage:oo,deleteImage:Gr,duplicateImage:Kr,addVideo:_r,updateVideo:jr,deleteVideo:$r,duplicateVideo:Xr,toggleVideoPlaying:Uo,addShape:Rs,updateShape:ro,duplicateShape:Yr,deleteShape:Jr,addText:Es,updateText:wt,deleteText:Zr,duplicateText:Qr,addFlashcard:Fs,updateFlashcard:no,deleteFlashcard:en,duplicateFlashcard:tn,editFlashcard:Wo,nextFlashcard:Bs,previousFlashcard:Os,addPhotoFrame:Ns,updatePhotoFrame:Pa,deletePhotoFrame:an,duplicatePhotoFrame:on,toggleImageDrawingMode:Vs,addImageAnnotation:qs,updateImageAnnotation:Sm,clearImageAnnotations:Cm,togglePhotoFrameDrawingMode:Hs,addPhotoFrameAnnotation:Us,updatePhotoFrameAnnotation:km,clearPhotoFrameAnnotations:Mm,addMultipleChoice:Ws,updateMultipleChoice:ia,editMultipleChoice:Tm,deleteMultipleChoice:rn,duplicateMultipleChoice:nn,addTrueFalse:zs,updateTrueFalse:la,deleteTrueFalse:sn,duplicateTrueFalse:ln,addShortAnswer:Gs,updateShortAnswer:zo,deleteShortAnswer:dn,duplicateShortAnswer:un,addLongAnswer:Ks,updateLongAnswer:Go,deleteLongAnswer:cn,duplicateLongAnswer:fn,addFillInTheBlanks:_s,updateFillInTheBlanks:Ko,deleteFillInTheBlanks:mn,duplicateFillInTheBlanks:pn,setShowMcqForm:da,setShowFlashcardForm:Da,setActivityType:js,setEditingActivity:_o,bringToFront:$s,sendToBack:Xs,toggleLock:Ys,setLink:hn,setAltText:gn,setAudioData:xn,updateLastLine:Am,finalizeDrawing:Js,setLines:Pm,updateLinePosition:Dm,updateLineTransform:bn,deleteLineById:vn,duplicateLine:Zs,updateElementOrder:jo,clearCanvas:Qs,undo:ei,redo:ti,saveToHistory:le,toggleSketchMode:Rm,setSketchMode:it,setEditingTextId:$o,setPresentationTitle:Em,setPresentationDescription:Fm,loadPresentationMetadata:ai}=Jl.actions;var Xo=e=>e.canvas.currentSlideId,ge=e=>{let o=e.canvas.currentSlideId,t=e.canvas.slides.findIndex(a=>a.id===o);return t>=0?e.canvas.slides[t]:void 0},Yo=e=>e.canvas.slides,oi=e=>e.canvas.slides.length<Ls,Bm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},ri=e=>e.canvas.presentationMetadata,Zl=Jl.reducer;var ed=e=>{let o=xe(),t=useRef(null),a=useRef(false),r=ee(i=>i.toolbar.selectedTool),n=ee(i=>i.toolbar.penColor),s=ee(i=>i.toolbar.strokeWidth),c=ee(i=>i.canvas.isSketchMode),l=ee(i=>i.canvas.slides.find(g=>g.id===i.canvas.currentSlideId)?.lines||[]),u=useCallback(i=>{t.current=i;},[]),f=useCallback(i=>{r==="pen"&&t.current&&(o(le()),t.current.startDrawing(i),a.current=true);},[r,o]),d=useCallback(i=>{!t.current||!a.current||t.current.draw(i);},[]),m=useCallback(()=>{if(!t.current||!a.current)return;let i=t.current.stopDrawing();a.current=false,i&&i.points.length>=4&&o(Ps(i)),o(Js()),e?.();},[o,e]);return {lines:l,tool:r,color:n,strokeWidth:s,isSketchMode:c,setCanvasRef:u,startDrawing:f,draw:d,stopDrawing:m}};var rd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:r,isSketchMode:n,style:s,xOffset:c=0,yOffset:l=0},u)=>{let f=useRef(null),d=useRef(false),m=useRef([]),i=useRef([]),h=useRef(null),g=useRef(t),p=useRef(a),y=useRef(r),x=useRef(n),v=useRef(c),L=useRef(l);useEffect(()=>{g.current=t,p.current=a,y.current=r,x.current=n,v.current=c,L.current=l;},[t,a,r,n,c,l]);let I=useCallback(()=>{let S=f.current;if(!S)return;let b=S.getContext("2d");b&&b.clearRect(0,0,S.width,S.height);},[]),k=useCallback(()=>{let S=f.current,b=i.current;if(!S||b.length<1)return;let A=S.getContext("2d");if(!A)return;if(A.clearRect(0,0,S.width,S.height),g.current==="eraser"?(A.globalCompositeOperation="destination-out",A.fillStyle="rgba(0,0,0,1)"):(A.globalCompositeOperation="source-over",A.fillStyle=p.current),b.length===1){A.beginPath(),A.arc(b[0].x,b[0].y,y.current/2,0,Math.PI*2),A.fill();return}let D=od(b,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:H=>H,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(D.length<2)){A.beginPath(),A.moveTo(D[0][0],D[0][1]);for(let H=1;H<D.length;H++)A.lineTo(D[H][0],D[H][1]);A.closePath(),A.fill();}},[]);return useImperativeHandle(u,()=>({startDrawing:S=>{d.current=true;let b={x:S.x-v.current,y:S.y-L.current};m.current=[{x:S.x,y:S.y}],i.current=[b],h.current=S,k();},draw:S=>{if(!d.current||!h.current)return;let b=S.x-h.current.x,A=S.y-h.current.y;if(Math.sqrt(b*b+A*A)<2)return;let D={x:S.x-v.current,y:S.y-L.current};m.current.push({x:S.x,y:S.y}),i.current.push(D),h.current=S,k();},stopDrawing:()=>{if(!d.current)return null;if(d.current=false,m.current.length<2)return m.current=[],i.current=[],h.current=null,I(),null;let b=od(m.current,{size:y.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:V=>V,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(V=>[V[0],V[1]]),A={tool:g.current,points:b,color:p.current,strokeWidth:y.current,isSketch:true};return m.current=[],i.current=[],h.current=null,I(),A},clear:()=>{I(),m.current=[],i.current=[],h.current=null,d.current=false;},isDrawing:()=>d.current,getCanvasElement:()=>f.current}),[I,k]),useEffect(()=>{let S=f.current;S&&(S.width=e,S.height=o);},[e,o]),jsx("canvas",{ref:f,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...s}})});rd.displayName="DirectDrawingCanvas";var nd=rd;var id=e=>{let o=xe(),a=ee(ge)?.images||[],r=useRef(new Map),n=useRef(new Map),s=useRef(new Set);useEffect(()=>{let f=new Set(a.map(d=>d.id));s.current.forEach(d=>{if(!f.has(d)){let m=n.current.get(d);m&&(m.src="",n.current.delete(d)),r.current.delete(d);}}),s.current=f;},[a]),useEffect(()=>()=>{n.current.forEach(f=>{f.src="";}),n.current.clear(),r.current.clear();},[]);let c=useCallback(f=>{if(n.current.has(f.id))return n.current.get(f.id);let d=new window.Image;return (f.src.startsWith("http://")||f.src.startsWith("https://"))&&(d.crossOrigin="anonymous"),d.src=f.src,n.current.set(f.id,d),d},[]),l=useCallback((f,d)=>{let m=f.target,i=m.id();a.find(g=>g.id===i)&&(o(oo({id:i,x:m.x(),y:m.y(),width:m.width(),height:m.height(),rotation:m.rotation()})),d?.());},[a,o]),u=useCallback((f,d)=>{let m=d.target,i=r.current.get(f);if(!i){console.error("\u274C Image node not found for id:",f);return}let h=m.scaleX(),g=m.scaleY(),p=m.rotation(),y=i.width(),x=i.height(),v=Math.max(5,y*h),L=Math.max(5,x*g);m.scaleX(1),m.scaleY(1),i.width(v),i.height(L),o(oo({id:f,width:v,height:L,x:m.x(),y:m.y(),rotation:p})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:c,imageRefs:r,handleDragEnd:l,handleImageTransformEnd:u}};var ld=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),n=useCallback((c,l)=>{let u=l.target,f=u.scaleX(),d=u.scaleY(),m=u.rotation(),i=Math.max(5,u.width()*f),h=Math.max(5,u.height()*d);u.scaleX(1),u.scaleY(1),u.width(i),u.height(h),o(ia({id:c,width:i,height:h,x:u.x(),y:u.y(),rotation:m})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:r,handleMcqTransform:n,mcqRefs:a,handleDragEnd:(c,l)=>{o(ia({id:l,x:c.target.x(),y:c.target.y()})),e?.();}}};var dd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),r=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),n=useCallback((c,l)=>{let u=l.target,f=u.scaleX(),d=u.scaleY(),m=u.rotation(),i=Math.max(5,u.width()*f),h=Math.max(5,u.height()*d);u.scaleX(1),u.scaleY(1),u.width(i),u.height(h),o(la({id:c,width:i,height:h,x:u.x(),y:u.y(),rotation:m})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:r,handleTrueFalseTransform:n,handleTrueFalseDragEnd:(c,l)=>{o(la({id:l,x:c.target.x(),y:c.target.y()})),e?.();},trueFalseRefs:a}};var ud=e=>{let o=xe(),a=ee(ge)?.videos||[],r=useRef(new Map),n=useCallback(l=>{o(Uo(l));},[o]),s=useCallback((l,u)=>{let f=u.target;o(jr({id:l,x:f.x(),y:f.y()})),e?.();},[o,e]),c=useCallback((l,u)=>{let f=u.target,d=f.scaleX(),m=f.scaleY(),i=f.rotation(),h=Math.max(5,f.width()*d),g=Math.max(5,f.height()*m);f.scaleX(1),f.scaleY(1),f.width(h),f.height(g),o(jr({id:l,width:h,height:g,x:f.x(),y:f.y(),rotation:i})),f.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:r,handleVideoClick:n,handleVideoDragEnd:s,handleVideoTransformEnd:c}};var md=e=>{let o=xe(),a=ee(ge)?.shapes||[],r=useRef(new Map),n=useRef(new Map),[s,c]=useState(false),l=useCallback((f,d)=>{let m=d.target;o(ro({id:f,x:m.x(),y:m.y()})),e?.();},[o,e]),u=useCallback((f,d)=>{let m=d.target,i=a.find(v=>v.id===f);if(!i)return;let h=m.scaleX(),g=m.scaleY(),p=i.type?.toLowerCase();p==="arrow"||p==="line"||(m.scaleX(1),m.scaleY(1));let x={id:f,x:m.x(),y:m.y(),width:Math.max(5,m.width()*h),height:Math.max(5,m.height()*g),rotation:m.rotation()};switch(p){case "circle":x.radius=m.width()*h/2;break;case "star":x.innerRadius=m.width()*h/4,x.outerRadius=m.width()*h/2;break;case "triangle":x.radius=m.width()*h/2;break;case "ellipse":x.radiusX=m.width()*h/2,x.radiusY=m.height()*g/2;break;case "polygon":x.radius=m.width()*h/2;break;case "ring":let v=h;x.innerRadius=i.innerRadius&&i.innerRadius*v,x.outerRadius=i.outerRadius&&i.outerRadius*v;break;case "wedge":x.radius=i.radius&&i.radius*h;break;case "arc":x.innerRadius=i.innerRadius&&i.innerRadius*h,x.outerRadius=i.outerRadius&&i.outerRadius*h;break;case "arrow":case "line":{x.scaleX=h,x.scaleY=g,delete x.width,delete x.height;break}}o(ro(x)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:r,isDragging:s,loadedShapesRef:n,handleShapeDragEnd:l,handleShapeResizeEnd:u}};var hd=(e,o)=>{let t=yt(),r=ee(ge)?.texts||[],n=useRef(new Map),[s,c]=useState(null),[l,u]=useState("");return {texts:r,textRefs:n,handleDragEnd:(p,y)=>{let x=p.target;t(le()),t(wt({id:y,x:x.x(),y:x.y()})),e();},handleTransformEnd:p=>{let y=n.current.get(p);if(!y)return;let x=y.scaleX(),v=y.scaleY(),L=r.find(k=>k.id===p);if(!L)return;let I=(x+v)/2;y.scaleX(1),y.scaleY(1),t(le()),t(wt({id:p,x:y.x(),y:y.y(),width:Math.max(5,(L.width||100)*x),height:Math.max(5,(L.height||50)*v),fontSize:Math.round(Math.max(8,L.fontSize*I)),rotation:y.rotation()})),e();},handleDoubleClick:p=>{let y=r.find(x=>x.id===p);y&&!y.locked&&(c(p),u(y.text));},startEditing:p=>{let y=r.find(x=>x.id===p);y&&!y.locked&&(c(p),u(y.text));},editingTextId:s,editingValue:l,handleEditingChange:p=>{u(p);},finishEditing:()=>{if(s){let p=n.current.get(s),y=r.find(v=>v.id===s);t(le());let x={id:s,text:l};if(y&&(y.fontWeight!==void 0&&(x.fontWeight=y.fontWeight),y.fontStyle!==void 0&&(x.fontStyle=y.fontStyle),y.textDecoration!==void 0&&(x.textDecoration=y.textDecoration)),o?.current&&l.trim()){let v=o.current,L=v.offsetWidth,I=v.offsetHeight,k=1;if(p){let W=p.getStage();W&&(k=W.scaleX());}let S=14,b=(L-S)/k,A=(I-S)/k,V=l.split(`
3
+ `).length,H=r.find(W=>W.id===s)?.fontSize||24,P=V*H*1.2+10;x.width=Math.max(200,b),x.height=Math.max(50,A,P);}else if(p&&l.trim()){let v=p.text(),L=p.width();p.text(l),p.width(void 0);let I=p.width(),k=p.height();p.text(v),p.width(L),x.width=Math.max(200,I+20),x.height=Math.max(50,k+20);}t(wt(x)),c(null),u(""),t($o(null)),e();}}}};var gd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],r=useRef(new Map),n=useCallback((s,c)=>{let l=s.target;o(zo({id:c,x:l.x(),y:l.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:r,handleShortAnswerDragEnd:n}};var xd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),r=useCallback((n,s)=>{let c=n.target;o(Go({id:s,x:c.x(),y:c.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:r}};var vd=e=>{let o=xe(),a=ee(ge)?.flashcards||[],r=useRef(new Map),n=useRef(new Map),s=useCallback((d,m)=>{if(n.current.has(m))return n.current.get(m);let i=new window.Image;return i.src=d,n.current.set(m,i),i},[]),c=useCallback((d,m)=>{let i=d.target,h=i.id();a.find(p=>p.id===h)&&(o(no({id:h,x:i.x(),y:i.y()})),m?.());},[a,o]),l=useCallback((d,m)=>{let i=m.target,h=i.scaleX(),g=i.scaleY(),p=i.rotation(),y=Math.max(50,i.width()*h),x=Math.max(50,i.height()*g);i.scaleX(1),i.scaleY(1),i.width(y),i.height(x),o(no({id:d,width:y,height:x,x:i.x(),y:i.y(),rotation:p})),i.getLayer()?.batchDraw(),e?.();},[o,e]),u=useCallback(d=>{o(Bs(d)),e?.();},[o,e]),f=useCallback(d=>{o(Os(d)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:s,flashcardRefs:r,handleDragEnd:c,handleFlashcardTransformEnd:l,handleNext:u,handlePrevious:f}};var Ld=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],r=useRef(new Map),[n,s]=useState(new Map),c=useCallback((i,h)=>{console.log("handleDragEnd"),o(Pa({id:h,x:i.target.x(),y:i.target.y()})),e?.();},[o,e]),l=useCallback((i,h)=>{let g=h.target,p=g.scaleX(),y=g.scaleY(),x=g.rotation(),v=a.find(k=>k.id===i);if(!v)return;let L=Math.max(100,v.width*p),I=Math.max(100,v.height*y);g.scaleX(1),g.scaleY(1),o(Pa({id:i,width:L,height:I,x:g.x(),y:g.y(),rotation:x})),g.getLayer()?.batchDraw(),e?.();},[o,e,a]),u=useCallback(async i=>{try{let h=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return s(g=>{let p=new Map(g);return p.set(i,h),p}),o(Pa({id:i,isCapturing:!0})),e?.(),h}catch(h){return console.error("Error accessing camera:",h),null}},[o,e]),f=useCallback(i=>{let h=n.get(i);h&&(h.getTracks().forEach(g=>g.stop()),s(g=>{let p=new Map(g);return p.delete(i),p}),o(Pa({id:i,isCapturing:false})),e?.());},[n,o,e]),d=useCallback((i,h)=>{let g=document.createElement("canvas");g.width=h.videoWidth,g.height=h.videoHeight;let p=g.getContext("2d");if(p){p.drawImage(h,0,0,g.width,g.height);let y=g.toDataURL("image/jpeg",.8);return o(Pa({id:i,capturedImageUrl:y,isCapturing:false})),f(i),e?.(),y}return null},[o,f,e]),m=useRef(n);return useEffect(()=>{m.current=n;},[n]),useEffect(()=>()=>{m.current.forEach(i=>{i.getTracks().forEach(h=>h.stop());});},[]),{photoFrames:a,photoFrameRefs:r,handleDragEnd:c,handlePhotoFrameTransformEnd:l,startCamera:u,stopCamera:f,capturePhoto:d,cameraStreams:n}};var Id=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((n,s)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...s,width:Math.max(o.minWidth,Math.min(s.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(s.height,o.maxHeight))}:s,[o]),a=useCallback((n,s,c,l,u,f,d,m=[])=>{if(e.current){if(n&&!m.find(g=>g.id===n)?.isPlaying){let g=s.get(n)||c.get(n)||l.get(n)||u.get(n)||f.get(n)||(d?d.get(n):null);if(g){e.current.boundBoxFunc(t),e.current.nodes([g]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),r=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:r,boundBoxFunc:t}};var dp=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},Md=(e,o)=>{let t=yt(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let r=useCallback(()=>{if(o.current)try{let s=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});s&&s.startsWith("data:")&&t(Ts({id:a.current,thumbnail:s}));}catch(s){console.warn("Could not generate thumbnail (likely CORS issue with images):",s);}},[o,t]),n=dp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var cp=e=>e.flatMap(o=>[o[0],o[1]]),wn=(e,o)=>{let t=od(e,{size:o?.size||8,thinning:o?.thinning||.5,smoothing:o?.smoothing||.5,streamline:o?.streamline||.5,simulatePressure:o?.simulatePressure!==false,easing:a=>a,start:{taper:0,cap:true},end:{taper:0,cap:true}});return cp(t)};var Td=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null),c=ee(v=>v.toolbar.selectedTool),l=ee(v=>v.toolbar.penColor),u=ee(v=>v.toolbar.strokeWidth),f=ee(v=>v.canvas.isSketchMode),d=ee(v=>v.canvas.slides.find(I=>I.id===v.canvas.currentSlideId)?.images.find(I=>I.id===e)),m=d?.annotations||[],i=d?.isDrawingMode||false,h=d?.width||1,g=d?.height||1,p=useCallback(v=>{if(c!=="pen"&&c!=="eraser")return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/h,I=v.y/g;s({tool:c,points:[L,I],color:l,strokeWidth:u/h,isSketch:f});},[c,l,u,f,h,g]),y=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let k;if(f)k=wn(r.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,A)=>A%2===0?b/h:b/g);else {let S=v.x/h,b=v.y/g;k=[...n.points,S,b];}s(S=>S?{...S,points:k}:null);},[f,u,n,h,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(qs({imageId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:m,activeLine:n,isDrawingMode:i,startDrawing:p,draw:y,stopDrawing:x,tool:c}};var Rd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>{let{annotations:c,activeLine:l,stopDrawing:m,tool:i}=Td(e.id);useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let h=false;useEffect(()=>{return;},[m,h]);let g=x=>{{n(e.id);return}},p=x=>{return;},y=x=>{};return jsxs(Group,{listening:i!=="pen"&&i!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x){t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();let v=x.getStage()?.container();if(v){let L=I=>{let k=x.getStage()?.getPointerPosition();if(k){let S={x:e.x,y:e.y,width:e.width,height:e.height};k.x>=S.x&&k.x<=S.x+S.width&&k.y>=S.y&&k.y<=S.y+S.height&&s(I,e.id,"image");}};v.addEventListener("contextmenu",L),x._contextMenuCleanup=()=>{v.removeEventListener("contextmenu",L);};}}else {let v=t.current.get(e.id);v?._contextMenuCleanup&&v._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:i!=="pen"&&i!=="eraser",onDragEnd:a,onTransformEnd:x=>r(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...i!=="pen"&&i!=="eraser"?{onClick:g,onTap:g,onMouseDown:g,onTouchStart:g,onMouseMove:p,onTouchMove:p,onMouseUp:y,onTouchEnd:y}:{}}),c?.map((x,v)=>{let L=x.points.map((k,S)=>S%2===0?k*e.width+e.x:k*e.height+e.y),I=x.strokeWidth*e.width;return jsx(Line,{points:L,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:I,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},v)}),l&&jsx(Line,{points:l.points.map((x,v)=>v%2===0?x*e.width+e.x:x*e.height+e.y),stroke:l.tool==="eraser"?"white":l.color,strokeWidth:l.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:l.tool==="eraser"?"destination-out":"source-over",fill:l.isSketch?l.color:void 0,closed:l.isSketch,listening:false},"active")]})});Rd.displayName="ImageWithDrawing";var ci=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(c=>{let l=o(c);return l?jsx(Rd,{img:c,loadedImage:l,imageRefs:t,onDragEnd:a,onTransform:r,onSelect:n,onContextMenu:s},c.id):null})}));ci.displayName="ImageLayer";var wp=({src:e,x:o,id:t,y:a,width:r,height:n,isSelected:s,rotation:c=0,onTransformEnd:l,onDragEnd:u})=>{let f=xe(),d=useRef(null),m=i=>{f(Uo(i));};return jsxs(Group,{draggable:true,x:o,y:a,width:r,height:n,rotation:c,onDragEnd:u,onTransformEnd:l,children:[jsx(Rect,{width:r,height:n,fill:"black",stroke:s?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${r}px`,height:`${n}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:d,src:e,controls:true,autoPlay:true,onClick:()=>m(t),onSeeking:i=>i.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Ed=wp;var Ap=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,nodeRef:s})=>{let[c,l]=useState(null),u=useSelector(g=>g.toolbar.selectedTool),f=u==="pen"||u==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let g=new window.Image;g.src=e.thumbnailDataUrl,g.onload=()=>{l(g);};}},[e.thumbnailDataUrl]),!c)return null;let d=e.width/2,m=e.height/2,i=Math.min(e.width,e.height)*.08,h=Math.max(40,Math.min(i,80));return jsxs(Group,{draggable:!f,listening:!f,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...f?{}:{onDragEnd:a,onTransformEnd:r},ref:g=>{if(s(g),g){let p=g.getStage()?.container();if(p){let y=x=>{let v=g.getStage()?.getPointerPosition();if(v){let L={x:e.x,y:e.y,width:e.width,height:e.height};v.x>=L.x&&v.x<=L.x+L.width&&v.y>=L.y&&v.y<=L.y+L.height&&n(x);}};p.addEventListener("contextmenu",y),g._contextMenuCleanup=()=>{p.removeEventListener("contextmenu",y);};}}},children:[jsx(Image$1,{image:c,width:e.width,height:e.height,listening:!f,...f?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:d,y:m,radius:h,fill:"white",listening:!f,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...f?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:d,y:m,radius:h*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!f,...f?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:d+h*.1,y:m,sides:3,radius:h*.35,fill:"white",rotation:90,listening:!f,...f?{}:{onClick:t,onTap:t}})]})},Bd=Ap;var pi=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:r,onTransformEnd:n,onContextMenu:s})=>jsx(Fragment,{children:e.map(c=>jsxs(be__default.Fragment,{children:[jsx(Bd,{video:c,isSelected:!c.isPlaying&&o===c.id,onClick:()=>a(c.id),onDragEnd:l=>r(c.id,l),onTransformEnd:l=>n(c.id,l),onContextMenu:l=>s(l,c.id,"video"),nodeRef:l=>{l?t.current.set(c.id,l):t.current.delete(c.id);}}),c.isPlaying&&(()=>{let l=c.x,u=c.y;if(c.isRecorded){let f=typeof window<"u"?window.innerWidth:c.width,d=typeof window<"u"?window.innerHeight:c.height;l=(f-c.width)/2,u=(d-c.height)/2;}return jsx(Ed,{id:c.id,src:c.objectUrl,x:l,y:u,width:c.width,height:c.height,isSelected:false,rotation:c.rotation,onTransformEnd:f=>n(c.id,f),onDragEnd:f=>r(c.id,f)})})()]},c.id))}));pi.displayName="VideoLayer";var hi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:r,handleShapeDragStart:n,onContextMenu:s})=>{let c=useSelector(u=>u.toolbar.selectedTool),l=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map((u,f)=>{let d=u.id||f,m={id:u.id,x:u.x,y:u.y,rotation:u.rotation,draggable:!u.locked&&!l,listening:!l,fill:u.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(u.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},radius:u.radius||u.width/2,width:u.width,height:u.width},d);case "star":return jsx(Star,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},numPoints:5,innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},d);case "triangle":return jsx(RegularPolygon,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},sides:3,radius:u.radius||u.width/2},d);case "polygon":return jsx(RegularPolygon,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},sides:u.sides||6,radius:u.radius||u.width/2},d);case "ellipse":return jsx(Ellipse,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},radiusX:u.radiusX||u.width/2,radiusY:u.radiusY||u.height/2},d);case "ring":return jsx(Ring,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},d);case "wedge":return jsx(Wedge,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},radius:u.radius||u.width/2,angle:u.angle||60},d);case "arrow":return jsx(Arrow,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},points:u.points||[0,0,u.width,0],pointerLength:u.pointerLength||10,pointerWidth:u.pointerWidth||10,stroke:"#000000",strokeWidth:u.strokeWidth||3,fill:"transparent"},d);case "line":return jsx(Line,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},points:u.points||[0,0,u.width,0],stroke:"#000000",strokeWidth:u.strokeWidth||3,fill:"transparent"},d);case "arc":return jsx(Arc,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2,angle:u.angle||90},d);case "rectangle":default:return jsx(Rect,{ref:i=>{i?o.current.set(u.id,i):o.current.delete(u.id);},...m,draggable:!u.locked&&!l,...l?{}:{onDragStart:i=>{n?.();},onDragEnd:i=>t(u.id,i),onTransformEnd:i=>a(u.id,i),onClick:()=>r(u.id),onContextMenu:i=>{i.evt.preventDefault(),s(i.evt,u.id,"shape");}},width:u.width,height:u.height,cornerRadius:u.type==="rounded-rectangle"?10:0},d)}})})});hi.displayName="ShapeLayer";var Vd=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:r,onContextMenu:n,onDoubleClick:s,editingTextId:c})=>{let l=useSelector(f=>f.toolbar.selectedTool),u=l==="pen"||l==="eraser";return jsx(Fragment,{children:e.map(f=>{let d=f.id===c,m=f.fontWeight==="bold",i=m?Math.max(1,f.fontSize/25):0;return jsx(Text,{id:f.id,ref:h=>{h?o.current.set(f.id,h):o.current.delete(f.id);},text:f.text,x:f.x,y:f.y,width:f.width,height:f.height,rotation:f.rotation,draggable:!f.locked&&!d&&!u,listening:!u,fontSize:f.fontSize,fontFamily:f.fontFamily,fontStyle:f.fontStyle,fontWeight:f.fontWeight,textDecoration:f.textDecoration,fill:f.fill,stroke:m?f.fill:void 0,strokeWidth:i,align:f.align,wrap:"none",lineHeight:1.2,opacity:d?0:1,visible:!d,...u?{}:{onClick:()=>r(f.id),onTap:()=>r(f.id),onDblClick:()=>s(f.id),onDblTap:()=>s(f.id),onDragEnd:h=>t(h,f.id),onTransformEnd:()=>a(f.id),onContextMenu:h=>{h.evt.preventDefault();let g=h.evt;n(g,f.id,"text");}}},f.id)})})};var eh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onNext:s,onPrevious:c,nodeRef:l})=>{let[u,f]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let p=new window.Image;p.src=e.images[e.currentIndex],p.onload=()=>{f(p);};}},[e.images,e.currentIndex]),!u||e.images.length===0)return null;let d=8,m=2,i=Math.min(e.width,e.height)*.08,h=Math.max(16,Math.min(i,32)),g=15;return jsxs(Group,{id:e.id,draggable:e.draggable&&!e.locked,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,onDragEnd:a,onTransformEnd:r,ref:p=>{if(l(p),p){let y=p.getStage()?.container();if(y){let x=v=>{let L=p.getStage()?.getPointerPosition();if(L){let I={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=I.x&&L.x<=I.x+I.width&&L.y>=I.y&&L.y<=I.y+I.height&&n(v);}};y.addEventListener("contextmenu",x),p._contextMenuCleanup=()=>{y.removeEventListener("contextmenu",x);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:d,fill:"white",shadowColor:"black",shadowBlur:o?12:8,shadowOpacity:o?.3:.2,shadowOffsetX:0,shadowOffsetY:2,onClick:t,onTap:t}),jsx(Rect,{width:e.width,height:e.height,cornerRadius:d,stroke:"#E5E7EB",strokeWidth:m,listening:false}),jsx(Image$1,{x:m+4,y:m+4,image:u,width:e.width-(m+4)*2,height:e.height-(m+4)*2,cornerRadius:d-m,onClick:t,onTap:t}),jsx(Rect,{x:m,y:e.height-50,width:e.width-m*2,height:50,cornerRadius:[0,0,d-m,d-m],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:50},fillLinearGradientColorStops:[0,"rgba(255, 255, 255, 0)",1,"rgba(255, 255, 255, 0.95)"],listening:false}),e.images.length>1&&(e.order==="sequential"||e.order==="random"&&e.navigationHistory&&e.navigationHistory.length>1)&&jsxs(Group,{x:g+h,y:e.height/2,onClick:p=>{p.cancelBubble=true,c();},onTap:p=>{p.cancelBubble=true,c();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-g-h,y:e.height/2,onClick:p=>{p.cancelBubble=true,s();},onTap:p=>{p.cancelBubble=true,s();},children:[jsx(Circle,{radius:h,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},Ud=eh;var bi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onNext:s,onPrevious:c,onContextMenu:l})=>jsx(Fragment,{children:e.map(u=>jsx(Ud,{flashcard:u,isSelected:t===u.id,onClick:()=>n(u.id),onDragEnd:a,onTransformEnd:f=>r(u.id,f),onContextMenu:f=>l(f,u.id,"flashcard"),onNext:()=>s(u.id),onPrevious:()=>c(u.id),nodeRef:f=>{f?o.current.set(u.id,f):o.current.delete(u.id);}},u.id))}));bi.displayName="FlashcardLayer";var zd=e=>{let o=xe(),t=useRef(false),a=useRef(false),r=useRef([]),[n,s]=useState(null);ee(v=>v.toolbar.selectedTool);let l=ee(v=>v.toolbar.penColor),u=ee(v=>v.toolbar.strokeWidth),f=ee(v=>v.canvas.isSketchMode),d=ee(v=>v.canvas.slides.find(I=>I.id===v.canvas.currentSlideId)?.photoFrames.find(I=>I.id===e)),m=d?.annotations||[],i=d?.isDrawingMode||false,h=d?.width||1,g=d?.height||1,p=useCallback(v=>{if(!i)return;t.current=true,a.current=false,r.current=[{x:v.x,y:v.y}];let L=v.x/h,I=v.y/g;s({tool:"pen",points:[L,I],color:l,strokeWidth:u/h,isSketch:f});},[i,l,u,f,h,g]),y=useCallback(v=>{if(!t.current||!n)return;a.current=true;let L=r.current[r.current.length-1];if(Math.sqrt(Math.pow(v.x-L.x,2)+Math.pow(v.y-L.y,2))<2)return;r.current.push({x:v.x,y:v.y});let k;if(f)k=wn(r.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((b,A)=>A%2===0?b/h:b/g);else {let S=v.x/h,b=v.y/g;k=[...n.points,S,b];}s(S=>S?{...S,points:k}:null);},[f,u,n,h,g]),x=useCallback(()=>{t.current&&(n&&n.points.length>0&&o(Us({frameId:e,line:n})),s(null),t.current=false,a.current=false,r.current=[]);},[o,e,n]);return {annotations:m,activeLine:n,isDrawingMode:i,startDrawing:p,draw:y,stopDrawing:x}};var dh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:r,onContextMenu:n,onStartCamera:s,onCapture:c,cameraStream:l,nodeRef:u})=>{let[f,d]=useState(null),[m,i]=useState(null),h=useRef(null),g=useRef(null),p=useRef(null),y=useRef(null),x=useRef(0),v=33,L=useSelector(O=>O.toolbar.selectedTool),I=L==="pen"||L==="eraser",{annotations:k,activeLine:S,isDrawingMode:b,startDrawing:A,draw:V,stopDrawing:D}=zd(e.id);useEffect(()=>{if(!b)return;let O=()=>{D();},X=()=>{D();};return window.addEventListener("mouseup",O),window.addEventListener("touchend",X),()=>{window.removeEventListener("mouseup",O),window.removeEventListener("touchend",X);}},[D,b]),useEffect(()=>{if(e.capturedImageUrl){let O=new window.Image;O.src=e.capturedImageUrl,O.onload=()=>{d(O);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&l){h.current||(h.current=document.createElement("video"),h.current.autoplay=true,h.current.playsInline=true),g.current||(g.current=document.createElement("canvas"));let O=h.current,X=g.current;O.srcObject=l;let U=()=>{X.width=O.videoWidth||640,X.height=O.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",X.width,X.height);let K=Q=>{if(Q-x.current<v){p.current=requestAnimationFrame(K);return}x.current=Q;let te=X.getContext("2d");if(te&&O.readyState===O.HAVE_ENOUGH_DATA){te.drawImage(O,0,0,X.width,X.height);let J=X.toDataURL("image/jpeg",.6),de=new window.Image;de.onload=()=>{i(de);},de.src=J;}p.current=requestAnimationFrame(K);};p.current=requestAnimationFrame(K);};return O.onloadedmetadata=U,O.readyState>=O.HAVE_METADATA&&U(),O.play().catch(K=>console.error("Error playing video:",K)),()=>{p.current&&(cancelAnimationFrame(p.current),p.current=null);}}return ()=>{i(null),y.current&&(y.current.src="");}},[e.isCapturing,l]);let H=()=>{h.current&&e.isCapturing&&c(h.current);},N=O=>{if(e.capturedImageUrl){if(!b){t();return}let X=O.currentTarget,U=X.getAbsoluteTransform().copy(),Q=X.getStage()?.getPointerPosition();if(Q){U.invert();let te=U.point(Q);A(te);}O.cancelBubble=true;}else t();},P=O=>{if(!b||!e.capturedImageUrl)return;let X=O.currentTarget,U=X.getAbsoluteTransform().copy(),Q=X.getStage()?.getPointerPosition();if(Q){U.invert();let te=U.point(Q);V(te);}},W=()=>{!b||!e.capturedImageUrl||D();},E=e.isCapturing?m:f,oe=Math.min(e.width,e.height)*.12,q=Math.max(25,Math.min(oe,50)),fe=e.width/2,z=e.height/2;return jsxs(Group,{id:e.id,draggable:!b&&!I,listening:true,x:e.x,y:e.y,...I?{}:{onDragEnd:a,onTransformEnd:r},rotation:e.rotation,width:e.width,height:e.height,ref:O=>{if(u(O),O){let X=O.getStage()?.container();if(X){let U=K=>{let Q=O.getStage()?.getPointerPosition();if(Q){let te={x:e.x,y:e.y,width:e.width,height:e.height};Q.x>=te.x&&Q.x<=te.x+te.width&&Q.y>=te.y&&Q.y<=te.y+te.height&&n(K);}};X.addEventListener("contextmenu",U),O._contextMenuCleanup=()=>{X.removeEventListener("contextmenu",U);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:E?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),E&&jsx(Image$1,{image:E,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:N,onTap:N,onMouseDown:N,onTouchStart:N,onMouseMove:P,onTouchMove:P,onMouseUp:W,onTouchEnd:W,...I?{}:{onDragEnd:a,onTransformEnd:r}}),k?.map((O,X)=>{let U=O.points.map((Q,te)=>te%2===0?Q*e.width:Q*e.height),K=O.strokeWidth*e.width;return jsx(Line,{points:U,stroke:O.tool==="eraser"?"white":O.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:O.tool==="eraser"?"destination-out":"source-over",fill:O.isSketch?O.color:void 0,closed:O.isSketch,listening:false},X)}),S&&jsx(Line,{points:S.points.map((O,X)=>X%2===0?O*e.width:O*e.height),stroke:S.tool==="eraser"?"white":S.color,strokeWidth:S.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:S.tool==="eraser"?"destination-out":"source-over",fill:S.isSketch?S.color:void 0,closed:S.isSketch,listening:false},"active"),!E&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:z-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:fe-q+6,y:z-60,width:q*1.6,height:q*1.6,radius:q,fill:"white",cornerRadius:8,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?H():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:fe-12,y:z-40,width:q*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?H():s();}})})]}),jsx(Text,{x:0,y:z,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:z+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:fe-24,y:z+104,width:q*1.6,height:q*1.6,radius:q,fill:"#096B76",cornerRadius:q,listening:true,onClick:O=>{O.cancelBubble=true,e.isCapturing?H():s();},onTap:O=>{O.cancelBubble=true,e.isCapturing?H():s();}}),jsx(Html,{groupProps:{x:fe-8,y:z+120,width:q*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:O=>{O.stopPropagation(),e.isCapturing?H():s();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"})]})]})},jd=dh;var Ii=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:r,onSelect:n,onStartCamera:s,onCapture:c,cameraStreams:l,onContextMenu:u})=>jsx(Fragment,{children:e.map(f=>jsx(jd,{photoFrame:f,isSelected:t===f.id,onClick:()=>n(f.id),onDragEnd:d=>a(d,f.id),onTransformEnd:d=>r(f.id,d),onContextMenu:d=>u(d,f.id,"photoFrame"),onStartCamera:()=>s(f.id),onCapture:d=>c(f.id,d),cameraStream:l.get(f.id),nodeRef:d=>{d?o.current.set(f.id,d):o.current.delete(f.id);}},f.id))}));Ii.displayName="PhotoFrameLayer";var Jd=({x:e,y:o,onAction:t,onClose:a,type:r,elementId:n="",isDrawingMode:s,menuRef:c})=>{useEffect(()=>{let d=i=>{c?.current&&!c.current.contains(i.target)&&a();},m=i=>{i.key==="Escape"&&a();};return document.addEventListener("mousedown",d),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",m);}},[a]);let l=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:s?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(m=>!(m.showForTypes&&!m.showForTypes.includes(r)||m.hideForTypes&&m.hideForTypes.includes(r))),[r,s]),u=(d,m)=>{d==="order"||d==="lock"?t(d,m):(t(d),a());},f=jsx("div",{ref:c,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:l.map((d,m)=>jsxs("button",{onClick:i=>u(d.action,i),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${d.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[d.icon,jsx("span",{className:`font-medium ${d.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:d.label})]}),d.hasSubmenu&&jsx("svg",{className:"h-4 w-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},m))})});return createPortal(f,document.body)};var Zd=({x:e,y:o,items:t,onClose:a})=>{let r=useRef(null);return useEffect(()=>{let n=s=>{r.current&&!r.current.contains(s.target)&&a();};return document.addEventListener("mousedown",n),()=>{document.removeEventListener("mousedown",n);}},[a]),jsx("div",{ref:r,className:"fixed z-101 min-w-[180px] rounded-lg border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"py-2",children:t.map((n,s)=>jsx("button",{onClick:()=>{n.onClick(),a();},className:"flex w-full items-center px-4 py-2.5 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50",children:jsx("span",{className:"font-medium",children:n.label})},s))})})};var Qd=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:r,onClose:n})=>{let[s,c]=useState(a),l=useRef(null);useEffect(()=>{l.current?.focus();},[]);let u=()=>{r(s),n();};return jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:e}),jsx("button",{onClick:n,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:l,type:"text",value:s,onChange:d=>c(d.target.value),onKeyDown:d=>{d.key==="Enter"?u():d.key==="Escape"&&n();},placeholder:t,className:"w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 focus:outline-none"})]}),jsxs("div",{className:"flex justify-end gap-3",children:[jsx("button",{onClick:n,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:u,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 eu=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,r]=useState(e),n=useRef(null);useEffect(()=>{let f=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let s=f=>{f.preventDefault(),o(a);},c=(f,d,m)=>{m/=100;let i=d*Math.min(m,1-m)/100,h=g=>{let p=(g+f/30)%12,y=m-i*Math.max(Math.min(p-3,9-p,1),-1);return Math.round(255*y).toString(16).padStart(2,"0")};return `#${h(0)}${h(8)}${h(4)}`},u=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:n,className:"pointer-events-auto max-h-[90vh] w-96 max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Change Shape Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:s,children:[jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-16 w-16 rounded-lg border-2 border-gray-300 shadow-sm",style:{backgroundColor:a}}),jsxs("div",{className:"flex-1",children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HEX COLOR"}),jsx("input",{type:"text",value:a,onChange:f=>r(f.target.value),className:"w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none",placeholder:"#000000"})]})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"COLOR PICKER"}),jsx("input",{type:"color",value:a,onChange:f=>r(f.target.value),className:"h-12 w-full cursor-pointer rounded-lg border border-gray-300"})]}),jsxs("div",{children:[jsx("label",{className:"mb-1 block text-xs font-semibold text-gray-500",children:"HUE SLIDER"}),jsx("input",{type:"range",min:"0",max:"360",defaultValue:"180",onChange:f=>{let d=parseInt(f.target.value),m=c(d,100,50);r(m);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"].map(f=>jsx("button",{type:"button",onClick:()=>r(f),className:`h-8 w-8 rounded-lg border-2 transition-all hover:scale-110 ${a.toUpperCase()===f.toUpperCase()?"border-blue-500 ring-2 ring-blue-200":"border-gray-300"}`,style:{backgroundColor:f},title:f},f))})]})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",className:"flex-1 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:"Apply Color"})]})]})]})});return createPortal(u,document.body)};var _h=({imageSrc:e,onCrop:o})=>{let[t]=ou(e),a=useRef(null),r=useRef(null),n=useRef(null),s=useMemo(()=>{if(!t)return {width:600,height:400};let h=Math.min(600/t.width,400/t.height);return {width:t.width*h,height:t.height*h}},[t]),c=useMemo(()=>{let m=s.width*.5,i=s.height*.5,h=(s.width-m)/2,g=(s.height-i)/2;return {x:h,y:g,width:m,height:i}},[s]),[l,u]=useState(c);useEffect(()=>{u(c);},[c]),useEffect(()=>{n.current&&r.current&&(n.current.nodes([r.current]),n.current.getLayer()?.batchDraw());},[l]),useEffect(()=>{o(l.x,l.y,l.width,l.height);},[l,o]);let f=()=>{let m=r.current;if(!m)return;let i=m.scaleX(),h=m.scaleY();m.scaleX(1),m.scaleY(1),u({x:m.x(),y:m.y(),width:Math.max(20,m.width()*i),height:Math.max(20,m.height()*h)});},d=()=>{let m=r.current;m&&u({x:m.x(),y:m.y(),width:m.width(),height:m.height()});};return jsx(Stage,{width:s.width,height:s.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:s.width,height:s.height}),jsx(Rect,{x:0,y:0,width:s.width,height:s.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:l.x,y:l.y,width:l.width,height:l.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:r,x:l.x,y:l.y,width:l.width,height:l.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:d,onTransformEnd:f,dragBoundFunc:m=>{let i=Math.max(0,Math.min(m.x,s.width-l.width)),h=Math.max(0,Math.min(m.y,s.height-l.height));return {x:i,y:h}}}),jsx(Transformer,{ref:n,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:false,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(m,i)=>i.width<20||i.height<20||i.x<0||i.y<0||i.x+i.width>s.width||i.y+i.height>s.height?m:i})]})})},ru=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[r,n]=useState({x:0,y:0,width:0,height:0}),[s]=ou(e);return useEffect(()=>{let f=d=>{d.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]),createPortal(jsx("div",{className:"bg-opacity-50 pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black",onMouseDown:f=>f.stopPropagation(),onMouseUp:f=>f.stopPropagation(),onMouseMove:f=>f.stopPropagation(),onTouchStart:f=>f.stopPropagation(),onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation(),children:jsxs("div",{ref:a,className:"pointer-events-auto max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{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(_h,{imageSrc:e,onCrop:(f,d,m,i)=>{n({x:f,y:d,width:m,height:i});}})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:()=>{if(!s)return;let m=Math.min(600/s.width,400/s.height),i=r.x/m,h=r.y/m,g=r.width/m,p=r.height/m,y=document.createElement("canvas");y.width=g,y.height=p;let x=y.getContext("2d");if(!x)return;x.drawImage(s,i,h,g,p,0,0,g,p);let v=y.toDataURL("image/png");o(v);},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-600",children:[jsx(Check,{size:16,weight:"bold"}),"Crop Image"]})]})]})}),document.body)};var rr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[r,n]=useState(false),[s,c]=useState(null),[l,u]=useState(0),[f,d]=useState(true),m=useRef(null),i=useRef([]),h=useRef(null),g=useRef(null),p=useRef(null),y=useRef(null),x=useRef(null),v=useRef(null);useEffect(()=>()=>{p.current&&cancelAnimationFrame(p.current),h.current&&clearInterval(h.current),g.current&&g.current.getTracks().forEach(b=>b.stop());},[]);let L=async()=>{try{let b,A=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let P=o.current.getLayers();console.log("Konva layers:",P.length),P.forEach((X,U)=>{let K=X.getChildren();console.log(`Layer ${U} children count:`,K.length);});let W=document.createElement("canvas");W.width=o.current.width(),W.height=o.current.height();let E=W.getContext("2d",{willReadFrequently:!1});if(!E){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",W.width,"x",W.height),x.current=W;let oe=()=>{if(E.clearRect(0,0,W.width,W.height),P.forEach(X=>{let U=X.getCanvas()._canvas;U&&E.drawImage(U,0,0);}),a?.current){let X=a.current;E.drawImage(X,0,0);}};v.current=oe,o.current.draw(),oe(),await new Promise(X=>setTimeout(X,100)),console.log("Creating captureStream..."),b=W.captureStream(30),console.log("Canvas stream created, tracks:",b.getTracks().length);let fe=b.getVideoTracks()[0];fe&&console.log("Video track:",fe.label,"state:",fe.readyState);let z=0,O=()=>{oe(),o?.current&&(o.current.getLayers().forEach(U=>{U.batchDraw();}),z++,z%60===0&&console.log("Drawing frame:",z)),p.current=requestAnimationFrame(O);};O();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{A=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(P){console.warn("Microphone access denied:",P);}let V=[...b.getVideoTracks()];A&&V.push(...A.getAudioTracks());let D=new MediaStream(V);g.current=D;let H="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?H="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?H="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?H="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(H="video/webm;codecs=vp8"),console.log("Using mimeType:",H);let N=new MediaRecorder(D,{mimeType:H,videoBitsPerSecond:25e5});m.current=N,i.current=[],N.ondataavailable=P=>{console.log("Data available, size:",P.data.size),P.data.size>0&&i.current.push(P.data);},N.onstop=()=>{console.log("Recording stopped, chunks:",i.current.length);let P=new Blob(i.current,{type:H});console.log("Final blob size:",P.size),o?.current&&v.current&&x.current&&(o.current.draw(),o.current.getLayers().forEach(E=>{E.batchDraw();}),v.current(),y.current=x.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",y.current.length)),D.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current),p.current&&(cancelAnimationFrame(p.current),p.current=null),c(P);},N.onerror=P=>{console.error("MediaRecorder error:",P);},console.log("Starting recording..."),N.start(1e3),n(!0),u(0),h.current=setInterval(()=>{u(P=>P+1);},1e3);}catch(b){console.error("Error starting screen recording:",b),alert("Failed to start recording. Please ensure you granted permission.");}},I=()=>{m.current&&r&&(console.log("Stopping recording, state:",m.current.state),m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),n(false));},k=()=>{if(s){let b=URL.createObjectURL(s),A=document.createElement("a");A.href=b,A.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(b);}},S=b=>{let A=Math.floor(b/60),V=b%60;return `${A.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return r?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:I,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!s&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>d(!f),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${f?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:f?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:L,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),s&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(s),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",S(l)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&s&&y.current&&(t(s,y.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:k,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:()=>{c(null),u(0);},className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Re-record"})]})]})]})]}),jsx("div",{className:"rounded-lg border border-[#A7B7D6] bg-blue-50 p-3",children:jsxs("p",{className:"text-start text-sm text-blue-900",children:[jsx("strong",{children:"Tip:"})," The canvas will be recorded automatically. The modal will disappear during recording so you can freely draw and edit."]})})]})})};var su=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:r})=>{let[n,s]=useState(false),[c,l]=useState(null),[u,f]=useState(false),[d,m]=useState(0),i=useRef(null),h=useRef([]),g=useRef(null),p=useRef(null);useEffect(()=>{o&&!c&&fetch(o).then(b=>b.blob()).then(b=>l(b)).catch(b=>console.error("Error loading audio:",b));},[o,c]);let y=async()=>{try{let b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),A=new MediaRecorder(b);i.current=A,h.current=[],A.ondataavailable=V=>{V.data.size>0&&h.current.push(V.data);},A.onstop=()=>{let V=new Blob(h.current,{type:"audio/webm"});l(V),b.getTracks().forEach(D=>D.stop()),g.current&&clearInterval(g.current);},A.start(),s(!0),m(0),g.current=setInterval(()=>{m(V=>V+1);},1e3);}catch(b){console.error("Error starting audio recording:",b),alert("Failed to start recording. Please allow microphone access.");}},x=()=>{i.current&&n&&(i.current.stop(),s(false));},v=()=>{if(c){let b=URL.createObjectURL(c),A=new Audio(b);p.current=A,A.onended=()=>{f(false),URL.revokeObjectURL(b);},A.play(),f(true);}},L=()=>{p.current&&(p.current.pause(),p.current.currentTime=0,f(false));},I=async()=>{if(c){let b=new FileReader;b.onloadend=()=>{let A=b.result;t(A),r();},b.readAsDataURL(c);}},k=()=>{l(null),a();},S=b=>{let A=Math.floor(b/60),V=b%60;return `${A.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};return n?jsxs("div",{className:"fixed top-4 left-1/2 z-103 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:S(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:x,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-103 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-sm rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-6",children:[jsxs("h3",{className:"text-lg font-semibold text-gray-900",children:["Record Audio for"," ",e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g," $1")]}),jsx("p",{className:"text-sm text-gray-600",children:"Record a voice note for this element"})]}),jsxs("div",{className:"flex flex-col gap-4",children:[!c&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:y,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),c&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:u?L:v,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),u?"Playing...":"Play Audio"]}),jsx("button",{onClick:k,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:I,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:r,className:"w-full rounded-lg bg-[#0000000A] p-3 text-base font-semibold text-[#00000099] transition-colors hover:cursor-pointer hover:bg-[#0000001A]",children:"Cancel"})]})]})})};var It=({audioData:e,x:o,y:t,width:a})=>{let[r,n]=useState(false),s=useRef(null);return jsx("button",{onClick:l=>{if(l.stopPropagation(),r&&s.current)s.current.pause(),s.current.currentTime=0,n(false);else {let u=new Audio(e);s.current=u,u.onended=()=>{n(false);},u.onerror=()=>{console.error("Error playing audio"),n(false);},u.play(),n(true);}},className:`absolute flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${r?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${o+a-35}px`,top:`${t+5}px`,width:"30px",height:"30px",zIndex:99},title:r?"Stop Audio":"Play Audio",children:r?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var du=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),r=ee(ge),n=useMemo(()=>{if(!r)return [];let g=[];return r.images?.forEach(p=>{g.push({id:p.id,type:"image",name:"Image",timestamp:p.timestamp||0});}),r.videos?.forEach(p=>{g.push({id:p.id,type:"video",name:"Video",timestamp:p.timestamp||0});}),r.shapes?.forEach(p=>{g.push({id:p.id,type:"shape",name:`${p.type} Shape`,timestamp:p.timestamp||0});}),r.texts?.forEach(p=>{g.push({id:p.id,type:"text",name:p.text.substring(0,20)+(p.text.length>20?"...":""),timestamp:p.timestamp||0});}),r.flashcards?.forEach(p=>{g.push({id:p.id,type:"flashcard",name:`Flashcard (${p.images.length} images)`,timestamp:p.timestamp||0});}),r.photoFrames?.forEach(p=>{g.push({id:p.id,type:"photoFrame",name:"Photo Frame",timestamp:p.timestamp||0});}),r.multipleChoices?.forEach(p=>{g.push({id:p.id,type:"mcq",name:"Multiple Choice",timestamp:p.timestamp||0});}),r.trueFalses?.forEach(p=>{g.push({id:p.id,type:"trueFalse",name:"True/False",timestamp:p.timestamp||0});}),r.shortAnswers?.forEach(p=>{g.push({id:p.id,type:"shortAnswer",name:"Short Answer",timestamp:p.timestamp||0});}),r.LongAnswer?.forEach(p=>{g.push({id:p.id,type:"longAnswer",name:"Long Answer",timestamp:p.timestamp||0});}),r.fillInTheBlanks?.forEach(p=>{g.push({id:p.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:p.timestamp||0});}),r.lines?.forEach(p=>{p.id&&g.push({id:p.id,type:"line",name:"Drawn Line",timestamp:p.timestamp||0});}),g.sort((p,y)=>y.timestamp-p.timestamp)},[r]),[s,c]=useState(n),[l,u]=useState(false);useEffect(()=>{l||c(n);},[n]);let f=g=>{let p="h-5 w-5";switch(g){case "image":return jsx(Image$3,{className:p});case "video":return jsx(VideoCamera,{className:p});case "shape":return jsx(Shapes$1,{className:p});case "text":return jsx(TextT,{className:p});case "flashcard":return jsx(Cards$1,{className:p});case "photoFrame":return jsx(FrameCorners,{className:p});case "line":return jsx("span",{className:p,children:"\u270F\uFE0F"});default:return jsx(Question,{className:p})}},d=g=>{if(g===0)return;let p=s[g],y=s[g-1];a(jo({id:p.id,type:p.type,newTimestamp:y.timestamp+1}));},m=g=>{if(g===s.length-1)return;let p=s[g],y=s[g+1];a(jo({id:p.id,type:p.type,newTimestamp:y.timestamp-1}));},i=g=>{u(true),c(g);},h=()=>{u(false);let g=Date.now();s.forEach((p,y)=>{let x=g-y;a(jo({id:p.id,type:p.type,newTimestamp:x}));});};return jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9998 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-9999 w-96 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-gray-200 bg-white shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 p-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(Stack$1,{className:"h-5 w-5 text-gray-700",weight:"bold"}),jsx("h3",{className:"font-semibold text-gray-900",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto p-2",children:s.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:s,onReorder:i,className:"space-y-1",children:s.map((g,p)=>{let y=g.id===e;return jsxs(Reorder.Item,{value:g,onDragEnd:h,className:`flex cursor-grab items-center gap-2 rounded-lg p-2 transition-colors active:cursor-grabbing ${y?"border border-blue-200 bg-blue-50":"border border-transparent hover:bg-gray-50"}`,whileDrag:{scale:1.02,boxShadow:"0 8px 20px rgba(0,0,0,0.15)",backgroundColor:"white",zIndex:50},children:[jsx("div",{className:"text-gray-400",children:jsx(DotsSixVertical,{className:"h-4 w-4",weight:"bold"})}),jsxs("div",{onClick:()=>t(g.id,g.type),className:"flex flex-1 cursor-pointer items-center gap-2",children:[jsx("div",{className:`${y?"text-blue-600":"text-gray-600"}`,children:f(g.type)}),jsx("span",{className:`text-sm ${y?"font-medium text-blue-900":"text-gray-700"}`,children:g.name})]}),jsxs("div",{className:"flex gap-1",children:[jsx("button",{onClick:x=>{x.stopPropagation(),d(p);},disabled:p===0,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move up (forward)",children:jsx(ArrowUp,{className:"h-4 w-4"})}),jsx("button",{onClick:x=>{x.stopPropagation(),m(p);},disabled:p===s.length-1,className:"rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-30",title:"Move down (backward)",children:jsx(ArrowDown,{className:"h-4 w-4"})})]})]},g.id)})})}),jsx("div",{className:"border-t border-gray-200 p-3 text-xs text-gray-500",children:jsx("p",{children:"Drag to reorder \u2022 Top layers appear above bottom layers"})})]})]})};var uu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>{let s=useSelector(z=>z.toolbar.selectedTool),c=s==="pen"||s==="eraser",[l,u]=useState(new Set),[f,d]=useState(false),[m,i]=useState(null),h=useRef(null);useEffect(()=>{let z=h.current;if(z)return a.current.set(e.id,z),()=>{a.current.delete(e.id);}},[e.id]);let g=new Set(e.data.responseOptions.correctIndex),p=g.size>1,y=z=>{f||u(p?O=>{let X=new Set(O);return X.has(z)?X.delete(z):X.add(z),X}:new Set([z]));},x=()=>{l.size>0&&d(true);},v=()=>{d(false),u(new Set);},L=l.size===g.size&&Array.from(l).every(z=>g.has(z)),I=Array.from(l).filter(z=>g.has(z)),k=p&&I.length>0&&!L,S=()=>L?"\u2713 Correct! Great job! \u{1F389}":k?`\u26A0 Partially correct (${I.length}/${g.size})`:"\u2717 Try again!",b=()=>L?{bg:"#dcfce7",text:"#166534"}:k?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},A=55,V=8,D=24,H=60,N=60,P=p&&!f?25:0,W=e.data.feedbackMode==="practice"?48:0,E=12,oe=H+P+(f?N:0),q=e.data.responseOptions.options.length*(A+V),fe=oe+q+E+W+D;return jsxs(Group,{ref:h,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:r,onClick:z=>t(e.id),onTap:z=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:fe,width:e.width,onTransformEnd:z=>o(e.id,z),onContextMenu:z=>{z.cancelBubble=true,n(z.evt,e.id,"mcq");}}),jsx(Text,{x:D+8,y:D,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-D*2,listening:false}),p&&!f&&e.data.feedbackMode==="practice"?jsx(Text,{x:D,y:D+35,text:`Select ${g.size} answers (${l.size}/${g.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-D*2,listening:false}):null,f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:D+24,y:H+P,width:e.width-D*2-40,height:N-20,fill:b().bg,cornerRadius:8}),jsx(Text,{x:D,y:H+P,width:e.width-D*2,height:N-20,text:S(),fontSize:16,fontStyle:"bold",fill:b().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((z,O)=>{let X=g.has(O),U=l.has(O),K=oe+O*(A+V),Q="#e5e7eb",te="#ffffff",J="#111827";return f&&X?(Q="#22c55e",te="#dcfce7",J="#1B9D2C"):f&&U&&!X?(Q="#ef4444",te="#fee2e2",J="#ef4444"):U&&(Q="#096B76",te="#ECFFF8",J="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:D+12,y:K+(A-20)/2,width:20,height:20,fill:U?"#096B76":"white",stroke:U?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:p?4:10,onClick:de=>{de.cancelBubble=true,y(O);},onTap:de=>{de.cancelBubble=true,y(O);}}),U&&jsx(Text,{x:D+12,y:K+(A-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:D+44,y:K,width:e.width-D*2-60,height:A,fill:te,stroke:Q,strokeWidth:2,cornerRadius:8,onClick:de=>{de.cancelBubble=true,y(O);},onTap:de=>{de.cancelBubble=true,y(O);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:A,text:z,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},O)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:oe+e.data.responseOptions.options.length*(A+V)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,i("check");},onMouseUp:z=>{z.cancelBubble=true,i(null),x();},onMouseLeave:z=>{z.cancelBubble=true,i(null);},onTouchStart:z=>{z.cancelBubble=true,i("check");},onTouchEnd:z=>{z.cancelBubble=true,i(null),x();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:D+14,width:(e.width-D*2-24)/(f?2:1),height:48,fill:l.size===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:D+14,width:(e.width-D*2-24)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-D*2)/2+8,onMouseDown:()=>i("reset"),onMouseUp:()=>{i(null),v();},onMouseLeave:()=>i(null),onTouchStart:()=>i("reset"),onTouchEnd:()=>{i(null),v();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:D,width:(e.width-D*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:D,width:(e.width-D*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});uu.displayName="MultipleChoice";var cu=uu;var Mi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:r})=>{let n=useDispatch(),s=useSelector(U=>U.toolbar.selectedTool),c=s==="pen"||s==="eraser",[l,u]=useState(false),[f,d]=useState(new Set),[m,i]=useState(false),[h,g]=useState(false),[p,y]=useState(0),x=340,v=100,L=window.innerWidth*.4,I=window.innerHeight*.5,k=x+20,S=v+60,b=L-40,A=I-300,V=useRef(null);useEffect(()=>{let U=V.current;if(U)return r.current.set(e.id,U),()=>{r.current.delete(e.id);}},[e.id]);let D=U=>{n(ia({id:e.id,x:U.target.x(),y:U.target.y()}));},H=U=>{let K=U.target,Q=K.x(),te=K.y(),J=window.innerWidth*.2,Y=Q+J>k&&Q<k+b&&te+50>S&&te<S+A;u(Y);},N=(U,K)=>{let Q=K.target,te=Q.x(),J=Q.y(),de=window.innerWidth*.2,Me=te+de>k&&te<k+b&&J+50>S&&J<S+A;d(Me?Re=>new Set(Re).add(U):Re=>{let Se=new Set(Re);return Se.delete(U),Se}),u(false);},P=()=>{i(true);},W=()=>{i(false),d(new Set),y(U=>U+1);},E=new Set(e.data.responseOptions.correctIndex),oe=f.size===E.size&&Array.from(f).every(U=>E.has(U)),q=Array.from(f).filter(U=>E.has(U)),fe=q.length>0&&!oe,z=()=>oe?"\u2713 Correct! Great job!":fe?`\u26A0 Partially correct (${q.length}/${E.size})`:"\u2717 Try again!",O=()=>oe?{bg:"#dcfce7",text:"#166534"}:fe?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},X=()=>m?oe?"#4CAF50":fe?"#f59e0b":"#ef4444":l?"#4CAF50":"#075560";return jsxs(Group,{ref:V,name:"mcq-element",width:L,height:I,draggable:!c,listening:!c,...c?{}:{onClick:U=>a(e.id),onTap:U=>a(e.id),onContextMenu:U=>{U.evt.preventDefault(),o(U.evt,e.id,"mcq");}},children:[jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:D,children:[jsx(Rect,{fill:"white",stroke:l?"#4CAF50":"#e5e7eb",strokeWidth:l?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?I-100:I-50,width:L,shadowColor:l?"#4CAF50":"transparent",shadowBlur:l?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:b,height:A,fill:"#EBF6F7",stroke:X(),strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:A+18,width:b-5,height:60,fill:O().bg,cornerRadius:8}),jsx(Text,{x:20,y:A+20,width:b,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:O().text,align:"center",verticalAlign:"middle"})]}),f.size===0&&!m&&jsx(Text,{x:20,y:60,width:b,height:A-60,text:E.size>1?`Drop ${E.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:m?I-200:I-160,children:[jsxs(Group,{onMouseDown:()=>{g(true),P();},onMouseUp:()=>g(false),onMouseLeave:()=>g(false),onTouchStart:()=>{g(true),P();},onTouchEnd:()=>g(false),scaleX:h?.95:1,scaleY:h?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:W,onTouchStart:W,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:b}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:b,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((U,K)=>{let Q=K%2,te=Math.floor(K/2),J=window.innerWidth*.2,de=50,Y=10,Me=f.has(K),Re=E.has(K),Se=m&&Me,Dt="transparent";return Se?Dt=Re?"#4CAF50":"#ef4444":Me&&(Dt="#4CAF50"),jsxs(Group,{x:340+Q*(J+Y),y:v+I-80+te*(de+Y),draggable:!m,onDragMove:H,onDragEnd:Za=>N(K,Za),opacity:m&&!Me?.5:1,children:[jsx(Rect,{width:J-20,height:de,fill:"white",stroke:Dt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:J-20,height:de,text:U,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${p}`)})]})};Mi.displayName="MultipleChoiceDragAndDrop";var fu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(cu,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:c=>r(c,s.id),onContextMenu:n},s.id):jsx(Mi,{multipleChoice:s,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:n},s.id))});var mu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(E=>E.toolbar.selectedTool),c=s==="pen"||s==="eraser",[l,u]=useState(null),[f,d]=useState(false),[m,i]=useState(null),h=useRef(null);useEffect(()=>{let E=h.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id]);let g=()=>{l!==null&&d(true);},p=()=>{d(false),u(null);},y=e.data.responseOptions.correctAnswer,x=l===y,v=E=>{f||u(E);},L=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",I=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},k=70,S=12,b=24,A=60,V=60,D=e.data.feedbackMode==="practice"?48:0,H=12,N=A+(f?V:0),P=2*(k+S),W=N+P+H+D+b;return jsxs(Group,{ref:h,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:E=>n(E,e.id),onClick:E=>t(e.id),onTap:E=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:W-20,width:e.width,onTransformEnd:E=>o(e.id,E),onContextMenu:E=>{E.cancelBubble=true,r(E.evt,e.id,"trueFalse");}}),jsx(Text,{x:b,y:b,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2,listening:false}),f&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:b,y:A,width:e.width-b*2,height:V-10,fill:I().bg,cornerRadius:8}),jsx(Text,{x:b,y:A,width:e.width-b*2,height:V-10,text:L(),fontSize:16,fontStyle:"bold",fill:I().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((E,oe)=>{let q=y===E.value,fe=l===E.value,z=(e.width-b*3)/2,O=b+oe*(z+b),X=N,U=E.value===true,K=U?"#10b981":"#ef4444",Q="#ffffff",te="#ffffff",J="#e5e7eb";return f&&(q?(te=U?"#f0fdf4":"#fef2f2",J=U?"#86efac":"#fecaca"):fe&&!q&&(te="#fee2e2",J="#ef4444")),fe&&!f&&(J="#096B76",te="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:O,y:X,width:z,height:k+50,fill:te,stroke:J,strokeWidth:2,cornerRadius:12,onClick:de=>{de.cancelBubble=true,v(E.value);},onTap:de=>{de.cancelBubble=true,v(E.value);}}),jsx(Circle,{x:O+z/2,y:X+40,radius:28,fill:K,listening:false}),U?jsx(Text,{x:O+z/2-14,y:X+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Q,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:O+z/2-14,y:X+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:Q,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:O,y:X+85,width:z,height:30,text:E.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},E.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:N+2*(k+S),children:[jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,i("check");},onMouseUp:E=>{E.cancelBubble=true,i(null),g();},onMouseLeave:E=>{E.cancelBubble=true,i(null);},onTouchStart:E=>{E.cancelBubble=true,i("check");},onTouchEnd:E=>{E.cancelBubble=true,i(null),g();},scaleX:m==="check"?.95:1,scaleY:m==="check"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,fill:l===null||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-b*2)/2+8,onMouseDown:()=>i("reset"),onMouseUp:()=>{i(null),p();},onMouseLeave:()=>i(null),onTouchStart:()=>i("reset"),onTouchEnd:()=>{i(null),p();},scaleX:m==="reset"?.95:1,scaleY:m==="reset"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});mu.displayName="TrueFalse";var pu=mu;var Gg="#FFFFFF",Pi=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),r=useSelector(K=>K.toolbar.selectedTool),n=r==="pen"||r==="eraser",[s,c]=useState(false),[l,u]=useState(null),[f,d]=useState(false),[m,i]=useState(false),[h,g]=useState(0),[p,y]=useState(false),x=340,v=100,L=window.innerWidth*.4,I=window.innerHeight*.5,k=L-40,S=I-300,b=20,A=60,V=k,D=S,H=L*.2-40,N=50,P=useRef(null),W=K=>{a(la({id:e.id,x:K.target.x(),y:K.target.y()}));},E=K=>{let Q=K.target,te=Q.x(),J=Q.y(),de=Math.max(0,Math.min(te+H,b+V)-Math.max(te,b)),Y=Math.max(0,Math.min(J+N,A+D)-Math.max(J,A)),Me=de*Y,Re=H*N;c(Me/Re>=.5);},oe=(K,Q)=>{let te=Q.target,J=te.x(),de=te.y(),Y=Math.max(0,Math.min(J+H,b+V)-Math.max(J,b)),Me=Math.max(0,Math.min(de+N,A+D)-Math.max(de,A)),Re=Y*Me,Se=H*N;if(Re/Se>=.5)u(K);else return;c(false);},q=()=>{d(true);},fe=()=>{d(false),u(null),g(K=>K+1);},z=e.data.responseOptions.correctAnswer,O=l===z,X=()=>O?"\u2713 Correct! Great job!":"\u2717 Try again!",U=()=>O?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:P,name:"trueFalse-element",width:L,height:I,draggable:!n,listening:!n,...n?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:v,rotation:e.rotation,onDragEnd:W,children:[jsx(Rect,{fill:"white",stroke:s?"#4CAF50":"#e5e7eb",strokeWidth:s?4:2,cornerRadius:12,height:f?I:e.data.feedbackMode==="practice"?I-50:I-100,width:L,shadowColor:s?"#4CAF50":"transparent",shadowBlur:s?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:k,height:S,fill:"transparent",stroke:s?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:k,height:60,fill:U().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:k,height:60,text:X(),fontSize:18,fontStyle:"bold",fill:U().text,align:"center",verticalAlign:"middle"})]}),l===null&&!f&&jsx(Text,{x:20,y:60,width:k,height:S-60,text:"Drop Your Answer Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:I-100,children:[jsxs(Group,{onMouseDown:()=>{l!==null&&(i(true),q());},onMouseUp:()=>i(false),onMouseLeave:()=>i(false),onTouchStart:()=>{l!==null&&(i(true),q());},onTouchEnd:()=>i(false),scaleX:m?.95:1,scaleY:m?.95:1,children:[jsx(Rect,{fill:l===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{y:50,onMouseDown:fe,onTouchStart:fe,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:k}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:k,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,Q)=>{let te=window.innerWidth*.2,J=50,de=10,Y=l===K.value,Me=z===K.value,Re=f&&Y,Se="transparent";return Re?Se=Me?"#4CAF50":"#ef4444":Y&&(Se="#4CAF50"),jsxs(Group,{x:16+Q*(te+de),y:v+I-300,draggable:!f,onDragMove:E,onDragEnd:Dt=>oe(K.value,Dt),opacity:f&&!Y?.5:1,children:[jsx(Rect,{width:te-40,height:J,fill:"#075560",stroke:Se,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:te-40,height:J,text:K.label,fontSize:18,fontStyle:"bold",fill:Gg,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${h}`)})]})})};Pi.displayName="TrueFalseDragAndDrop";var hu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(s=>s.data.responseType==="classic"?jsx(pu,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n,handleDragEnd:r},s.id):jsx(Pi,{trueFalse:s,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:n},s.id))});var fa=new WeakMap,vo=new WeakMap,ur={current:[]},Ri=false,dr=0,lr=new Set,Rn=new Map;function gu(e){let o=Array.from(e).sort((t,a)=>t instanceof Vt&&t.options.deps.includes(a)?1:a instanceof Vt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(ur.current.includes(t))continue;ur.current.push(t),t.recompute();let a=vo.get(t);if(a)for(let r of a){let n=fa.get(r);n&&gu(n);}}}function jg(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function $g(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function En(e){if(dr>0&&!Rn.has(e)&&Rn.set(e,e.prevState),lr.add(e),!(dr>0)&&!Ri)try{for(Ri=!0;lr.size>0;){let o=Array.from(lr);lr.clear();for(let t of o){let a=Rn.get(t)??t.prevState;t.prevState=a,jg(t);}for(let t of o){let a=fa.get(t);a&&(ur.current.push(t),gu(a));}for(let t of o){let a=fa.get(t);if(a)for(let r of a)$g(r);}}}finally{Ri=false,ur.current=[],Rn.clear();}}function ut(e){dr++;try{e();}finally{if(dr--,dr===0){let o=lr.values().next().value;o&&En(o);}}}function xu(e){return typeof e=="function"}var _t=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var r,n;this.listeners.add(a);let s=(n=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:n.call(r,a,this);return ()=>{this.listeners.delete(a),s?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,r;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):xu(o)?this.state=o(this.prevState):this.state=o,(r=(a=this.options)==null?void 0:a.onUpdate)==null||r.call(a),En(this);}};var Vt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),r=new Array(t);for(let n=0;n<t;n++){let s=this.options.deps[n];a[n]=s.prevState,r[n]=s.state;}return this.lastSeenDepValues=r,{prevDepVals:a,currDepVals:r,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let r=this.getDepVals();this.state=this.options.fn(r),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let n of this.options.deps)n instanceof e&&n.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:r}=this.getDepVals();for(let n=0;n<r.length;n++)if(r[n]!==a[n]){t=true;break}t&&this.recompute();},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(let t of this._subscriptions)t();}),this.subscribe=t=>{var a,r;this.listeners.add(t);let n=(r=(a=this.options).onSubscribe)==null?void 0:r.call(a,t,this);return ()=>{this.listeners.delete(t),n?.();}},this.options=o,this.state=o.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals});}registerOnGraph(o=this.options.deps){for(let t of o)if(t instanceof e)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof _t){let a=fa.get(t);a||(a=new Set,fa.set(t,a)),a.add(this);let r=vo.get(this);r||(r=new Set,vo.set(this,r)),r.add(t);}}unregisterFromGraph(o=this.options.deps){for(let t of o)if(t instanceof e)this.unregisterFromGraph(t.options.deps);else if(t instanceof _t){let a=fa.get(t);a&&a.delete(this);let r=vo.get(this);r&&r.delete(t);}}};function Xg(e){return typeof e=="function"}function Ei(e,...o){return Xg(e)?e(...o):e}function bu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ma,tt,Je,cr,pa,Oa,Zt,yo,fr,Fn,mr,wo,Na=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:r=1e3}){Ae(this,ma,true);Ae(this,tt);Ae(this,Je);Ae(this,cr);Ae(this,pa);Ae(this,Oa);Ae(this,Zt);Ae(this,yo);Ae(this,fr,0);Ae(this,Fn,5);Ae(this,mr,()=>{this.debugLog("Connected to event bus"),Ce(this,Oa,true),this.debugLog("Emitting queued events",_(this,pa)),_(this,pa).forEach(o=>this.emitEventToBus(o)),Ce(this,pa,[]),this.stopConnectLoop(),_(this,Je).call(this).removeEventListener("tanstack-connect-success",_(this,mr));});Ae(this,wo,()=>{if(_(this,Je).call(this).addEventListener("tanstack-connect-success",_(this,mr)),_(this,fr)<_(this,Fn)){Yl(this,fr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,Je).call(this).removeEventListener("tanstack-connect",_(this,wo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ce(this,tt,o),Ce(this,ma,a),Ce(this,Je,this.getGlobalTarget),Ce(this,cr,t),this.debugLog(" Initializing event subscription for plugin",_(this,tt)),Ce(this,pa,[]),Ce(this,Oa,false),Ce(this,Zt,null),Ce(this,yo,r);}startConnectLoop(){_(this,Zt)!==null||_(this,Oa)||(this.debugLog(`Starting connect loop (every ${_(this,yo)}ms)`),Ce(this,Zt,setInterval(_(this,wo),_(this,yo))));}stopConnectLoop(){_(this,Zt)!==null&&(clearInterval(_(this,Zt)),Ce(this,Zt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,cr)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,tt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return _(this,tt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,Je).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,Je).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!_(this,ma)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!_(this,Oa)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,pa).push({type:`${_(this,tt)}:${o}`,payload:t,pluginId:_(this,tt)}),typeof CustomEvent<"u"&&(_(this,wo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,tt)}:${o}`,payload:t,pluginId:_(this,tt)})}on(o,t){let a=`${_(this,tt)}:${o}`;if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let r=n=>{this.debugLog("Received event from bus",n.detail),t(n.detail);};return _(this,Je).call(this).addEventListener(a,r),this.debugLog("Registered event to bus",a),()=>{_(this,Je).call(this).removeEventListener(a,r);}}onAll(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!_(this,ma))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let r=a.detail;_(this,tt)&&r.pluginId!==_(this,tt)||o(r);};return _(this,Je).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,Je).call(this).removeEventListener("tanstack-devtools-global",t)}};ma=new WeakMap,tt=new WeakMap,Je=new WeakMap,cr=new WeakMap,pa=new WeakMap,Oa=new WeakMap,Zt=new WeakMap,yo=new WeakMap,fr=new WeakMap,Fn=new WeakMap,mr=new WeakMap,wo=new WeakMap;var Fi=class extends Na{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},vu=(e,o)=>{Bi.emit(e,o);},Bi=new Fi;function yu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Yg={enabled:true,leading:true,trailing:true,wait:0},ha,ct,Va,qa,Ha,Lo,Bn=class{constructor(o,t){Ae(this,ha);Ae(this,ct);Ae(this,Va);Ae(this,qa);Ae(this,Ha);Ae(this,Lo);this.fn=o,this.store=new _t(yu()),this.setOptions=a=>{this.options={...this.options,...a},_(this,Va).call(this)||this.cancel();},Ce(this,ct,a=>{this.store.setState(r=>{let n={...r,...a},{isPending:s}=n;return {...n,status:_(this,Va).call(this)?s?"pending":"idle":"disabled"}}),vu("Throttler",this);}),Ce(this,Va,()=>!!Ei(this.options.enabled,this)),Ce(this,qa,()=>Ei(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,ct).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let r=Date.now(),n=r-this.store.state.lastExecutionTime,s=_(this,qa).call(this);if(this.options.leading&&n>=s)_(this,Ha).call(this,...a);else if(_(this,ct).call(this,{lastArgs:a}),!_(this,ha)&&this.options.trailing){let c=this.store.state.lastExecutionTime?r-this.store.state.lastExecutionTime:0,l=s-c;_(this,ct).call(this,{isPending:true}),Ce(this,ha,setTimeout(()=>{let{lastArgs:u}=this.store.state;u!==void 0&&_(this,Ha).call(this,...u);},l));}},Ce(this,Ha,(...a)=>{if(!_(this,Va).call(this))return;this.fn(...a);let r=Date.now(),n=r+_(this,qa).call(this);_(this,Lo).call(this),_(this,ct).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:r,nextExecutionTime:n,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||_(this,ct).call(this,{nextExecutionTime:void 0});},_(this,qa).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,Ha).call(this,...this.store.state.lastArgs);},Ce(this,Lo,()=>{_(this,ha)&&(clearTimeout(_(this,ha)),Ce(this,ha,void 0));}),this.cancel=()=>{_(this,Lo).call(this),_(this,ct).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,ct).call(this,yu());},this.key=bu(t.key),this.options={...Yg,...t},_(this,ct).call(this,this.options.initialState??{}),Bi.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,ct).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ha=new WeakMap,ct=new WeakMap,Va=new WeakMap,qa=new WeakMap,Ha=new WeakMap,Lo=new WeakMap;function Oi(e,o){return new Bn(e,o).maybeExecute}function ga(e,o){return typeof e=="function"?e(o):e}function xa(e,o){return qn(o).reduce((a,r)=>{if(a===null)return null;if(typeof a<"u")return a[r]},e)}function Io(e,o,t){let a=qn(o);function r(n){if(!a.length)return ga(t,n);let s=a.shift();if(typeof s=="string"||typeof s=="number"&&!Array.isArray(n))return typeof n=="object"?(n===null&&(n={}),{...n,[s]:r(n[s])}):{[s]:r()};if(Array.isArray(n)&&typeof s=="number"){let c=n.slice(0,s);return [...c.length?c:new Array(s),r(n[s]),...n.slice(s+1)]}return [...new Array(s),r()]}return r(e)}function Vi(e,o){let t=qn(o);function a(r){if(!r)return;if(t.length===1){let s=t[0];if(Array.isArray(r)&&typeof s=="number")return r.filter((u,f)=>f!==s);let{[s]:c,...l}=r;return l}let n=t.shift();if(typeof n=="string"&&typeof r=="object")return {...r,[n]:a(r[n])};if(typeof n=="number"&&Array.isArray(r)){if(n>=r.length)return r;let s=r.slice(0,n);return [...s.length?s:new Array(n),a(r[n]),...r.slice(n+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var Jg=/^(\d+)$/gm,Zg=/\.(\d+)(?=\.)/gm,Qg=/^(\d+)\./gm,ex=/\.(\d+$)/gm,tx=/\.{2,}/gm,Ni="__int__",On=`${Ni}$1`;function qn(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(Jg,On).replace(Zg,`.${On}.`).replace(Qg,`${On}.`).replace(ex,`.${On}`).replace(tx,".").split(".").map(o=>{if(o.startsWith(Ni)){let t=o.substring(Ni.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function qi(e){return !(Array.isArray(e)&&e.length===0)}function So(e,o){let t=a=>a.validators.filter(Boolean).map(r=>({cause:r.cause,validate:r.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Co(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:r,onDynamicAsyncDebounceMs:n}=o.validators||{},s=t??0,c=l=>l.validators.filter(Boolean).map(u=>{let f=u?.cause||e,d=s;switch(f){case "change":d=r??s;break;case "blur":d=a??s;break;case "dynamic":d=n??s;break;case "submit":d=0;break}return e==="submit"&&(d=0),{cause:f,validate:u.fn,debounceMs:d}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:c})}var pr=e=>!!e&&typeof e=="object"&&"fields"in e;function ba(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[r,n]of e)if(!o.has(r)||!Object.is(n,o.get(r)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let r of e)if(!o.has(r))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let r of t)if(!a.includes(r)||!ba(e[r],o[r]))return false;return true}var Hn=({newFormValidatorError:e,isPreviousErrorFromFormValidator:o,previousErrorValue:t})=>e?{newErrorValue:e,newSource:"form"}:o?{newErrorValue:void 0,newSource:void 0}:t?{newErrorValue:t,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},Un=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function Ge(e,o){return e==null?o:{...e,...o}}var Ua=256,Vn=[],Nn;for(;Ua--;)Vn[Ua]=(Ua+256).toString(16).substring(1);function Hi(){let e=0,o,t="";if(!Nn||Ua+16>256){for(Nn=new Array(256),e=256;e--;)Nn[e]=256*Math.random()|0;e=0,Ua=0;}for(;e<16;e++)o=Nn[Ua+e],e===6?t+=Vn[o&15|64]:e===8?t+=Vn[o&63|128]:t+=Vn[o],e&1&&e>1&&e<11&&(t+="-");return Ua++,t}var va=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let o=e.event.async,t=o?void 0:{fn:e.validators.onMount,cause:"mount"},a={fn:o?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},r={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},n={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},s=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,r,n,s],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[r,s],form:e.form});case "change":return e.runValidation({validators:[a,s],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function ax(e,o){let t=new Map;for(let a of e){let r=a.path??[],n=o,s="";for(let c=0;c<r.length;c++){let l=r[c];if(l===void 0)continue;let u=typeof l=="object"?l.key:l,f=Number(u);Array.isArray(n)&&!Number.isNaN(f)?s+=`[${f}]`:s+=(c>0?".":"")+String(u),typeof n=="object"&&n!==null?n=n[u]:n=void 0;}t.set(s,(t.get(s)??[]).concat(a));}return Object.fromEntries(t)}var wu=(e,o)=>{let t=ax(e,o);return {form:t,fields:t}},ya={validate({value:e,validationSource:o},t){let a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("async function passed to sync validator");if(a.issues)return o==="field"?a.issues:wu(a.issues,e)},async validateAsync({value:e,validationSource:o},t){let a=await t["~standard"].validate(e);if(a.issues)return o==="field"?a.issues:wu(a.issues,e)}},Wn=e=>!!e&&"~standard"in e;var ko={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function hr(e){function o(d,m,i,h){let g=a(d,m,i,h);({insert:()=>c(g,d,m),remove:()=>l(g),swap:()=>h!==void 0&&f(g,d,m,h),move:()=>h!==void 0&&u(g,d,m,h)})[i]();}function t(d,m){return `${d}[${m}]`}function a(d,m,i,h){let g=[t(d,m)];if(i==="swap")g.push(t(d,h));else if(i==="move"){let[p,y]=[Math.min(m,h),Math.max(m,h)];for(let x=p;x<=y;x++)g.push(t(d,x));}else {let p=e.getFieldValue(d),y=Array.isArray(p)?p.length:0;for(let x=m+1;x<y;x++)g.push(t(d,x));}return Object.keys(e.fieldInfo).filter(p=>g.some(y=>p.startsWith(y)))}function r(d,m){return d.replace(/\[(\d+)\]/,(i,h)=>{let g=parseInt(h,10);return `[${m==="up"?g+1:Math.max(0,g-1)}]`})}function n(d,m){(m==="up"?d:[...d].reverse()).forEach(h=>{let g=r(h.toString(),m),p=e.getFieldMeta(g);p?e.setFieldMeta(h,p):e.setFieldMeta(h,s());});}let s=()=>ko,c=(d,m,i)=>{n(d,"down"),d.forEach(h=>{h.toString().startsWith(t(m,i))&&e.setFieldMeta(h,s());});},l=d=>{n(d,"up");},u=(d,m,i,h)=>{let g=new Map(Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,i))).map(p=>[p,e.getFieldMeta(p)]));n(d,i<h?"up":"down"),Object.keys(e.fieldInfo).filter(p=>p.startsWith(t(m,h))).forEach(p=>{let y=p.replace(t(m,h),t(m,i)),x=g.get(y);x&&e.setFieldMeta(p,x);});},f=(d,m,i,h)=>{d.forEach(g=>{if(!g.toString().startsWith(t(m,i)))return;let p=g.toString().replace(t(m,i),t(m,h)),[y,x]=[e.getFieldMeta(g),e.getFieldMeta(p)];y&&e.setFieldMeta(p,y),x&&e.setFieldMeta(g,x);});};return {handleArrayFieldMetaShift:o}}var Ui=class extends Na{constructor(){super({pluginId:"form-devtools"});}},ft=new Ui;function Wi(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 xr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),r=this.store.mount(),n=()=>{a(),r(),ft.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:s}=this.options.validators||{};return ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),s&&this.validateSync("mount"),n},this.update=a=>{if(!a)return;let r=this.options;this.options=a;let n=!!a.transform?.deps?.some((l,u)=>l!==this.prevTransformArray[u]),s=a.defaultValues&&!ba(a.defaultValues,r.defaultValues)&&!this.state.isTouched,c=!ba(a.defaultState,r.defaultState)&&!this.state.isTouched;!s&&!c&&!n||(ut(()=>{this.baseStore.setState(()=>Wi(Object.assign({},this.state,c?a.defaultState:{},s?{values:a.defaultValues}:{},n?{_force_re_eval:!this.state._force_re_eval}:{})));}),ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,r)=>{let{fieldMeta:n}=this.state,s=this.resetFieldMeta(n);a&&!r?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>Wi({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}));},this.validateAllFields=async a=>{let r=[];return ut(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;let c=s.instance;r.push(Promise.resolve().then(()=>c.validate(a,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(l=>({...l,isTouched:!0}));});}),(await Promise.all(r)).flat()},this.validateArrayFieldsStartingFrom=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null,l=[`${a}[${r}]`];for(let m=r+1;m<=(c??0);m++)l.push(`${a}[${m}]`);let u=Object.keys(this.fieldInfo).filter(m=>l.some(i=>m.startsWith(i))),f=[];return ut(()=>{u.forEach(m=>{f.push(Promise.resolve().then(()=>this.validateField(m,n)));});}),(await Promise.all(f)).flat()},this.validateField=(a,r)=>{let n=this.fieldInfo[a]?.instance;return n?(n.state.meta.isTouched||n.setMeta(s=>({...s,isTouched:true})),n.validate(r)):[]},this.validateSync=a=>{let r=So(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va}),n=false,s={};return ut(()=>{for(let u of r){if(!u.validate)continue;let f=this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:d,fieldErrors:m}=zn(f),i=gr(u.cause);for(let h of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[h]===void 0)continue;let g=this.getFieldMeta(h);if(!g)continue;let{errorMap:p,errorSourceMap:y}=g,x=m?.[h],{newErrorValue:v,newSource:L}=Hn({newFormValidatorError:x,isPreviousErrorFromFormValidator:y?.[i]==="form",previousErrorValue:p?.[i]});L==="form"&&(s[h]={...s[h],[i]:x}),p?.[i]!==v&&this.setFieldMeta(h,I=>({...I,errorMap:{...I.errorMap,[i]:v},errorSourceMap:{...I.errorSourceMap,[i]:L}}));}this.state.errorMap?.[i]!==d&&this.baseStore.setState(h=>({...h,errorMap:{...h.errorMap,[i]:d}})),(d||m)&&(n=!0);}let c=gr("submit");this.state.errorMap?.[c]&&a!=="submit"&&!n&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[c]:void 0}}));let l=gr("server");this.state.errorMap?.[l]&&a!=="server"&&!n&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[l]:void 0}}));}),{hasErrored:n,fieldsErrorMap:s}},this.validateAsync=async a=>{let r=Co(a,{...this.options,form:this,validationLogic:this.options.validationLogic||va});this.state.isFormValidating||this.baseStore.setState(u=>({...u,isFormValidating:true}));let n=[],s;for(let u of r){if(!u.validate)continue;let f=gr(u.cause);this.state.validationMetaMap[f]?.lastAbortController.abort();let m=new AbortController;this.state.validationMetaMap[f]={lastAbortController:m},n.push(new Promise(async i=>{let h;try{h=await new Promise((x,v)=>{setTimeout(async()=>{if(m.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:m.signal},type:"validateAsync"}));}catch(L){v(L);}},u.debounceMs);});}catch(x){h=x;}let{formError:g,fieldErrors:p}=zn(h);p&&(s=s?{...s,...p}:p);let y=gr(u.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let v=this.getFieldMeta(x);if(!v)continue;let{errorMap:L,errorSourceMap:I}=v,k=s?.[x],{newErrorValue:S,newSource:b}=Hn({newFormValidatorError:k,isPreviousErrorFromFormValidator:I?.[y]==="form",previousErrorValue:L?.[y]});L?.[y]!==S&&this.setFieldMeta(x,A=>({...A,errorMap:{...A.errorMap,[y]:S},errorSourceMap:{...A.errorSourceMap,[y]:b}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[y]:g}})),i(s?{fieldErrors:s,errorMapKey:y}:void 0);}));}let c=[],l={};if(n.length){c=await Promise.all(n);for(let u of c)if(u?.fieldErrors){let{errorMapKey:f}=u;for(let[d,m]of Object.entries(u.fieldErrors)){let h={...l[d]||{},[f]:m};l[d]=h;}}}return this.baseStore.setState(u=>({...u,isFormValidating:false})),l},this.validate=a=>{let{hasErrored:r,fieldsErrorMap:n}=this.validateSync(a);return r&&!this.options.asyncAlways?n:this.validateAsync(a)},this.getFieldValue=a=>xa(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var r;return (r=this.fieldInfo)[a]||(r[a]={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}})},this.setFieldMeta=(a,r)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[a]:ga(r,n.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((r,n)=>{let s=n;return r[s]=ko,r},{}),this.setFieldValue=(a,r,n)=>{let s=n?.dontUpdateMeta??false,c=n?.dontRunListeners??false,l=n?.dontValidate??false;ut(()=>{s||this.setFieldMeta(a,u=>({...u,isTouched:!0,isDirty:!0,errorMap:{...u?.errorMap,onMount:void 0}})),this.baseStore.setState(u=>({...u,values:Io(u.values,a,r)}));}),c||this.getFieldInfo(a).instance?.triggerOnChangeListener(),l||this.validateField(a,"change");},this.deleteField=a=>{let n=[...Object.keys(this.fieldInfo).filter(s=>{let c=a.toString();return s!==c&&s.startsWith(c)}),a];this.baseStore.setState(s=>{let c={...s};return n.forEach(l=>{c.values=Vi(c.values,l),delete this.fieldInfo[l],delete c.fieldMetaBase[l];}),c});},this.pushFieldValue=(a,r,n)=>{this.setFieldValue(a,s=>[...Array.isArray(s)?s:[],r],n);},this.insertFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,l=>[...l.slice(0,r),n,...l.slice(r)],Ge(s,{dontValidate:true}));let c=s?.dontValidate??false;c||await this.validateField(a,"change"),hr(this).handleArrayFieldMetaShift(a,r,"insert"),c||await this.validateArrayFieldsStartingFrom(a,r,"change");},this.replaceFieldValue=async(a,r,n,s)=>{this.setFieldValue(a,l=>l.map((u,f)=>f===r?n:u),Ge(s,{dontValidate:true})),(s?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.removeFieldValue=async(a,r,n)=>{let s=this.getFieldValue(a),c=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(a,u=>u.filter((f,d)=>d!==r),Ge(n,{dontValidate:true})),hr(this).handleArrayFieldMetaShift(a,r,"remove"),c!==null){let u=`${a}[${c}]`;this.deleteField(u);}(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,r,"change"));},this.swapFieldValues=(a,r,n,s)=>{this.setFieldValue(a,l=>{let u=l[r],f=l[n];return Io(Io(l,`${r}`,f),`${n}`,u)},Ge(s,{dontValidate:true})),hr(this).handleArrayFieldMetaShift(a,r,"swap",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.moveFieldValues=(a,r,n,s)=>{this.setFieldValue(a,l=>{let u=[...l];return u.splice(n,0,u.splice(r,1)[0]),u},Ge(s,{dontValidate:true})),hr(this).handleArrayFieldMetaShift(a,r,"move",n),(s?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${r}]`,"change"),this.validateField(`${a}[${n}]`,"change"));},this.clearFieldValues=(a,r)=>{let n=this.getFieldValue(a),s=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,[],Ge(r,{dontValidate:true})),s!==null)for(let l=0;l<=s;l++){let u=`${a}[${l}]`;this.deleteField(u);}(r?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:ko},values:this.options.defaultValues?Io(r.values,a,xa(this.options.defaultValues,a)):r.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[r,n])=>(Object.keys(n).length&&n.errors.length&&(a[r]={errors:n.errors,errorMap:n.errorMap}),a),{})}),this.parseValuesWithSchema=a=>ya.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ya.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??Hi(),this._devtoolsSubmissionOverride=false,this.baseStore=new _t(Wi({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Vt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],l=r[0],u=0,f={};for(let d of Object.keys(l.fieldMetaBase)){let m=l.fieldMetaBase[d],i=c?.fieldMetaBase[d],h=s?.[d],g=xa(l.values,d),p=h?.errors;if(!i||m.errorMap!==i.errorMap){p=Object.values(m.errorMap??{}).filter(I=>I!==void 0);let L=this.getFieldInfo(d)?.instance;L&&!L.options.disableErrorFlat&&(p=p?.flat(1));}let y=!qi(p??[]),x=!m.isDirty,v=ba(g,xa(this.options.defaultValues,d))||ba(g,this.getFieldInfo(d)?.instance?.options.defaultValue);if(h&&h.isPristine===x&&h.isValid===y&&h.isDefaultValue===v&&h.errors===p&&m===i){f[d]=h,u++;continue}f[d]={...m,errors:p,isPristine:x,isValid:y,isDefaultValue:v};}return Object.keys(l.fieldMetaBase).length&&s&&u===Object.keys(l.fieldMetaBase).length?s:f}}),this.store=new Vt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:r,prevVal:n})=>{let s=n,c=a?.[0],l=r[0],u=r[1],f=Object.values(u).filter(Boolean),d=f.some(P=>P.isValidating),m=f.every(P=>P.isValid),i=f.some(P=>P.isTouched),h=f.some(P=>P.isBlurred),g=f.every(P=>P.isDefaultValue),p=i&&l.errorMap?.onMount,y=f.some(P=>P.isDirty),x=!y,v=!!(l.errorMap?.onMount||f.some(P=>P?.errorMap?.onMount)),L=!!d,I=s?.errors??[];(!c||l.errorMap!==c.errorMap)&&(I=Object.values(l.errorMap).reduce((P,W)=>W===void 0?P:W&&pr(W)?(P.push(W.form),P):(P.push(W),P),[]));let k=I.length===0,S=m&&k,b=this.options.canSubmitWhenInvalid??false,A=l.submissionAttempts===0&&!i&&!v||!L&&!l.isSubmitting&&S||b,V=l.errorMap;if(p&&(I=I.filter(P=>P!==l.errorMap.onMount),V=Object.assign(V,{onMount:void 0})),s&&c&&s.errorMap===V&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===I&&s.isFieldsValidating===d&&s.isFieldsValid===m&&s.isFormValid===k&&s.isValid===S&&s.canSubmit===A&&s.isTouched===i&&s.isBlurred===h&&s.isPristine===x&&s.isDefaultValue===g&&s.isDirty===y&&ba(c,l))return s;let D={...l,errorMap:V,fieldMeta:this.fieldMetaDerived.state,errors:I,isFieldsValidating:d,isFieldsValid:m,isFormValid:k,isValid:S,canSubmit:A,isTouched:i,isBlurred:h,isPristine:x,isDefaultValue:g,isDirty:y},H=this.options.transform?.deps??[];if(H.length!==this.prevTransformArray.length||H.some((P,W)=>P!==this.prevTransformArray[W])){let P=Object.assign({},this,{state:D});this.options.transform?.fn(P),D=P.state,this.prevTransformArray=H;}return D}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=Oi(a=>ft.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),ft.on("request-form-state",a=>{a.payload.id===this._formId&&ft.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),ft.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),ft.on("request-form-force-submit",a=>{a.payload.id===this._formId&&(this._devtoolsSubmissionOverride=true,this.handleSubmit(),this._devtoolsSubmissionOverride=false);});}get state(){return this.store.state}get formId(){return this._formId}runValidator(o){return Wn(o.validate)?ya[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(r=>({...r,isSubmitted:false,submissionAttempts:r.submissionAttempts+1,isSubmitSuccessful:false})),ut(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance&&(r.instance.state.meta.isTouched||r.instance.setMeta(n=>({...n,isTouched:!0})));});});let t=o??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(r=>({...r,isSubmitting:true}));let a=()=>{this.baseStore.setState(r=>({...r,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(r=>r.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ut(()=>{Object.values(this.fieldInfo).forEach(r=>{r.instance?.options.listeners?.onSubmit?.({value:r.instance.state.value,fieldApi:r.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ut(()=>{this.baseStore.setState(r=>({...r,isSubmitted:!0,isSubmitSuccessful:!0})),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(r){throw this.baseStore.setState(n=>({...n,isSubmitSuccessful:false})),ft.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:r}),a(),r}}setErrorMap(o){ut(()=>{Object.entries(o).forEach(([t,a])=>{let r=t;if(pr(a)){let{formError:n,fieldErrors:s}=zn(a);for(let c of Object.keys(this.fieldInfo))this.getFieldMeta(c)&&this.setFieldMeta(c,u=>({...u,errorMap:{...u.errorMap,[r]:s?.[c]},errorSourceMap:{...u.errorSourceMap,[r]:"form"}}));this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[r]:n}}));}else this.baseStore.setState(n=>({...n,errorMap:{...n.errorMap,[r]:a}}));});});}};function zn(e){if(e){if(pr(e)){let o=zn(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function gr(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 br=class{constructor(o){this.options={},this.mount=()=>{let t=this.store.mount();this.options.defaultValue!==void 0&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:true});let a=this.getInfo();a.instance=this,this.update(this.options);let{onMount:r}=this.options.validators||{};if(r){let n=this.runValidator({validate:r,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});n&&this.setMeta(s=>({...s,errorMap:{...s?.errorMap,onMount:n},errorSourceMap:{...s?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let r=xa(t.form.options.defaultValues,t.name),n=t.defaultValue??r;a?this.setValue(s=>s||n,{dontUpdateMeta:true}):n!==void 0&&this.setValue(n,{dontUpdateMeta:true});}this.form.getFieldMeta(this.name)===void 0&&this.setMeta(this.state.meta);},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,a)=>{this.form.setFieldValue(this.name,t,Ge(a,{dontRunListeners:true,dontValidate:true})),a?.dontRunListeners||this.triggerOnChangeListener(),a?.dontValidate||this.validate("change");},this.getMeta=()=>this.store.state.meta,this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(t,a)=>{this.form.pushFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,r)=>{this.form.insertFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,r)=>{this.form.replaceFieldValue(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,Ge(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,r)=>{this.form.swapFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,r)=>{this.form.moveFieldValues(this.name,t,a,Ge(r,{dontRunListeners:true})),r?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,Ge(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),r=[];for(let n of a){if(!n.instance)continue;let{onChangeListenTo:s,onBlurListenTo:c}=n.instance.options.validators||{};t==="change"&&s?.includes(this.name)&&r.push(n.instance),t==="blur"&&c?.includes(this.name)&&r.push(n.instance);}return r},this.validateSync=(t,a)=>{let r=So(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),s=this.getLinkedFields(t).reduce((u,f)=>{let d=So(t,{...f.options,form:f.form,validationLogic:f.form.options.validationLogic||va});return d.forEach(m=>{m.field=f;}),u.concat(d)},[]),c=false;ut(()=>{let u=(f,d)=>{let m=Gn(d.cause),i=d.validate?Lu(f.runValidator({validate:d.validate,value:{value:f.store.state.value,validationSource:"field",fieldApi:f},type:"validate"})):void 0,h=a[m],{newErrorValue:g,newSource:p}=Un({formLevelError:h,fieldLevelError:i});f.state.meta.errorMap?.[m]!==g&&f.setMeta(y=>({...y,errorMap:{...y.errorMap,[m]:g},errorSourceMap:{...y.errorSourceMap,[m]:p}})),g&&(c=!0);};for(let f of r)u(this,f);for(let f of s)f.validate&&u(f.field,f);});let l=Gn("submit");return this.state.meta.errorMap?.[l]&&t!=="submit"&&!c&&this.setMeta(u=>({...u,errorMap:{...u.errorMap,[l]:void 0},errorSourceMap:{...u.errorSourceMap,[l]:void 0}})),{hasErrored:c}},this.validateAsync=async(t,a)=>{let r=Co(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||va}),n=await a,s=this.getLinkedFields(t),c=s.reduce((m,i)=>{let h=Co(t,{...i.options,form:i.form,validationLogic:i.form.options.validationLogic||va});return h.forEach(g=>{g.field=i;}),m.concat(h)},[]);this.state.meta.isValidating||this.setMeta(m=>({...m,isValidating:true}));for(let m of s)m.setMeta(i=>({...i,isValidating:true}));let l=[],u=[],f=(m,i,h)=>{let g=Gn(i.cause);m.getInfo().validationMetaMap[g]?.lastAbortController.abort();let y=new AbortController;this.getInfo().validationMetaMap[g]={lastAbortController:y},h.push(new Promise(async x=>{let v;try{v=await new Promise((b,A)=>{this.timeoutIds.validations[i.cause]&&clearTimeout(this.timeoutIds.validations[i.cause]),this.timeoutIds.validations[i.cause]=setTimeout(async()=>{if(y.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:i.validate,value:{value:m.store.state.value,fieldApi:m,signal:y.signal,validationSource:"field"},type:"validateAsync"}));}catch(V){A(V);}},i.debounceMs);});}catch(b){v=b;}if(y.signal.aborted)return x(void 0);let L=Lu(v),I=n[this.name]?.[g],{newErrorValue:k,newSource:S}=Un({formLevelError:I,fieldLevelError:L});m.setMeta(b=>({...b,errorMap:{...b?.errorMap,[g]:k},errorSourceMap:{...b.errorSourceMap,[g]:S}})),x(k);}));};for(let m of r)m.validate&&f(this,m,l);for(let m of c)m.validate&&f(m.field,m,u);let d=[];(l.length||u.length)&&(d=await Promise.all(l),await Promise.all(u)),this.setMeta(m=>({...m,isValidating:false}));for(let m of s)m.setMeta(i=>({...i,isValidating:false}));return d.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:r}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:n}=this.validateSync(t,r[this.name]??{});if(n&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Gn(t)]?.lastAbortController.abort(),this.state.meta.errors;let s=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,s)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>ya.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ya.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Vt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...ko,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Wn(o.validate)?ya[o.type](o.value,o.validate):o.validate(o.value)}setErrorMap(o){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...o}}));}triggerOnBlurListener(){let o=this.form.options.listeners?.onBlurDebounceMs;o&&o>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this});}triggerOnChangeListener(){let o=this.form.options.listeners?.onChangeDebounceMs;o&&o>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});},o)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});}};function Lu(e){if(e)return e}function Gn(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 Kn(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,rx)}function rx(e,o){if(Object.is(e,o))return true;if(typeof e!="object"||e===null||typeof o!="object"||o===null)return false;if(e instanceof Map&&o instanceof Map){if(e.size!==o.size)return false;for(let[a,r]of e)if(!o.has(a)||!Object.is(r,o.get(a)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let a of e)if(!o.has(a))return false;return true}if(e instanceof Date&&o instanceof Date)return e.getTime()===o.getTime();let t=Iu(e);if(t.length!==Iu(o).length)return false;for(let a=0;a<t.length;a++)if(!Object.prototype.hasOwnProperty.call(o,t[a])||!Object.is(e[t[a]],o[t[a]]))return false;return true}function Iu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Mo=typeof window<"u"?useLayoutEffect:useEffect;function cx(e){let[o]=useState(()=>{let a=new br({...e,form:e.form,name:e.name});return a.Field=zi,a});return Mo(o.mount,[o]),Mo(()=>{o.update(e);}),Kn(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var zi=(({children:e,...o})=>{let t=cx(o),a=useMemo(()=>ga(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function px({form:e,selector:o,children:t}){let a=Kn(e.store,o);return ga(t,a)}function Gi(e){let o=useId(),[t]=useState(()=>{let a=new xr({...e,formId:o}),r=a;return r.Field=function(s){return jsx(zi,{...s,form:a})},r.Subscribe=function(s){return jsx(px,{form:a,selector:s.selector,children:s.children})},r});return Mo(t.mount,[]),Mo(()=>{t.update(e);}),t}function Ki({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 Sx=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[s,c]=useState(n),l=Gi({defaultValues:{questionType:n,responseType:e?.data.responseType||"classic",feedbackMode:e?.data.feedbackMode||"practice",question:e?.data.question||"",responseOptions:{options:e?.data.responseOptions.options||["","","",""],correctIndex:e?.data.questionType==="multiple-choice"?e.data.responseOptions.correctIndex||[]:[],correctAnswer:e?.data.questionType==="true-false"?e.data.responseOptions.correctAnswer:false,correctShortAnswer:(e?.data.questionType==="short-answer"||e?.data.questionType==="fill-in-the-blank")&&e.data.responseOptions.correctShortAnswer||"",correctLongAnswer:e?.data.questionType==="long-answer"&&e.data.responseOptions.correctLongAnswer||""}},onSubmit:async({value:d})=>{if(d.questionType==="true-false"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctAnswer:d.responseOptions.correctAnswer??false}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:300,rotation:r?e.rotation:0};o(r?la(m):zs(m));}else if(d.questionType==="multiple-choice"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctIndex:d.responseOptions.correctIndex??[]}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:575,height:r?e.height:400,rotation:r?e.rotation:0};o(r?ia(m):Ws(m));}else if(d.questionType==="short-answer"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?zo(m):Gs(m));}else if(d.questionType==="fill-in-the-blank"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctShortAnswer:d.responseOptions.correctShortAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Ko(m):_s(m));}else if(d.questionType==="long-answer"){let m={id:r?e.id:v4(),data:{questionType:d.questionType,responseType:d.responseType,feedbackMode:d.feedbackMode,question:d.question,responseOptions:{options:d.responseOptions.options,correctLongAnswer:d.responseOptions.correctLongAnswer??""}},x:r?e.x:500,y:r?e.y:200,width:r?e.width:400,height:r?e.height:400,rotation:r?e.rotation:0};o(r?Go(m):Ks(m));}o(da(false));}}),u=()=>{o(da(false));},f=jsx("div",{className:"fixed inset-0 z-106 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-6 shadow-lg",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-240px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-100px)] w-full flex-col gap-1 rounded-lg bg-white p-4",onSubmit:d=>{d.preventDefault(),d.stopPropagation(),l.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-4",children:[jsxs("div",{className:"flex flex-col gap-1",children:[jsx("h2",{className:"text-2xl font-bold text-[#000000CC]",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"font-semibold text-[#00000099]",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-8 w-8 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600",onClick:()=>{u();},children:jsx("span",{className:"text-xl text-white",children:"\u2715"})})]}),jsxs("div",{className:"mb-4 flex justify-between gap-6",children:[jsx(l.Field,{name:"questionType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:m=>{d.handleChange(m.target.value),c(m.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-4 py-3 pr-10 font-semibold text-[#000000CC] ${r?"cursor-not-allowed bg-gray-100 opacity-60":"bg-white"}`,children:[jsx("option",{value:"multiple-choice",children:"Multiple Choice"}),jsx("option",{value:"true-false",children:"True/False"}),jsx("option",{value:"short-answer",children:"Short Answer"}),jsx("option",{value:"fill-in-the-blank",children:"Fill in the blank"}),jsx("option",{value:"long-answer",children:"Long Answer"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),r&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Question type cannot be changed when editing"}),jsx(Ki,{field:d})]})}),s&&!["short-answer","fill-in-the-blank","long-answer"].includes(s)&&jsx(l.Field,{name:"responseType",children:d=>jsxs("div",{className:"flex w-full flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:d.name,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:m=>d.handleChange(m.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-4 py-3 pr-10 font-semibold text-[#000000CC]",children:[jsx("option",{value:"classic",children:"Classic"}),jsx("option",{value:"drag-and-drop",children:"Drag and Drop"})]}),jsx("div",{className:"pointer-events-none absolute top-1/2 right-3 -translate-y-1/2",children:jsx("svg",{className:"h-5 w-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),jsx(Ki,{field:d})]})})]}),jsx(l.Field,{name:"feedbackMode",children:d=>jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-2 rounded-lg bg-gray-100 p-1.5 ${s==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>d.handleChange("practice"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",size:16}),"Practice Mode"]}),jsxs("button",{type:"button",disabled:s==="long-answer",onClick:()=>d.handleChange("test"),className:`flex w-full items-center gap-2 rounded-lg px-4 py-2 text-base font-medium transition-all ${d.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",size:16}),"Assessment Mode"]})]}),s==="long-answer"&&jsx("p",{className:"text-xs text-gray-500 italic",children:"Long answer questions are only available in Assessment Mode"}),jsx(Ki,{field:d})]})}),jsx(l.Field,{name:"question",validators:{onChange:({value:d})=>d?void 0:"A question is required"},children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-[#00000066] uppercase",children:"Question"}),jsx("div",{className:"relative",children:jsx("input",{className:"outline-primary/50 w-full resize-none rounded-lg border border-gray-300 bg-white px-4 py-3 text-gray-900",value:d.state.value,onChange:m=>d.handleChange(m.target.value),onBlur:d.handleBlur,placeholder:"Enter Your Question"})}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),s==="true-false"&&jsx(l.Field,{name:"responseOptions.correctAnswer",children:d=>{let m=d.state.value;return jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{className:"text-base font-semibold text-[#00000066] uppercase",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-4",children:[jsxs("button",{type:"button",onClick:()=>d.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"True"}),m===true&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>d.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-6 py-5 transition-all ${m===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",size:52}),jsx("span",{className:"mt-2 text-lg font-semibold text-black",children:"False"}),m===false&&jsx("span",{className:"absolute top-2 right-2 rounded-full bg-green-600 px-3 py-0.5 text-xs font-medium text-white",children:"Correct"})]})]}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Select the correct answer for this true/false question"})]})}}),s==="multiple-choice"&&jsx(l.Field,{name:"responseOptions",validators:{onChange:({value:d})=>{if(d.options.filter(i=>!i.trim()).length>0)return "All options must have text";if(!d.correctIndex||d.correctIndex.length===0)return "Please select at least one correct answer"}},children:d=>{let m=(p,y)=>{let x=[...d.state.value.options];x[p]=y,d.handleChange({...d.state.value,options:x});},i=()=>{if(d.state.value.options.length>=6){alert("Maximum 6 options allowed");return}d.handleChange({...d.state.value,options:[...d.state.value.options,""]});},h=p=>{if(d.state.value.options.length<=2){alert("Minimum 2 options required");return}let y=d.state.value.options.filter((v,L)=>L!==p),x=d.state.value.correctIndex?.filter(v=>v!==p).map(v=>v>p?v-1:v);d.handleChange({...d.state.value,options:y,correctIndex:x});},g=p=>{let y=d.state.value.correctIndex||[];if(y.includes(p))d.handleChange({...d.state.value,correctIndex:y.filter(v=>v!==p)});else {if(y.length>=6){alert("Maximum 6 correct answers allowed");return}d.handleChange({...d.state.value,correctIndex:[...y,p]});}};return jsxs("div",{className:"mb-4 flex flex-col gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:d.name,className:"mb-2 text-base font-semibold text-gray-900",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-4 flex flex-col gap-3",children:d.state.value.options.map((p,y)=>{let x=!p.trim(),v=d.state.value.correctIndex?.includes(y),L=d.state.meta.isTouched&&x;return jsxs("div",{className:"flex w-full items-center gap-3 px-1",children:[jsx("button",{type:"button",onClick:()=>g(y),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${v?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:v&&jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),jsx("div",{className:`w-full rounded-lg border-2 px-4 py-3 transition-colors ${L?"border-red-500 bg-red-50":v?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${y+1}`,value:p,onChange:I=>m(y,I.target.value),onBlur:d.handleBlur,className:"w-full flex-1 border-none bg-transparent text-gray-900 placeholder:text-gray-400 focus:outline-none"})}),d.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>h(y),className:"text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",size:24})})]},y)})}),jsx("button",{type:"button",onClick:i,disabled:d.state.value.options.length>=6,className:"mx-2 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-3 text-lg font-semibold text-[#00000066] disabled:cursor-not-allowed",children:"+ Add Option"}),d.state.value.correctIndex.length===0||d.state.meta.errors.length>0?jsx("span",{className:"px-2 text-base font-semibold text-red-500",children:d.state.meta.errors.join(", ")}):jsxs("div",{className:"flex w-fit items-center gap-1 rounded-lg bg-[#F2FFF4] px-2 py-1 text-[#1B9D2C]",children:[jsx(CheckCircle,{weight:"fill"}),jsx("p",{className:"",children:"Correct answer selected"})]})]})}}),(s==="short-answer"||s==="fill-in-the-blank")&&jsx(l.Field,{name:"responseOptions.correctShortAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-gray-900",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:d.state.value,onChange:m=>{d.handleChange(m.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"Learners must write this answer exactly (case-insensitive)."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),s==="long-answer"&&jsx(l.Field,{name:"responseOptions.correctLongAnswer",children:d=>jsxs("div",{className:"mb-6 flex flex-col gap-2",children:[jsx("label",{htmlFor:d.name,className:"text-sm font-semibold text-gray-900",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:d.state.value,onChange:m=>{d.handleChange(m.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-3 text-gray-900 transition-colors"}),jsx("p",{className:"text-sm font-semibold text-gray-500",children:"This will be used as a reference answer for manual grading."}),d.state.meta.errors.length>0&&jsx("span",{className:"text-sm font-semibold text-red-500",children:d.state.meta.errors.join(", ")})]})}),jsx(l.Subscribe,{selector:d=>[d.canSubmit,d.isSubmitting],children:([d,m])=>jsx("button",{type:"submit",disabled:!d,className:"mt-2 mb-4 w-full rounded-lg bg-[#096B76] px-6 py-3 font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50",children:m?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,document.body)},ku=Sx;var Mu=({text:e,position:o})=>{let t=xe(),a=u=>{t(le()),t(wt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+u))}));},r=u=>{t(le()),t(wt({id:e.id,fill:u}));},n=()=>{t(le()),t(wt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},s=()=>{t(le()),t(wt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},c=()=>{t(le()),t(wt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},l=u=>{t(le()),t(wt({id:e.id,fontFamily:u}));};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:u=>u.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:u=>l(u.target.value),className:"rounded border border-gray-300 bg-white px-2 py-1 text-xs hover:bg-gray-50",children:[jsx("option",{value:"Arial",children:"Arial"}),jsx("option",{value:"Helvetica",children:"Helvetica"}),jsx("option",{value:"Times New Roman",children:"Times"}),jsx("option",{value:"Courier New",children:"Courier"}),jsx("option",{value:"Georgia",children:"Georgia"}),jsx("option",{value:"Verdana",children:"Verdana"}),jsx("option",{value:"Comic Sans MS",children:"Comic Sans"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-8 text-center text-xs font-medium",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-7 w-7 items-center justify-center rounded text-sm font-bold hover:bg-gray-100",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"ml-1 flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:n,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:jsx(TextB,{size:16,weight:"bold"})}),jsx("button",{onClick:s,className:`flex h-7 w-7 items-center justify-center rounded transition-colors ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:jsx(TextItalic,{size:16,weight:"bold"})}),jsx("button",{onClick:c,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:u=>r(u.target.value),className:"h-7 w-7 cursor-pointer rounded border border-gray-300",title:"Text color",style:{padding:"2px"}})})})]})};var Au=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:r,scale:n,textareaRef:s})=>{let c=useRef(null),l=useMemo(()=>({fontSize:`${e.fontSize*n}px`,fontFamily:e.fontFamily,fontStyle:e.fontStyle,fontWeight:e.fontWeight==="bold"?"bold":"normal",textDecoration:e.textDecoration,color:e.fill,border:"2px solid #4A90E2",outline:"none",padding:"5px",background:"white",resize:"none",overflow:"hidden",width:"auto",minWidth:"200px",minHeight:"50px",lineHeight:"1.2",transform:`rotate(${e.rotation}deg)`,transformOrigin:"top left",whiteSpace:"pre",overflowWrap:"normal",boxSizing:"border-box"}),[e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,e.rotation,n]),u=useCallback(f=>{f.style.height="auto",f.style.height=`${f.scrollHeight}px`;let d=document.createElement("span");d.style.font=window.getComputedStyle(f).font,d.style.fontSize=f.style.fontSize,d.style.fontFamily=f.style.fontFamily,d.style.fontWeight=f.style.fontWeight,d.style.fontStyle=f.style.fontStyle,d.style.visibility="hidden",d.style.position="absolute",d.style.whiteSpace="pre";let m=f.value.split(`
4
+ `),i=0;document.body.appendChild(d);for(let g of m){d.textContent=g||" ";let p=d.offsetWidth;p>i&&(i=p);}document.body.removeChild(d);let h=10;f.style.width=`${Math.max(200,i+h+20)}px`;},[]);return useEffect(()=>{let f=c.current;f&&(f.style.fontSize=`${e.fontSize*n}px`,f.style.fontFamily=e.fontFamily,f.style.fontStyle=e.fontStyle,f.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",f.style.textDecoration=e.textDecoration,f.style.color=e.fill,u(f));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,n,u]),jsx("div",{style:{position:"absolute",top:`${r.top}px`,left:`${r.left}px`,zIndex:1e3},children:jsx("textarea",{ref:f=>{if(c.current=f,s.current=f,f){f.focus();let d=f.value.length;f.setSelectionRange(d,d),u(f);}},value:o,onChange:f=>{t(f.target.value);},onKeyDown:f=>{f.key==="Escape"&&a();},style:l},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var Pu=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(P=>P.toolbar.selectedTool),c=s==="pen"||s==="eraser",l=useRef(null),[u,f]=useState(""),[d,m]=useState(false),[i,h]=useState(null);useEffect(()=>{let P=l.current;if(P)return a.current.set(e.id,P),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=d&&u.trim().toLowerCase()===g,y=()=>{m(false),f("");},x=()=>p?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",v=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,I=60,k=d?40:0,S=d?54:20,b=50,A=12,V=e.data.feedbackMode==="practice"?48:0,D=12,H=30,N=I+k+H+b+A+D+V+L;return jsxs(Group,{ref:l,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:N,name:"sa-element",...c?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:N,onTransformEnd:P=>t(e.id,P),onContextMenu:P=>{P.cancelBubble=true,r(P.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:I+k+H-S,width:e.width-L*2+4,height:b+6,fill:"#ffffff",stroke:p?"#22c55e":d?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:I+k+H-S},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${b}px`,pointerEvents:d?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:P=>f(P.target.value),disabled:d,placeholder:"Type your answer...",className:"h-full w-full border-0 bg-white px-3 text-gray-900 focus:outline-none",style:{fontSize:"16px",pointerEvents:d?"none":"auto"}})}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:I+80,width:e.width/2+24,height:k,fill:v().bg,cornerRadius:8}),jsx(Text,{x:36,y:I+80,width:e.width-L*2,height:k,text:x(),fontSize:12,fontStyle:"bold",fill:v().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:I+k+H+b+A+D,children:[jsxs(Group,{onMouseDown:P=>{P.cancelBubble=true,h("check");},onMouseUp:P=>{P.cancelBubble=true,h(null),u.length>0&&m(true);},onMouseLeave:P=>{P.cancelBubble=true,h(null);},onTouchStart:P=>{P.cancelBubble=true,h("check");},onTouchEnd:P=>{P.cancelBubble=true,h(null),u.length>0&&m(true);},scaleX:i==="check"?.95:1,scaleY:i==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(d?2:1),height:48,fill:u.length===0||d?"#9ca3af":"#096B76",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/(d?2:1),height:48,text:d?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),d&&jsxs(Group,{x:(e.width-L*2)/2+8,onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),y();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),y();},scaleX:i==="reset"?.95:1,scaleY:i==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:P=>P.cancelBubble=true,onTap:P=>P.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Pu.displayName="ShortAnswer";var Du=Pu;var Eu=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(Du,{shortAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id)},s.id))});var Fu=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],r=useRef(new Map),n=useCallback((s,c)=>{let l=s.target;o(Ko({id:c,x:l.x(),y:l.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:r,handleFillInTheBlanksDragEnd:n}};var Ct=24,$i=51,Sr=64,Bu=15,Xn=32,Ou=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:r,fibRefs:n})=>{let s=useSelector(b=>b.toolbar.selectedTool),c=s==="pen"||s==="eraser",l=useRef(null),[u,f]=useState(""),[d,m]=useState(false),[i,h]=useState(null);useEffect(()=>{let b=l.current;if(b)return n.current.set(e.id,b),()=>{n.current.delete(e.id);}},[e.id,n]);let g=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",p=d&&u.trim().toLowerCase()===g,y=()=>{m(false),f("");},x=()=>{u.length>0&&m(true);},v=e.width-Ct*2,L=(v-Bu)/2,I=e.data.feedbackMode==="practice",k=useMemo(()=>{let b=Ct,A=b;b+=60;let V=b;b+=35;let D=b;b+=$i+16;let H=b;d&&(b+=Xn+16);let N=b;return I&&(b+=Sr),b+=Ct,{questionY:A,helperTextY:V,inputY:D,feedbackY:H,buttonsY:N,totalHeight:b}},[d,I]),S=()=>d?p?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:l,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...c?{}:{onDragEnd:b=>a(b,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:k.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:b=>t(e.id,b),onContextMenu:b=>{b.cancelBubble=true,r?.(b.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Ct,y:k.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:v,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Ct,y:k.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:v,listening:false}),jsx(Rect,{x:Ct,y:k.inputY,width:v,height:$i,fill:"#ffffff",stroke:S(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Ct,y:k.inputY},divProps:{style:{width:`${v}px`,height:`${$i}px`,pointerEvents:d?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:b=>f(b.target.value),disabled:d,placeholder:"Type your answer here...",style:{width:"100%",height:"100%",border:"none",outline:"none",padding:"0 16px",fontSize:"16px",fontWeight:600,color:"rgba(0,0,0,0.6)",backgroundColor:"transparent",borderRadius:"8px"}})}),d&&jsxs(Group,{y:k.feedbackY,children:[jsx(Rect,{x:Ct,width:p?206:140,height:Xn,fill:p?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:p?"\u2713":"\u2717",x:Ct+10,y:0,width:16,height:Xn,fontSize:14,fill:p?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:p?"Right Answer, Great Job!":"Wrong Answer",x:Ct+30,y:0,height:Xn,fontSize:14,fontStyle:"600",fill:p?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),I&&jsxs(Group,{y:k.buttonsY,children:[jsxs(Group,{x:Ct,onMouseDown:b=>{b.cancelBubble=true,h("reset");},onMouseUp:b=>{b.cancelBubble=true,h(null),y();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("reset");},onTouchEnd:b=>{b.cancelBubble=true,h(null),y();},scaleX:i==="reset"?.98:1,scaleY:i==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Sr,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Sr,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Ct+L+Bu,onMouseDown:b=>{b.cancelBubble=true,h("submit");},onMouseUp:b=>{b.cancelBubble=true,h(null),x();},onMouseLeave:b=>{b.cancelBubble=true,h(null);},onTouchStart:b=>{b.cancelBubble=true,h("submit");},onTouchEnd:b=>{b.cancelBubble=true,h(null),x();},scaleX:i==="submit"?.98:1,scaleY:i==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Sr,fill:u.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Sr,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ou.displayName="FillInTheBlanks";var Nu=Ou;var qu=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n})=>jsx(Fragment,{children:e.map(s=>jsx(Nu,{fillInTheBlank:s,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:r,fibRefs:n},s.id))});var Zi=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>{let s=useSelector(N=>N.toolbar.selectedTool),c=s==="pen"||s==="eraser",l=useRef(null),[u,f]=useState(""),[d,m]=useState(false),[i,h]=useState(null);useEffect(()=>{let N=l.current;if(N)return a.current.set(e.id,N),()=>{a.current.delete(e.id);}},[e.id,a]);let g=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",p=d&&u.trim().toLowerCase()===g,y=()=>{m(false),f("");},x=()=>p?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",v=()=>p?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,I=60,k=d?60:0,S=120,b=12,A=48,V=12,D=30,H=I+k+D+S+b+V+A+L;return jsxs(Group,{ref:l,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...c?{}:{onDragEnd:n,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:N=>{let P=l.current?.getStage()?.getPointerPosition();if(!P||!r)return;let W={x:e.x,y:e.y,width:e.width,height:e.height};P.x>=W.x&&P.x<=W.x+W.width&&P.y>=W.y&&P.y<=W.y+W.height&&r(N.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:H,onTransformEnd:N=>t(e.id,N)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),d&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:I,width:e.width-L*2,height:k,fill:v().bg,cornerRadius:8}),jsx(Text,{x:L,y:I,width:e.width-L*2,height:k,text:x(),fontSize:14,fontStyle:"bold",fill:v().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:I+k+b,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:I+k+D,width:e.width-L*2,height:S,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:I+k+D},divProps:{style:{width:`${e.width-L*2}px`,height:`${S}px`,pointerEvents:d?"none":"auto"}},children:jsx("textarea",{value:u,onChange:N=>f(N.target.value),disabled:d,placeholder:`Type your extended answer here...\r
5
5
  \r
6
- This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:u?"none":"auto"}})}),jsx(Group,{y:I+k+R+S+b+V,children:u&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),w();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),w();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:q=>q.cancelBubble=true,onTap:q=>q.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})]})})]})});ji.displayName="LongAnswer";var Eu=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(ji,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id)},s.id))});var Wa=1920,za=1080,Nu=3840,Vu=2160,Yx=e=>{let o=0,t=0,a=Wa,r=za;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:Wa,height:za};let n=(i,d,f,u)=>{o=Math.min(o,i),t=Math.min(t,d),a=Math.max(a,i+f),r=Math.max(r,d+u);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let d=i.x||0,f=i.y||0,u=i.scaleX||1,m=i.scaleY||1;for(let l=0;l<i.points.length;l+=2){let h=d+i.points[l]*u,g=f+i.points[l+1]*m;o=Math.min(o,h),t=Math.min(t,g),a=Math.max(a,h),r=Math.max(r,g);}}}),e.images?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>n(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>n(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>n(i.x,i.y,i.width,i.height));let s=Math.min(a-o,Nu),c=Math.min(r-t,Vu);return o=Math.max(o,a-Nu),t=Math.max(t,r-Vu),{minX:o,minY:t,maxX:a,maxY:r,width:s,height:c}},Jx=(e,o,t={minX:0,minY:0,maxX:Wa,maxY:za,width:Wa,height:za})=>{let a=Math.max(t.width,Wa),r=Math.max(t.height,za),n=e/o,s=a/r,c,i,d,u=0;if(n>s){i=r,c=Math.round(i*n),d=o/i;}else {c=a,i=Math.round(c/n),d=e/c;let m=r*d;u=(o-m)/2;}return {scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:u,baseWidth:c,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},qu=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},Zx=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a}={})=>{let r=yt(),n=ee(y=>y.toolbar.selectedTool),s=ee(ge),c=ee($o),i=s?.editingActivity,d=s?.showMcqForm,f=s?.lines||[],u=useRef(null),m=useRef(null),[l,h]=useState(null),[g,p]=useState(""),w=useRef(null),[x,v]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Wa,stageHeight:za,offsetX:0,offsetY:0,baseWidth:Wa,baseHeight:za,contentOffsetX:0,contentOffsetY:0}),L=useMemo(()=>Yx(s||null),[c]),[I,k]=useState(null),[S,b]=useState(null),[A,V]=useState(null),[R,H]=useState(null),[q,P]=useState(null),[W,E]=useState(null),[oe,N]=useState(null),[fe,z]=useState(false),[O,X]=useState(null),[U,K]=useState(false),Q=useRef(null),te=useRef(null),J=useRef(null),{debouncedGenerateThumbnail:de}=vd(c,u);useEffect(()=>{let y=()=>{if(m.current){let T=m.current.getBoundingClientRect(),D=Jx(T.width,T.height,L);v(D);}};y();let C=new ResizeObserver(y);return m.current&&C.observe(m.current),window.addEventListener("resize",y),()=>{C.disconnect(),window.removeEventListener("resize",y);}},[L]),useEffect(()=>{if(u.current){let y=u.current.container();y&&(y.style.cursor="");}},[n]);let Y=useCallback(()=>{u.current&&requestAnimationFrame(()=>{if(!u.current)return;u.current.getLayers().forEach(D=>D.batchDraw());let C=1/6,T=u.current.toDataURL({pixelRatio:C});p(T),de();});},[de]),Me=useRef(c);useEffect(()=>{Me.current!==c&&(Me.current=c,Y());},[c,Y]);let De=useRef(null),Se=useRef(true);useEffect(()=>{if(!s)return;let y=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),C=De.current?.count!==y;!Se.current&&C&&setTimeout(()=>{Y();},100),De.current={slideId:c,count:y},Se.current=false;},[s,c,Y]),useEffect(()=>{u.current&&e&&e(u);},[e]),useEffect(()=>{J.current&&a&&a(J);},[a]);let{startDrawing:Rt,draw:Ja,stopDrawing:Er,setCanvasRef:Fr,tool:fs,color:ms,strokeWidth:ps,isSketchMode:hs}=_l(Y),Ma=useRef(new Map),{images:F,getLoadedImage:ne,imageRefs:ve,handleDragEnd:he,handleImageTransformEnd:se}=Ql(Y),{videos:re,videoRefs:Te,handleVideoClick:Dt,handleVideoDragEnd:Yt,handleVideoTransformEnd:st}=ad(Y),{multipleChoice:Ee,handleMcqTransform:qe,mcqRefs:ht,handleDragEnd:Ta}=ed(Y),{trueFalse:Za,handleTrueFalseTransform:Qa,trueFalseRefs:Aa,handleTrueFalseDragEnd:Et}=td(Y),{shortAnswers:ra,saRefs:Ft,handleShortAnswerDragEnd:Df}=ld(Y),{longAnswers:Ef,handleLongAnswerDragEnd:Ff}=dd(Y),{fillInTheBlanks:Bf,handleFillInTheBlanksDragEnd:Of,fibRefs:Br}=ku(Y),{transformerRef:ue,boundBoxFunc:gt}=hd(),{shapes:Nf,shapeRefs:Or,isDragging:Pl,handleShapeDragEnd:Vf,handleShapeResizeEnd:qf}=nd(Y),{texts:qo,textRefs:na,handleDragEnd:Hf,handleTransformEnd:Uf,handleDoubleClick:Wf,startEditing:Nr,editingTextId:me,editingValue:Rl,handleEditingChange:Dl,finishEditing:gs}=id(Y,Q);useEffect(()=>{t&&t(Nr);},[t,Nr]);let Vr=ee(y=>y.canvas.editingTextId);useEffect(()=>{Vr&&Vr!==me&&Nr(Vr);},[Vr,me,Nr]);let{flashcards:zf,flashcardRefs:qr,handleDragEnd:Gf,handleFlashcardTransformEnd:Kf,handleNext:_f,handlePrevious:jf}=cd(Y),{photoFrames:El,photoFrameRefs:Hr,handleDragEnd:$f,handlePhotoFrameTransformEnd:Xf,startCamera:Yf,capturePhoto:Jf,cameraStreams:Zf}=pd(Y);useEffect(()=>{if(ue.current){if(me){ue.current.nodes([]),ue.current.getLayer()?.batchDraw();return}if(l&&!re.find(T=>T.id===l)?.isPlaying){let T=Ma.current.get(l)||ve.current.get(l)||Te.current.get(l)||Or.current.get(l)||na.current.get(l)||ht.current.get(l)||qr.current.get(l)||Hr.current.get(l)||Ft.current.get(l)||Aa.current.get(l)||Br.current.get(l);if(T){let D=T.attrs?.locked;if(T.visible()&&D!==true){ue.current.nodes([T]),ue.current.getLayer()?.batchDraw();return}}}ue.current.nodes([]),ue.current.getLayer()?.batchDraw();}},[l,me,re,Ma,ve,Te,Or,na,qr,Hr,El,ht,Aa,Br,ue]);let Ue=useCallback(y=>{h(y),o?.(y);},[o]),eo=useCallback(()=>{h(null),o?.(null),ue.current&&(ue.current.nodes([]),ue.current.getLayer()?.batchDraw());},[ue,o]),Fl=useCallback(y=>s?s.lines?.some(C=>C.id===y)?"line":s.images?.some(C=>C.id===y)?"image":s.videos?.some(C=>C.id===y)?"video":s.shapes?.some(C=>C.id===y)?"shape":s.texts?.some(C=>C.id===y)?"text":s.flashcards?.some(C=>C.id===y)?"flashcard":s.photoFrames?.some(C=>C.id===y)?"photoFrame":s.multipleChoices?.some(C=>C.id===y)?"mcq":s.trueFalses?.some(C=>C.id===y)?"trueFalse":s.shortAnswers?.some(C=>C.id===y)?"shortAnswer":s.LongAnswer?.some(C=>C.id===y)?"longAnswer":s.fillInTheBlanks?.some(C=>C.id===y)?"fillInTheBlanks":null:null,[s]),Bl=useCallback((y,C)=>{switch(r(le()),C){case "line":r(xn(y));break;case "image":r(Wr(y));break;case "video":r(_r(y));break;case "shape":r(Xr(y));break;case "text":r(Yr(y));break;case "flashcard":r(Zr(y));break;case "photoFrame":r(en(y));break;case "mcq":r(an(y));break;case "trueFalse":r(rn(y));break;case "shortAnswer":r(sn(y));break;case "longAnswer":r(dn(y));break;case "fillInTheBlanks":r(cn(y));break}eo(),Y();},[r,eo,Y]);useEffect(()=>{let y=C=>{if(C.key!=="Delete"||!l||me)return;let T=document.activeElement;if(T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement||T?.getAttribute("contenteditable")==="true")return;C.preventDefault();let ke=Fl(l);ke&&Bl(l,ke);};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[l,me,Fl,Bl]),useEffect(()=>{let y=ue.current;return ()=>{y&&y.nodes([]);}},[c]),useEffect(()=>{let y=C=>{me&&C.target.tagName!=="TEXTAREA"&&gs();};return document.addEventListener("mousedown",y),()=>{document.removeEventListener("mousedown",y);}},[me,gs]),useEffect(()=>{let y=me||l;if(!y||l&&me){b(null);return}let C=na.current.get(y),T=u.current;if(!C||!T){b(null);return}let D=T.container().getBoundingClientRect(),ke=C.absolutePosition(),Le=T.scaleX();b({x:D.left+(ke.x+C.width()*Le/2)*Le,y:D.top+ke.y*Le});},[l,me,qo,na]),useEffect(()=>{if(!me){V(null);return}let y=na.current.get(me),C=u.current;if(!y||!C){V(null);return}let T=C.container().getBoundingClientRect(),D=y.absolutePosition(),ke=C.scaleX();V({top:T.top+D.y*ke,left:T.left+D.x*ke,scale:ke});},[me,qo,na]);let Ol=useCallback(y=>{let C=y.target.getClassName(),T=y.target===y.target.getStage(),D=C==="Transformer"||y.target.getParent()?.getClassName()==="Transformer",ke=C==="Image",Le=C==="Text",ae=C==="Group"||y.target.getParent()?.getClassName()==="Group",Bt=C==="Circle"||C==="Star"||C==="RegularPolygon"||C==="Ellipse"||C==="Ring"||C==="Wedge"||C==="Arrow"||C==="Line"||C==="Arc"||C==="Rect"&&y.target.attrs.id,bt=C==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:C,clickedOnImage:ke,clickedOnGroup:ae,tool:n,targetId:y.target.attrs?.id}),T&&!D&&!ke&&!Le&&!ae&&!Bt&&!bt&&eo(),!(n==="pen"||n==="eraser")&&(ke||Le||D||ae||Bt||bt))return;let _e=y.target.getStage()?.getPointerPosition();if(!_e)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let B=qu(_e,x);Rt(B);}},[n,Rt,eo,x]),Nl=useCallback(y=>{if(Pl)return;let C=y.target.getStage()?.getPointerPosition();if(!C)return;let T=qu(C,x);Ja(T);},[Ja,Pl,x]),Vl=useCallback(()=>{Er();},[Er]),Qf=useCallback(y=>{he(y,Y);},[he,Y]),em=useCallback(y=>{Dt(y),Ue(y);},[Dt,Ue]),xt=useCallback((y,C,T)=>{y.preventDefault();let D=y.clientX,ke=y.clientY,Le=w.current?.offsetHeight||450,ae=w.current?.offsetWidth||450,Bt=window.innerHeight,bt=window.innerWidth,Ze=D,_e=ke;ke+Le>Bt&&(_e=ke-Le),D+ae>bt&&(Ze=D-ae),k({x:Ze,y:_e,elementId:C,elementType:T}),Ue(C);},[Ue]),ql=useCallback(y=>{r(Ko(y)),r(da(true));},[r]),tm=useCallback(y=>{r(Uo(y)),r(Ra(true));},[r]),am=useCallback((y,C)=>{if(!I)return;let{elementId:T,elementType:D}=I;switch(y){case "order":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(k(null),D==="line")break;let ke=s?D==="image"?s.images.find(M=>M.id===T):s.videos.find(M=>M.id===T):null;P({type:"link",defaultValue:ke?.link||""});break;case "voice":if(k(null),D==="line")break;let Le=s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="text"?s.texts.find(M=>M.id===T):D==="flashcard"?s.flashcards.find(M=>M.id===T):D==="photoFrame"?s.photoFrames.find(M=>M.id===T):D==="mcq"?s.multipleChoices.find(M=>M.id===T):D==="fillInTheBlanks"?s.fillInTheBlanks.find(M=>M.id===T):D==="longAnswer"?s.LongAnswer.find(M=>M.id===T):D==="shortAnswer"?s.shortAnswers.find(M=>M.id===T):D==="trueFalse"?s.trueFalses.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):null:null;X({elementId:T,elementType:D,existingAudio:Le?.audioData});break;case "edit":k(null);let ae=null;D==="mcq"?ae=s?.multipleChoices.find(M=>M.id===T):D==="trueFalse"?ae=s?.trueFalses.find(M=>M.id===T):D==="shortAnswer"?ae=s?.shortAnswers.find(M=>M.id===T):D==="longAnswer"?ae=s?.LongAnswer.find(M=>M.id===T):D==="fillInTheBlanks"&&(ae=s?.fillInTheBlanks.find(M=>M.id===T)),ae&&ql(ae);break;case "editFlashcard":k(null);let Bt=s?.flashcards.find(M=>M.id===T);Bt&&tm(Bt);break;case "color":k(null);let bt=s?.shapes.find(M=>M.id===T);E({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(k(null),D==="image"){let M=s?.images.find(dm=>dm.id===T);M&&N({elementId:T,imageSrc:M.src});}break;case "draw":k(null),D==="image"?r(Bs(T)):D==="photoFrame"&&r(Ns(T));break;case "duplicate":r(le()),D==="line"?r(Xs(T)):D==="image"?r(zr(T)):D==="video"?r(jr(T)):D==="shape"?r($r(T)):D==="text"?r(Jr(T)):D==="flashcard"?r(Qr(T)):D==="photoFrame"?r(tn(T)):D==="mcq"?r(on(T)):D==="trueFalse"?r(nn(T)):D==="shortAnswer"?r(ln(T)):D==="fillInTheBlanks"?r(fn(T)):D==="longAnswer"&&r(un(T)),Y();break;case "infinite-clone":r(le());let Ze=5;for(let M=0;M<Ze;M++)D==="image"?r(zr(T)):D==="video"?r(jr(T)):D==="shape"?r($r(T)):D==="text"?r(Jr(T)):D==="flashcard"?r(Qr(T)):D==="photoFrame"?r(tn(T)):D==="mcq"?r(on(T)):D==="trueFalse"?r(nn(T)):D==="shortAnswer"?r(ln(T)):D==="fillInTheBlanks"?r(fn(T)):D==="longAnswer"&&r(un(T));Y();break;case "make-response":if(k(null),D==="line")break;let _e=`#response-${T}`;r(le()),r(mn({id:T,type:D,link:_e})),(s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):D==="flashcard"?s.flashcards.find(M=>M.id===T):D==="photoFrame"?s.photoFrames.find(M=>M.id===T):s.multipleChoices.find(M=>M.id===T):null)?.altText||r(pn({id:T,type:D,altText:"Interactive response area"})),Y(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(k(null),D==="line")break;let B=s?D==="image"?s.images.find(M=>M.id===T):D==="video"?s.videos.find(M=>M.id===T):D==="shape"?s.shapes.find(M=>M.id===T):null:null;P({type:"altText",defaultValue:B?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),k(null),K(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(le()),D==="line"?r(xn(T)):D==="image"?r(Wr(T)):D==="video"?r(_r(T)):D==="shape"?r(Xr(T)):D==="text"?r(Yr(T)):D==="flashcard"?r(Zr(T)):D==="photoFrame"?r(en(T)):D==="mcq"?r(an(T)):D==="trueFalse"?r(rn(T)):D==="shortAnswer"?r(sn(T)):D==="longAnswer"?r(dn(T)):D==="fillInTheBlanks"&&r(cn(T)),eo(),Y();break}},[I,r,Y,eo,s,ql]),om=useCallback(()=>{k(null),H(null);},[]),xs=useCallback(y=>{if(!I)return;let{elementId:C,elementType:T}=I;switch(r(le()),y){case "bring-to-front":T!=="line"&&r(Ks({id:C,type:T}));break;case "send-to-back":T!=="line"&&r(_s({id:C,type:T}));break;case "lock":case "unlock":T!=="line"&&r(js({id:C,type:T}));break}Y(),k(null),H(null);},[I,r,Y]),rm=useCallback(y=>{if(!I||!q)return;let{elementId:C,elementType:T}=I;r(le()),q.type==="link"&&T!=="line"?r(mn({id:C,type:T,link:y})):q.type==="altText"&&T!=="line"&&r(pn({id:C,type:T,altText:y})),Y(),P(null);},[I,q,r,Y]),nm=useCallback(y=>{if(!O)return;let{elementId:C,elementType:T}=O;r(le()),r(hn({id:C,type:T,audioData:y})),Y(),X(null);},[O,r,Y]),sm=useCallback(()=>{if(!O)return;let{elementId:y,elementType:C}=O;r(le()),r(hn({id:y,type:C,audioData:""})),Y();},[O,r,Y]),im=useCallback(y=>{if(!W)return;let{elementId:C}=W;r(le()),r(oo({id:C,color:y})),Y(),E(null);},[W,r,Y]),lm=useCallback(y=>{if(!oe)return;let{elementId:C}=oe;r(le()),r(ao({id:C,src:y})),Y(),N(null);},[oe,r,Y]);return jsxs("div",{ref:m,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(Jl,{ref:y=>{if(te.current=y,Fr(y),y){let C=y.getCanvasElement();C&&(J.current=C,a&&a(J));}},width:x.baseWidth,height:x.baseHeight,tool:fs,color:ms,strokeWidth:ps/x.scale,isSketchMode:hs,xOffset:x.contentOffsetX,yOffset:x.contentOffsetY-x.offsetY/x.scale,style:{width:x.stageWidth,height:x.stageHeight}}),jsxs(Stage,{ref:u,width:x.stageWidth,height:x.stageHeight,scaleX:x.scaleX,scaleY:x.scaleY,x:x.offsetX,y:0,onMouseDown:Ol,onMouseMove:Nl,onMouseUp:Vl,onTouchStart:Ol,onTouchMove:Nl,onTouchEnd:Vl,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:x.baseWidth,height:x.stageHeight/x.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-x.contentOffsetX,y:x.offsetY/x.scale-x.contentOffsetY,children:(()=>{let y=[];return f.forEach((C,T)=>{y.push({type:"line",timestamp:C.timestamp||T,element:{...C,id:C.id??`line-${T}`},index:T});}),Nf.forEach(C=>{y.push({type:"shape",timestamp:C.timestamp||0,element:C});}),F.forEach(C=>{y.push({type:"image",timestamp:C.timestamp||0,element:C});}),re.forEach(C=>{y.push({type:"video",timestamp:C.timestamp||0,element:C});}),qo.forEach(C=>{y.push({type:"text",timestamp:C.timestamp||0,element:C});}),zf.forEach(C=>{y.push({type:"flashcard",timestamp:C.timestamp||0,element:C});}),El.forEach(C=>{y.push({type:"photoFrame",timestamp:C.timestamp||0,element:C});}),Ee.forEach(C=>{y.push({type:"mcq",timestamp:C.timestamp||0,element:C});}),Za.forEach(C=>{y.push({type:"trueFalse",timestamp:C.timestamp||0,element:C});}),ra.forEach(C=>{y.push({type:"shortAnswer",timestamp:C.timestamp||0,element:C});}),Ef.forEach(C=>{y.push({type:"longAnswer",timestamp:C.timestamp||0,element:C});}),Bf.forEach(C=>{y.push({type:"fillInTheBlanks",timestamp:C.timestamp||0,element:C});}),y.sort((C,T)=>C.timestamp-T.timestamp),y.map((C,T)=>{let D=`${C.type}-${"id"in C.element&&C.element.id||C.index||T}`,ke="id"in C.element?C.element.id:void 0,Le=ke&&l===ke;switch(C.type){case "line":let ae=C.element,Bt=C.index||0,bt=ae.tool==="eraser",Ze=ae.isSketch&&ae.tool==="pen",_e=ae.isSketch&&bt,vt=ae.id||`line-${Bt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),n==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{r(le()),r(Ur(Bt));},onTap:()=>{r(le()),r(Ur(Bt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:B=>{let M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:B=>{let M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},D):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:B=>{B?Ma.current.set(vt,B):Ma.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:n==="select",listening:n==="select",onClick:()=>{n==="select"&&(console.log("Line clicked:",vt),Ue(vt));},onTap:()=>{n==="select"&&(console.log("Line tapped:",vt),Ue(vt));},onDragEnd:B=>{r(le()),r(gn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onTransformEnd:B=>{r(le()),r(gn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onMouseEnter:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),xt(M,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ma.current.get(l);console.log("Line Transformer - selectedId:",l,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "shape":return jsxs(be__default.Fragment,{children:[jsx(ui,{onSelect:Ue,shapes:[C.element],shapeRefs:Or,handleShapeDragEnd:Vf,handleShapeResizeEnd:qf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Or.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "image":return jsxs(be__default.Fragment,{children:[jsx(si,{images:[C.element],getLoadedImage:ne,imageRefs:ve,onDragEnd:Qf,onTransform:se,onSelect:Ue,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ve.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "video":return jsxs(be__default.Fragment,{children:[jsx(di,{videos:[C.element],selectedId:l,videoRefs:Te,onVideoClick:em,onDragEnd:Yt,onTransformEnd:st,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Te.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "text":return jsxs(be__default.Fragment,{children:[jsx(Pd,{texts:[C.element],textRefs:na,onDragEnd:Hf,onTransformEnd:Uf,onSelect:Ue,onContextMenu:xt,onDoubleClick:Wf,editingTextId:me,editingValue:Rl,onEditingChange:Dl}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=na.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(mi,{flashcards:[C.element],flashcardRefs:qr,selectedId:l,onDragEnd:Gf,onTransform:Kf,onSelect:Ue,onNext:_f,onPrevious:jf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=qr.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(bi,{photoFrames:[C.element],photoFrameRefs:Hr,selectedId:l,onDragEnd:$f,onTransform:Xf,onSelect:Ue,onStartCamera:Yf,onCapture:Jf,cameraStreams:Zf,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Hr.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(ru,{handleMcqTransform:qe,multipleChoice:[C.element],handleSelect:Ue,mcqRefs:ht,handleDragEnd:Ta,onContextMenu:xt}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ht.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(iu,{trueFalses:[C.element],handleTrueFalseTransform:Qa,handleSelect:Ue,trueFalseRefs:Aa,onContextMenu:xt,handleDragEnd:Et}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Aa.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(Cu,{shortAnswers:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:Df}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Eu,{longAnswer:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:Ff}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(Ru,{fillInTheBlanks:[C.element],handleSelect:Ue,handleTransform:qe,onContextMenu:xt,handleDragEnd:Of,fibRefs:Br}),Le&&!me&&l&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Br.current.get(l);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},D);default:return null}})})()})]}),I&&jsx(zd,{menuRef:w,x:I.x,y:I.y,type:I.elementType,onAction:am,onClose:om,isDrawingMode:I.elementType==="image"?s?.images.find(y=>y.id===I.elementId)?.isDrawingMode:I.elementType==="photoFrame"?s?.photoFrames.find(y=>y.id===I.elementId)?.isDrawingMode:false}),R&&I&&jsx(Gd,{x:R.x,y:R.y,items:R.type==="order"?[{label:"Bring to Front",onClick:()=>xs("bring-to-front")},{label:"Send to Back",onClick:()=>xs("send-to-back")}]:[{label:s&&(I.elementType==="image"?s.images.find(y=>y.id===I.elementId)?.locked:s.videos.find(y=>y.id===I.elementId)?.locked)?"Unlock":"Lock",onClick:()=>xs(s&&(I.elementType==="image"?s.images.find(y=>y.id===I.elementId)?.locked:s.videos.find(y=>y.id===I.elementId)?.locked)?"unlock":"lock")}],onClose:()=>H(null)}),q&&jsx(Kd,{title:q.type==="link"?"Add Link":"Add Alt Text",label:q.type==="link"?"URL":"Alternative Text",placeholder:q.type==="link"?"https://example.com":"Describe this image/video",defaultValue:q.defaultValue,onSave:rm,onClose:()=>P(null)}),W&&jsx(_d,{defaultColor:W.defaultColor,onConfirm:im,onCancel:()=>E(null)}),oe&&jsx(Yd,{imageSrc:oe.imageSrc,onConfirm:lm,onCancel:()=>N(null)}),fe&&jsx(or,{onClose:()=>z(false),stageRef:u}),O&&jsx(Zd,{elementId:O.elementId,elementType:O.elementType,existingAudio:O.existingAudio,onSave:nm,onDelete:sm,onClose:()=>X(null)}),U&&jsx(tu,{selectedElementId:l||void 0,onClose:()=>K(false),onSelectElement:y=>{Ue(y),K(false);}}),s?.images.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.videos.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.shapes?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.texts?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.flashcards?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.photoFrames?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.multipleChoices?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.trueFalses?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.shortAnswers?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.LongAnswer?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),s?.fillInTheBlanks?.filter(y=>y.audioData).map(y=>jsx(It,{audioData:y.audioData,x:y.x,y:y.y,width:y.width},`audio-${y.id}`)),d&&jsx(bu,{editElement:i}),S&&(()=>{let y=me||l;if(!y)return null;let C=qo.find(T=>T.id===y);return C?jsx(vu,{text:C,position:S}):null})(),A&&me&&(()=>{let y=qo.find(C=>C.id===me);return y?jsx(wu,{text:y,editingValue:Rl,onEditingChange:Dl,onFinish:gs,position:{top:A.top,left:A.left},scale:A.scale,textareaRef:Q},me):null})()]})},Qx=Zx;var eb="SchooplaVideoStorage";var $t="videos",Yn=()=>new Promise((e,o)=>{let t=indexedDB.open(eb,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains($t)||r.createObjectStore($t,{keyPath:"id"});};}),Ga=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Yn(),n=a.transaction([$t],"readwrite").objectStore($t),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,i)=>{let d=n.put(s);d.onsuccess=()=>c(!0),d.onerror=()=>i(d.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var Hu=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Yn(),t=e.transaction([$t],"readonly").objectStore($t);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,c=new Map;s.forEach(i=>{c.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},$i=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Yn(),a=o.transaction([$t],"readwrite").objectStore($t);await new Promise((r,n)=>{let s=a.delete(e);s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Uu=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Yn(),t=e.transaction([$t],"readwrite").objectStore($t);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Wu=e=>URL.createObjectURL(e);function wa(e,o=[]){let t=[];function a(n,s){let c=be.createContext(s),i=t.length;t=[...t,s];let d=u=>{let{scope:m,children:l,...h}=u,g=m?.[e]?.[i]||c,p=be.useMemo(()=>h,Object.values(h));return jsx(g.Provider,{value:p,children:l})};d.displayName=n+"Provider";function f(u,m){let l=m?.[e]?.[i]||c,h=be.useContext(l);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${n}\``)}return [d,f]}let r=()=>{let n=t.map(s=>be.createContext(s));return function(c){let i=c?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:i}}),[c,i])}};return r.scopeName=e,[a,ab(r,...o)]}function ab(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let s=a.reduce((c,{useScope:i,scopeName:d})=>{let u=i(n)[`__scope${d}`];return {...c,...u}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function zu(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Cr(...e){return o=>{let t=false,a=e.map(r=>{let n=zu(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():zu(e[r],null);}}}}function Tt(...e){return be.useCallback(Cr(...e),e)}function _u(e){let o=ob(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),i=c.find(nb);if(i){let d=i.props.children,f=c.map(u=>u===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function ob(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=ib(r),c=sb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?Cr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var rb=Symbol("radix.slottable");function nb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rb}function sb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let i=n(...c);return r(...c),i}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function ib(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var ub=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rt=ub.reduce((e,o)=>{let t=_u(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:s,...c}=r,i=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...c,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function $e(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function Xi(e){let o=cb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),i=c.find(mb);if(i){let d=i.props.children,f=c.map(u=>u===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:u);return jsx(o,{...s,ref:r,children:be.isValidElement(d)?be.cloneElement(d,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function cb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=hb(r),c=pb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?Cr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var fb=Symbol("radix.slottable");function mb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===fb}function pb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let i=n(...c);return r(...c),i}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function hb(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function Jn(e){let o=e+"CollectionProvider",[t,a]=wa(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=g=>{let{scope:p,children:w}=g,x=be__default.useRef(null),v=be__default.useRef(new Map).current;return jsx(r,{scope:p,itemMap:v,collectionRef:x,children:w})};s.displayName=o;let c=e+"CollectionSlot",i=Xi(c),d=be__default.forwardRef((g,p)=>{let{scope:w,children:x}=g,v=n(c,w),L=Tt(p,v.collectionRef);return jsx(i,{ref:L,children:x})});d.displayName=c;let f=e+"CollectionItemSlot",u="data-radix-collection-item",m=Xi(f),l=be__default.forwardRef((g,p)=>{let{scope:w,children:x,...v}=g,L=be__default.useRef(null),I=Tt(p,L),k=n(f,w);return be__default.useEffect(()=>(k.itemMap.set(L,{ref:L,...v}),()=>void k.itemMap.delete(L))),jsx(m,{[u]:"",ref:I,children:x})});l.displayName=f;function h(g){let p=n(e+"CollectionConsumer",g);return be__default.useCallback(()=>{let x=p.collectionRef.current;if(!x)return [];let v=Array.from(x.querySelectorAll(`[${u}]`));return Array.from(p.itemMap.values()).sort((k,S)=>v.indexOf(k.ref.current)-v.indexOf(S.ref.current))},[p.collectionRef,p.itemMap])}return [{Provider:s,Slot:d,ItemSlot:l},h,a]}var To=globalThis?.document?be.useLayoutEffect:()=>{};var gb=be[" useId ".trim().toString()]||(()=>{}),xb=0;function Yu(e){let[o,t]=be.useState(gb());return To(()=>{t(a=>a??String(xb++));},[e]),(o?`radix-${o}`:"")}function Ju(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var bb=be[" useInsertionEffect ".trim().toString()]||To;function Qt({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=vb({defaultProp:o,onChange:t}),c=e!==void 0,i=c?e:r;{let f=be.useRef(e!==void 0);be.useEffect(()=>{let u=f.current;u!==c&&console.warn(`${a} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=c;},[c,a]);}let d=be.useCallback(f=>{if(c){let u=yb(f)?f(e):f;u!==e&&s.current?.(u);}else n(f);},[c,e,n,s]);return [i,d]}function vb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return bb(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function yb(e){return typeof e=="function"}var wb=be.createContext(void 0);function Po(e){let o=be.useContext(wb);return e||o||"ltr"}var Zi="rovingFocusGroup.onEntryFocus",Lb={bubbles:false,cancelable:true},kr="RovingFocusGroup",[Qi,Zu,Ib]=Jn(kr),[Sb,el]=wa(kr,[Ib]),[Cb,kb]=Sb(kr),Qu=be.forwardRef((e,o)=>jsx(Qi.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Qi.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Mb,{...e,ref:o})})}));Qu.displayName=kr;var Mb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:i,onEntryFocus:d,preventScrollOnEntryFocus:f=false,...u}=e,m=be.useRef(null),l=Tt(o,m),h=Po(n),[g,p]=Qt({prop:s,defaultProp:c??null,onChange:i,caller:kr}),[w,x]=be.useState(false),v=Ju(d),L=Zu(t),I=be.useRef(false),[k,S]=be.useState(0);return be.useEffect(()=>{let b=m.current;if(b)return b.addEventListener(Zi,v),()=>b.removeEventListener(Zi,v)},[v]),jsx(Cb,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:g,onItemFocus:be.useCallback(b=>p(b),[p]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>S(b=>b+1),[]),onFocusableItemRemove:be.useCallback(()=>S(b=>b-1),[]),children:jsx(rt.div,{tabIndex:w||k===0?-1:0,"data-orientation":a,...u,ref:l,style:{outline:"none",...e.style},onMouseDown:$e(e.onMouseDown,()=>{I.current=true;}),onFocus:$e(e.onFocus,b=>{let A=!I.current;if(b.target===b.currentTarget&&A&&!w){let V=new CustomEvent(Zi,Lb);if(b.currentTarget.dispatchEvent(V),!V.defaultPrevented){let R=L().filter(E=>E.focusable),H=R.find(E=>E.active),q=R.find(E=>E.id===g),W=[H,q,...R].filter(Boolean).map(E=>E.ref.current);ac(W,f);}}I.current=false;}),onBlur:$e(e.onBlur,()=>x(false))})})}),ec="RovingFocusGroupItem",tc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...c}=e,i=Yu(),d=n||i,f=kb(ec,t),u=f.currentTabStopId===d,m=Zu(t),{onFocusableItemAdd:l,onFocusableItemRemove:h,currentTabStopId:g}=f;return be.useEffect(()=>{if(a)return l(),()=>h()},[a,l,h]),jsx(Qi.ItemSlot,{scope:t,id:d,focusable:a,active:r,children:jsx(rt.span,{tabIndex:u?0:-1,"data-orientation":f.orientation,...c,ref:o,onMouseDown:$e(e.onMouseDown,p=>{a?f.onItemFocus(d):p.preventDefault();}),onFocus:$e(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:$e(e.onKeyDown,p=>{if(p.key==="Tab"&&p.shiftKey){f.onItemShiftTab();return}if(p.target!==p.currentTarget)return;let w=Pb(p,f.orientation,f.dir);if(w!==void 0){if(p.metaKey||p.ctrlKey||p.altKey||p.shiftKey)return;p.preventDefault();let v=m().filter(L=>L.focusable).map(L=>L.ref.current);if(w==="last")v.reverse();else if(w==="prev"||w==="next"){w==="prev"&&v.reverse();let L=v.indexOf(p.currentTarget);v=f.loop?Rb(v,L+1):v.slice(L+1);}setTimeout(()=>ac(v));}}),children:typeof s=="function"?s({isCurrentTabStop:u,hasTabStop:g!=null}):s})})});tc.displayName=ec;var Tb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Ab(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Pb(e,o,t){let a=Ab(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Tb[a]}function ac(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Rb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var oc=Qu,rc=tc;var sc="Toggle",tl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,c]=Qt({prop:t,onChange:r,defaultProp:a??false,caller:sc});return jsx(rt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:$e(e.onClick,()=>{e.disabled||c(!s);})})});tl.displayName=sc;var La="ToggleGroup",[lc]=wa(La,[el]),dc=el(),al=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Fb,{...a,ref:o});if(t==="multiple")return jsx(Bb,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${La}\``)});al.displayName=La;var[uc,cc]=lc(La),Fb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=Qt({prop:t,defaultProp:a??"",onChange:r,caller:La});return jsx(uc,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(fc,{...n,ref:o})})}),Bb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=Qt({prop:t,defaultProp:a??[],onChange:r,caller:La}),i=be__default.useCallback(f=>c((u=[])=>[...u,f]),[c]),d=be__default.useCallback(f=>c((u=[])=>u.filter(m=>m!==f)),[c]);return jsx(uc,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:i,onItemDeactivate:d,children:jsx(fc,{...n,ref:o})})});al.displayName=La;var[Ob,Nb]=lc(La),fc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:c=true,...i}=e,d=dc(t),f=Po(s),u={role:"group",dir:f,...i};return jsx(Ob,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(oc,{asChild:true,...d,orientation:n,dir:f,loop:c,children:jsx(rt.div,{...u,ref:o})}):jsx(rt.div,{...u,ref:o})})}),es="ToggleGroupItem",Vb=be__default.forwardRef((e,o)=>{let t=cc(es,e.__scopeToggleGroup),a=Nb(es,e.__scopeToggleGroup),r=dc(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,c={...e,pressed:n,disabled:s},i=be__default.useRef(null);return a.rovingFocus?jsx(rc,{asChild:true,...r,focusable:!s,active:n,ref:i,children:jsx(ic,{...c,ref:o})}):jsx(ic,{...c,ref:o})});Vb.displayName=es;var ic=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=cc(es,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=n.type==="single"?s:void 0;return jsx(tl,{...c,...r,ref:o,onPressedChange:i=>{i?n.onItemActivate(a):n.onItemDeactivate(a);}})}),mc=al;function pc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=pc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function ts(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=pc(e))&&(a&&(a+=" "),a+=o);return a}var Hb=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},Ub=(e,o)=>({classGroupId:e,validator:o}),vc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var hc=[],Wb="arbitrary..",zb=e=>{let o=Kb(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return Gb(s);let c=s.split("-"),i=c[0]===""&&c.length>1?1:0;return yc(c,i,o)},getConflictingClassGroupIds:(s,c)=>{if(c){let i=a[s],d=t[s];return i?d?Hb(d,i):i:d||hc}return t[s]||hc}}},yc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let d=yc(e,o+1,n);if(d)return d}let s=t.validators;if(s===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),i=s.length;for(let d=0;d<i;d++){let f=s[d];if(f.validator(c))return f.classGroupId}},Gb=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?Wb+a:void 0})(),Kb=e=>{let{theme:o,classGroups:t}=e;return _b(t,o)},_b=(e,o)=>{let t=vc();for(let a in e){let r=e[a];nl(r,t,a,o);}return t},nl=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];jb(s,o,t,a);}},jb=(e,o,t,a)=>{if(typeof e=="string"){$b(e,o,t);return}if(typeof e=="function"){Xb(e,o,t,a);return}Yb(e,o,t,a);},$b=(e,o,t)=>{let a=e===""?o:wc(o,e);a.classGroupId=t;},Xb=(e,o,t,a)=>{if(Jb(e)){nl(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Ub(t,e));},Yb=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[c,i]=r[s];nl(i,wc(o,c),t,a);}},wc=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let s=a[n],c=t.nextPart.get(s);c||(c=vc(),t.nextPart.set(s,c)),t=c;}return t},Jb=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Zb=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,s)=>{t[n]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let s=t[n];if(s!==void 0)return s;if((s=a[n])!==void 0)return r(n,s),s},set(n,s){n in t?t[n]=s:r(n,s);}}};var Qb=[],gc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),ev=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,c=0,i=0,d,f=r.length;for(let g=0;g<f;g++){let p=r[g];if(s===0&&c===0){if(p===":"){n.push(r.slice(i,g)),i=g+1;continue}if(p==="/"){d=g;continue}}p==="["?s++:p==="]"?s--:p==="("?c++:p===")"&&c--;}let u=n.length===0?r:r.slice(i),m=u,l=false;u.endsWith("!")?(m=u.slice(0,-1),l=true):u.startsWith("!")&&(m=u.slice(1),l=true);let h=d&&d>i?d-i:void 0;return gc(n,l,m,h)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):gc(Qb,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},tv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let s=t[n],c=s[0]==="[",i=o.has(s);c||i?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(s)):r.push(s);}return r.length>0&&(r.sort(),a.push(...r)),a}},av=e=>({cache:Zb(e.cacheSize),parseClassName:ev(e),sortModifiers:tv(e),...zb(e)}),ov=/\s+/,rv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],c=e.trim().split(ov),i="";for(let d=c.length-1;d>=0;d-=1){let f=c[d],{isExternal:u,modifiers:m,hasImportantModifier:l,baseClassName:h,maybePostfixModifierPosition:g}=t(f);if(u){i=f+(i.length>0?" "+i:i);continue}let p=!!g,w=a(p?h.substring(0,g):h);if(!w){if(!p){i=f+(i.length>0?" "+i:i);continue}if(w=a(h),!w){i=f+(i.length>0?" "+i:i);continue}p=false;}let x=m.length===0?"":m.length===1?m[0]:n(m).join(":"),v=l?x+"!":x,L=v+w;if(s.indexOf(L)>-1)continue;s.push(L);let I=r(w,p);for(let k=0;k<I.length;++k){let S=I[k];s.push(v+S);}i=f+(i.length>0?" "+i:i);}return i},nv=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Lc(t))&&(r&&(r+=" "),r+=a);return r},Lc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Lc(e[a]))&&(t&&(t+=" "),t+=o);return t},sv=(e,...o)=>{let t,a,r,n,s=i=>{let d=o.reduce((f,u)=>u(f),e());return t=av(d),a=t.cache.get,r=t.cache.set,n=c,c(i)},c=i=>{let d=a(i);if(d)return d;let f=rv(i,t);return r(i,f),f};return n=s,(...i)=>n(nv(...i))},iv=[],Ve=e=>{let o=t=>t[e]||iv;return o.isThemeGetter=true,o},Ic=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Sc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,lv=/^\d+\/\d+$/,dv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,cv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,fv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,mv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ro=e=>lv.test(e),ie=e=>!!e&&!Number.isNaN(Number(e)),Ia=e=>!!e&&Number.isInteger(Number(e)),ol=e=>e.endsWith("%")&&ie(e.slice(0,-1)),ea=e=>dv.test(e),pv=()=>true,hv=e=>uv.test(e)&&!cv.test(e),Cc=()=>false,gv=e=>fv.test(e),xv=e=>mv.test(e),bv=e=>!j(e)&&!$(e),vv=e=>Do(e,Tc,Cc),j=e=>Ic.test(e),ja=e=>Do(e,Ac,hv),rl=e=>Do(e,Sv,ie),xc=e=>Do(e,kc,Cc),yv=e=>Do(e,Mc,xv),as=e=>Do(e,Pc,gv),$=e=>Sc.test(e),Mr=e=>Eo(e,Ac),wv=e=>Eo(e,Cv),bc=e=>Eo(e,kc),Lv=e=>Eo(e,Tc),Iv=e=>Eo(e,Mc),os=e=>Eo(e,Pc,true),Do=(e,o,t)=>{let a=Ic.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Eo=(e,o,t=false)=>{let a=Sc.exec(e);return a?a[1]?o(a[1]):t:false},kc=e=>e==="position"||e==="percentage",Mc=e=>e==="image"||e==="url",Tc=e=>e==="length"||e==="size"||e==="bg-size",Ac=e=>e==="length",Sv=e=>e==="number",Cv=e=>e==="family-name",Pc=e=>e==="shadow";var kv=()=>{let e=Ve("color"),o=Ve("font"),t=Ve("text"),a=Ve("font-weight"),r=Ve("tracking"),n=Ve("leading"),s=Ve("breakpoint"),c=Ve("container"),i=Ve("spacing"),d=Ve("radius"),f=Ve("shadow"),u=Ve("inset-shadow"),m=Ve("text-shadow"),l=Ve("drop-shadow"),h=Ve("blur"),g=Ve("perspective"),p=Ve("aspect"),w=Ve("ease"),x=Ve("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...L(),$,j],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],b=()=>[$,j,i],A=()=>[Ro,"full","auto",...b()],V=()=>[Ia,"none","subgrid",$,j],R=()=>["auto",{span:["full",Ia,$,j]},Ia,$,j],H=()=>[Ia,"auto",$,j],q=()=>["auto","min","max","fr",$,j],P=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...b()],oe=()=>[Ro,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],N=()=>[e,$,j],fe=()=>[...L(),bc,xc,{position:[$,j]}],z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],O=()=>["auto","cover","contain",Lv,vv,{size:[$,j]}],X=()=>[ol,Mr,ja],U=()=>["","none","full",d,$,j],K=()=>["",ie,Mr,ja],Q=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[ie,ol,bc,xc],de=()=>["","none",h,$,j],Y=()=>["none",ie,$,j],Me=()=>["none",ie,$,j],De=()=>[ie,$,j],Se=()=>[Ro,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ea],breakpoint:[ea],color:[pv],container:[ea],"drop-shadow":[ea],ease:["in","out","in-out"],font:[bv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ea],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ea],shadow:[ea],spacing:["px",ie],text:[ea],"text-shadow":[ea],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ro,j,$,p]}],container:["container"],columns:[{columns:[ie,j,$,c]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:A()}],"inset-x":[{"inset-x":A()}],"inset-y":[{"inset-y":A()}],start:[{start:A()}],end:[{end:A()}],top:[{top:A()}],right:[{right:A()}],bottom:[{bottom:A()}],left:[{left:A()}],visibility:["visible","invisible","collapse"],z:[{z:[Ia,"auto",$,j]}],basis:[{basis:[Ro,"full","auto",c,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ie,Ro,"auto","initial","none",j]}],grow:[{grow:["",ie,$,j]}],shrink:[{shrink:["",ie,$,j]}],order:[{order:[Ia,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":V()}],"col-start-end":[{col:R()}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":V()}],"row-start-end":[{row:R()}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":q()}],"auto-rows":[{"auto-rows":q()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...P(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...P()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":P()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:oe()}],w:[{w:[c,"screen",...oe()]}],"min-w":[{"min-w":[c,"screen","none",...oe()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[s]},...oe()]}],h:[{h:["screen","lh",...oe()]}],"min-h":[{"min-h":["screen","lh","none",...oe()]}],"max-h":[{"max-h":["screen","lh",...oe()]}],"font-size":[{text:["base",t,Mr,ja]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,rl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ol,j]}],"font-family":[{font:[wv,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,j]}],"line-clamp":[{"line-clamp":[ie,"none",$,rl]}],leading:[{leading:[n,...b()]}],"list-image":[{"list-image":["none",$,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:[ie,"from-font","auto",$,ja]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[ie,"auto",$,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:fe()}],"bg-repeat":[{bg:z()}],"bg-size":[{bg:O()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ia,$,j],radial:["",$,j],conic:[Ia,$,j]},Iv,yv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:X()}],"gradient-via-pos":[{via:X()}],"gradient-to-pos":[{to:X()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:U()}],"rounded-s":[{"rounded-s":U()}],"rounded-e":[{"rounded-e":U()}],"rounded-t":[{"rounded-t":U()}],"rounded-r":[{"rounded-r":U()}],"rounded-b":[{"rounded-b":U()}],"rounded-l":[{"rounded-l":U()}],"rounded-ss":[{"rounded-ss":U()}],"rounded-se":[{"rounded-se":U()}],"rounded-ee":[{"rounded-ee":U()}],"rounded-es":[{"rounded-es":U()}],"rounded-tl":[{"rounded-tl":U()}],"rounded-tr":[{"rounded-tr":U()}],"rounded-br":[{"rounded-br":U()}],"rounded-bl":[{"rounded-bl":U()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Q(),"hidden","none"]}],"divide-style":[{divide:[...Q(),"hidden","none"]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...Q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ie,$,j]}],"outline-w":[{outline:["",ie,Mr,ja]}],"outline-color":[{outline:N()}],shadow:[{shadow:["","none",f,os,as]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":["none",u,os,as]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[ie,ja]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":["none",m,os,as]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[ie,$,j]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ie]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[ie]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:fe()}],"mask-repeat":[{mask:z()}],"mask-size":[{mask:O()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:de()}],brightness:[{brightness:[ie,$,j]}],contrast:[{contrast:[ie,$,j]}],"drop-shadow":[{"drop-shadow":["","none",l,os,as]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:["",ie,$,j]}],"hue-rotate":[{"hue-rotate":[ie,$,j]}],invert:[{invert:["",ie,$,j]}],saturate:[{saturate:[ie,$,j]}],sepia:[{sepia:["",ie,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":de()}],"backdrop-brightness":[{"backdrop-brightness":[ie,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[ie,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ie,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ie,$,j]}],"backdrop-invert":[{"backdrop-invert":["",ie,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[ie,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[ie,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",ie,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ie,"initial",$,j]}],ease:[{ease:["linear","initial",w,$,j]}],delay:[{delay:[ie,$,j]}],animate:[{animate:["none",x,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,j]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:Y()}],"rotate-x":[{"rotate-x":Y()}],"rotate-y":[{"rotate-y":Y()}],"rotate-z":[{"rotate-z":Y()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:De()}],"skew-x":[{"skew-x":De()}],"skew-y":[{"skew-y":De()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Se()}],"translate-x":[{"translate-x":Se()}],"translate-y":[{"translate-y":Se()}],"translate-z":[{"translate-z":Se()}],"translate-none":["translate-none"],accent:[{accent:N()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:N()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,j]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,j]}],fill:[{fill:["none",...N()]}],"stroke-w":[{stroke:[ie,Mr,ja,rl]}],stroke:[{stroke:["none",...N()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var Rc=sv(kv);function Sa(...e){return Rc(ts(e))}var Tv=be.createContext({size:"default",variant:"default",spacing:0});function Ca({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(mc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Sa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(Tv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Pv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Oc=createSlice({name:"toolbar",initialState:Pv,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:Wt,setPenColor:rs,setStrokeWidth:il,setFontSize:zA,setFontFamily:GA,setFontStyle:KA,setFontWeight:_A,setTextDecoration:jA,setTextColor:$A}=Oc.actions,Nc=Oc.reducer;var Vc=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,n]=useState(null),[s,c]=useState(0),[i,d]=useState(null),[f,u]=useState(false),m=useRef(null),l=useRef([]),h=useRef(null),g=useRef(null),p=useRef(null);useEffect(()=>((async()=>{try{let b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});d(b),u(!0),p.current&&(p.current.srcObject=b);}catch(b){console.error("Error accessing camera:",b),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),i&&i.getTracks().forEach(b=>b.stop());}),[]);let w=()=>{i&&(i.getTracks().forEach(S=>S.stop()),d(null),u(false));},x=async()=>{try{let S=null,b=null;try{S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(q){console.error("Error accessing camera for recording:",q),alert("Failed to access camera for recording.");return}try{b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(q){console.warn("Microphone access denied:",q);}let A=[...S.getVideoTracks()];b&&A.push(...b.getAudioTracks());let V=new MediaStream(A),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");let H=new MediaRecorder(V,{mimeType:R,videoBitsPerSecond:25e5});m.current=H,l.current=[],H.ondataavailable=q=>{q.data.size>0&&l.current.push(q.data);},H.onstop=()=>{let q=new Blob(l.current,{type:R}),P=document.createElement("video");P.src=URL.createObjectURL(q),P.muted=!0,P.currentTime=.1,P.onseeked=()=>{let W=document.createElement("canvas");W.width=P.videoWidth,W.height=P.videoHeight;let E=W.getContext("2d");E&&(E.drawImage(P,0,0),g.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(P.src);},V.getTracks().forEach(W=>W.stop()),S&&S.getTracks().forEach(W=>W.stop()),b&&b.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current),n(q),w();},H.onerror=q=>{console.error("MediaRecorder error:",q);},H.start(1e3),a(!0),c(0),h.current=setInterval(()=>{c(q=>q+1);},1e3);}catch(S){console.error("Error starting camera recording:",S),alert("Failed to start recording. Please check permissions.");}},v=()=>{m.current&&t&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),a(false));},L=()=>{if(r){let S=URL.createObjectURL(r),b=document.createElement("a");b.href=S,b.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(S);}},I=S=>{let b=Math.floor(S/60),A=S%60;return `${b.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`},k=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50 p-6",onMouseDown:S=>{S.target===S.currentTarget&&e(),S.stopPropagation();},onMouseUp:S=>S.stopPropagation(),onMouseMove:S=>S.stopPropagation(),onTouchStart:S=>S.stopPropagation(),onTouchMove:S=>S.stopPropagation(),onTouchEnd:S=>S.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:S=>S.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:p,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!t&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:x,disabled:!f,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!f&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),t&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:v,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:I(s)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",I(s)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),c(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:L,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&g.current&&(o(r,g.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,document.body)};var ta=40,Hc=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[c,i]=useState(false),d=useRef(null),f=useRef(null);useEffect(()=>{let x=v=>{v.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let u=x=>{let v=x.target.files;if(!v||v.length===0)return;let L=ta-a.length;if(L<=0){alert(`You can only upload a maximum of ${ta} images`);return}let I=Array.from(v).slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${ta} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=R=>{R.target?.result?b(R.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]),f.current&&(f.current.value="");});},m=x=>{x.preventDefault(),i(false);let v=Array.from(x.dataTransfer.files).filter(S=>S.type.startsWith("image/"));if(v.length===0)return;let L=ta-a.length;if(L<=0){alert(`You can only upload a maximum of ${ta} images`);return}let I=v.slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${ta} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=R=>{R.target?.result?b(R.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]);});},l=x=>{x.preventDefault(),i(true);},h=()=>{i(false);},g=x=>{r(v=>v.filter((L,I)=>I!==x));},w=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:d,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);},className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=ta?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ta," images"]}):jsxs("span",{children:[a.length,"/",ta," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:u,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:l,onDragLeave:h,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${c?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp$1,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((x,v)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${v+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>g(v),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:v+1})]},v))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(w,document.body)};var ns={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},_v={enabled:true};function ul(e){return e?{tools:{...ns.tools,...e.tools},actions:{...ns.actions,...e.actions}}:ns}var jv={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},$v={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var wy=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:r}={})=>{let n=xe(),s=ee(F=>F.canvas.slides.find(ne=>ne.id===F.canvas.currentSlideId)),c=s?.videos||[],i=s?.editingFlashcard,d=ee(F=>F.toolbar.selectedTool),f=ee(F=>F.toolbar.penColor),u=s?.showMcqForm,m=s?.showFlashcardForm,l=useMemo(()=>ul(r),[r]),{tools:h,actions:g}=l,p=c.some(F=>F.isRecorded&&F.isPlaying),w=ee(F=>F.toolbar.fontSize),x=ee(F=>F.toolbar.fontFamily),v=ee(F=>F.toolbar.fontStyle),L=ee(F=>F.toolbar.fontWeight),I=ee(F=>F.toolbar.textDecoration),k=ee(F=>F.toolbar.textColor),[S,b]=useState(false),[A,V]=useState(false),[R,H]=useState(false),[q,P]=useState(false),[W,E]=useState(false),oe=useRef(null),N=useRef(null),fe=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),z=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),O=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),X=useMemo(()=>fe.filter(F=>{let ne=h[F.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[h,fe]),U=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?z:Array.isArray(F)?z.filter(ne=>F.includes(ne.name)):z},[h.shapes,z]),K=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?O:Array.isArray(F)?O.filter(ne=>F.includes(ne.name)):O},[h.activities,O]),Q=useMemo(()=>{let F=h.media;return F===false?{photoFrame:false,image:false,video:false}:F===true?{photoFrame:true,image:true,video:true}:Array.isArray(F)?{photoFrame:F.includes("photo-frame"),image:F.includes("image"),video:F.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),te=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),J=F=>{let ne=F.target.files;!ne||ne.length===0||(n(Wt("select")),n(it(false)),P(false),Array.from(ne).forEach(ve=>{let he=new FileReader;he.onload=se=>{let re=new window.Image;re.src=se.target?.result,re.onload=()=>{let Te=re.width/re.height,Dt=300,Yt=300,st=re.width,Ee=re.height;st>Dt&&(st=Dt,Ee=st/Te),Ee>Yt&&(Ee=Yt,st=Ee*Te),n(le());let qe=(window.innerWidth-st)/2,ht=(window.innerHeight-Ee)/2;n(Ts({id:v4(),src:re.src,x:qe,y:ht,width:st,height:Ee,draggable:true,rotation:0}));};},he.readAsDataURL(ve);}),F.target.value="");},de=async F=>{let ne=F.target.files;if(!(!ne||ne.length===0)){console.log("files",F),n(Wt("select")),n(it(false)),P(false);for(let ve of Array.from(ne))try{let he=URL.createObjectURL(ve),se=document.createElement("video");console.log("video",se),se.src=he,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Et,ra)=>{let Ft=setTimeout(()=>ra(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ft),Et();},se.onerror=()=>{clearTimeout(Ft),ra(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Et,ra)=>{let Ft=setTimeout(()=>ra(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ft),Et()):se.onloadeddata=()=>{clearTimeout(Ft),Et();};});let re=Math.min(.8,se.duration/2);console.log("Seeking to:",re),se.currentTime=re,await new Promise(Et=>{let ra=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Et();},5e3);se.onseeked=()=>{clearTimeout(ra),console.log("Seek completed"),Et();};});let Te=document.createElement("canvas"),Dt=se.videoWidth/se.videoHeight,Yt=400,st=400,Ee=se.videoWidth,qe=se.videoHeight;Ee>Yt&&(Ee=Yt,qe=Ee/Dt),qe>st&&(qe=st,Ee=qe*Dt),Te.width=Ee,Te.height=qe;let ht=Te.getContext("2d",{willReadFrequently:!1});if(!ht)throw new Error("Failed to get canvas context");if(await new Promise(Et=>setTimeout(Et,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ee,height:qe}),ht.drawImage(se,0,0,Ee,qe);let Ta=Te.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ta.length),n(le());let Za=(window.innerWidth-Ee)/2,Qa=(window.innerHeight-qe)/2,Aa=v4();await Ga(Aa,ve,Ta),n(Gr({id:Aa,objectUrl:he,thumbnailDataUrl:Ta,videoBlob:ve,x:Za,y:Qa,width:Ee,height:qe,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${ve.name}`);}catch(he){console.error("Error processing video:",he),alert(`Failed to process video: ${ve.name}`);}F.target.value="";}},Y=(F,ne,ve)=>{n(le()),n(Wt("select")),n(it(false));let he=300,se=300,re=(window.innerWidth-he)/2,Te=(window.innerHeight-se)/2;n(ve?ro({id:ve,images:F,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true}):Rs({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true})),n(Ra(false));},Me=()=>{n(le()),n(Wt("select")),n(it(false));let F=400,ne=300,ve=(window.innerWidth-F)/2,he=(window.innerHeight-ne)/2;n(Fs({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ve,y:he,width:F,height:ne,rotation:0,draggable:true,isCapturing:false})),E(false);},De=F=>{let he=(window.innerWidth-100)/2,se=(window.innerHeight-100)/2,re={};switch(F.name){case "circle":case "ring":case "wedge":case "arc":re.radius=50,(F.name==="ring"||F.name==="arc")&&(re.innerRadius=25,re.outerRadius=50),(F.name==="wedge"||F.name==="arc")&&(re.angle=F.name==="wedge"?60:90);break;case "ellipse":re.radiusX=60,re.radiusY=40;break;case "triangle":re.radius=50,re.sides=3;break;case "polygon":re.radius=50,re.sides=6;break;case "star":re.innerRadius=25,re.outerRadius=50,re.numPoints=5;break;case "arrow":case "line":re.points=[0,0,100,0],F.name==="arrow"&&(re.pointerLength=10,re.pointerWidth=10);break}let Te={id:`shape-${Date.now()}`,type:F.name,x:he,y:se,width:100,height:100,rotation:0,color:f,...re};n(le()),n(it(false)),n(Wt(F.name)),n(As(Te));},Se=F=>{if(n(Wt(F)),F==="select")n(it(false));else if(F==="text"){n(it(false)),n(le());let ne=200,ve=50,he=(window.innerWidth-ne)/2,se=(window.innerHeight-ve)/2,re=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(Ps({id:re,text:"",x:he,y:se,width:ne,height:ve,rotation:0,draggable:true,fontSize:w,fontFamily:x,fontStyle:v,fontWeight:L,textDecoration:I,fill:k,align:"left"})),setTimeout(()=>{n(jo(re));},100),a&&a(re);}else n(it(true));},Rt=()=>{n(Ys()),n(Wt("select")),n(it(false));},Ja=()=>{o?o():t?b(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Er=()=>{V(true);},Fr=async(F,ne)=>{try{n(Wt("select")),n(it(!1));let ve=URL.createObjectURL(F),he=document.createElement("video");he.src=ve,he.muted=!0,he.playsInline=!0,he.preload="auto",await new Promise((Ta,Za)=>{let Qa=setTimeout(()=>Za(new Error("Metadata load timeout")),1e4);he.onloadedmetadata=()=>{clearTimeout(Qa),Ta();},he.onerror=()=>{clearTimeout(Qa),Za(new Error("Failed to load video"));};});let se=640,re=he.videoWidth/he.videoHeight,Te=se,Dt=Te/re,Yt=window.innerWidth,st=window.innerHeight;n(le());let Ee=(Yt-Te)/2,qe=(st-Dt)/2,ht=v4();await Ga(ht,F,ne),n(Gr({id:ht,objectUrl:ve,thumbnailDataUrl:ne,videoBlob:F,x:Ee,y:qe,width:Te,height:Dt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),b(!1),V(!1);}catch(ve){console.error("Error adding recorded video to canvas:",ve),alert("Failed to add video to canvas. Please try again.");}},fs=F=>{n(Wt("select")),n(it(false)),n(Ko(null)),F&&n(Gs(F)),n(da(!u));},ms=()=>{n(Uo(null)),n(Ra(true)),E(false);},ps=()=>{H(!R);},hs=()=>{P(!q);},Ma=()=>{E(!W);};return p?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ca,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:X.map((F,ne)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 2xl:py-3 ${F.name===d?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){hs(),H(false),E(false),Se(F.name);return}else if(F.name==="shapes"){ps(),P(false),E(false),Se(F.name);return}else if(F.name==="activities"){Se(F.name),Ma(),H(false),P(false);return}Se(F.name),H(false),P(false),E(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),R&&jsx(Ca,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:U.map((F,ne)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",onClick:()=>De(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),q&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Q.photoFrame&&jsx("div",{title:"Photo frame",onClick:Me,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Q.image&&jsx("div",{title:"Image",onClick:()=>oe.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),Q.video&&jsx("div",{title:"Video",onClick:()=>N.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})})]}),W&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[te&&jsx("div",{title:"Flashcard",onClick:()=>ms(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),K.map((F,ne)=>jsx("div",{title:F.label,onClick:()=>fs(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Ca,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>n(Js()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>n(Zs()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:Ja,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6279F8]",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Er,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6BBB93]",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>Rt(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl 2xl:text-2xl"})})]})]}),jsx("input",{ref:oe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:J}),jsx("input",{ref:N,type:"file",accept:"video/*",className:"hidden",onChange:de}),!o&&S&&t&&jsx(or,{onClose:()=>b(false),stageRef:t,onRecordingComplete:Fr}),A&&jsx(Vc,{onClose:()=>V(false),onRecordingComplete:Fr}),m&&jsx(Hc,{editingFlashcard:i,onConfirm:Y,onCancel:()=>n(Ra(false))})]})},Ly=wy;var pl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=sa(Xo),s=(sa(h=>h.canvas.slides.find(g=>g.id===h.canvas.currentSlideId))?.videos||[]).some(h=>h.isRecorded&&h.isPlaying),[c,i]=useState(false),[d,f]=useState(null),[u,m]=useState(null),l=async()=>{if(a.length===0){m({type:"error",message:"No slides to publish"});return}if(!e){m({type:"error",message:"No publish handler provided"});return}i(true),m(null);try{let h=await e(a,g=>{f(g);});h.success?m({type:"success",message:h.message}):m({type:"error",message:h.message});}catch(h){m({type:"error",message:h instanceof Error?h.message:"An unexpected error occurred"});}finally{i(false),setTimeout(()=>{f(null),m(null);},3e3);}};return s?null:jsxs("button",{onClick:l,disabled:c||a.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Ty=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,showPublishButton:r=true,showBackButton:n=true,className:s="",rightContent:c,leftContent:i})=>jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${s}`,children:[i||jsxs("div",{className:"flex items-center gap-6",children:[n&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"text-xl font-medium text-[#000000CC] md:text-2xl",children:e}),jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[jsx(CloudArrowUp,{weight:"fill",color:"#63748A",className:"text-sm md:text-xl"}),jsx("span",{className:"text-sm font-medium text-[#63748A] md:text-base",children:o})]})]})]}),c||r&&a&&jsx(pl,{onPublish:a})]});function hl(e,[o,t]){return Math.min(t,Math.max(o,e))}function zc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function Kc(e){let[o,t]=be.useState(void 0);return To(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],s,c;if("borderBoxSize"in n){let i=n.borderBoxSize,d=Array.isArray(i)?i[0]:i;s=d.inlineSize,c=d.blockSize;}else s=e.offsetWidth,c=e.offsetHeight;t({width:s,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var _c=["PageUp","PageDown"],jc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$c={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Oo="Slider",[gl,Py,Ry]=Jn(Oo),[Xc]=wa(Oo,[Ry]),[Dy,ls]=Xc(Oo),Yc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:c=false,minStepsBetweenThumbs:i=0,defaultValue:d=[a],value:f,onValueChange:u=()=>{},onValueCommit:m=()=>{},inverted:l=false,form:h,...g}=e,p=be.useRef(new Set),w=be.useRef(0),v=s==="horizontal"?Ey:Fy,[L=[],I]=Qt({prop:f,defaultProp:d,onChange:R=>{[...p.current][w.current]?.focus(),u(R);}}),k=be.useRef(L);function S(R){let H=qy(L,R);V(R,H);}function b(R){V(R,w.current);}function A(){let R=k.current[w.current];L[w.current]!==R&&m(L);}function V(R,H,{commit:q}={commit:false}){let P=zy(n),W=Gy(Math.round((R-a)/n)*n+a,P),E=hl(W,[a,r]);I((oe=[])=>{let N=Ny(oe,E,H);if(Wy(N,i*n)){w.current=N.indexOf(E);let fe=String(N)!==String(oe);return fe&&q&&m(N),fe?N:oe}else return oe});}return jsx(Dy,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:r,valueIndexToChangeRef:w,thumbs:p.current,values:L,orientation:s,form:h,children:jsx(gl.Provider,{scope:e.__scopeSlider,children:jsx(gl.Slot,{scope:e.__scopeSlider,children:jsx(v,{"aria-disabled":c,"data-disabled":c?"":void 0,...g,ref:o,onPointerDown:$e(g.onPointerDown,()=>{c||(k.current=L);}),min:a,max:r,inverted:l,onSlideStart:c?void 0:S,onSlideMove:c?void 0:b,onSlideEnd:c?void 0:A,onHomeKeyDown:()=>!c&&V(a,0,{commit:true}),onEndKeyDown:()=>!c&&V(r,L.length-1,{commit:true}),onStepKeyDown:({event:R,direction:H})=>{if(!c){let W=_c.includes(R.key)||R.shiftKey&&jc.includes(R.key)?10:1,E=w.current,oe=L[E],N=n*W*H;V(oe+N,E,{commit:true});}}})})})})});Yc.displayName=Oo;var[Jc,Zc]=Xc(Oo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Ey=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:c,onSlideEnd:i,onStepKeyDown:d,...f}=e,[u,m]=be.useState(null),l=Tt(o,v=>m(v)),h=be.useRef(void 0),g=Po(r),p=g==="ltr",w=p&&!n||!p&&n;function x(v){let L=h.current||u.getBoundingClientRect(),I=[0,L.width],S=vl(I,w?[t,a]:[a,t]);return h.current=L,S(v-L.left)}return jsx(Jc,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:jsx(Qc,{dir:g,"data-orientation":"horizontal",...f,ref:l,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{let L=x(v.clientX);s?.(L);},onSlideMove:v=>{let L=x(v.clientX);c?.(L);},onSlideEnd:()=>{h.current=void 0,i?.();},onStepKeyDown:v=>{let I=$c[w?"from-left":"from-right"].includes(v.key);d?.({event:v,direction:I?-1:1});}})})}),Fy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:c,onStepKeyDown:i,...d}=e,f=be.useRef(null),u=Tt(o,f),m=be.useRef(void 0),l=!r;function h(g){let p=m.current||f.current.getBoundingClientRect(),w=[0,p.height],v=vl(w,l?[a,t]:[t,a]);return m.current=p,v(g-p.top)}return jsx(Jc,{scope:e.__scopeSlider,startEdge:l?"bottom":"top",endEdge:l?"top":"bottom",size:"height",direction:l?1:-1,children:jsx(Qc,{"data-orientation":"vertical",...d,ref:u,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{let p=h(g.clientY);n?.(p);},onSlideMove:g=>{let p=h(g.clientY);s?.(p);},onSlideEnd:()=>{m.current=void 0,c?.();},onStepKeyDown:g=>{let w=$c[l?"from-bottom":"from-top"].includes(g.key);i?.({event:g,direction:w?-1:1});}})})}),Qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:c,onStepKeyDown:i,...d}=e,f=ls(Oo,t);return jsx(rt.span,{...d,ref:o,onKeyDown:$e(e.onKeyDown,u=>{u.key==="Home"?(s(u),u.preventDefault()):u.key==="End"?(c(u),u.preventDefault()):_c.concat(jc).includes(u.key)&&(i(u),u.preventDefault());}),onPointerDown:$e(e.onPointerDown,u=>{let m=u.target;m.setPointerCapture(u.pointerId),u.preventDefault(),f.thumbs.has(m)?m.focus():a(u);}),onPointerMove:$e(e.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&r(u);}),onPointerUp:$e(e.onPointerUp,u=>{let m=u.target;m.hasPointerCapture(u.pointerId)&&(m.releasePointerCapture(u.pointerId),n(u));})})}),ef="SliderTrack",tf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ls(ef,t);return jsx(rt.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});tf.displayName=ef;var xl="SliderRange",af=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=ls(xl,t),n=Zc(xl,t),s=be.useRef(null),c=Tt(o,s),i=r.values.length,d=r.values.map(m=>nf(m,r.min,r.max)),f=i>1?Math.min(...d):0,u=100-Math.max(...d);return jsx(rt.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:c,style:{...e.style,[n.startEdge]:f+"%",[n.endEdge]:u+"%"}})});af.displayName=xl;var bl="SliderThumb",of=be.forwardRef((e,o)=>{let t=Py(e.__scopeSlider),[a,r]=be.useState(null),n=Tt(o,c=>r(c)),s=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(By,{...e,ref:n,index:s})}),By=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=ls(bl,t),c=Zc(bl,t),[i,d]=be.useState(null),f=Tt(o,x=>d(x)),u=i?s.form||!!i.closest("form"):true,m=Kc(i),l=s.values[a],h=l===void 0?0:nf(l,s.min,s.max),g=Vy(a,s.values.length),p=m?.[c.size],w=p?Hy(p,h,c.direction):0;return be.useEffect(()=>{if(i)return s.thumbs.add(i),()=>{s.thumbs.delete(i);}},[i,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${h}% + ${w}px)`},children:[jsx(gl.ItemSlot,{scope:e.__scopeSlider,children:jsx(rt.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":s.min,"aria-valuenow":l,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...n,ref:f,style:l===void 0?{display:"none"}:e.style,onFocus:$e(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),u&&jsx(rf,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:l},a)]})});of.displayName=bl;var Oy="RadioBubbleInput",rf=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=Tt(r,a),s=zc(o);return be.useEffect(()=>{let c=r.current;if(!c)return;let i=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&f){let u=new Event("input",{bubbles:true});f.call(c,o),c.dispatchEvent(u);}},[s,o]),jsx(rt.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});rf.displayName=Oy;function Ny(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function nf(e,o,t){let n=100/(t-o)*(e-o);return hl(n,[0,100])}function Vy(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function qy(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function Hy(e,o,t){let a=e/2,n=vl([0,50],[0,a]);return (a-n(o)*t)*t}function Uy(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Wy(e,o){if(o>0){let t=Uy(e);return Math.min(...t)>=o}return true}function vl(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function zy(e){return (String(e).split(".")[1]||"").length}function Gy(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var sf=Yc,lf=tf,df=af,uf=of;function ff({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:c,...i}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(sf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Sa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(lf,{"data-slot":"slider-track",className:Sa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",s),children:jsx(df,{"data-slot":"slider-range",className:Sa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:d.length},(f,u)=>jsx(uf,{"data-slot":"slider-thumb",className:Sa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",c)},u))]})}var $y=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Xy=({colors:e=$y,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let n=ee(c=>c.toolbar.penColor),s=xe();return jsxs("div",{className:`absolute bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:p-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(ff,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:c=>s(il(c[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(Ca,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(c=>jsx("button",{value:c.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${n===c.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:c.value},onClick:()=>s(rs(c.value))},c.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(rs(c.target.value))}),jsx(Plus,{color:"#00000099"})]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center px-2 2xl:px-4",children:jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033] lg:h-12 lg:w-12",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(ks(c.target.value))})})})]})};function Yy({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var pf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Zy=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),wl=e=>{let o=Zy(e);return o.charAt(0).toUpperCase()+o.slice(1)},ds=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),hf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var gf={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 bf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:s,...c},i)=>createElement("svg",{ref:i,...gf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:ds("lucide",r),...!n&&!hf(c)&&{"aria-hidden":"true"},...c},[...s.map(([d,f])=>createElement(d,f)),...Array.isArray(n)?n:[n]]));var us=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(bf,{ref:n,iconNode:o,className:ds(`lucide-${pf(wl(e))}`,`lucide-${e}`,a),...r}));return t.displayName=wl(e),t};var aw=[["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"}]],Rr=us("copy",aw);var ow=[["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"}]],Dr=us("trash-2",ow);var yf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"shadow-lg":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:r,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:c=>{c.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Rr,{size:14})}),!a&&jsx("button",{onClick:c=>{c.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Dr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var iw=()=>{let e=yt(),o=sa(Xo),t=sa($o),a=sa(Qs),[r,n]=useState(true),i=(sa(l=>l.canvas.slides.find(h=>h.id===l.canvas.currentSlideId))?.videos||[]).some(l=>l.isRecorded&&l.isPlaying),d=()=>{a&&e(ws());},f=l=>{e(Ss(l));},u=l=>{e(Is(l));},m=l=>{o.length>1&&e(Ls(l));};return i?null:jsxs("div",{className:"pointer-events-none fixed top-22.5 right-0 bottom-0 z-100 hidden items-start md:flex",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[o.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:o.map((l,h)=>jsx(yf,{slide:l,index:h,isSelected:l.id===t,isSingleSlide:o.length===1,onSelect:()=>f(l.id),onDuplicate:()=>u(l.id),onDelete:()=>m(l.id)},l.id))}),jsxs("button",{onClick:d,disabled:!a,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${a?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var lw="SchooplaEditorDB",dw=1,ka="slides",Ll="schoopla_current_slide_id",Il=()=>new Promise((e,o)=>{let t=indexedDB.open(lw,dw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ka)||r.createObjectStore(ka,{keyPath:"id"});};}),Sl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Il(),a=o.transaction([ka],"readwrite").objectStore(ka);await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);});for(let r of e)await new Promise((n,s)=>{let c=a.add(r);c.onsuccess=()=>n(!0),c.onerror=()=>s(c.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Cl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Il(),t=e.transaction([ka],"readonly").objectStore(ka);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.y}))),a(s.length>0?s:null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},cs=async()=>{try{let e=await Il(),t=e.transaction([ka],"readwrite").objectStore(ka);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(Ll),await Uu();}catch(e){console.error("Error clearing local data:",e);}},kl=e=>{try{localStorage.setItem(Ll,e);}catch(o){console.error("Error saving current slide ID:",o);}},Ml=()=>{try{return localStorage.getItem(Ll)}catch(e){return console.error("Error loading current slide ID:",e),null}},If=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}};var uw=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides"],cw=["canvas/clearCanvas"],fw=If((e,o)=>{Sl(e),kl(o);},500),mw=(e,o)=>{Sl(e),kl(o);},Tl=false,Sf=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;$i(r).catch(n=>{console.error("Error deleting video blob:",n);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,s=e.getState().canvas.slides.find(c=>c.id===r);s&&s.videos&&s.videos.length>0&&s.videos.forEach(c=>{$i(c.id).catch(i=>{console.error("Error deleting video blob:",i);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),c=n.canvas.slides.find(i=>i.id===n.canvas.currentSlideId)?.videos.find(i=>i.id===r);c&&c.videoBlob&&setTimeout(()=>{let i=e.getState(),f=i.canvas.slides.find(u=>u.id===i.canvas.currentSlideId)?.videos.find(u=>u.id!==r&&u.x===c.x+20&&u.y===c.y+20);f&&c.videoBlob&&Ga(f.id,c.videoBlob,f.thumbnailDataUrl).catch(u=>{console.error("Error saving duplicated video blob:",u);});},0);}let a=o(t);if(t.type&&cw.includes(t.type)){if(!Tl){Tl=true;try{let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;mw(n,s);}finally{setTimeout(()=>{Tl=false;},0);}}}else if(t.type&&uw.includes(t.type)){let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;fw(n,s);}return a});new QueryClient;var gw=configureStore({reducer:{toolbar:Nc,canvas:Gl},middleware:e=>e({serializableCheck:false}).concat(Sf)});var xw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:s,quality:a,pixelRatio:r}),i=document.createElement("a");i.download=`${n}.${t}`,i.href=c,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},bw=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,s)=>{try{let c=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:c,quality:a,pixelRatio:r});fetch(i).then(d=>d.blob()).then(d=>n(d)).catch(d=>s(d));}catch(c){s(c);}})},vw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var yw=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),c=o.x+s*a,i=o.y+s*r;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-i,2))},Al=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let s=1;s<e.length-1;s++){let c=yw(e[s],r,n);c>t&&(t=c,a=s);}if(t>o){let s=Al(e.slice(0,a+1),o),c=Al(e.slice(a),o);return [...s.slice(0,-1),...c]}return [r,n]},ww=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Lw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Cf=(e,o=1.5)=>{if(e.length<=4)return e;let t=ww(e),a=Al(t,o);return Lw(a)},kf=(e,o=1.5)=>({...e,points:Cf(e.points,o)}),Iw=(e,o=1.5)=>e.map(t=>kf(t,o)),Sw=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var Cw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Mf=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,s)=>{let c=new Image;c.onload=()=>{let{width:i,height:d}=c;if(i>t||d>a){let h=i/d;i>d?(i=Math.min(i,t),d=i/h):(d=Math.min(d,a),i=d*h);}let f=document.createElement("canvas");f.width=i,f.height=d;let u=f.getContext("2d");if(!u){s(new Error("Failed to get canvas context"));return}u.drawImage(c,0,0,i,d);let m=Cw(e),l=f.toDataURL(m,r);n(l);},c.onerror=s,c.src=e;})};var Ya=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},No=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Vo=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",kw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,s=[],c=0;for(let i of e){let d=[],f=[],u=[];for(let m of i.images){let l=m.src;if(t&&l.startsWith("data:"))try{l=await Mf(l,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(l.startsWith("data:")){let h=Ya(l),g=No(l);c+=h.byteLength;let p={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,buffer:h,mimeType:g};if(m.audioData&&m.audioData.startsWith("data:")){let w=Ya(m.audioData),x=No(m.audioData);c+=w.byteLength,p.audioBuffer=w,p.audioMimeType=x;}d.push(p);}}for(let m of i.videos){let l,h;if(m.videoBlob)l=await m.videoBlob.arrayBuffer(),h=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))l=Ya(m.videoData),h=No(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}c+=l.byteLength;let g={id:m.id,thumbnailDataUrl:m.thumbnailDataUrl,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,isPlaying:m.isPlaying,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isRecorded:m.isRecorded,buffer:l,mimeType:h};if(m.audioData&&m.audioData.startsWith("data:")){let p=Ya(m.audioData),w=No(m.audioData);c+=p.byteLength,g.audioBuffer=p,g.audioMimeType=w;}f.push(g);}for(let m of i.photoFrames){let l={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:m.draggable,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isCapturing:m.isCapturing};if(m.capturedImageUrl&&m.capturedImageUrl.startsWith("data:")){let h=Ya(m.capturedImageUrl),g=No(m.capturedImageUrl);c+=h.byteLength,l.buffer=h,l.mimeType=g;}if(m.audioData&&m.audioData.startsWith("data:")){let h=Ya(m.audioData),g=No(m.audioData);c+=h.byteLength,l.audioBuffer=h,l.audioMimeType=g;}u.push(l);}s.push({...i,images:d,videos:f,photoFrames:u});}return {slides:s,totalSize:c}},Mw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},Tw=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${s}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${s}`,thumbnailFileKey:`slide_${r}_video_${s}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${s}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${s}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,c,i),n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,d,f);}}),a.videos.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,c,i),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let d=Ya(n.thumbnailDataUrl),f=new Blob([d],{type:"image/jpeg"}),u=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,f,u);}if(n.audioBuffer&&n.audioMimeType){let d=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,d,f);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let c=new Blob([n.buffer],{type:n.mimeType}),i=`${n.id}.${Vo(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,c,i);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),i=`${n.id}_audio.${Vo(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,c,i);}});}),o};var Pw=()=>{let e=yt();useEffect(()=>{(async()=>{try{let t=await Cl(),a=Ml();if(t&&t.length>0){let r=await Hu(),n=t.map(c=>{if(c.videos&&c.videos.length>0){let i=c.videos.map(d=>{let f=r.get(d.id);if(f){let u=Wu(f.blob);return {...d,objectUrl:u,thumbnailDataUrl:f.thumbnailDataUrl,videoBlob:f.blob}}else return d});return {...c,videos:i}}return c}),s=a&&n.find(c=>c.id===a)?a:n[0].id;e(to({slides:n,currentSlideId:s}));}}catch(t){console.error("Error loading persisted slides:",t);}})();},[e]);};var Af=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),Pf=new WeakSet,Rf=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await Ga(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},Rw=()=>{let e=yt(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||Pf.has(a))return;Pf.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await cs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let c=n&&r.find(d=>d.id===n)?n:r[0].id,i=Af(r);e(to({slides:i,currentSlideId:c})),await Rf(i);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await cs(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let c=n&&r.find(d=>d.id===n)?n:r[0].id,i=Af(r);e(to({slides:i,currentSlideId:c})),await Rf(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
6
+ This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:d?"none":"auto"}})}),jsx(Group,{y:I+k+D+S+b+V,children:d&&jsxs(Group,{onMouseDown:()=>h("reset"),onMouseUp:()=>{h(null),y();},onMouseLeave:()=>h(null),onTouchStart:()=>h("reset"),onTouchEnd:()=>{h(null),y();},scaleX:i==="reset"?.95:1,scaleY:i==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:N=>N.cancelBubble=true,onTap:N=>N.cancelBubble=true}),jsx(Text,{x:L,width:e.width-L*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});Zi.displayName="LongAnswer";var Uu=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:n})=>jsx(Fragment,{children:e.map(s=>jsx(Zi,{longAnswer:s,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:r,handleDragEnd:c=>n(c,s.id)},s.id))});var Wa=1920,za=1080,Ku=3840,_u=2160,ib=e=>{let o=0,t=0,a=Wa,r=za;if(!e)return {minX:o,minY:t,maxX:a,maxY:r,width:Wa,height:za};let n=(l,u,f,d)=>{o=Math.min(o,l),t=Math.min(t,u),a=Math.max(a,l+f),r=Math.max(r,u+d);};e.lines?.forEach(l=>{if(l.points&&l.points.length>=2){let u=l.x||0,f=l.y||0,d=l.scaleX||1,m=l.scaleY||1;for(let i=0;i<l.points.length;i+=2){let h=u+l.points[i]*d,g=f+l.points[i+1]*m;o=Math.min(o,h),t=Math.min(t,g),a=Math.max(a,h),r=Math.max(r,g);}}}),e.images?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.videos?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shapes?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.texts?.forEach(l=>n(l.x,l.y,l.width||200,l.height||l.fontSize||24)),e.flashcards?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.photoFrames?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.multipleChoices?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.trueFalses?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.shortAnswers?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.LongAnswer?.forEach(l=>n(l.x,l.y,l.width,l.height)),e.fillInTheBlanks?.forEach(l=>n(l.x,l.y,l.width,l.height));let s=Math.min(a-o,Ku),c=Math.min(r-t,_u);return o=Math.max(o,a-Ku),t=Math.max(t,r-_u),{minX:o,minY:t,maxX:a,maxY:r,width:s,height:c}},lb=(e,o,t={minX:0,minY:0,maxX:Wa,maxY:za,width:Wa,height:za})=>{let a=Math.max(t.width,Wa),r=Math.max(t.height,za),n=e/o,s=a/r,c,l,u,d=0;if(n>s){l=r,c=Math.round(l*n),u=o/l;}else {c=a,l=Math.round(c/n),u=e/c;let m=r*u;d=(o-m)/2;}return {scale:u,scaleX:u,scaleY:u,stageWidth:e,stageHeight:o,offsetX:0,offsetY:d,baseWidth:c,baseHeight:l,contentOffsetX:t.minX,contentOffsetY:t.minY}},ju=(e,o)=>{let t=o.contentOffsetX||0,a=o.contentOffsetY||0;return {x:(e.x-o.offsetX)/o.scale+t,y:(e.y-o.offsetY)/o.scale+a}},db=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a}={})=>{let r=yt(),n=ee(w=>w.toolbar.selectedTool),s=ee(ge),c=ee(Xo),l=s?.editingActivity,u=s?.showMcqForm,f=s?.lines||[],d=useRef(null),m=useRef(null),[i,h]=useState(null),[g,p]=useState(""),y=useRef(null),[x,v]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:Wa,stageHeight:za,offsetX:0,offsetY:0,baseWidth:Wa,baseHeight:za,contentOffsetX:0,contentOffsetY:0}),L=useMemo(()=>ib(s||null),[c]),[I,k]=useState(null),[S,b]=useState(null),[A,V]=useState(null),[D,H]=useState(null),[N,P]=useState(null),[W,E]=useState(null),[oe,q]=useState(null),[fe,z]=useState(false),[O,X]=useState(null),[U,K]=useState(false),Q=useRef(null),te=useRef(null),J=useRef(null),{debouncedGenerateThumbnail:de}=Md(c,d);useEffect(()=>{let w=()=>{if(m.current){let T=m.current.getBoundingClientRect(),R=lb(T.width,T.height,L);v(R);}};w();let C=new ResizeObserver(w);return m.current&&C.observe(m.current),window.addEventListener("resize",w),()=>{C.disconnect(),window.removeEventListener("resize",w);}},[L]),useEffect(()=>{if(d.current){let w=d.current.container();w&&(w.style.cursor="");}},[n]);let Y=useCallback(()=>{d.current&&requestAnimationFrame(()=>{if(!d.current)return;d.current.getLayers().forEach(R=>R.batchDraw());let C=1/6,T=d.current.toDataURL({pixelRatio:C});p(T),de();});},[de]),Me=useRef(c);useEffect(()=>{Me.current!==c&&(Me.current=c,Y());},[c,Y]);let Re=useRef(null),Se=useRef(true);useEffect(()=>{if(!s)return;let w=(s.lines?.length||0)+(s.images?.length||0)+(s.videos?.length||0)+(s.shapes?.length||0)+(s.texts?.length||0)+(s.flashcards?.length||0)+(s.photoFrames?.length||0)+(s.multipleChoices?.length||0)+(s.trueFalses?.length||0)+(s.shortAnswers?.length||0)+(s.LongAnswer?.length||0)+(s.fillInTheBlanks?.length||0),C=Re.current?.count!==w;!Se.current&&C&&setTimeout(()=>{Y();},100),Re.current={slideId:c,count:w},Se.current=false;},[s,c,Y]),useEffect(()=>{d.current&&e&&e(d);},[e]),useEffect(()=>{J.current&&a&&a(J);},[a]);let{startDrawing:Dt,draw:Za,stopDrawing:Br,setCanvasRef:Or,tool:hs,color:gs,strokeWidth:xs,isSketchMode:bs}=ed(Y),Ma=useRef(new Map),{images:F,getLoadedImage:ne,imageRefs:ve,handleDragEnd:he,handleImageTransformEnd:se}=id(Y),{videos:re,videoRefs:Te,handleVideoClick:Rt,handleVideoDragEnd:Yt,handleVideoTransformEnd:st}=ud(Y),{multipleChoice:Ee,handleMcqTransform:qe,mcqRefs:ht,handleDragEnd:Ta}=ld(Y),{trueFalse:Qa,handleTrueFalseTransform:eo,trueFalseRefs:Aa,handleTrueFalseDragEnd:Et}=dd(Y),{shortAnswers:na,saRefs:Ft,handleShortAnswerDragEnd:Uf}=gd(Y),{longAnswers:Wf,handleLongAnswerDragEnd:zf}=xd(Y),{fillInTheBlanks:Gf,handleFillInTheBlanksDragEnd:Kf,fibRefs:Nr}=Fu(Y),{transformerRef:ue,boundBoxFunc:gt}=Id(),{shapes:_f,shapeRefs:Vr,isDragging:Vl,handleShapeDragEnd:jf,handleShapeResizeEnd:$f}=md(Y),{texts:Ho,textRefs:sa,handleDragEnd:Xf,handleTransformEnd:Yf,handleDoubleClick:Jf,startEditing:qr,editingTextId:me,editingValue:ql,handleEditingChange:Hl,finishEditing:vs}=hd(Y,Q);useEffect(()=>{t&&t(qr);},[t,qr]);let Hr=ee(w=>w.canvas.editingTextId);useEffect(()=>{Hr&&Hr!==me&&qr(Hr);},[Hr,me,qr]);let{flashcards:Zf,flashcardRefs:Ur,handleDragEnd:Qf,handleFlashcardTransformEnd:em,handleNext:tm,handlePrevious:am}=vd(Y),{photoFrames:Ul,photoFrameRefs:Wr,handleDragEnd:om,handlePhotoFrameTransformEnd:rm,startCamera:nm,capturePhoto:sm,cameraStreams:im}=Ld(Y);useEffect(()=>{if(ue.current){if(me){ue.current.nodes([]),ue.current.getLayer()?.batchDraw();return}if(i&&!re.find(T=>T.id===i)?.isPlaying){let T=Ma.current.get(i)||ve.current.get(i)||Te.current.get(i)||Vr.current.get(i)||sa.current.get(i)||ht.current.get(i)||Ur.current.get(i)||Wr.current.get(i)||Ft.current.get(i)||Aa.current.get(i)||Nr.current.get(i);if(T){let R=T.attrs?.locked;if(T.visible()&&R!==true){ue.current.nodes([T]),ue.current.getLayer()?.batchDraw();return}}}ue.current.nodes([]),ue.current.getLayer()?.batchDraw();}},[i,me,re,Ma,ve,Te,Vr,sa,Ur,Wr,Ul,ht,Aa,Nr,ue]);let Ue=useCallback(w=>{h(w),o?.(w);},[o]),to=useCallback(()=>{h(null),o?.(null),ue.current&&(ue.current.nodes([]),ue.current.getLayer()?.batchDraw());},[ue,o]),Wl=useCallback(w=>s?s.lines?.some(C=>C.id===w)?"line":s.images?.some(C=>C.id===w)?"image":s.videos?.some(C=>C.id===w)?"video":s.shapes?.some(C=>C.id===w)?"shape":s.texts?.some(C=>C.id===w)?"text":s.flashcards?.some(C=>C.id===w)?"flashcard":s.photoFrames?.some(C=>C.id===w)?"photoFrame":s.multipleChoices?.some(C=>C.id===w)?"mcq":s.trueFalses?.some(C=>C.id===w)?"trueFalse":s.shortAnswers?.some(C=>C.id===w)?"shortAnswer":s.LongAnswer?.some(C=>C.id===w)?"longAnswer":s.fillInTheBlanks?.some(C=>C.id===w)?"fillInTheBlanks":null:null,[s]),zl=useCallback((w,C)=>{switch(r(le()),C){case "line":r(vn(w));break;case "image":r(Gr(w));break;case "video":r($r(w));break;case "shape":r(Jr(w));break;case "text":r(Zr(w));break;case "flashcard":r(en(w));break;case "photoFrame":r(an(w));break;case "mcq":r(rn(w));break;case "trueFalse":r(sn(w));break;case "shortAnswer":r(dn(w));break;case "longAnswer":r(cn(w));break;case "fillInTheBlanks":r(mn(w));break}to(),Y();},[r,to,Y]);useEffect(()=>{let w=C=>{if(C.key!=="Delete"||!i||me)return;let T=document.activeElement;if(T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement||T?.getAttribute("contenteditable")==="true")return;C.preventDefault();let ke=Wl(i);ke&&zl(i,ke);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[i,me,Wl,zl]),useEffect(()=>{let w=ue.current;return ()=>{w&&w.nodes([]);}},[c]),useEffect(()=>{let w=C=>{me&&C.target.tagName!=="TEXTAREA"&&vs();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[me,vs]),useEffect(()=>{let w=me||i;if(!w||i&&me){b(null);return}let C=sa.current.get(w),T=d.current;if(!C||!T){b(null);return}let R=T.container().getBoundingClientRect(),ke=C.absolutePosition(),Le=T.scaleX();b({x:R.left+(ke.x+C.width()*Le/2)*Le,y:R.top+ke.y*Le});},[i,me,Ho,sa]),useEffect(()=>{if(!me){V(null);return}let w=sa.current.get(me),C=d.current;if(!w||!C){V(null);return}let T=C.container().getBoundingClientRect(),R=w.absolutePosition(),ke=C.scaleX();V({top:T.top+R.y*ke,left:T.left+R.x*ke,scale:ke});},[me,Ho,sa]);let Gl=useCallback(w=>{let C=w.target.getClassName(),T=w.target===w.target.getStage(),R=C==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",ke=C==="Image",Le=C==="Text",ae=C==="Group"||w.target.getParent()?.getClassName()==="Group",Bt=C==="Circle"||C==="Star"||C==="RegularPolygon"||C==="Ellipse"||C==="Ring"||C==="Wedge"||C==="Arrow"||C==="Line"||C==="Arc"||C==="Rect"&&w.target.attrs.id,bt=C==="Group";if(console.log("\u{1F5B1}\uFE0F Canvas handleMouseDown:",{targetClass:C,clickedOnImage:ke,clickedOnGroup:ae,tool:n,targetId:w.target.attrs?.id}),T&&!R&&!ke&&!Le&&!ae&&!Bt&&!bt&&to(),!(n==="pen"||n==="eraser")&&(ke||Le||R||ae||Bt||bt))return;let _e=w.target.getStage()?.getPointerPosition();if(!_e)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let B=ju(_e,x);Dt(B);}},[n,Dt,to,x]),Kl=useCallback(w=>{if(Vl)return;let C=w.target.getStage()?.getPointerPosition();if(!C)return;let T=ju(C,x);Za(T);},[Za,Vl,x]),_l=useCallback(()=>{Br();},[Br]),lm=useCallback(w=>{he(w,Y);},[he,Y]),dm=useCallback(w=>{Rt(w),Ue(w);},[Rt,Ue]),xt=useCallback((w,C,T)=>{w.preventDefault();let R=w.clientX,ke=w.clientY,Le=y.current?.offsetHeight||450,ae=y.current?.offsetWidth||450,Bt=window.innerHeight,bt=window.innerWidth,Ze=R,_e=ke;ke+Le>Bt&&(_e=ke-Le),R+ae>bt&&(Ze=R-ae),k({x:Ze,y:_e,elementId:C,elementType:T}),Ue(C);},[Ue]),jl=useCallback(w=>{r(_o(w)),r(da(true));},[r]),um=useCallback(w=>{r(Wo(w)),r(Da(true));},[r]),cm=useCallback((w,C)=>{if(!I)return;let{elementId:T,elementType:R}=I;switch(w){case "order":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(C){let M=C.target.getBoundingClientRect();H({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(k(null),R==="line")break;let ke=s?R==="image"?s.images.find(M=>M.id===T):s.videos.find(M=>M.id===T):null;P({type:"link",defaultValue:ke?.link||""});break;case "voice":if(k(null),R==="line")break;let Le=s?R==="image"?s.images.find(M=>M.id===T):R==="video"?s.videos.find(M=>M.id===T):R==="text"?s.texts.find(M=>M.id===T):R==="flashcard"?s.flashcards.find(M=>M.id===T):R==="photoFrame"?s.photoFrames.find(M=>M.id===T):R==="mcq"?s.multipleChoices.find(M=>M.id===T):R==="fillInTheBlanks"?s.fillInTheBlanks.find(M=>M.id===T):R==="longAnswer"?s.LongAnswer.find(M=>M.id===T):R==="shortAnswer"?s.shortAnswers.find(M=>M.id===T):R==="trueFalse"?s.trueFalses.find(M=>M.id===T):R==="shape"?s.shapes.find(M=>M.id===T):null:null;X({elementId:T,elementType:R,existingAudio:Le?.audioData});break;case "edit":k(null);let ae=null;R==="mcq"?ae=s?.multipleChoices.find(M=>M.id===T):R==="trueFalse"?ae=s?.trueFalses.find(M=>M.id===T):R==="shortAnswer"?ae=s?.shortAnswers.find(M=>M.id===T):R==="longAnswer"?ae=s?.LongAnswer.find(M=>M.id===T):R==="fillInTheBlanks"&&(ae=s?.fillInTheBlanks.find(M=>M.id===T)),ae&&jl(ae);break;case "editFlashcard":k(null);let Bt=s?.flashcards.find(M=>M.id===T);Bt&&um(Bt);break;case "color":k(null);let bt=s?.shapes.find(M=>M.id===T);E({elementId:T,elementType:"shape",defaultColor:bt?.color||"#096B76"});break;case "crop":if(k(null),R==="image"){let M=s?.images.find(bm=>bm.id===T);M&&q({elementId:T,imageSrc:M.src});}break;case "draw":k(null),R==="image"?r(Vs(T)):R==="photoFrame"&&r(Hs(T));break;case "duplicate":r(le()),R==="line"?r(Zs(T)):R==="image"?r(Kr(T)):R==="video"?r(Xr(T)):R==="shape"?r(Yr(T)):R==="text"?r(Qr(T)):R==="flashcard"?r(tn(T)):R==="photoFrame"?r(on(T)):R==="mcq"?r(nn(T)):R==="trueFalse"?r(ln(T)):R==="shortAnswer"?r(un(T)):R==="fillInTheBlanks"?r(pn(T)):R==="longAnswer"&&r(fn(T)),Y();break;case "infinite-clone":r(le());let Ze=5;for(let M=0;M<Ze;M++)R==="image"?r(Kr(T)):R==="video"?r(Xr(T)):R==="shape"?r(Yr(T)):R==="text"?r(Qr(T)):R==="flashcard"?r(tn(T)):R==="photoFrame"?r(on(T)):R==="mcq"?r(nn(T)):R==="trueFalse"?r(ln(T)):R==="shortAnswer"?r(un(T)):R==="fillInTheBlanks"?r(pn(T)):R==="longAnswer"&&r(fn(T));Y();break;case "make-response":if(k(null),R==="line")break;let _e=`#response-${T}`;r(le()),r(hn({id:T,type:R,link:_e})),(s?R==="image"?s.images.find(M=>M.id===T):R==="video"?s.videos.find(M=>M.id===T):R==="shape"?s.shapes.find(M=>M.id===T):R==="flashcard"?s.flashcards.find(M=>M.id===T):R==="photoFrame"?s.photoFrames.find(M=>M.id===T):s.multipleChoices.find(M=>M.id===T):null)?.altText||r(gn({id:T,type:R,altText:"Interactive response area"})),Y(),console.log(`Element ${T} marked as interactive response area`);break;case "accessibility":if(k(null),R==="line")break;let B=s?R==="image"?s.images.find(M=>M.id===T):R==="video"?s.videos.find(M=>M.id===T):R==="shape"?s.shapes.find(M=>M.id===T):null:null;P({type:"altText",defaultValue:B?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),k(null),K(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(le()),R==="line"?r(vn(T)):R==="image"?r(Gr(T)):R==="video"?r($r(T)):R==="shape"?r(Jr(T)):R==="text"?r(Zr(T)):R==="flashcard"?r(en(T)):R==="photoFrame"?r(an(T)):R==="mcq"?r(rn(T)):R==="trueFalse"?r(sn(T)):R==="shortAnswer"?r(dn(T)):R==="longAnswer"?r(cn(T)):R==="fillInTheBlanks"&&r(mn(T)),to(),Y();break}},[I,r,Y,to,s,jl]),fm=useCallback(()=>{k(null),H(null);},[]),ys=useCallback(w=>{if(!I)return;let{elementId:C,elementType:T}=I;switch(r(le()),w){case "bring-to-front":T!=="line"&&r($s({id:C,type:T}));break;case "send-to-back":T!=="line"&&r(Xs({id:C,type:T}));break;case "lock":case "unlock":T!=="line"&&r(Ys({id:C,type:T}));break}Y(),k(null),H(null);},[I,r,Y]),mm=useCallback(w=>{if(!I||!N)return;let{elementId:C,elementType:T}=I;r(le()),N.type==="link"&&T!=="line"?r(hn({id:C,type:T,link:w})):N.type==="altText"&&T!=="line"&&r(gn({id:C,type:T,altText:w})),Y(),P(null);},[I,N,r,Y]),pm=useCallback(w=>{if(!O)return;let{elementId:C,elementType:T}=O;r(le()),r(xn({id:C,type:T,audioData:w})),Y(),X(null);},[O,r,Y]),hm=useCallback(()=>{if(!O)return;let{elementId:w,elementType:C}=O;r(le()),r(xn({id:w,type:C,audioData:""})),Y();},[O,r,Y]),gm=useCallback(w=>{if(!W)return;let{elementId:C}=W;r(le()),r(ro({id:C,color:w})),Y(),E(null);},[W,r,Y]),xm=useCallback(w=>{if(!oe)return;let{elementId:C}=oe;r(le()),r(oo({id:C,src:w})),Y(),q(null);},[oe,r,Y]);return jsxs("div",{ref:m,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(nd,{ref:w=>{if(te.current=w,Or(w),w){let C=w.getCanvasElement();C&&(J.current=C,a&&a(J));}},width:x.baseWidth,height:x.baseHeight,tool:hs,color:gs,strokeWidth:xs/x.scale,isSketchMode:bs,xOffset:x.contentOffsetX,yOffset:x.contentOffsetY-x.offsetY/x.scale,style:{width:x.stageWidth,height:x.stageHeight}}),jsxs(Stage,{ref:d,width:x.stageWidth,height:x.stageHeight,scaleX:x.scaleX,scaleY:x.scaleY,x:x.offsetX,y:0,onMouseDown:Gl,onMouseMove:Kl,onMouseUp:_l,onTouchStart:Gl,onTouchMove:Kl,onTouchEnd:_l,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:x.baseWidth,height:x.stageHeight/x.scale,fill:s?.backgroundColor||"white"})}),jsx(Layer,{x:-x.contentOffsetX,y:x.offsetY/x.scale-x.contentOffsetY,children:(()=>{let w=[];return f.forEach((C,T)=>{w.push({type:"line",timestamp:C.timestamp||T,element:{...C,id:C.id??`line-${T}`},index:T});}),_f.forEach(C=>{w.push({type:"shape",timestamp:C.timestamp||0,element:C});}),F.forEach(C=>{w.push({type:"image",timestamp:C.timestamp||0,element:C});}),re.forEach(C=>{w.push({type:"video",timestamp:C.timestamp||0,element:C});}),Ho.forEach(C=>{w.push({type:"text",timestamp:C.timestamp||0,element:C});}),Zf.forEach(C=>{w.push({type:"flashcard",timestamp:C.timestamp||0,element:C});}),Ul.forEach(C=>{w.push({type:"photoFrame",timestamp:C.timestamp||0,element:C});}),Ee.forEach(C=>{w.push({type:"mcq",timestamp:C.timestamp||0,element:C});}),Qa.forEach(C=>{w.push({type:"trueFalse",timestamp:C.timestamp||0,element:C});}),na.forEach(C=>{w.push({type:"shortAnswer",timestamp:C.timestamp||0,element:C});}),Wf.forEach(C=>{w.push({type:"longAnswer",timestamp:C.timestamp||0,element:C});}),Gf.forEach(C=>{w.push({type:"fillInTheBlanks",timestamp:C.timestamp||0,element:C});}),w.sort((C,T)=>C.timestamp-T.timestamp),w.map((C,T)=>{let R=`${C.type}-${"id"in C.element&&C.element.id||C.index||T}`,ke="id"in C.element?C.element.id:void 0,Le=ke&&i===ke;switch(C.type){case "line":let ae=C.element,Bt=C.index||0,bt=ae.tool==="eraser",Ze=ae.isSketch&&ae.tool==="pen",_e=ae.isSketch&&bt,vt=ae.id||`line-${Bt}`;return ae.x===void 0&&(ae.x=0),ae.y===void 0&&(ae.y=0),ae.scaleX===void 0&&(ae.scaleX=1),ae.scaleY===void 0&&(ae.scaleY=1),ae.rotation===void 0&&(ae.rotation=0),n==="eraser"?jsx(Group,{x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,onClick:()=>{r(le()),r(zr(Bt));},onTap:()=>{r(le()),r(zr(Bt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:B=>{let M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%23ff000033' stroke='%23ff0000' stroke-width='2'/%3E%3C/svg%3E") 12 12, pointer`);},onMouseLeave:B=>{let M=B.target.getStage();M&&(M.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},R):jsxs(be__default.Fragment,{children:[jsx(Group,{id:vt,ref:B=>{B?Ma.current.set(vt,B):Ma.current.delete(vt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:n==="select",listening:n==="select",onClick:()=>{n==="select"&&(console.log("Line clicked:",vt),Ue(vt));},onTap:()=>{n==="select"&&(console.log("Line tapped:",vt),Ue(vt));},onDragEnd:B=>{r(le()),r(bn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onTransformEnd:B=>{r(le()),r(bn({id:vt,x:B.target.x(),y:B.target.y(),scaleX:B.target.scaleX(),scaleY:B.target.scaleY(),rotation:B.target.rotation()})),Y();},onMouseEnter:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:B=>{if(n==="select"){let M=B.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:B=>{let M=B.evt;M.preventDefault(),xt(M,vt,"line");},children:jsx(Line,{points:ae.points||[],stroke:Ze||_e?void 0:ae.color,strokeWidth:Ze||_e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:Ze||_e?bt?"black":ae.color:void 0,closed:Ze||_e,tension:0,globalCompositeOperation:bt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ma.current.get(i);console.log("Line Transformer - selectedId:",i,"node found:",!!M),M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "shape":return jsxs(be__default.Fragment,{children:[jsx(hi,{onSelect:Ue,shapes:[C.element],shapeRefs:Vr,handleShapeDragEnd:jf,handleShapeResizeEnd:$f,onContextMenu:xt}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Vr.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "image":return jsxs(be__default.Fragment,{children:[jsx(ci,{images:[C.element],getLoadedImage:ne,imageRefs:ve,onDragEnd:lm,onTransform:se,onSelect:Ue,onContextMenu:xt}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ve.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "video":return jsxs(be__default.Fragment,{children:[jsx(pi,{videos:[C.element],selectedId:i,videoRefs:Te,onVideoClick:dm,onDragEnd:Yt,onTransformEnd:st,onContextMenu:xt}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Te.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "text":return jsxs(be__default.Fragment,{children:[jsx(Vd,{texts:[C.element],textRefs:sa,onDragEnd:Xf,onTransformEnd:Yf,onSelect:Ue,onContextMenu:xt,onDoubleClick:Jf,editingTextId:me,editingValue:ql,onEditingChange:Hl}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=sa.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(bi,{flashcards:[C.element],flashcardRefs:Ur,selectedId:i,onDragEnd:Qf,onTransform:em,onSelect:Ue,onNext:tm,onPrevious:am,onContextMenu:xt}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ur.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Ii,{photoFrames:[C.element],photoFrameRefs:Wr,selectedId:i,onDragEnd:om,onTransform:rm,onSelect:Ue,onStartCamera:nm,onCapture:sm,cameraStreams:im,onContextMenu:xt}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Wr.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(fu,{handleMcqTransform:qe,multipleChoice:[C.element],handleSelect:Ue,mcqRefs:ht,handleDragEnd:Ta,onContextMenu:xt}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=ht.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(hu,{trueFalses:[C.element],handleTrueFalseTransform:eo,handleSelect:Ue,trueFalseRefs:Aa,onContextMenu:xt,handleDragEnd:Et}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Aa.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(Eu,{shortAnswers:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:Uf}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(Uu,{longAnswer:[C.element],handleSelect:Ue,handleTransform:qe,saRefs:Ft,onContextMenu:xt,handleDragEnd:zf}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Ft.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(qu,{fillInTheBlanks:[C.element],handleSelect:Ue,handleTransform:qe,onContextMenu:xt,handleDragEnd:Kf,fibRefs:Nr}),Le&&!me&&i&&jsx(Transformer,{ref:B=>{if(B&&ue.current!==B){ue.current=B;let M=Nr.current.get(i);M&&M.visible()&&(B.nodes([M]),B.getLayer()?.batchDraw());}},boundBoxFunc:gt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},R);default:return null}})})()})]}),I&&jsx(Jd,{menuRef:y,x:I.x,y:I.y,type:I.elementType,onAction:cm,onClose:fm,isDrawingMode:I.elementType==="image"?s?.images.find(w=>w.id===I.elementId)?.isDrawingMode:I.elementType==="photoFrame"?s?.photoFrames.find(w=>w.id===I.elementId)?.isDrawingMode:false}),D&&I&&jsx(Zd,{x:D.x,y:D.y,items:D.type==="order"?[{label:"Bring to Front",onClick:()=>ys("bring-to-front")},{label:"Send to Back",onClick:()=>ys("send-to-back")}]:[{label:s&&(I.elementType==="image"?s.images.find(w=>w.id===I.elementId)?.locked:s.videos.find(w=>w.id===I.elementId)?.locked)?"Unlock":"Lock",onClick:()=>ys(s&&(I.elementType==="image"?s.images.find(w=>w.id===I.elementId)?.locked:s.videos.find(w=>w.id===I.elementId)?.locked)?"unlock":"lock")}],onClose:()=>H(null)}),N&&jsx(Qd,{title:N.type==="link"?"Add Link":"Add Alt Text",label:N.type==="link"?"URL":"Alternative Text",placeholder:N.type==="link"?"https://example.com":"Describe this image/video",defaultValue:N.defaultValue,onSave:mm,onClose:()=>P(null)}),W&&jsx(eu,{defaultColor:W.defaultColor,onConfirm:gm,onCancel:()=>E(null)}),oe&&jsx(ru,{imageSrc:oe.imageSrc,onConfirm:xm,onCancel:()=>q(null)}),fe&&jsx(rr,{onClose:()=>z(false),stageRef:d}),O&&jsx(su,{elementId:O.elementId,elementType:O.elementType,existingAudio:O.existingAudio,onSave:pm,onDelete:hm,onClose:()=>X(null)}),U&&jsx(du,{selectedElementId:i||void 0,onClose:()=>K(false),onSelectElement:w=>{Ue(w),K(false);}}),s?.images.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.videos.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.shapes?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.texts?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.flashcards?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),s?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(It,{audioData:w.audioData,x:w.x,y:w.y,width:w.width},`audio-${w.id}`)),u&&jsx(ku,{editElement:l}),S&&(()=>{let w=me||i;if(!w)return null;let C=Ho.find(T=>T.id===w);return C?jsx(Mu,{text:C,position:S}):null})(),A&&me&&(()=>{let w=Ho.find(C=>C.id===me);return w?jsx(Au,{text:w,editingValue:ql,onEditingChange:Hl,onFinish:vs,position:{top:A.top,left:A.left},scale:A.scale,textareaRef:Q},me):null})()]})},ub=db;var cb="SchooplaVideoStorage";var $t="videos",Zn=()=>new Promise((e,o)=>{let t=indexedDB.open(cb,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains($t)||r.createObjectStore($t,{keyPath:"id"});};}),Ga=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await Zn(),n=a.transaction([$t],"readwrite").objectStore($t),s={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,l)=>{let u=n.put(s);u.onsuccess=()=>c(!0),u.onerror=()=>l(u.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var $u=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await Zn(),t=e.transaction([$t],"readonly").objectStore($t);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result,c=new Map;s.forEach(l=>{c.set(l.id,{blob:l.blob,thumbnailDataUrl:l.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Qi=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await Zn(),a=o.transaction([$t],"readwrite").objectStore($t);await new Promise((r,n)=>{let s=a.delete(e);s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},Xu=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await Zn(),t=e.transaction([$t],"readwrite").objectStore($t);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},Yu=e=>URL.createObjectURL(e);function wa(e,o=[]){let t=[];function a(n,s){let c=be.createContext(s),l=t.length;t=[...t,s];let u=d=>{let{scope:m,children:i,...h}=d,g=m?.[e]?.[l]||c,p=be.useMemo(()=>h,Object.values(h));return jsx(g.Provider,{value:p,children:i})};u.displayName=n+"Provider";function f(d,m){let i=m?.[e]?.[l]||c,h=be.useContext(i);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${n}\``)}return [u,f]}let r=()=>{let n=t.map(s=>be.createContext(s));return function(c){let l=c?.[e]||n;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return r.scopeName=e,[a,mb(r,...o)]}function mb(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(n){let s=a.reduce((c,{useScope:l,scopeName:u})=>{let d=l(n)[`__scope${u}`];return {...c,...d}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:s}),[s])}};return t.scopeName=o.scopeName,t}function Ju(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function kr(...e){return o=>{let t=false,a=e.map(r=>{let n=Ju(r,o);return !t&&typeof n=="function"&&(t=true),n});if(t)return ()=>{for(let r=0;r<a.length;r++){let n=a[r];typeof n=="function"?n():Ju(e[r],null);}}}}function Tt(...e){return be.useCallback(kr(...e),e)}function ec(e){let o=pb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),l=c.find(gb);if(l){let u=l.props.children,f=c.map(d=>d===l?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:d);return jsx(o,{...s,ref:r,children:be.isValidElement(u)?be.cloneElement(u,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function pb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=bb(r),c=xb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?kr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var hb=Symbol("radix.slottable");function gb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===hb}function xb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let l=n(...c);return r(...c),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function bb(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var wb=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rt=wb.reduce((e,o)=>{let t=ec(`Primitive.${o}`),a=be.forwardRef((r,n)=>{let{asChild:s,...c}=r,l=s?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(l,{...c,ref:n})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function $e(e,o,{checkForDefaultPrevented:t=true}={}){return function(r){if(e?.(r),t===false||!r.defaultPrevented)return o?.(r)}}function el(e){let o=Lb(e),t=be.forwardRef((a,r)=>{let{children:n,...s}=a,c=be.Children.toArray(n),l=c.find(Sb);if(l){let u=l.props.children,f=c.map(d=>d===l?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:d);return jsx(o,{...s,ref:r,children:be.isValidElement(u)?be.cloneElement(u,void 0,f):null})}return jsx(o,{...s,ref:r,children:n})});return t.displayName=`${e}.Slot`,t}function Lb(e){let o=be.forwardRef((t,a)=>{let{children:r,...n}=t;if(be.isValidElement(r)){let s=kb(r),c=Cb(n,r.props);return r.type!==be.Fragment&&(c.ref=a?kr(a,s):s),be.cloneElement(r,c)}return be.Children.count(r)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Ib=Symbol("radix.slottable");function Sb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ib}function Cb(e,o){let t={...o};for(let a in o){let r=e[a],n=o[a];/^on[A-Z]/.test(a)?r&&n?t[a]=(...c)=>{let l=n(...c);return r(...c),l}:r&&(t[a]=r):a==="style"?t[a]={...r,...n}:a==="className"&&(t[a]=[r,n].filter(Boolean).join(" "));}return {...e,...t}}function kb(e){let o=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning;return t?e.ref:(o=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=o&&"isReactWarning"in o&&o.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}function Qn(e){let o=e+"CollectionProvider",[t,a]=wa(o),[r,n]=t(o,{collectionRef:{current:null},itemMap:new Map}),s=g=>{let{scope:p,children:y}=g,x=be__default.useRef(null),v=be__default.useRef(new Map).current;return jsx(r,{scope:p,itemMap:v,collectionRef:x,children:y})};s.displayName=o;let c=e+"CollectionSlot",l=el(c),u=be__default.forwardRef((g,p)=>{let{scope:y,children:x}=g,v=n(c,y),L=Tt(p,v.collectionRef);return jsx(l,{ref:L,children:x})});u.displayName=c;let f=e+"CollectionItemSlot",d="data-radix-collection-item",m=el(f),i=be__default.forwardRef((g,p)=>{let{scope:y,children:x,...v}=g,L=be__default.useRef(null),I=Tt(p,L),k=n(f,y);return be__default.useEffect(()=>(k.itemMap.set(L,{ref:L,...v}),()=>void k.itemMap.delete(L))),jsx(m,{[d]:"",ref:I,children:x})});i.displayName=f;function h(g){let p=n(e+"CollectionConsumer",g);return be__default.useCallback(()=>{let x=p.collectionRef.current;if(!x)return [];let v=Array.from(x.querySelectorAll(`[${d}]`));return Array.from(p.itemMap.values()).sort((k,S)=>v.indexOf(k.ref.current)-v.indexOf(S.ref.current))},[p.collectionRef,p.itemMap])}return [{Provider:s,Slot:u,ItemSlot:i},h,a]}var Ao=globalThis?.document?be.useLayoutEffect:()=>{};var Mb=be[" useId ".trim().toString()]||(()=>{}),Tb=0;function rc(e){let[o,t]=be.useState(Mb());return Ao(()=>{t(a=>a??String(Tb++));},[e]),(o?`radix-${o}`:"")}function nc(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Ab=be[" useInsertionEffect ".trim().toString()]||Ao;function ea({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[r,n,s]=Pb({defaultProp:o,onChange:t}),c=e!==void 0,l=c?e:r;{let f=be.useRef(e!==void 0);be.useEffect(()=>{let d=f.current;d!==c&&console.warn(`${a} is changing from ${d?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=c;},[c,a]);}let u=be.useCallback(f=>{if(c){let d=Db(f)?f(e):f;d!==e&&s.current?.(d);}else n(f);},[c,e,n,s]);return [l,u]}function Pb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),r=be.useRef(t),n=be.useRef(o);return Ab(()=>{n.current=o;},[o]),be.useEffect(()=>{r.current!==t&&(n.current?.(t),r.current=t);},[t,r]),[t,a,n]}function Db(e){return typeof e=="function"}var Rb=be.createContext(void 0);function Do(e){let o=be.useContext(Rb);return e||o||"ltr"}var ol="rovingFocusGroup.onEntryFocus",Eb={bubbles:false,cancelable:true},Mr="RovingFocusGroup",[rl,sc,Fb]=Qn(Mr),[Bb,nl]=wa(Mr,[Fb]),[Ob,Nb]=Bb(Mr),ic=be.forwardRef((e,o)=>jsx(rl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(rl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Vb,{...e,ref:o})})}));ic.displayName=Mr;var Vb=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:r=false,dir:n,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:f=false,...d}=e,m=be.useRef(null),i=Tt(o,m),h=Do(n),[g,p]=ea({prop:s,defaultProp:c??null,onChange:l,caller:Mr}),[y,x]=be.useState(false),v=nc(u),L=sc(t),I=be.useRef(false),[k,S]=be.useState(0);return be.useEffect(()=>{let b=m.current;if(b)return b.addEventListener(ol,v),()=>b.removeEventListener(ol,v)},[v]),jsx(Ob,{scope:t,orientation:a,dir:h,loop:r,currentTabStopId:g,onItemFocus:be.useCallback(b=>p(b),[p]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>S(b=>b+1),[]),onFocusableItemRemove:be.useCallback(()=>S(b=>b-1),[]),children:jsx(rt.div,{tabIndex:y||k===0?-1:0,"data-orientation":a,...d,ref:i,style:{outline:"none",...e.style},onMouseDown:$e(e.onMouseDown,()=>{I.current=true;}),onFocus:$e(e.onFocus,b=>{let A=!I.current;if(b.target===b.currentTarget&&A&&!y){let V=new CustomEvent(ol,Eb);if(b.currentTarget.dispatchEvent(V),!V.defaultPrevented){let D=L().filter(E=>E.focusable),H=D.find(E=>E.active),N=D.find(E=>E.id===g),W=[H,N,...D].filter(Boolean).map(E=>E.ref.current);uc(W,f);}}I.current=false;}),onBlur:$e(e.onBlur,()=>x(false))})})}),lc="RovingFocusGroupItem",dc=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:r=false,tabStopId:n,children:s,...c}=e,l=rc(),u=n||l,f=Nb(lc,t),d=f.currentTabStopId===u,m=sc(t),{onFocusableItemAdd:i,onFocusableItemRemove:h,currentTabStopId:g}=f;return be.useEffect(()=>{if(a)return i(),()=>h()},[a,i,h]),jsx(rl.ItemSlot,{scope:t,id:u,focusable:a,active:r,children:jsx(rt.span,{tabIndex:d?0:-1,"data-orientation":f.orientation,...c,ref:o,onMouseDown:$e(e.onMouseDown,p=>{a?f.onItemFocus(u):p.preventDefault();}),onFocus:$e(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:$e(e.onKeyDown,p=>{if(p.key==="Tab"&&p.shiftKey){f.onItemShiftTab();return}if(p.target!==p.currentTarget)return;let y=Ub(p,f.orientation,f.dir);if(y!==void 0){if(p.metaKey||p.ctrlKey||p.altKey||p.shiftKey)return;p.preventDefault();let v=m().filter(L=>L.focusable).map(L=>L.ref.current);if(y==="last")v.reverse();else if(y==="prev"||y==="next"){y==="prev"&&v.reverse();let L=v.indexOf(p.currentTarget);v=f.loop?Wb(v,L+1):v.slice(L+1);}setTimeout(()=>uc(v));}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:g!=null}):s})})});dc.displayName=lc;var qb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Hb(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Ub(e,o,t){let a=Hb(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return qb[a]}function uc(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function Wb(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var cc=ic,fc=dc;var pc="Toggle",sl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:r,...n}=e,[s,c]=ea({prop:t,onChange:r,defaultProp:a??false,caller:pc});return jsx(rt.button,{type:"button","aria-pressed":s,"data-state":s?"on":"off","data-disabled":e.disabled?"":void 0,...n,ref:o,onClick:$e(e.onClick,()=>{e.disabled||c(!s);})})});sl.displayName=pc;var La="ToggleGroup",[gc]=wa(La,[nl]),xc=nl(),il=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Kb,{...a,ref:o});if(t==="multiple")return jsx(_b,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${La}\``)});il.displayName=La;var[bc,vc]=gc(La),Kb=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=ea({prop:t,defaultProp:a??"",onChange:r,caller:La});return jsx(bc,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>s?[s]:[],[s]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(yc,{...n,ref:o})})}),_b=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:r=()=>{},...n}=e,[s,c]=ea({prop:t,defaultProp:a??[],onChange:r,caller:La}),l=be__default.useCallback(f=>c((d=[])=>[...d,f]),[c]),u=be__default.useCallback(f=>c((d=[])=>d.filter(m=>m!==f)),[c]);return jsx(bc,{scope:e.__scopeToggleGroup,type:"multiple",value:s,onItemActivate:l,onItemDeactivate:u,children:jsx(yc,{...n,ref:o})})});il.displayName=La;var[jb,$b]=gc(La),yc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:r=true,orientation:n,dir:s,loop:c=true,...l}=e,u=xc(t),f=Do(s),d={role:"group",dir:f,...l};return jsx(jb,{scope:t,rovingFocus:r,disabled:a,children:r?jsx(cc,{asChild:true,...u,orientation:n,dir:f,loop:c,children:jsx(rt.div,{...d,ref:o})}):jsx(rt.div,{...d,ref:o})})}),as="ToggleGroupItem",Xb=be__default.forwardRef((e,o)=>{let t=vc(as,e.__scopeToggleGroup),a=$b(as,e.__scopeToggleGroup),r=xc(e.__scopeToggleGroup),n=t.value.includes(e.value),s=a.disabled||e.disabled,c={...e,pressed:n,disabled:s},l=be__default.useRef(null);return a.rovingFocus?jsx(fc,{asChild:true,...r,focusable:!s,active:n,ref:l,children:jsx(hc,{...c,ref:o})}):jsx(hc,{...c,ref:o})});Xb.displayName=as;var hc=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...r}=e,n=vc(as,t),s={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=n.type==="single"?s:void 0;return jsx(sl,{...c,...r,ref:o,onPressedChange:l=>{l?n.onItemActivate(a):n.onItemDeactivate(a);}})}),wc=il;function Lc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(o=0;o<r;o++)e[o]&&(t=Lc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function os(){for(var e,o,t=0,a="",r=arguments.length;t<r;t++)(e=arguments[t])&&(o=Lc(e))&&(a&&(a+=" "),a+=o);return a}var Jb=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},Zb=(e,o)=>({classGroupId:e,validator:o}),Mc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Ic=[],Qb="arbitrary..",ev=e=>{let o=av(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return tv(s);let c=s.split("-"),l=c[0]===""&&c.length>1?1:0;return Tc(c,l,o)},getConflictingClassGroupIds:(s,c)=>{if(c){let l=a[s],u=t[s];return l?u?Jb(u,l):l:u||Ic}return t[s]||Ic}}},Tc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let r=e[o],n=t.nextPart.get(r);if(n){let u=Tc(e,o+1,n);if(u)return u}let s=t.validators;if(s===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),l=s.length;for(let u=0;u<l;u++){let f=s[u];if(f.validator(c))return f.classGroupId}},tv=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?Qb+a:void 0})(),av=e=>{let{theme:o,classGroups:t}=e;return ov(t,o)},ov=(e,o)=>{let t=Mc();for(let a in e){let r=e[a];ul(r,t,a,o);}return t},ul=(e,o,t,a)=>{let r=e.length;for(let n=0;n<r;n++){let s=e[n];rv(s,o,t,a);}},rv=(e,o,t,a)=>{if(typeof e=="string"){nv(e,o,t);return}if(typeof e=="function"){sv(e,o,t,a);return}iv(e,o,t,a);},nv=(e,o,t)=>{let a=e===""?o:Ac(o,e);a.classGroupId=t;},sv=(e,o,t,a)=>{if(lv(e)){ul(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Zb(t,e));},iv=(e,o,t,a)=>{let r=Object.entries(e),n=r.length;for(let s=0;s<n;s++){let[c,l]=r[s];ul(l,Ac(o,c),t,a);}},Ac=(e,o)=>{let t=e,a=o.split("-"),r=a.length;for(let n=0;n<r;n++){let s=a[n],c=t.nextPart.get(s);c||(c=Mc(),t.nextPart.set(s,c)),t=c;}return t},lv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,dv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),r=(n,s)=>{t[n]=s,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(n){let s=t[n];if(s!==void 0)return s;if((s=a[n])!==void 0)return r(n,s),s},set(n,s){n in t?t[n]=s:r(n,s);}}};var uv=[],Sc=(e,o,t,a,r)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:r}),cv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=r=>{let n=[],s=0,c=0,l=0,u,f=r.length;for(let g=0;g<f;g++){let p=r[g];if(s===0&&c===0){if(p===":"){n.push(r.slice(l,g)),l=g+1;continue}if(p==="/"){u=g;continue}}p==="["?s++:p==="]"?s--:p==="("?c++:p===")"&&c--;}let d=n.length===0?r:r.slice(l),m=d,i=false;d.endsWith("!")?(m=d.slice(0,-1),i=true):d.startsWith("!")&&(m=d.slice(1),i=true);let h=u&&u>l?u-l:void 0;return Sc(n,i,m,h)};if(o){let r=o+":",n=a;a=s=>s.startsWith(r)?n(s.slice(r.length)):Sc(uv,false,s,void 0,true);}if(t){let r=a;a=n=>t({className:n,parseClassName:r});}return a},fv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],r=[];for(let n=0;n<t.length;n++){let s=t[n],c=s[0]==="[",l=o.has(s);c||l?(r.length>0&&(r.sort(),a.push(...r),r=[]),a.push(s)):r.push(s);}return r.length>0&&(r.sort(),a.push(...r)),a}},mv=e=>({cache:dv(e.cacheSize),parseClassName:cv(e),sortModifiers:fv(e),...ev(e)}),pv=/\s+/,hv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:r,sortModifiers:n}=o,s=[],c=e.trim().split(pv),l="";for(let u=c.length-1;u>=0;u-=1){let f=c[u],{isExternal:d,modifiers:m,hasImportantModifier:i,baseClassName:h,maybePostfixModifierPosition:g}=t(f);if(d){l=f+(l.length>0?" "+l:l);continue}let p=!!g,y=a(p?h.substring(0,g):h);if(!y){if(!p){l=f+(l.length>0?" "+l:l);continue}if(y=a(h),!y){l=f+(l.length>0?" "+l:l);continue}p=false;}let x=m.length===0?"":m.length===1?m[0]:n(m).join(":"),v=i?x+"!":x,L=v+y;if(s.indexOf(L)>-1)continue;s.push(L);let I=r(y,p);for(let k=0;k<I.length;++k){let S=I[k];s.push(v+S);}l=f+(l.length>0?" "+l:l);}return l},gv=(...e)=>{let o=0,t,a,r="";for(;o<e.length;)(t=e[o++])&&(a=Pc(t))&&(r&&(r+=" "),r+=a);return r},Pc=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=Pc(e[a]))&&(t&&(t+=" "),t+=o);return t},xv=(e,...o)=>{let t,a,r,n,s=l=>{let u=o.reduce((f,d)=>d(f),e());return t=mv(u),a=t.cache.get,r=t.cache.set,n=c,c(l)},c=l=>{let u=a(l);if(u)return u;let f=hv(l,t);return r(l,f),f};return n=s,(...l)=>n(gv(...l))},bv=[],Ve=e=>{let o=t=>t[e]||bv;return o.isThemeGetter=true,o},Dc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Rc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,vv=/^\d+\/\d+$/,yv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,wv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Lv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Iv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Sv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ro=e=>vv.test(e),ie=e=>!!e&&!Number.isNaN(Number(e)),Ia=e=>!!e&&Number.isInteger(Number(e)),ll=e=>e.endsWith("%")&&ie(e.slice(0,-1)),ta=e=>yv.test(e),Cv=()=>true,kv=e=>wv.test(e)&&!Lv.test(e),Ec=()=>false,Mv=e=>Iv.test(e),Tv=e=>Sv.test(e),Av=e=>!j(e)&&!$(e),Pv=e=>Eo(e,Oc,Ec),j=e=>Dc.test(e),ja=e=>Eo(e,Nc,kv),dl=e=>Eo(e,Bv,ie),Cc=e=>Eo(e,Fc,Ec),Dv=e=>Eo(e,Bc,Tv),rs=e=>Eo(e,Vc,Mv),$=e=>Rc.test(e),Tr=e=>Fo(e,Nc),Rv=e=>Fo(e,Ov),kc=e=>Fo(e,Fc),Ev=e=>Fo(e,Oc),Fv=e=>Fo(e,Bc),ns=e=>Fo(e,Vc,true),Eo=(e,o,t)=>{let a=Dc.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Fo=(e,o,t=false)=>{let a=Rc.exec(e);return a?a[1]?o(a[1]):t:false},Fc=e=>e==="position"||e==="percentage",Bc=e=>e==="image"||e==="url",Oc=e=>e==="length"||e==="size"||e==="bg-size",Nc=e=>e==="length",Bv=e=>e==="number",Ov=e=>e==="family-name",Vc=e=>e==="shadow";var Nv=()=>{let e=Ve("color"),o=Ve("font"),t=Ve("text"),a=Ve("font-weight"),r=Ve("tracking"),n=Ve("leading"),s=Ve("breakpoint"),c=Ve("container"),l=Ve("spacing"),u=Ve("radius"),f=Ve("shadow"),d=Ve("inset-shadow"),m=Ve("text-shadow"),i=Ve("drop-shadow"),h=Ve("blur"),g=Ve("perspective"),p=Ve("aspect"),y=Ve("ease"),x=Ve("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...L(),$,j],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],b=()=>[$,j,l],A=()=>[Ro,"full","auto",...b()],V=()=>[Ia,"none","subgrid",$,j],D=()=>["auto",{span:["full",Ia,$,j]},Ia,$,j],H=()=>[Ia,"auto",$,j],N=()=>["auto","min","max","fr",$,j],P=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...b()],oe=()=>[Ro,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],q=()=>[e,$,j],fe=()=>[...L(),kc,Cc,{position:[$,j]}],z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],O=()=>["auto","cover","contain",Ev,Pv,{size:[$,j]}],X=()=>[ll,Tr,ja],U=()=>["","none","full",u,$,j],K=()=>["",ie,Tr,ja],Q=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[ie,ll,kc,Cc],de=()=>["","none",h,$,j],Y=()=>["none",ie,$,j],Me=()=>["none",ie,$,j],Re=()=>[ie,$,j],Se=()=>[Ro,"full",...b()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ta],breakpoint:[ta],color:[Cv],container:[ta],"drop-shadow":[ta],ease:["in","out","in-out"],font:[Av],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ta],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ta],shadow:[ta],spacing:["px",ie],text:[ta],"text-shadow":[ta],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ro,j,$,p]}],container:["container"],columns:[{columns:[ie,j,$,c]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:I()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:A()}],"inset-x":[{"inset-x":A()}],"inset-y":[{"inset-y":A()}],start:[{start:A()}],end:[{end:A()}],top:[{top:A()}],right:[{right:A()}],bottom:[{bottom:A()}],left:[{left:A()}],visibility:["visible","invisible","collapse"],z:[{z:[Ia,"auto",$,j]}],basis:[{basis:[Ro,"full","auto",c,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ie,Ro,"auto","initial","none",j]}],grow:[{grow:["",ie,$,j]}],shrink:[{shrink:["",ie,$,j]}],order:[{order:[Ia,"first","last","none",$,j]}],"grid-cols":[{"grid-cols":V()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":V()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":N()}],"auto-rows":[{"auto-rows":N()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...P(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...P()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":P()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:oe()}],w:[{w:[c,"screen",...oe()]}],"min-w":[{"min-w":[c,"screen","none",...oe()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[s]},...oe()]}],h:[{h:["screen","lh",...oe()]}],"min-h":[{"min-h":["screen","lh","none",...oe()]}],"max-h":[{"max-h":["screen","lh",...oe()]}],"font-size":[{text:["base",t,Tr,ja]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,dl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ll,j]}],"font-family":[{font:[Rv,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,$,j]}],"line-clamp":[{"line-clamp":[ie,"none",$,dl]}],leading:[{leading:[n,...b()]}],"list-image":[{"list-image":["none",$,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:q()}],"text-color":[{text:q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:[ie,"from-font","auto",$,ja]}],"text-decoration-color":[{decoration:q()}],"underline-offset":[{"underline-offset":[ie,"auto",$,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:fe()}],"bg-repeat":[{bg:z()}],"bg-size":[{bg:O()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ia,$,j],radial:["",$,j],conic:[Ia,$,j]},Fv,Dv]}],"bg-color":[{bg:q()}],"gradient-from-pos":[{from:X()}],"gradient-via-pos":[{via:X()}],"gradient-to-pos":[{to:X()}],"gradient-from":[{from:q()}],"gradient-via":[{via:q()}],"gradient-to":[{to:q()}],rounded:[{rounded:U()}],"rounded-s":[{"rounded-s":U()}],"rounded-e":[{"rounded-e":U()}],"rounded-t":[{"rounded-t":U()}],"rounded-r":[{"rounded-r":U()}],"rounded-b":[{"rounded-b":U()}],"rounded-l":[{"rounded-l":U()}],"rounded-ss":[{"rounded-ss":U()}],"rounded-se":[{"rounded-se":U()}],"rounded-ee":[{"rounded-ee":U()}],"rounded-es":[{"rounded-es":U()}],"rounded-tl":[{"rounded-tl":U()}],"rounded-tr":[{"rounded-tr":U()}],"rounded-br":[{"rounded-br":U()}],"rounded-bl":[{"rounded-bl":U()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Q(),"hidden","none"]}],"divide-style":[{divide:[...Q(),"hidden","none"]}],"border-color":[{border:q()}],"border-color-x":[{"border-x":q()}],"border-color-y":[{"border-y":q()}],"border-color-s":[{"border-s":q()}],"border-color-e":[{"border-e":q()}],"border-color-t":[{"border-t":q()}],"border-color-r":[{"border-r":q()}],"border-color-b":[{"border-b":q()}],"border-color-l":[{"border-l":q()}],"divide-color":[{divide:q()}],"outline-style":[{outline:[...Q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ie,$,j]}],"outline-w":[{outline:["",ie,Tr,ja]}],"outline-color":[{outline:q()}],shadow:[{shadow:["","none",f,ns,rs]}],"shadow-color":[{shadow:q()}],"inset-shadow":[{"inset-shadow":["none",d,ns,rs]}],"inset-shadow-color":[{"inset-shadow":q()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:q()}],"ring-offset-w":[{"ring-offset":[ie,ja]}],"ring-offset-color":[{"ring-offset":q()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":q()}],"text-shadow":[{"text-shadow":["none",m,ns,rs]}],"text-shadow-color":[{"text-shadow":q()}],opacity:[{opacity:[ie,$,j]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ie]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":q()}],"mask-image-linear-to-color":[{"mask-linear-to":q()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":q()}],"mask-image-t-to-color":[{"mask-t-to":q()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":q()}],"mask-image-r-to-color":[{"mask-r-to":q()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":q()}],"mask-image-b-to-color":[{"mask-b-to":q()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":q()}],"mask-image-l-to-color":[{"mask-l-to":q()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":q()}],"mask-image-x-to-color":[{"mask-x-to":q()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":q()}],"mask-image-y-to-color":[{"mask-y-to":q()}],"mask-image-radial":[{"mask-radial":[$,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":q()}],"mask-image-radial-to-color":[{"mask-radial-to":q()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[ie]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":q()}],"mask-image-conic-to-color":[{"mask-conic-to":q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:fe()}],"mask-repeat":[{mask:z()}],"mask-size":[{mask:O()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,j]}],filter:[{filter:["","none",$,j]}],blur:[{blur:de()}],brightness:[{brightness:[ie,$,j]}],contrast:[{contrast:[ie,$,j]}],"drop-shadow":[{"drop-shadow":["","none",i,ns,rs]}],"drop-shadow-color":[{"drop-shadow":q()}],grayscale:[{grayscale:["",ie,$,j]}],"hue-rotate":[{"hue-rotate":[ie,$,j]}],invert:[{invert:["",ie,$,j]}],saturate:[{saturate:[ie,$,j]}],sepia:[{sepia:["",ie,$,j]}],"backdrop-filter":[{"backdrop-filter":["","none",$,j]}],"backdrop-blur":[{"backdrop-blur":de()}],"backdrop-brightness":[{"backdrop-brightness":[ie,$,j]}],"backdrop-contrast":[{"backdrop-contrast":[ie,$,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ie,$,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ie,$,j]}],"backdrop-invert":[{"backdrop-invert":["",ie,$,j]}],"backdrop-opacity":[{"backdrop-opacity":[ie,$,j]}],"backdrop-saturate":[{"backdrop-saturate":[ie,$,j]}],"backdrop-sepia":[{"backdrop-sepia":["",ie,$,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ie,"initial",$,j]}],ease:[{ease:["linear","initial",y,$,j]}],delay:[{delay:[ie,$,j]}],animate:[{animate:["none",x,$,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,j]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:Y()}],"rotate-x":[{"rotate-x":Y()}],"rotate-y":[{"rotate-y":Y()}],"rotate-z":[{"rotate-z":Y()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:Re()}],"skew-x":[{"skew-x":Re()}],"skew-y":[{"skew-y":Re()}],transform:[{transform:[$,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Se()}],"translate-x":[{"translate-x":Se()}],"translate-y":[{"translate-y":Se()}],"translate-z":[{"translate-z":Se()}],"translate-none":["translate-none"],accent:[{accent:q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:q()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,j]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,j]}],fill:[{fill:["none",...q()]}],"stroke-w":[{stroke:[ie,Tr,ja,dl]}],stroke:[{stroke:["none",...q()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var qc=xv(Nv);function Sa(...e){return qc(os(e))}var qv=be.createContext({size:"default",variant:"default",spacing:0});function Ca({className:e,variant:o,size:t,spacing:a=1,children:r,...n}){return jsx(wc,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Sa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...n,children:jsx(qv.Provider,{value:{variant:o,size:t,spacing:a},children:r})})}var Uv={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Gc=createSlice({name:"toolbar",initialState:Uv,reducers:{setTool:(e,o)=>{e.selectedTool=o.payload;},setPenColor:(e,o)=>{e.penColor=o.payload;},setStrokeWidth:(e,o)=>{e.strokeWidth=o.payload;},setFontSize:(e,o)=>{e.fontSize=o.payload;},setFontFamily:(e,o)=>{e.fontFamily=o.payload;},setFontStyle:(e,o)=>{e.fontStyle=o.payload;},setFontWeight:(e,o)=>{e.fontWeight=o.payload;},setTextDecoration:(e,o)=>{e.textDecoration=o.payload;},setTextColor:(e,o)=>{e.textColor=o.payload;}}}),{setTool:Wt,setPenColor:ss,setStrokeWidth:fl,setFontSize:aP,setFontFamily:oP,setFontStyle:rP,setFontWeight:nP,setTextDecoration:sP,setTextColor:iP}=Gc.actions,Kc=Gc.reducer;var _c=({onClose:e,onRecordingComplete:o})=>{let[t,a]=useState(false),[r,n]=useState(null),[s,c]=useState(0),[l,u]=useState(null),[f,d]=useState(false),m=useRef(null),i=useRef([]),h=useRef(null),g=useRef(null),p=useRef(null);useEffect(()=>((async()=>{try{let b=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});u(b),d(!0),p.current&&(p.current.srcObject=b);}catch(b){console.error("Error accessing camera:",b),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{h.current&&clearInterval(h.current),l&&l.getTracks().forEach(b=>b.stop());}),[]);let y=()=>{l&&(l.getTracks().forEach(S=>S.stop()),u(null),d(false));},x=async()=>{try{let S=null,b=null;try{S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(N){console.error("Error accessing camera for recording:",N),alert("Failed to access camera for recording.");return}try{b=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(N){console.warn("Microphone access denied:",N);}let A=[...S.getVideoTracks()];b&&A.push(...b.getAudioTracks());let V=new MediaStream(A),D="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?D="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?D="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?D="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(D="video/webm;codecs=vp8");let H=new MediaRecorder(V,{mimeType:D,videoBitsPerSecond:25e5});m.current=H,i.current=[],H.ondataavailable=N=>{N.data.size>0&&i.current.push(N.data);},H.onstop=()=>{let N=new Blob(i.current,{type:D}),P=document.createElement("video");P.src=URL.createObjectURL(N),P.muted=!0,P.currentTime=.1,P.onseeked=()=>{let W=document.createElement("canvas");W.width=P.videoWidth,W.height=P.videoHeight;let E=W.getContext("2d");E&&(E.drawImage(P,0,0),g.current=W.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(P.src);},V.getTracks().forEach(W=>W.stop()),S&&S.getTracks().forEach(W=>W.stop()),b&&b.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current),n(N),y();},H.onerror=N=>{console.error("MediaRecorder error:",N);},H.start(1e3),a(!0),c(0),h.current=setInterval(()=>{c(N=>N+1);},1e3);}catch(S){console.error("Error starting camera recording:",S),alert("Failed to start recording. Please check permissions.");}},v=()=>{m.current&&t&&(m.current.state!=="inactive"&&(m.current.requestData(),setTimeout(()=>{m.current&&m.current.state!=="inactive"&&m.current.stop();},100)),a(false));},L=()=>{if(r){let S=URL.createObjectURL(r),b=document.createElement("a");b.href=S,b.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(S);}},I=S=>{let b=Math.floor(S/60),A=S%60;return `${b.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`},k=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50 p-6",onMouseDown:S=>{S.target===S.currentTarget&&e(),S.stopPropagation();},onMouseUp:S=>S.stopPropagation(),onMouseMove:S=>S.stopPropagation(),onTouchStart:S=>S.stopPropagation(),onTouchMove:S=>S.stopPropagation(),onTouchEnd:S=>S.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:S=>S.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:p,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!t&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:x,disabled:!f,className:"flex h-20 w-20 items-center justify-center rounded-full bg-blue-500 text-white shadow-2xl transition-all hover:scale-110 hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:jsx(Record,{className:"h-10 w-10",weight:"fill"})})}),!f&&jsx("div",{className:"absolute top-1/3 left-1/2 -translate-x-1/2 text-center",children:jsx("p",{className:"text-lg font-medium text-white",children:"Click to start camera"})})]}),t&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:v,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:I(s)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",I(s)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),c(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick:L,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&g.current&&(o(r,g.current),e());},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"})]})]})]})]})]})});return createPortal(k,document.body)};var aa=40,$c=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,r]=useState(t?.images||[]),[n,s]=useState(t?.order||"sequential"),[c,l]=useState(false),u=useRef(null),f=useRef(null);useEffect(()=>{let x=v=>{v.key==="Escape"&&o();};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[o]);let d=x=>{let v=x.target.files;if(!v||v.length===0)return;let L=aa-a.length;if(L<=0){alert(`You can only upload a maximum of ${aa} images`);return}let I=Array.from(v).slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${aa} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=D=>{D.target?.result?b(D.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]),f.current&&(f.current.value="");});},m=x=>{x.preventDefault(),l(false);let v=Array.from(x.dataTransfer.files).filter(S=>S.type.startsWith("image/"));if(v.length===0)return;let L=aa-a.length;if(L<=0){alert(`You can only upload a maximum of ${aa} images`);return}let I=v.slice(0,L);I.length<v.length&&alert(`Only ${L} more images can be added (max ${aa} total)`);let k=I.map(S=>new Promise((b,A)=>{let V=new FileReader;V.onload=D=>{D.target?.result?b(D.target.result):A(new Error("Failed to read file"));},V.onerror=A,V.readAsDataURL(S);}));Promise.all(k).then(S=>{r(b=>[...b,...S]);});},i=x=>{x.preventDefault(),l(true);},h=()=>{l(false);},g=x=>{r(v=>v.filter((L,I)=>I!==x));},y=jsx("div",{className:"pointer-events-none fixed inset-0 z-100 flex items-center justify-center bg-black/50",onMouseDown:x=>{x.target===x.currentTarget&&o(),x.stopPropagation();},onMouseUp:x=>x.stopPropagation(),onMouseMove:x=>x.stopPropagation(),onTouchStart:x=>x.stopPropagation(),onTouchMove:x=>x.stopPropagation(),onTouchEnd:x=>x.stopPropagation(),children:jsxs("div",{ref:u,className:"pointer-events-auto max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:x=>x.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x=>{if(x.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,n,t?.id);},className:"overflow-y-auto p-6",style:{maxHeight:"calc(90vh - 140px)"},children:[jsxs("div",{className:"space-y-6",children:[jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between text-sm font-medium text-[#000000CC]",children:[jsxs("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:[jsx(Image$2,{size:16}),"Upload Images"]}),jsx("span",{className:"flex items-center gap-1 rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:a.length>=aa?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",aa," images"]}):jsxs("span",{children:[a.length,"/",aa," images"]})})]}),jsx("input",{ref:f,type:"file",accept:"image/*",multiple:true,onChange:d,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:m,onDragOver:i,onDragLeave:h,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${c?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>s("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="sequential"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>s("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${n==="random"?"border-primary/80 text-black":"border-gray-200 bg-white text-gray-900 hover:border-gray-300"}`,children:jsxs("div",{className:"flex flex-col items-start gap-2",children:[jsx("div",{className:`rounded bg-[#0000000A] p-2 ${n==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((x,v)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:x,alt:`Flashcard ${v+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>g(v),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:v+1})]},v))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(y,document.body)};var is={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:true,media:true},actions:{undo:true,redo:true,screenRecord:true,cameraRecord:true,clear:true}},oy={enabled:true};function hl(e){return e?{tools:{...is.tools,...e.tools},actions:{...is.actions,...e.actions}}:is}var ry={tools:{select:true,pen:false,eraser:false,text:false,shapes:false,activities:false,media:false},actions:{undo:false,redo:false,screenRecord:false,cameraRecord:false,clear:false}},ny={tools:{select:true,pen:true,eraser:true,text:true,shapes:true,activities:false,media:["image"]},actions:{undo:true,redo:true,screenRecord:false,cameraRecord:false,clear:true}};var Ry=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:r}={})=>{let n=xe(),s=ee(F=>F.canvas.slides.find(ne=>ne.id===F.canvas.currentSlideId)),c=s?.videos||[],l=s?.editingFlashcard,u=ee(F=>F.toolbar.selectedTool),f=ee(F=>F.toolbar.penColor),d=s?.showMcqForm,m=s?.showFlashcardForm,i=useMemo(()=>hl(r),[r]),{tools:h,actions:g}=i,p=c.some(F=>F.isRecorded&&F.isPlaying),y=ee(F=>F.toolbar.fontSize),x=ee(F=>F.toolbar.fontFamily),v=ee(F=>F.toolbar.fontStyle),L=ee(F=>F.toolbar.fontWeight),I=ee(F=>F.toolbar.textDecoration),k=ee(F=>F.toolbar.textColor),[S,b]=useState(false),[A,V]=useState(false),[D,H]=useState(false),[N,P]=useState(false),[W,E]=useState(false),oe=useRef(null),q=useRef(null),fe=useMemo(()=>[{name:"select",icon:Cursor,label:"Select",configKey:"select"},{name:"pen",icon:PenNib,label:"Pen",configKey:"pen"},{name:"eraser",icon:Eraser,label:"Eraser",configKey:"eraser"},{name:"text",icon:TextAa,label:"Text",configKey:"text"},{name:"shapes",icon:Shapes,label:"Shapes",configKey:"shapes"},{name:"activities",icon:Cards,label:"Activities",configKey:"activities"},{name:"image",icon:Image$2,label:"Media",configKey:"media"}],[]),z=useMemo(()=>[{name:"rectangle",icon:Square,label:"Rect"},{name:"circle",icon:Circle$1,label:"Circle"},{name:"ellipse",icon:Circle$1,label:"Ellipse"},{name:"triangle",icon:Triangle,label:"Tri"},{name:"polygon",icon:Hexagon,label:"Hex"},{name:"star",icon:Star$1,label:"Star"},{name:"ring",icon:Circle$1,label:"Ring"},{name:"wedge",icon:Pizza,label:"Wedge"},{name:"arrow",icon:ArrowRight,label:"Arrow"},{name:"line",icon:LineSegment,label:"Line"},{name:"arc",icon:Circuitry,label:"Arc"}],[]),O=useMemo(()=>[{name:"multiple-choice",icon:ListBullets,label:"MCQ"},{name:"true-false",icon:ToggleRight,label:"True-False"},{name:"short-answer",icon:Textbox,label:"Short Answer"},{name:"fill-in-the-blank",icon:TextUnderline,label:"Fill in the Blank"}],[]),X=useMemo(()=>fe.filter(F=>{let ne=h[F.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[h,fe]),U=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?z:Array.isArray(F)?z.filter(ne=>F.includes(ne.name)):z},[h.shapes,z]),K=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?O:Array.isArray(F)?O.filter(ne=>F.includes(ne.name)):O},[h.activities,O]),Q=useMemo(()=>{let F=h.media;return F===false?{photoFrame:false,image:false,video:false}:F===true?{photoFrame:true,image:true,video:true}:Array.isArray(F)?{photoFrame:F.includes("photo-frame"),image:F.includes("image"),video:F.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),te=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),J=F=>{let ne=F.target.files;!ne||ne.length===0||(n(Wt("select")),n(it(false)),P(false),Array.from(ne).forEach(ve=>{let he=new FileReader;he.onload=se=>{let re=new window.Image;re.src=se.target?.result,re.onload=()=>{let Te=re.width/re.height,Rt=300,Yt=300,st=re.width,Ee=re.height;st>Rt&&(st=Rt,Ee=st/Te),Ee>Yt&&(Ee=Yt,st=Ee*Te),n(le());let qe=(window.innerWidth-st)/2,ht=(window.innerHeight-Ee)/2;n(Ds({id:v4(),src:re.src,x:qe,y:ht,width:st,height:Ee,draggable:true,rotation:0}));};},he.readAsDataURL(ve);}),F.target.value="");},de=async F=>{let ne=F.target.files;if(!(!ne||ne.length===0)){console.log("files",F),n(Wt("select")),n(it(false)),P(false);for(let ve of Array.from(ne))try{let he=URL.createObjectURL(ve),se=document.createElement("video");console.log("video",se),se.src=he,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((Et,na)=>{let Ft=setTimeout(()=>na(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ft),Et();},se.onerror=()=>{clearTimeout(Ft),na(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((Et,na)=>{let Ft=setTimeout(()=>na(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ft),Et()):se.onloadeddata=()=>{clearTimeout(Ft),Et();};});let re=Math.min(.8,se.duration/2);console.log("Seeking to:",re),se.currentTime=re,await new Promise(Et=>{let na=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Et();},5e3);se.onseeked=()=>{clearTimeout(na),console.log("Seek completed"),Et();};});let Te=document.createElement("canvas"),Rt=se.videoWidth/se.videoHeight,Yt=400,st=400,Ee=se.videoWidth,qe=se.videoHeight;Ee>Yt&&(Ee=Yt,qe=Ee/Rt),qe>st&&(qe=st,Ee=qe*Rt),Te.width=Ee,Te.height=qe;let ht=Te.getContext("2d",{willReadFrequently:!1});if(!ht)throw new Error("Failed to get canvas context");if(await new Promise(Et=>setTimeout(Et,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ee,height:qe}),ht.drawImage(se,0,0,Ee,qe);let Ta=Te.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Ta.length),n(le());let Qa=(window.innerWidth-Ee)/2,eo=(window.innerHeight-qe)/2,Aa=v4();await Ga(Aa,ve,Ta),n(_r({id:Aa,objectUrl:he,thumbnailDataUrl:Ta,videoBlob:ve,x:Qa,y:eo,width:Ee,height:qe,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${ve.name}`);}catch(he){console.error("Error processing video:",he),alert(`Failed to process video: ${ve.name}`);}F.target.value="";}},Y=(F,ne,ve)=>{n(le()),n(Wt("select")),n(it(false));let he=300,se=300,re=(window.innerWidth-he)/2,Te=(window.innerHeight-se)/2;n(ve?no({id:ve,images:F,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true}):Fs({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:ne,x:re,y:Te,width:he,height:se,rotation:0,draggable:true})),n(Da(false));},Me=()=>{n(le()),n(Wt("select")),n(it(false));let F=400,ne=300,ve=(window.innerWidth-F)/2,he=(window.innerHeight-ne)/2;n(Ns({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ve,y:he,width:F,height:ne,rotation:0,draggable:true,isCapturing:false})),E(false);},Re=F=>{let he=(window.innerWidth-100)/2,se=(window.innerHeight-100)/2,re={};switch(F.name){case "circle":case "ring":case "wedge":case "arc":re.radius=50,(F.name==="ring"||F.name==="arc")&&(re.innerRadius=25,re.outerRadius=50),(F.name==="wedge"||F.name==="arc")&&(re.angle=F.name==="wedge"?60:90);break;case "ellipse":re.radiusX=60,re.radiusY=40;break;case "triangle":re.radius=50,re.sides=3;break;case "polygon":re.radius=50,re.sides=6;break;case "star":re.innerRadius=25,re.outerRadius=50,re.numPoints=5;break;case "arrow":case "line":re.points=[0,0,100,0],F.name==="arrow"&&(re.pointerLength=10,re.pointerWidth=10);break}let Te={id:`shape-${Date.now()}`,type:F.name,x:he,y:se,width:100,height:100,rotation:0,color:f,...re};n(le()),n(it(false)),n(Wt(F.name)),n(Rs(Te));},Se=F=>{if(n(Wt(F)),F==="select")n(it(false));else if(F==="text"){n(it(false)),n(le());let ne=200,ve=50,he=(window.innerWidth-ne)/2,se=(window.innerHeight-ve)/2,re=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;n(Es({id:re,text:"",x:he,y:se,width:ne,height:ve,rotation:0,draggable:true,fontSize:y,fontFamily:x,fontStyle:v,fontWeight:L,textDecoration:I,fill:k,align:"left"})),setTimeout(()=>{n($o(re));},100),a&&a(re);}else n(it(true));},Dt=()=>{n(Qs()),n(Wt("select")),n(it(false));},Za=()=>{o?o():t?b(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Br=()=>{V(true);},Or=async(F,ne)=>{try{n(Wt("select")),n(it(!1));let ve=URL.createObjectURL(F),he=document.createElement("video");he.src=ve,he.muted=!0,he.playsInline=!0,he.preload="auto",await new Promise((Ta,Qa)=>{let eo=setTimeout(()=>Qa(new Error("Metadata load timeout")),1e4);he.onloadedmetadata=()=>{clearTimeout(eo),Ta();},he.onerror=()=>{clearTimeout(eo),Qa(new Error("Failed to load video"));};});let se=640,re=he.videoWidth/he.videoHeight,Te=se,Rt=Te/re,Yt=window.innerWidth,st=window.innerHeight;n(le());let Ee=(Yt-Te)/2,qe=(st-Rt)/2,ht=v4();await Ga(ht,F,ne),n(_r({id:ht,objectUrl:ve,thumbnailDataUrl:ne,videoBlob:F,x:Ee,y:qe,width:Te,height:Rt,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),b(!1),V(!1);}catch(ve){console.error("Error adding recorded video to canvas:",ve),alert("Failed to add video to canvas. Please try again.");}},hs=F=>{n(Wt("select")),n(it(false)),n(_o(null)),F&&n(js(F)),n(da(!d));},gs=()=>{n(Wo(null)),n(Da(true)),E(false);},xs=()=>{H(!D);},bs=()=>{P(!N);},Ma=()=>{E(!W);};return p?null:jsxs("div",{className:"konva-editor-root",children:[jsxs("div",{className:"fixed top-1/3 z-50 flex -translate-y-1/2 flex-col justify-center gap-8 p-4 md:top-1/2",children:[jsxs("div",{className:"hidden items-center md:flex",children:[jsx(Ca,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:X.map((F,ne)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 2xl:py-3 ${F.name===u?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){bs(),H(false),E(false),Se(F.name);return}else if(F.name==="shapes"){xs(),P(false),E(false),Se(F.name);return}else if(F.name==="activities"){Se(F.name),Ma(),H(false),P(false);return}Se(F.name),H(false),P(false),E(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),D&&jsx(Ca,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:U.map((F,ne)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",onClick:()=>Re(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))}),N&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Q.photoFrame&&jsx("div",{title:"Photo frame",onClick:Me,className:"hover:bg-primary/10 cursor-pointer rounded-md p-3",children:jsx(CameraPlus,{weight:"fill",size:24,className:"text-primary"})}),Q.image&&jsx("div",{title:"Image",onClick:()=>oe.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),Q.video&&jsx("div",{title:"Video",onClick:()=>q.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})})]}),W&&jsxs(Ca,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[te&&jsx("div",{title:"Flashcard",onClick:()=>gs(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})}),K.map((F,ne)=>jsx("div",{title:F.label,onClick:()=>hs(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2 2xl:p-3",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl 2xl:text-2xl"})},ne))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Ca,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>n(ei()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Undo",children:jsx(ArrowCounterClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>n(ti()),className:"hover:bg-primary/10 text-primary cursor-pointer rounded-md px-4 py-3",title:"Redo",children:jsx(ArrowClockwise,{weight:"bold",className:"text-primary text-xl 2xl:text-2xl"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:Za,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6279F8]",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Br,className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#6BBB93]",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl 2xl:text-2xl"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>Dt(),className:"hover:bg-primary/10 cursor-pointer rounded-md px-4 py-3 text-[#E92222]",title:"Clear",children:jsx(Trash,{weight:"fill",className:"text-xl 2xl:text-2xl"})})]})]}),jsx("input",{ref:oe,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:J}),jsx("input",{ref:q,type:"file",accept:"video/*",className:"hidden",onChange:de}),!o&&S&&t&&jsx(rr,{onClose:()=>b(false),stageRef:t,onRecordingComplete:Or}),A&&jsx(_c,{onClose:()=>V(false),onRecordingComplete:Or}),m&&jsx($c,{editingFlashcard:l,onConfirm:Y,onCancel:()=>n(Da(false))})]})},Ey=Ry;var vl=({onPublish:e,label:o="Publish Slides",className:t})=>{let a=Jt(Yo),r=Jt(ri),c=(Jt(g=>g.canvas.slides.find(p=>p.id===g.canvas.currentSlideId))?.videos||[]).some(g=>g.isRecorded&&g.isPlaying),[l,u]=useState(false),[f,d]=useState(null),[m,i]=useState(null),h=async()=>{if(a.length===0){i({type:"error",message:"No slides to publish"});return}if(!e){i({type:"error",message:"No publish handler provided"});return}u(true),i(null);try{let g=await e(a,r,p=>{d(p);});g.success?i({type:"success",message:g.message}):i({type:"error",message:g.message});}catch(g){i({type:"error",message:g instanceof Error?g.message:"An unexpected error occurred"});}finally{u(false),setTimeout(()=>{d(null),i(null);},3e3);}};return c?null:jsxs("button",{onClick:h,disabled:l||a.length===0||!e,className:"bg-primary flex cursor-pointer items-center justify-center gap-2 rounded-lg p-2 font-medium text-white transition-colors md:px-4 md:py-3",children:[jsx(Export,{color:"#fff",className:"md:text-2xl"})," Publish"]})};var Vy=({title:e="Untitled",autoSaveMessage:o="Auto-saved just now",onBack:t,onPublish:a,onTitleChange:r,onDescriptionChange:n,showPublishButton:s=true,showBackButton:c=true,editableTitle:l=true,editableDescription:u=true,className:f="",rightContent:d,leftContent:m})=>{let[i,h]=useState(false),[g,p]=useState(false),[y,x]=useState(e),[v,L]=useState(o),I=useRef(null),k=useRef(null);useEffect(()=>{x(e);},[e]),useEffect(()=>{L(o);},[o]),useEffect(()=>{i&&I.current&&(I.current.focus(),I.current.select());},[i]),useEffect(()=>{g&&k.current&&(k.current.focus(),k.current.select());},[g]);let S=()=>{l&&h(true);},b=()=>{u&&p(true);},A=()=>{h(false),y.trim()&&y!==e?r?.(y.trim()):y.trim()||x(e);},V=()=>{p(false),v.trim()&&v!==o?n?.(v.trim()):v.trim()||L(o);},D=N=>{N.key==="Enter"?A():N.key==="Escape"&&(x(e),h(false));},H=N=>{N.key==="Enter"?V():N.key==="Escape"&&(L(o),p(false));};return jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${f}`,children:[m||jsxs("div",{className:"flex items-center gap-6",children:[c&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[i?jsx("input",{ref:I,type:"text",value:y,onChange:N=>x(N.target.value),onBlur:A,onKeyDown:D,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:S,title:y,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${l?"hover:border-primary cursor-text":""}`,children:y}),g?jsx("input",{ref:k,type:"text",value:v,onChange:N=>L(N.target.value),onBlur:V,onKeyDown:H,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:b,title:v,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${u?"hover:border-primary cursor-text":""}`,children:v})]})]}),d||s&&a&&jsx(vl,{onPublish:a})]})};function wl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Zc(e){let o=be.useRef({value:e,previous:e});return be.useMemo(()=>(o.current.value!==e&&(o.current.previous=o.current.value,o.current.value=e),o.current.previous),[e])}function ef(e){let[o,t]=be.useState(void 0);return Ao(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;let n=r[0],s,c;if("borderBoxSize"in n){let l=n.borderBoxSize,u=Array.isArray(l)?l[0]:l;s=u.inlineSize,c=u.blockSize;}else s=e.offsetWidth,c=e.offsetHeight;t({width:s,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}var tf=["PageUp","PageDown"],af=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],of={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Oo="Slider",[Ll,Hy,Uy]=Qn(Oo),[rf]=wa(Oo,[Uy]),[Wy,cs]=rf(Oo),nf=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:r=100,step:n=1,orientation:s="horizontal",disabled:c=false,minStepsBetweenThumbs:l=0,defaultValue:u=[a],value:f,onValueChange:d=()=>{},onValueCommit:m=()=>{},inverted:i=false,form:h,...g}=e,p=be.useRef(new Set),y=be.useRef(0),v=s==="horizontal"?zy:Gy,[L=[],I]=ea({prop:f,defaultProp:u,onChange:D=>{[...p.current][y.current]?.focus(),d(D);}}),k=be.useRef(L);function S(D){let H=Xy(L,D);V(D,H);}function b(D){V(D,y.current);}function A(){let D=k.current[y.current];L[y.current]!==D&&m(L);}function V(D,H,{commit:N}={commit:false}){let P=Qy(n),W=ew(Math.round((D-a)/n)*n+a,P),E=wl(W,[a,r]);I((oe=[])=>{let q=jy(oe,E,H);if(Zy(q,l*n)){y.current=q.indexOf(E);let fe=String(q)!==String(oe);return fe&&N&&m(q),fe?q:oe}else return oe});}return jsx(Wy,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:r,valueIndexToChangeRef:y,thumbs:p.current,values:L,orientation:s,form:h,children:jsx(Ll.Provider,{scope:e.__scopeSlider,children:jsx(Ll.Slot,{scope:e.__scopeSlider,children:jsx(v,{"aria-disabled":c,"data-disabled":c?"":void 0,...g,ref:o,onPointerDown:$e(g.onPointerDown,()=>{c||(k.current=L);}),min:a,max:r,inverted:i,onSlideStart:c?void 0:S,onSlideMove:c?void 0:b,onSlideEnd:c?void 0:A,onHomeKeyDown:()=>!c&&V(a,0,{commit:true}),onEndKeyDown:()=>!c&&V(r,L.length-1,{commit:true}),onStepKeyDown:({event:D,direction:H})=>{if(!c){let W=tf.includes(D.key)||D.shiftKey&&af.includes(D.key)?10:1,E=y.current,oe=L[E],q=n*W*H;V(oe+q,E,{commit:true});}}})})})})});nf.displayName=Oo;var[sf,lf]=rf(Oo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),zy=be.forwardRef((e,o)=>{let{min:t,max:a,dir:r,inverted:n,onSlideStart:s,onSlideMove:c,onSlideEnd:l,onStepKeyDown:u,...f}=e,[d,m]=be.useState(null),i=Tt(o,v=>m(v)),h=be.useRef(void 0),g=Do(r),p=g==="ltr",y=p&&!n||!p&&n;function x(v){let L=h.current||d.getBoundingClientRect(),I=[0,L.width],S=Cl(I,y?[t,a]:[a,t]);return h.current=L,S(v-L.left)}return jsx(sf,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:jsx(df,{dir:g,"data-orientation":"horizontal",...f,ref:i,style:{...f.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{let L=x(v.clientX);s?.(L);},onSlideMove:v=>{let L=x(v.clientX);c?.(L);},onSlideEnd:()=>{h.current=void 0,l?.();},onStepKeyDown:v=>{let I=of[y?"from-left":"from-right"].includes(v.key);u?.({event:v,direction:I?-1:1});}})})}),Gy=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:r,onSlideStart:n,onSlideMove:s,onSlideEnd:c,onStepKeyDown:l,...u}=e,f=be.useRef(null),d=Tt(o,f),m=be.useRef(void 0),i=!r;function h(g){let p=m.current||f.current.getBoundingClientRect(),y=[0,p.height],v=Cl(y,i?[a,t]:[t,a]);return m.current=p,v(g-p.top)}return jsx(sf,{scope:e.__scopeSlider,startEdge:i?"bottom":"top",endEdge:i?"top":"bottom",size:"height",direction:i?1:-1,children:jsx(df,{"data-orientation":"vertical",...u,ref:d,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{let p=h(g.clientY);n?.(p);},onSlideMove:g=>{let p=h(g.clientY);s?.(p);},onSlideEnd:()=>{m.current=void 0,c?.();},onStepKeyDown:g=>{let y=of[i?"from-bottom":"from-top"].includes(g.key);l?.({event:g,direction:y?-1:1});}})})}),df=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:r,onSlideEnd:n,onHomeKeyDown:s,onEndKeyDown:c,onStepKeyDown:l,...u}=e,f=cs(Oo,t);return jsx(rt.span,{...u,ref:o,onKeyDown:$e(e.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(c(d),d.preventDefault()):tf.concat(af).includes(d.key)&&(l(d),d.preventDefault());}),onPointerDown:$e(e.onPointerDown,d=>{let m=d.target;m.setPointerCapture(d.pointerId),d.preventDefault(),f.thumbs.has(m)?m.focus():a(d);}),onPointerMove:$e(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d);}),onPointerUp:$e(e.onPointerUp,d=>{let m=d.target;m.hasPointerCapture(d.pointerId)&&(m.releasePointerCapture(d.pointerId),n(d));})})}),uf="SliderTrack",cf=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=cs(uf,t);return jsx(rt.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...a,ref:o})});cf.displayName=uf;var Il="SliderRange",ff=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,r=cs(Il,t),n=lf(Il,t),s=be.useRef(null),c=Tt(o,s),l=r.values.length,u=r.values.map(m=>hf(m,r.min,r.max)),f=l>1?Math.min(...u):0,d=100-Math.max(...u);return jsx(rt.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...a,ref:c,style:{...e.style,[n.startEdge]:f+"%",[n.endEdge]:d+"%"}})});ff.displayName=Il;var Sl="SliderThumb",mf=be.forwardRef((e,o)=>{let t=Hy(e.__scopeSlider),[a,r]=be.useState(null),n=Tt(o,c=>r(c)),s=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(Ky,{...e,ref:n,index:s})}),Ky=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:r,...n}=e,s=cs(Sl,t),c=lf(Sl,t),[l,u]=be.useState(null),f=Tt(o,x=>u(x)),d=l?s.form||!!l.closest("form"):true,m=ef(l),i=s.values[a],h=i===void 0?0:hf(i,s.min,s.max),g=$y(a,s.values.length),p=m?.[c.size],y=p?Yy(p,h,c.direction):0;return be.useEffect(()=>{if(l)return s.thumbs.add(l),()=>{s.thumbs.delete(l);}},[l,s.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${h}% + ${y}px)`},children:[jsx(Ll.ItemSlot,{scope:e.__scopeSlider,children:jsx(rt.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":s.min,"aria-valuenow":i,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...n,ref:f,style:i===void 0?{display:"none"}:e.style,onFocus:$e(e.onFocus,()=>{s.valueIndexToChangeRef.current=a;})})}),d&&jsx(pf,{name:r??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:i},a)]})});mf.displayName=Sl;var _y="RadioBubbleInput",pf=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let r=be.useRef(null),n=Tt(r,a),s=Zc(o);return be.useEffect(()=>{let c=r.current;if(!c)return;let l=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==o&&f){let d=new Event("input",{bubbles:true});f.call(c,o),c.dispatchEvent(d);}},[s,o]),jsx(rt.input,{style:{display:"none"},...t,ref:n,defaultValue:o})});pf.displayName=_y;function jy(e=[],o,t){let a=[...e];return a[t]=o,a.sort((r,n)=>r-n)}function hf(e,o,t){let n=100/(t-o)*(e-o);return wl(n,[0,100])}function $y(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function Xy(e,o){if(e.length===1)return 0;let t=e.map(r=>Math.abs(r-o)),a=Math.min(...t);return t.indexOf(a)}function Yy(e,o,t){let a=e/2,n=Cl([0,50],[0,a]);return (a-n(o)*t)*t}function Jy(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Zy(e,o){if(o>0){let t=Jy(e);return Math.min(...t)>=o}return true}function Cl(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];let a=(o[1]-o[0])/(e[1]-e[0]);return o[0]+a*(t-e[0])}}function Qy(e){return (String(e).split(".")[1]||"").length}function ew(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var gf=nf,xf=cf,bf=ff,vf=mf;function wf({className:e,defaultValue:o,value:t,min:a=0,max:r=100,rangeClassName:n,trackClassName:s,thumbClassName:c,...l}){let u=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,r],[t,o,a,r]);return jsxs(gf,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:r,className:Sa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...l,children:[jsx(xf,{"data-slot":"slider-track",className:Sa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",s),children:jsx(bf,{"data-slot":"slider-range",className:Sa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",n)})}),Array.from({length:u.length},(f,d)=>jsx(vf,{"data-slot":"slider-thumb",className:Sa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",c)},d))]})}var rw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],nw=({colors:e=rw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:r=""})=>{let n=ee(c=>c.toolbar.penColor),s=xe();return jsxs("div",{className:`absolute bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 transform gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:p-6 ${r}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-3 w-3 rounded-full bg-black"}),jsx(wf,{defaultValue:[12],max:28,min:6,step:1,className:"w-28 lg:w-48",rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:c=>s(fl(c[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs(Ca,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(c=>jsx("button",{value:c.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${n===c.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:c.value},onClick:()=>s(ss(c.value))},c.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(ss(c.target.value))}),jsx(Plus,{color:"#00000099"})]})]}),a&&jsx("div",{className:"h-16 border bg-[#0000001A]"})]}),a&&jsx("div",{className:"flex items-center px-2 2xl:px-4",children:jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000033] bg-[#ffff] text-xl text-[#00000033] lg:h-12 lg:w-12",children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:c=>s(As(c.target.value))})})})]})};function sw({children:e,className:o="",style:t}){return jsx("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:e})}var If=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),lw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),Ml=e=>{let o=lw(e);return o.charAt(0).toUpperCase()+o.slice(1)},fs=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Sf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Cf={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 Mf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:r="",children:n,iconNode:s,...c},l)=>createElement("svg",{ref:l,...Cf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:fs("lucide",r),...!n&&!Sf(c)&&{"aria-hidden":"true"},...c},[...s.map(([u,f])=>createElement(u,f)),...Array.isArray(n)?n:[n]]));var ms=(e,o)=>{let t=forwardRef(({className:a,...r},n)=>createElement(Mf,{ref:n,iconNode:o,className:fs(`lucide-${If(Ml(e))}`,`lucide-${e}`,a),...r}));return t.displayName=Ml(e),t};var fw=[["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"}]],Rr=ms("copy",fw);var mw=[["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"}]],Er=ms("trash-2",mw);var Af=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:r,onDuplicate:n,onDelete:s})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"shadow-lg":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:r,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:c=>{c.stopPropagation(),n();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Rr,{size:14})}),!a&&jsx("button",{onClick:c=>{c.stopPropagation(),s();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Er,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var xw=()=>{let e=yt(),o=Jt(Yo),t=Jt(Xo),a=Jt(oi),[r,n]=useState(true),l=(Jt(i=>i.canvas.slides.find(h=>h.id===i.canvas.currentSlideId))?.videos||[]).some(i=>i.isRecorded&&i.isPlaying),u=()=>{a&&e(Ss());},f=i=>{e(Ms(i));},d=i=>{e(ks(i));},m=i=>{o.length>1&&e(Cs(i));};return l?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-100 flex items-start",children:[jsxs(motion.div,{initial:false,animate:{x:r?0:320},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:"pointer-events-auto flex h-full w-80 flex-col overflow-hidden border-l border-gray-300 bg-gray-50 shadow-xl",children:[jsx("div",{className:"bg-white p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>n(false),className:"flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition-colors",title:"Hide Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})}),jsx("h2",{className:"text-lg font-semibold text-black",children:"Pages"})]}),jsxs("span",{className:"text-sm text-gray-600",children:[o.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:o.map((i,h)=>jsx(Af,{slide:i,index:h,isSelected:i.id===t,isSingleSlide:o.length===1,onSelect:()=>f(i.id),onDuplicate:()=>d(i.id),onDelete:()=>m(i.id)},i.id))}),jsxs("button",{onClick:u,disabled:!a,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${a?"bg-primary text-white":"cursor-not-allowed bg-gray-300 text-gray-500"}`,children:[jsx(Plus,{size:18}),"Add Page"]})]})]}),jsx(AnimatePresence,{children:!r&&jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>n(true),className:"pointer-events-auto absolute top-2 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-l-lg transition-colors hover:bg-gray-100",title:"Show Slides",children:jsx(SidebarSimple,{size:24,weight:"bold"})},"toggle")})]})};var bw="SchooplaEditorDB",vw=1,ka="slides",No="metadata",Tl="schoopla_current_slide_id",Rf="presentation_metadata",Fr=()=>new Promise((e,o)=>{let t=indexedDB.open(bw,vw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let r=a.target.result;r.objectStoreNames.contains(ka)||r.createObjectStore(ka,{keyPath:"id"}),r.objectStoreNames.contains(No)||r.createObjectStore(No,{keyPath:"id"});};}),Al=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await Fr(),a=o.transaction([ka],"readwrite").objectStore(ka);await new Promise((r,n)=>{let s=a.clear();s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);});for(let r of e)await new Promise((n,s)=>{let c=a.add(r);c.onsuccess=()=>n(!0),c.onerror=()=>s(c.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Pl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await Fr(),t=e.transaction([ka],"readonly").objectStore(ka);return new Promise((a,r)=>{let n=t.getAll();n.onsuccess=()=>{e.close();let s=n.result;console.log("\u2705 Loaded from IndexedDB:",s.length,"slides"),s.length>0&&s[0].images&&console.log("First slide images:",s[0].images.map(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.y}))),a(s.length>0?s:null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading from IndexedDB:",e);try{let o=localStorage.getItem("schoopla_slides_backup");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}},ps=async()=>{try{let e=await Fr(),t=e.transaction([ka],"readwrite").objectStore(ka);await new Promise((a,r)=>{let n=t.clear();n.onsuccess=()=>a(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(Tl),await Xu();}catch(e){console.error("Error clearing local data:",e);}},Dl=e=>{try{localStorage.setItem(Tl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Rl=()=>{try{return localStorage.getItem(Tl)}catch(e){return console.error("Error loading current slide ID:",e),null}},El=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Fl=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await Fr(),a=o.transaction([No],"readwrite").objectStore(No);await new Promise((r,n)=>{let s=a.put({id:Rf,...e});s.onsuccess=()=>r(!0),s.onerror=()=>n(s.error);}),o.close(),console.log("\u2705 Presentation metadata saved successfully");}catch(o){console.error("Error saving presentation metadata:",o);try{localStorage.setItem("schoopla_presentation_metadata",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Bl=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await Fr(),t=e.transaction([No],"readonly").objectStore(No);return new Promise((a,r)=>{let n=t.get(Rf);n.onsuccess=()=>{e.close();let s=n.result;if(s){let{id:c,...l}=s;console.log("\u2705 Loaded presentation metadata:",l),a(l);}else console.log("No presentation metadata found"),a(null);},n.onerror=()=>{e.close(),r(n.error);};})}catch(e){console.error("Error loading presentation metadata:",e);try{let o=localStorage.getItem("schoopla_presentation_metadata");return o?JSON.parse(o):null}catch(o){return console.error("localStorage fallback failed:",o),null}}};var yw=["canvas/finalizeDrawing","canvas/setLines","canvas/removeLine","canvas/addImage","canvas/updateImage","canvas/deleteImage","canvas/duplicateImage","canvas/addVideo","canvas/updateVideo","canvas/deleteVideo","canvas/duplicateVideo","canvas/addShape","canvas/updateShape","canvas/deleteShape","canvas/duplicateShape","canvas/addText","canvas/updateText","canvas/deleteText","canvas/duplicateText","canvas/addFlashcard","canvas/updateFlashcard","canvas/deleteFlashcard","canvas/duplicateFlashcard","canvas/addPhotoFrame","canvas/updatePhotoFrame","canvas/deletePhotoFrame","canvas/duplicatePhotoFrame","canvas/toggleImageDrawingMode","canvas/addImageAnnotation","canvas/updateImageAnnotation","canvas/clearImageAnnotations","canvas/togglePhotoFrameDrawingMode","canvas/addPhotoFrameAnnotation","canvas/updatePhotoFrameAnnotation","canvas/clearPhotoFrameAnnotations","canvas/addMultipleChoice","canvas/updateMultipleChoice","canvas/deleteMultipleChoice","canvas/duplicateMultipleChoice","canvas/addTrueFalse","canvas/updateTrueFalse","canvas/deleteTrueFalse","canvas/duplicateTrueFalse","canvas/addShortAnswer","canvas/updateShortAnswer","canvas/deleteShortAnswer","canvas/duplicateShortAnswer","canvas/addLongAnswer","canvas/updateLongAnswer","canvas/deleteLongAnswer","canvas/duplicateLongAnswer","canvas/addFillInTheBlanks","canvas/updateFillInTheBlanks","canvas/deleteFillInTheBlanks","canvas/duplicateFillInTheBlanks","canvas/bringToFront","canvas/sendToBack","canvas/toggleLock","canvas/setLink","canvas/setAltText","canvas/setAudioData","canvas/updateElementOrder","canvas/updateLinePosition","canvas/updateLineTransform","canvas/setBackgroundColor","canvas/addSlide","canvas/deleteSlide","canvas/duplicateSlide","canvas/reorderSlides"],ww=["canvas/clearCanvas"],Lw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],Iw=El((e,o)=>{Al(e),Dl(o);},500),Sw=El(e=>{Fl(e);},500),Cw=(e,o)=>{Al(e),Dl(o);},Ol=false,Ef=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let r=t.payload;Qi(r).catch(n=>{console.error("Error deleting video blob:",n);});}if(t.type==="canvas/deleteSlide"&&t.payload){let r=t.payload,s=e.getState().canvas.slides.find(c=>c.id===r);s&&s.videos&&s.videos.length>0&&s.videos.forEach(c=>{Qi(c.id).catch(l=>{console.error("Error deleting video blob:",l);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let r=t.payload,n=e.getState(),c=n.canvas.slides.find(l=>l.id===n.canvas.currentSlideId)?.videos.find(l=>l.id===r);c&&c.videoBlob&&setTimeout(()=>{let l=e.getState(),f=l.canvas.slides.find(d=>d.id===l.canvas.currentSlideId)?.videos.find(d=>d.id!==r&&d.x===c.x+20&&d.y===c.y+20);f&&c.videoBlob&&Ga(f.id,c.videoBlob,f.thumbnailDataUrl).catch(d=>{console.error("Error saving duplicated video blob:",d);});},0);}let a=o(t);if(t.type&&ww.includes(t.type)){if(!Ol){Ol=true;try{let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;Cw(n,s);}finally{setTimeout(()=>{Ol=false;},0);}}}else if(t.type&&yw.includes(t.type)){let r=e.getState(),{slides:n,currentSlideId:s}=r.canvas;Iw(n,s);}else if(t.type&&Lw.includes(t.type)){let r=e.getState(),{presentationMetadata:n}=r.canvas;Sw(n);}return a});new QueryClient;var Tw=configureStore({reducer:{toolbar:Kc,canvas:Zl},middleware:e=>e({serializableCheck:false}).concat(Ef)});var Aw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2,fileName:n=`slide-${Date.now()}`}=o;try{let s=t==="png"?"image/png":"image/jpeg",c=e.toDataURL({mimeType:s,quality:a,pixelRatio:r}),l=document.createElement("a");l.download=`${n}.${t}`,l.href=c,document.body.appendChild(l),l.click(),document.body.removeChild(l);}catch(s){throw console.error("Error exporting slide:",s),new Error("Failed to export slide")}},Pw=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o;return new Promise((n,s)=>{try{let c=t==="png"?"image/png":"image/jpeg",l=e.toDataURL({mimeType:c,quality:a,pixelRatio:r});fetch(l).then(u=>u.blob()).then(u=>n(u)).catch(u=>s(u));}catch(c){s(c);}})},Dw=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:r=2}=o,n=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:n,quality:a,pixelRatio:r})};var Rw=(e,o,t)=>{let a=t.x-o.x,r=t.y-o.y;if(a===0&&r===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let n=a*a+r*r,s=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*r)/n)),c=o.x+s*a,l=o.y+s*r;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-l,2))},Nl=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,r=e[0],n=e[e.length-1];for(let s=1;s<e.length-1;s++){let c=Rw(e[s],r,n);c>t&&(t=c,a=s);}if(t>o){let s=Nl(e.slice(0,a+1),o),c=Nl(e.slice(a),o);return [...s.slice(0,-1),...c]}return [r,n]},Ew=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},Fw=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},Ff=(e,o=1.5)=>{if(e.length<=4)return e;let t=Ew(e),a=Nl(t,o);return Fw(a)},Bf=(e,o=1.5)=>({...e,points:Ff(e.points,o)}),Bw=(e,o=1.5)=>e.map(t=>Bf(t,o)),Ow=(e,o)=>{let t=e.length/2,a=o.length/2,r=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${r}%`}};var Nw=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var Of=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:r=.85}=o;return new Promise((n,s)=>{let c=new Image;c.onload=()=>{let{width:l,height:u}=c;if(l>t||u>a){let h=l/u;l>u?(l=Math.min(l,t),u=l/h):(u=Math.min(u,a),l=u*h);}let f=document.createElement("canvas");f.width=l,f.height=u;let d=f.getContext("2d");if(!d){s(new Error("Failed to get canvas context"));return}d.drawImage(c,0,0,l,u);let m=Nw(e),i=f.toDataURL(m,r);n(i);},c.onerror=s,c.src=e;})};var Ja=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return a.buffer},Vo=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",qo=e=>({"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/wav":"wav","audio/webm":"weba"})[e]||"bin",Vw=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:r=1080,imageQuality:n=.85}=o,s=[],c=0;for(let l of e){let u=[],f=[],d=[];for(let m of l.images){let i=m.src;if(t&&i.startsWith("data:"))try{i=await Of(i,{maxWidth:a,maxHeight:r,quality:n});}catch(h){console.warn("Failed to optimize image, using original:",h);}if(i.startsWith("data:")){let h=Ja(i),g=Vo(i);c+=h.byteLength;let p={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,buffer:h,mimeType:g};if(m.audioData&&m.audioData.startsWith("data:")){let y=Ja(m.audioData),x=Vo(m.audioData);c+=y.byteLength,p.audioBuffer=y,p.audioMimeType=x;}u.push(p);}}for(let m of l.videos){let i,h;if(m.videoBlob)i=await m.videoBlob.arrayBuffer(),h=m.videoBlob.type;else if(m.videoData&&m.videoData.startsWith("data:"))i=Ja(m.videoData),h=Vo(m.videoData);else {console.warn(`Video ${m.id} has no blob or videoData, skipping`);continue}c+=i.byteLength;let g={id:m.id,thumbnailDataUrl:m.thumbnailDataUrl,x:m.x,y:m.y,width:m.width,height:m.height,draggable:m.draggable,isPlaying:m.isPlaying,rotation:m.rotation,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isRecorded:m.isRecorded,buffer:i,mimeType:h};if(m.audioData&&m.audioData.startsWith("data:")){let p=Ja(m.audioData),y=Vo(m.audioData);c+=p.byteLength,g.audioBuffer=p,g.audioMimeType=y;}f.push(g);}for(let m of l.photoFrames){let i={id:m.id,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:m.draggable,locked:m.locked,link:m.link,altText:m.altText,zIndex:m.zIndex,isCapturing:m.isCapturing};if(m.capturedImageUrl&&m.capturedImageUrl.startsWith("data:")){let h=Ja(m.capturedImageUrl),g=Vo(m.capturedImageUrl);c+=h.byteLength,i.buffer=h,i.mimeType=g;}if(m.audioData&&m.audioData.startsWith("data:")){let h=Ja(m.audioData),g=Vo(m.audioData);c+=h.byteLength,i.audioBuffer=h,i.audioMimeType=g;}d.push(i);}s.push({...l,images:u,videos:f,photoFrames:d});}return {slides:s,totalSize:c}},qw=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},Hw=e=>{let o=new FormData,t=e.slides.map((a,r)=>({id:a.id,name:a.name,thumbnail:a.thumbnail,backgroundColor:a.backgroundColor,lines:a.lines,shapes:a.shapes,flashcards:a.flashcards,texts:a.texts,createdAt:a.createdAt,updatedAt:a.updatedAt,multipleChoices:a.multipleChoices,showMcqForm:a.showMcqForm,images:a.images.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,mimeType:n.mimeType,fileKey:`slide_${r}_image_${s}`,audioFileKey:n.audioBuffer?`slide_${r}_image_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),videos:a.videos.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,draggable:n.draggable,isPlaying:n.isPlaying,rotation:n.rotation,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isRecorded:n.isRecorded,mimeType:n.mimeType,fileKey:`slide_${r}_video_${s}`,thumbnailFileKey:`slide_${r}_video_${s}_thumbnail`,audioFileKey:n.audioBuffer?`slide_${r}_video_${s}_audio`:void 0,audioMimeType:n.audioMimeType})),photoFrames:a.photoFrames.map((n,s)=>({id:n.id,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,draggable:n.draggable,locked:n.locked,link:n.link,altText:n.altText,zIndex:n.zIndex,isCapturing:n.isCapturing,mimeType:n.mimeType,fileKey:n.buffer?`slide_${r}_photoframe_${s}`:void 0,audioFileKey:n.audioBuffer?`slide_${r}_photoframe_${s}_audio`:void 0,audioMimeType:n.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,r)=>{a.images.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${qo(n.mimeType)}`;if(o.append(`slide_${r}_image_${s}`,c,l),n.audioBuffer&&n.audioMimeType){let u=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${qo(n.audioMimeType)}`;o.append(`slide_${r}_image_${s}_audio`,u,f);}}),a.videos.forEach((n,s)=>{let c=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${qo(n.mimeType)}`;if(o.append(`slide_${r}_video_${s}`,c,l),n.thumbnailDataUrl&&n.thumbnailDataUrl.startsWith("data:")){let u=Ja(n.thumbnailDataUrl),f=new Blob([u],{type:"image/jpeg"}),d=`${n.id}_thumbnail.jpg`;o.append(`slide_${r}_video_${s}_thumbnail`,f,d);}if(n.audioBuffer&&n.audioMimeType){let u=new Blob([n.audioBuffer],{type:n.audioMimeType}),f=`${n.id}_audio.${qo(n.audioMimeType)}`;o.append(`slide_${r}_video_${s}_audio`,u,f);}}),a.photoFrames.forEach((n,s)=>{if(n.buffer&&n.mimeType){let c=new Blob([n.buffer],{type:n.mimeType}),l=`${n.id}.${qo(n.mimeType)}`;o.append(`slide_${r}_photoframe_${s}`,c,l);}if(n.audioBuffer&&n.audioMimeType){let c=new Blob([n.audioBuffer],{type:n.audioMimeType}),l=`${n.id}_audio.${qo(n.audioMimeType)}`;o.append(`slide_${r}_photoframe_${s}_audio`,c,l);}});}),o};var zw=()=>{let e=yt(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let r=await Pl(),n=Rl(),s=await Bl();if(r&&r.length>0){let c=await $u(),l=r.map(f=>{if(f.videos&&f.videos.length>0){let d=f.videos.map(m=>{let i=c.get(m.id);if(i){let h=Yu(i.blob);return {...m,objectUrl:h,thumbnailDataUrl:i.thumbnailDataUrl,videoBlob:i.blob}}else return m});return {...f,videos:d}}return f}),u=n&&l.find(f=>f.id===n)?n:l[0].id;e(ao({slides:l,currentSlideId:u}));}s&&e(ai({title:s.title,description:s.description}));}catch(r){console.error("Error loading persisted slides:",r);}finally{t(false);}})();},[e]),{isLoading:o}};var Vf=e=>e.map(o=>({...o,lines:o.lines||[],shapes:o.shapes||[],images:o.images||[],videos:o.videos||[],flashcards:o.flashcards||[],photoFrames:o.photoFrames||[],texts:o.texts||[],multipleChoices:o.multipleChoices||[],trueFalses:o.trueFalses||[],shortAnswers:o.shortAnswers||[],LongAnswer:o.LongAnswer||[],fillInTheBlanks:o.fillInTheBlanks||[],createdAt:o.createdAt||Date.now(),updatedAt:o.updatedAt||Date.now(),showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,activityType:o.activityType||""})),qf=new WeakSet,Hf=async e=>{for(let o of e)if(o.videos&&o.videos.length>0){for(let t of o.videos)if(t.videoBlob)try{await Ga(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},Gw=()=>{let e=yt(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||qf.has(a))return;qf.add(a);let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await ps(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(u){console.error("Error clearing local data:",u);}let c=n&&r.find(u=>u.id===n)?n:r[0].id,l=Vf(r);e(ao({slides:l,currentSlideId:c})),await Hf(l);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:r,currentSlideId:n,skipLocalPersistence:s=true}=a;if(s)try{await ps(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(u){console.error("Error clearing local data:",u);}let c=n&&r.find(u=>u.id===n)?n:r[0].id,l=Vf(r);e(ao({slides:l,currentSlideId:c})),await Hf(l);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
7
7
 
8
8
  lucide-react/dist/esm/shared/src/utils.js:
9
9
  lucide-react/dist/esm/defaultAttributes.js:
@@ -18,5 +18,5 @@ lucide-react/dist/esm/lucide-react.js:
18
18
  * This source code is licensed under the ISC license.
19
19
  * See the LICENSE file in the root directory of this source tree.
20
20
  *)
21
- */export{$v as BASIC_EDITOR_TOOLBAR_CONFIG,Xy as BottomToolbar,Qx as Canvas,_v as DEFAULT_CONTEXT_MENU_CONFIG,ns as DEFAULT_TOOLBAR_CONFIG,Yy as EditorRoot,pl as PublishButton,or as ScreenRecorder,iw as SlideNavigation,Ly as Toolbar,Ty as TopNavBar,jv as VIEWER_TOOLBAR_CONFIG,zs as addFillInTheBlanks,Rs as addFlashcard,Ts as addImage,Os as addImageAnnotation,Ms as addLine,Ws as addLongAnswer,qs as addMultipleChoice,Fs as addPhotoFrame,Vs as addPhotoFrameAnnotation,As as addShape,Us as addShortAnswer,ws as addSlide,Ps as addText,Hs as addTrueFalse,Gr as addVideo,Mw as arrayBufferToBase64,Ks as bringToFront,Ys as clearCanvas,gm as clearImageAnnotations,cs as clearLocalData,bm as clearPhotoFrameAnnotations,ys as createEmptySlide,cn as deleteFillInTheBlanks,Zr as deleteFlashcard,Wr as deleteImage,xn as deleteLineById,dn as deleteLongAnswer,an as deleteMultipleChoice,en as deletePhotoFrame,Xr as deleteShape,sn as deleteShortAnswer,Ls as deleteSlide,Yr as deleteText,rn as deleteTrueFalse,_r as deleteVideo,fn as duplicateFillInTheBlanks,Qr as duplicateFlashcard,zr as duplicateImage,Xs as duplicateLine,un as duplicateLongAnswer,on as duplicateMultipleChoice,tn as duplicatePhotoFrame,$r as duplicateShape,ln as duplicateShortAnswer,Is as duplicateSlide,Jr as duplicateText,nn as duplicateTrueFalse,jr as duplicateVideo,Uo as editFlashcard,vm as editMultipleChoice,bw as exportSlideAsBlob,xw as exportSlideAsImage,$s as finalizeDrawing,Sw as getCompressionStats,vw as getSlideDataURL,Ml as loadCurrentSlideId,Cl as loadFromIndexedDB,to as loadSlides,ul as mergeToolbarConfig,Ds as nextFlashcard,Tw as prepareFormData,kw as prepareSlidesForPublishing,Es as previousFlashcard,Zs as redo,Ur as removeLine,pm as reorderSlides,le as saveToHistory,Xo as selectAllSlides,Qs as selectCanAddSlide,ge as selectCurrentSlide,$o as selectCurrentSlideId,Sm as selectSlideById,_s as sendToBack,Gs as setActivityType,pn as setAltText,hn as setAudioData,ks as setBackgroundColor,Ss as setCurrentSlide,Ko as setEditingActivity,jo as setEditingTextId,wm as setLines,mn as setLink,rs as setPenColor,Ra as setShowFlashcardForm,da as setShowMcqForm,it as setSketchMode,il as setStrokeWidth,Wt as setTool,Cf as simplifyFlatPoints,kf as simplifyLine,Iw as simplifyLines,gw as store,Bs as toggleImageDrawingMode,js as toggleLock,Ns as togglePhotoFrameDrawingMode,Im as toggleSketchMode,Ho as toggleVideoPlaying,Js as undo,_o as updateElementOrder,Go as updateFillInTheBlanks,ro as updateFlashcard,ao as updateImage,hm as updateImageAnnotation,ym as updateLastLine,Lm as updateLinePosition,gn as updateLineTransform,zo as updateLongAnswer,ia as updateMultipleChoice,Pa as updatePhotoFrame,xm as updatePhotoFrameAnnotation,oo as updateShape,Wo as updateShortAnswer,Cs as updateSlideThumbnail,wt as updateText,la as updateTrueFalse,Kr as updateVideo,xe as useDispatch,Rw as useInitialSlides,ee as useSelector,Pw as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
+ */export{ny as BASIC_EDITOR_TOOLBAR_CONFIG,nw as BottomToolbar,ub as Canvas,oy as DEFAULT_CONTEXT_MENU_CONFIG,is as DEFAULT_TOOLBAR_CONFIG,sw as EditorRoot,vl as PublishButton,rr as ScreenRecorder,xw as SlideNavigation,Ey as Toolbar,Vy as TopNavBar,ry as VIEWER_TOOLBAR_CONFIG,_s as addFillInTheBlanks,Fs as addFlashcard,Ds as addImage,qs as addImageAnnotation,Ps as addLine,Ks as addLongAnswer,Ws as addMultipleChoice,Ns as addPhotoFrame,Us as addPhotoFrameAnnotation,Rs as addShape,Gs as addShortAnswer,Ss as addSlide,Es as addText,zs as addTrueFalse,_r as addVideo,qw as arrayBufferToBase64,$s as bringToFront,Qs as clearCanvas,Cm as clearImageAnnotations,ps as clearLocalData,Mm as clearPhotoFrameAnnotations,Is as createEmptySlide,mn as deleteFillInTheBlanks,en as deleteFlashcard,Gr as deleteImage,vn as deleteLineById,cn as deleteLongAnswer,rn as deleteMultipleChoice,an as deletePhotoFrame,Jr as deleteShape,dn as deleteShortAnswer,Cs as deleteSlide,Zr as deleteText,sn as deleteTrueFalse,$r as deleteVideo,pn as duplicateFillInTheBlanks,tn as duplicateFlashcard,Kr as duplicateImage,Zs as duplicateLine,fn as duplicateLongAnswer,nn as duplicateMultipleChoice,on as duplicatePhotoFrame,Yr as duplicateShape,un as duplicateShortAnswer,ks as duplicateSlide,Qr as duplicateText,ln as duplicateTrueFalse,Xr as duplicateVideo,Wo as editFlashcard,Tm as editMultipleChoice,Pw as exportSlideAsBlob,Aw as exportSlideAsImage,Js as finalizeDrawing,Ow as getCompressionStats,Dw as getSlideDataURL,Rl as loadCurrentSlideId,Pl as loadFromIndexedDB,ai as loadPresentationMetadata,Bl as loadPresentationMetadataFromDB,ao as loadSlides,hl as mergeToolbarConfig,Bs as nextFlashcard,Hw as prepareFormData,Vw as prepareSlidesForPublishing,Os as previousFlashcard,ti as redo,zr as removeLine,Im as reorderSlides,Fl as savePresentationMetadata,le as saveToHistory,Yo as selectAllSlides,oi as selectCanAddSlide,ge as selectCurrentSlide,Xo as selectCurrentSlideId,ri as selectPresentationMetadata,Bm as selectSlideById,Xs as sendToBack,js as setActivityType,gn as setAltText,xn as setAudioData,As as setBackgroundColor,Ms as setCurrentSlide,_o as setEditingActivity,$o as setEditingTextId,Pm as setLines,hn as setLink,ss as setPenColor,Fm as setPresentationDescription,Em as setPresentationTitle,Da as setShowFlashcardForm,da as setShowMcqForm,it as setSketchMode,fl as setStrokeWidth,Wt as setTool,Ff as simplifyFlatPoints,Bf as simplifyLine,Bw as simplifyLines,Tw as store,Vs as toggleImageDrawingMode,Ys as toggleLock,Hs as togglePhotoFrameDrawingMode,Rm as toggleSketchMode,Uo as toggleVideoPlaying,ei as undo,jo as updateElementOrder,Ko as updateFillInTheBlanks,no as updateFlashcard,oo as updateImage,Sm as updateImageAnnotation,Am as updateLastLine,Dm as updateLinePosition,bn as updateLineTransform,Go as updateLongAnswer,ia as updateMultipleChoice,Pa as updatePhotoFrame,km as updatePhotoFrameAnnotation,ro as updateShape,zo as updateShortAnswer,Ts as updateSlideThumbnail,wt as updateText,la as updateTrueFalse,jr as updateVideo,xe as useDispatch,Gw as useInitialSlides,ee as useSelector,zw as useSlidesPersistence};//# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map