@turnix-co/konva-editor 3.0.18 → 3.0.20

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,createContext,useState,useMemo,createElement,useContext,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,createSelector,configureStore}from'@reduxjs/toolkit';import Sd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X as X$1,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,CaretLeft,Plus,CaretDown,CaretUp,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Pen}from'@phosphor-icons/react/dist/ssr';import {EyeIcon,Stack as Stack$1,X as X$2,DotsSixVertical,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 Iu from'use-image';import {AnimatePresence,motion,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 md=e=>{throw TypeError(e)};var pd=(e,o,t)=>o.has(e)||md("Cannot "+t);var j=(e,o,t)=>(pd(e,o,"read from private field"),t?t.call(e):o.get(e)),Pe=(e,o,t)=>o.has(e)?md("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Ce=(e,o,t,a)=>(pd(e,o,"write to private field"),o.set(e,t),t);var hd=(e,o,t,a)=>({set _(s){Ce(e,o,s);},get _(){return j(e,o,a)}});var xe=()=>useDispatch(),Q=e=>useSelector(e),at=xe,ct=Q;var Bn=20,Nn=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),Fn=Nn("Slide 1"),Hm={slides:[Fn],currentSlideId:Fn.id,history:{[Fn.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false},gd=createSlice({name:"canvas",initialState:Hm,reducers:{addSlide:e=>{if(e.slides.length>=Bn)return;let o=Nn(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(l=>l.isActive).length<=1)return;let r=e.slides.findIndex(l=>l.id===t);if(r===-1)return;let n=e.slides[r];if(a?(n.isActive=false,n.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let l=e.slides.filter(d=>d.isActive);l.length>0&&(e.currentSlideId=l[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=Bn)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],s={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),isActive:true,lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,s),e.currentSlideId=s.id,e.history[s.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[s]=e.slides.splice(t,1);e.slides.splice(a,0,s);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(s=>s.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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,newTimestamp:r}=o.payload;switch(s){case "image":let n=t.images.find(b=>b.id===a);n&&(n.timestamp=r);break;case "video":let l=t.videos.find(b=>b.id===a);l&&(l.timestamp=r);break;case "shape":let d=t.shapes.find(b=>b.id===a);d&&(d.timestamp=r);break;case "text":let u=t.texts.find(b=>b.id===a);u&&(u.timestamp=r);break;case "flashcard":let m=t.flashcards.find(b=>b.id===a);m&&(m.timestamp=r);break;case "photoFrame":let f=t.photoFrames.find(b=>b.id===a);f&&(f.timestamp=r);break;case "mcq":let i=t.multipleChoices.find(b=>b.id===a);i&&(i.timestamp=r);break;case "trueFalse":let c=t.trueFalses.find(b=>b.id===a);c&&(c.timestamp=r);break;case "shortAnswer":let p=t.shortAnswers.find(b=>b.id===a);p&&(p.timestamp=r);break;case "longAnswer":let y=t.LongAnswer.find(b=>b.id===a);y&&(y.timestamp=r);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(b=>b.id===a);h&&(h.timestamp=r);break;case "line":let x=t.lines.find(b=>b.id===a);x&&(x.timestamp=r);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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.multipleChoices[t.multipleChoices.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.trueFalses[t.trueFalses.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.shortAnswers[t.shortAnswers.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.LongAnswer[t.LongAnswer.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(s),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 s=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.push(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.push(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.push(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.push(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.push(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.push(n);}}else if(s==="trueFalse"){let r=t.trueFalses.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.trueFalses.splice(r,1);t.trueFalses.push(n);}}else if(s==="shortAnswer"){let r=t.shortAnswers.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shortAnswers.splice(r,1);t.shortAnswers.push(n);}}else if(s==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(n);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.unshift(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.unshift(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.unshift(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.unshift(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.unshift(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.unshift(n);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload,n=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(l=>l.id===a);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,link:r}=o.payload,l=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="mcq"?t.multipleChoices:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);l&&(l.link=r,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,altText:r}=o.payload,l=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);l&&(l.altText=r,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,audioData:r}=o.payload,l=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);l&&(l.audioData=r,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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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 s=a.images.map((r,n)=>n).filter(r=>r!==a.currentIndex);if(s.length>0){let r=s[Math.floor(Math.random()*s.length)];a.navigationHistory.push(r),a.currentIndex=r;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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 s=o.past.pop();e.slides[t]=s;}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 s=o.future.shift();e.slides[t]=s;}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 s=JSON.parse(JSON.stringify(t));a.past.push(s),a.future=[],a.past.length>20&&a.past.shift();}catch(s){console.warn("Failed to save to history - data too large:",s),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;}}}),{addSlide:Vn,deleteSlide:qn,duplicateSlide:Hn,setCurrentSlide:Un,updateSlideThumbnail:Wn,setBackgroundColor:zn,reorderSlides:Um,loadSlides:io,addLine:Gn,removeLine:Yr,addImage:Kn,updateImage:lo,deleteImage:Jr,duplicateImage:Zr,addVideo:Qr,updateVideo:es,deleteVideo:ts,duplicateVideo:as,toggleVideoPlaying:jo,addShape:_n,updateShape:uo,duplicateShape:os,deleteShape:rs,addText:jn,updateText:It,deleteText:ss,duplicateText:ns,addFlashcard:Xn,updateFlashcard:co,deleteFlashcard:is,duplicateFlashcard:ls,editFlashcard:Xo,nextFlashcard:$n,previousFlashcard:Yn,addPhotoFrame:Jn,updatePhotoFrame:Ba,deletePhotoFrame:ds,duplicatePhotoFrame:us,toggleImageDrawingMode:Zn,addImageAnnotation:Qn,updateImageAnnotation:Wm,clearImageAnnotations:zm,togglePhotoFrameDrawingMode:ei,addPhotoFrameAnnotation:ti,updatePhotoFrameAnnotation:Gm,clearPhotoFrameAnnotations:Km,addMultipleChoice:ai,updateMultipleChoice:ca,editMultipleChoice:_m,deleteMultipleChoice:cs,duplicateMultipleChoice:fs,addTrueFalse:oi,updateTrueFalse:fa,deleteTrueFalse:ms,duplicateTrueFalse:ps,addShortAnswer:ri,updateShortAnswer:$o,deleteShortAnswer:hs,duplicateShortAnswer:gs,addLongAnswer:si,updateLongAnswer:Yo,deleteLongAnswer:xs,duplicateLongAnswer:bs,addFillInTheBlanks:ni,updateFillInTheBlanks:Jo,deleteFillInTheBlanks:vs,duplicateFillInTheBlanks:ys,setShowMcqForm:ma,setShowFlashcardForm:Oa,setActivityType:ii,setEditingActivity:Zo,bringToFront:li,sendToBack:di,toggleLock:ui,setLink:ws,setAltText:Ls,setAudioData:Ss,updateLastLine:jm,finalizeDrawing:ci,setLines:Xm,updateLinePosition:$m,updateLineTransform:Is,deleteLineById:Cs,duplicateLine:fi,updateElementOrder:Qo,clearCanvas:mi,undo:pi,redo:hi,saveToHistory:ce,toggleSketchMode:Ym,setSketchMode:ft,setEditingTextId:er,setPresentationTitle:gi,setPresentationDescription:xi,loadPresentationMetadata:bi,setMetadataLoaded:ks}=gd.actions;var xd=e=>e.canvas.slides,fo=e=>e.canvas.currentSlideId,he=createSelector([xd,fo],(e,o)=>e.find(t=>t.id===o)),mo=createSelector([xd],e=>e.filter(o=>o.isActive!==false)),vi=e=>e.canvas.slides,yi=createSelector([mo],e=>e.length<Bn),Jm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},tr=e=>e.canvas.presentationMetadata,wi=e=>e.canvas.metadataLoaded,bd=gd.reducer;var yd=e=>{let o=xe(),t=useRef(null),a=useRef(false),s=Q(c=>c.toolbar.selectedTool),r=Q(c=>c.toolbar.penColor),n=Q(c=>c.toolbar.strokeWidth),l=Q(c=>c.canvas.isSketchMode),d=Q(c=>c.canvas.slides.find(y=>y.id===c.canvas.currentSlideId)?.lines||[]),u=useCallback(c=>{t.current=c;},[]),m=useCallback(c=>{s==="pen"&&t.current&&(o(ce()),t.current.startDrawing(c),a.current=true);},[s,o]),f=useCallback(c=>{!t.current||!a.current||t.current.draw(c);},[]),i=useCallback(()=>{if(!t.current||!a.current)return;let c=t.current.stopDrawing();a.current=false,c&&c.points.length>=4&&o(Gn(c)),o(ci()),e?.();},[o,e]);return {lines:d,tool:s,color:r,strokeWidth:n,isSketchMode:l,setCanvasRef:u,startDrawing:m,draw:f,stopDrawing:i}};var Id=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:s,isSketchMode:r,style:n,xOffset:l=0,yOffset:d=0},u)=>{let m=useRef(null),f=useRef(false),i=useRef([]),c=useRef([]),p=useRef(null),y=useRef(t),h=useRef(a),x=useRef(s),b=useRef(r),g=useRef(l),L=useRef(d);useEffect(()=>{y.current=t,h.current=a,x.current=s,b.current=r,g.current=l,L.current=d;},[t,a,s,r,l,d]);let C=useCallback(()=>{let k=m.current;if(!k)return;let v=k.getContext("2d");v&&v.clearRect(0,0,k.width,k.height);},[]),S=useCallback(()=>{let k=m.current,v=c.current;if(!k||v.length<1)return;let M=k.getContext("2d");if(!M)return;if(M.clearRect(0,0,k.width,k.height),y.current==="eraser"?(M.globalCompositeOperation="destination-out",M.fillStyle="rgba(0,0,0,1)"):(M.globalCompositeOperation="source-over",M.fillStyle=h.current),v.length===1){M.beginPath(),M.arc(v[0].x,v[0].y,x.current/2,0,Math.PI*2),M.fill();return}let D=Sd(v,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:O=>O,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(D.length<2)){M.beginPath(),M.moveTo(D[0][0],D[0][1]);for(let O=1;O<D.length;O++)M.lineTo(D[O][0],D[O][1]);M.closePath(),M.fill();}},[]);return useImperativeHandle(u,()=>({startDrawing:k=>{f.current=true;let v={x:k.x-g.current,y:k.y-L.current};i.current=[{x:k.x,y:k.y}],c.current=[v],p.current=k,S();},draw:k=>{if(!f.current||!p.current)return;let v=k.x-p.current.x,M=k.y-p.current.y;if(Math.sqrt(v*v+M*M)<2)return;let D={x:k.x-g.current,y:k.y-L.current};i.current.push({x:k.x,y:k.y}),c.current.push(D),p.current=k,S();},stopDrawing:()=>{if(!f.current)return null;if(f.current=false,i.current.length<2)return i.current=[],c.current=[],p.current=null,C(),null;let v=Sd(i.current,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:B=>B,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(B=>[B[0],B[1]]),M={tool:y.current,points:v,color:h.current,strokeWidth:x.current,isSketch:true};return i.current=[],c.current=[],p.current=null,C(),M},clear:()=>{C(),i.current=[],c.current=[],p.current=null,f.current=false;},isDrawing:()=>f.current,getCanvasElement:()=>m.current}),[C,S]),useEffect(()=>{let k=m.current;k&&(k.width=e,k.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});Id.displayName="DirectDrawingCanvas";var Cd=Id;var Md=e=>{let o=xe(),a=Q(he)?.images||[],s=useRef(new Map),r=useRef(new Map),n=useRef(new Set);useEffect(()=>{let m=new Set(a.map(f=>f.id));n.current.forEach(f=>{if(!m.has(f)){let i=r.current.get(f);i&&(i.src="",r.current.delete(f)),s.current.delete(f);}}),n.current=m;},[a]),useEffect(()=>()=>{r.current.forEach(m=>{m.src="";}),r.current.clear(),s.current.clear();},[]);let l=useCallback(m=>{if(r.current.has(m.id))return r.current.get(m.id);let f=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=m.src,r.current.set(m.id,f),f},[]),d=useCallback((m,f)=>{let i=m.target,c=i.id();a.find(y=>y.id===c)&&(o(lo({id:c,x:i.x(),y:i.y(),width:i.width(),height:i.height(),rotation:i.rotation()})),f?.());},[a,o]),u=useCallback((m,f)=>{let i=f.target,c=s.current.get(m);if(!c){console.error("\u274C Image node not found for id:",m);return}let p=i.scaleX(),y=i.scaleY(),h=i.rotation(),x=c.width(),b=c.height(),g=Math.max(5,x*p),L=Math.max(5,b*y);i.scaleX(1),i.scaleY(1),c.width(g),c.height(L),o(lo({id:m,width:g,height:L,x:i.x(),y:i.y(),rotation:h})),i.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:l,imageRefs:s,handleDragEnd:d,handleImageTransformEnd:u}};var Td=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),s=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((l,d)=>{let u=d.target,m=u.scaleX(),f=u.scaleY(),i=u.rotation(),c=Math.max(5,u.width()*m),p=Math.max(5,u.height()*f);u.scaleX(1),u.scaleY(1),u.width(c),u.height(p),o(ca({id:l,width:c,height:p,x:u.x(),y:u.y(),rotation:i})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:s,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(l,d)=>{o(ca({id:d,x:l.target.x(),y:l.target.y()})),e?.();}}};var Ad=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),s=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((l,d)=>{let u=d.target,m=u.scaleX(),f=u.scaleY(),i=u.rotation(),c=Math.max(5,u.width()*m),p=Math.max(5,u.height()*f);u.scaleX(1),u.scaleY(1),u.width(c),u.height(p),o(fa({id:l,width:c,height:p,x:u.x(),y:u.y(),rotation:i})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:s,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(l,d)=>{o(fa({id:d,x:l.target.x(),y:l.target.y()})),e?.();},trueFalseRefs:a}};var Pd=e=>{let o=xe(),a=Q(he)?.videos||[],s=useRef(new Map),r=useCallback(d=>{o(jo(d));},[o]),n=useCallback((d,u)=>{let m=u.target;o(es({id:d,x:m.x(),y:m.y()})),e?.();},[o,e]),l=useCallback((d,u)=>{let m=u.target,f=m.scaleX(),i=m.scaleY(),c=m.rotation(),p=Math.max(5,m.width()*f),y=Math.max(5,m.height()*i);m.scaleX(1),m.scaleY(1),m.width(p),m.height(y),o(es({id:d,width:p,height:y,x:m.x(),y:m.y(),rotation:c})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:s,handleVideoClick:r,handleVideoDragEnd:n,handleVideoTransformEnd:l}};var Ed=e=>{let o=xe(),a=Q(he)?.shapes||[],s=useRef(new Map),r=useRef(new Map),[n,l]=useState(false),d=useCallback((m,f)=>{let i=f.target;o(uo({id:m,x:i.x(),y:i.y()})),e?.();},[o,e]),u=useCallback((m,f)=>{let i=f.target,c=a.find(g=>g.id===m);if(!c)return;let p=i.scaleX(),y=i.scaleY(),h=c.type?.toLowerCase();h==="arrow"||h==="line"||(i.scaleX(1),i.scaleY(1));let b={id:m,x:i.x(),y:i.y(),width:Math.max(5,i.width()*p),height:Math.max(5,i.height()*y),rotation:i.rotation()};switch(h){case "circle":b.radius=i.width()*p/2;break;case "star":b.innerRadius=i.width()*p/4,b.outerRadius=i.width()*p/2;break;case "triangle":b.radius=i.width()*p/2;break;case "ellipse":b.radiusX=i.width()*p/2,b.radiusY=i.height()*y/2;break;case "polygon":b.radius=i.width()*p/2;break;case "ring":let g=p;b.innerRadius=c.innerRadius&&c.innerRadius*g,b.outerRadius=c.outerRadius&&c.outerRadius*g;break;case "wedge":b.radius=c.radius&&c.radius*p;break;case "arc":b.innerRadius=c.innerRadius&&c.innerRadius*p,b.outerRadius=c.outerRadius&&c.outerRadius*p;break;case "arrow":case "line":{b.scaleX=p,b.scaleY=y,delete b.width,delete b.height;break}}o(uo(b)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:s,isDragging:n,loadedShapesRef:r,handleShapeDragEnd:d,handleShapeResizeEnd:u}};var Bd=(e,o)=>{let t=at(),s=Q(he)?.texts||[],r=useRef(new Map),[n,l]=useState(null),[d,u]=useState("");return {texts:s,textRefs:r,handleDragEnd:(h,x)=>{let b=h.target;t(ce()),t(It({id:x,x:b.x(),y:b.y()})),e();},handleTransformEnd:h=>{let x=r.current.get(h);if(!x)return;let b=x.scaleX(),g=x.scaleY(),L=s.find(S=>S.id===h);if(!L)return;let C=(b+g)/2;x.scaleX(1),x.scaleY(1),t(ce()),t(It({id:h,x:x.x(),y:x.y(),width:Math.max(5,(L.width||100)*b),height:Math.max(5,(L.height||50)*g),fontSize:Math.round(Math.max(8,L.fontSize*C)),rotation:x.rotation()})),e();},handleDoubleClick:h=>{let x=s.find(b=>b.id===h);x&&!x.locked&&(l(h),u(x.text));},startEditing:h=>{let x=s.find(b=>b.id===h);x&&!x.locked&&(l(h),u(x.text));},editingTextId:n,editingValue:d,handleEditingChange:h=>{u(h);},finishEditing:()=>{if(n){let h=r.current.get(n),x=s.find(g=>g.id===n);t(ce());let b={id:n,text:d};if(x&&(x.fontWeight!==void 0&&(b.fontWeight=x.fontWeight),x.fontStyle!==void 0&&(b.fontStyle=x.fontStyle),x.textDecoration!==void 0&&(b.textDecoration=x.textDecoration)),o?.current&&d.trim()){let g=o.current,L=g.offsetWidth,C=g.offsetHeight,S=1;if(h){let U=h.getStage();U&&(S=U.scaleX());}let k=14,v=(L-k)/S,M=(C-k)/S,B=d.split(`
3
- `).length,O=s.find(U=>U.id===n)?.fontSize||24,T=B*O*1.2+10;b.width=Math.max(200,v),b.height=Math.max(50,M,T);}else if(h&&d.trim()){let g=h.text(),L=h.width();h.text(d),h.width(void 0);let C=h.width(),S=h.height();h.text(g),h.width(L),b.width=Math.max(200,C+20),b.height=Math.max(50,S+20);}t(It(b)),l(null),u(""),t(er(null)),e();}}}};var Od=e=>{let o=useDispatch(),a=useSelector(he)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,l)=>{let d=n.target;o($o({id:l,x:d.x(),y:d.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var Nd=e=>{let o=useDispatch(),t=useSelector(he),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let l=r.target;o(Yo({id:n,x:l.x(),y:l.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var qd=e=>{let o=xe(),a=Q(he)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((f,i)=>{if(r.current.has(i))return r.current.get(i);let c=new window.Image;return c.src=f,r.current.set(i,c),c},[]),l=useCallback((f,i)=>{let c=f.target,p=c.id();a.find(h=>h.id===p)&&(o(co({id:p,x:c.x(),y:c.y()})),i?.());},[a,o]),d=useCallback((f,i)=>{let c=i.target,p=c.scaleX(),y=c.scaleY(),h=c.rotation(),x=Math.max(50,c.width()*p),b=Math.max(50,c.height()*y);c.scaleX(1),c.scaleY(1),c.width(x),c.height(b),o(co({id:f,width:x,height:b,x:c.x(),y:c.y(),rotation:h})),c.getLayer()?.batchDraw(),e?.();},[o,e]),u=useCallback(f=>{o($n(f)),e?.();},[o,e]),m=useCallback(f=>{o(Yn(f)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:l,handleFlashcardTransformEnd:d,handleNext:u,handlePrevious:m}};var Wd=e=>{let o=xe(),a=Q(he)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),l=useCallback((c,p)=>{console.log("handleDragEnd"),o(Ba({id:p,x:c.target.x(),y:c.target.y()})),e?.();},[o,e]),d=useCallback((c,p)=>{let y=p.target,h=y.scaleX(),x=y.scaleY(),b=y.rotation(),g=a.find(S=>S.id===c);if(!g)return;let L=Math.max(100,g.width*h),C=Math.max(100,g.height*x);y.scaleX(1),y.scaleY(1),o(Ba({id:c,width:L,height:C,x:y.x(),y:y.y(),rotation:b})),y.getLayer()?.batchDraw(),e?.();},[o,e,a]),u=useCallback(async c=>{try{let p=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(y=>{let h=new Map(y);return h.set(c,p),h}),o(Ba({id:c,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),m=useCallback(c=>{let p=r.get(c);p&&(p.getTracks().forEach(y=>y.stop()),n(y=>{let h=new Map(y);return h.delete(c),h}),o(Ba({id:c,isCapturing:false})),e?.());},[r,o,e]),f=useCallback((c,p)=>{let y=document.createElement("canvas");y.width=p.videoWidth,y.height=p.videoHeight;let h=y.getContext("2d");if(h){h.drawImage(p,0,0,y.width,y.height);let x=y.toDataURL("image/jpeg",.8);return o(Ba({id:c,capturedImageUrl:x,isCapturing:false})),m(c),e?.(),x}return null},[o,m,e]),i=useRef(r);return useEffect(()=>{i.current=r;},[r]),useEffect(()=>()=>{i.current.forEach(c=>{c.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:l,handlePhotoFrameTransformEnd:d,startCamera:u,stopCamera:m,capturePhoto:f,cameraStreams:r}};var zd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((r,n,l,d,u,m,f,i=[])=>{if(e.current){if(r&&!i.find(y=>y.id===r)?.isPlaying){let y=n.get(r)||l.get(r)||d.get(r)||u.get(r)||m.get(r)||(f?f.get(r):null);if(y){e.current.boundBoxFunc(t),e.current.nodes([y]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),s=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:s,boundBoxFunc:t}};var Cp=(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])},jd=(e,o)=>{let t=at(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let s=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});n&&n.startsWith("data:")&&t(Wn({id:a.current,thumbnail:n}));}catch(n){console.warn("Could not generate thumbnail (likely CORS issue with images):",n);}},[o,t]),r=Cp(s,500);return {generateThumbnail:s,debouncedGenerateThumbnail:r}};var Mp=e=>e.flatMap(o=>[o[0],o[1]]),Ts=(e,o)=>{let t=Sd(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 Mp(t)};var Xd=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),l=Q(g=>g.toolbar.selectedTool),d=Q(g=>g.toolbar.penColor),u=Q(g=>g.toolbar.strokeWidth),m=Q(g=>g.canvas.isSketchMode),f=Q(g=>g.canvas.slides.find(C=>C.id===g.canvas.currentSlideId)?.images.find(C=>C.id===e)),i=f?.annotations||[],c=f?.isDrawingMode||false,p=f?.width||1,y=f?.height||1,h=useCallback(g=>{if(l!=="pen"&&l!=="eraser")return;t.current=true,a.current=false,s.current=[{x:g.x,y:g.y}];let L=g.x/p,C=g.y/y;n({tool:l,points:[L,C],color:d,strokeWidth:u/p,isSketch:m});},[l,d,u,m,p,y]),x=useCallback(g=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;s.current.push({x:g.x,y:g.y});let S;if(m)S=Ts(s.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((v,M)=>M%2===0?v/p:v/y);else {let k=g.x/p,v=g.y/y;S=[...r.points,k,v];}n(k=>k?{...k,points:S}:null);},[m,u,r,p,y]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(Qn({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:i,activeLine:r,isDrawingMode:c,startDrawing:h,draw:x,stopDrawing:b,tool:l}};var Zd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>{let{annotations:l,activeLine:d,stopDrawing:i,tool:c}=Xd(e.id);useEffect(()=>{let b=t.current.get(e.id);b&&(b.width()!==e.width||b.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:b.width(),konvaHeight:b.height()}),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[i,p]);let y=b=>{{r(e.id);return}},h=b=>{return;},x=b=>{};return jsxs(Group,{listening:c!=="pen"&&c!=="eraser",children:[jsx(Image$1,{id:e.id,ref:b=>{if(b){t.current.set(e.id,b),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw();let g=b.getStage()?.container();if(g){let L=C=>{let S=b.getStage()?.getPointerPosition();if(S){let k={x:e.x,y:e.y,width:e.width,height:e.height};S.x>=k.x&&S.x<=k.x+k.width&&S.y>=k.y&&S.y<=k.y+k.height&&n(C,e.id,"image");}};g.addEventListener("contextmenu",L),b._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",L);};}}else {let g=t.current.get(e.id);g?._contextMenuCleanup&&g._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:c!=="pen"&&c!=="eraser",onDragEnd:a,onTransformEnd:b=>s(e.id,b),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...c!=="pen"&&c!=="eraser"?{onClick:y,onTap:y,onMouseDown:y,onTouchStart:y,onMouseMove:h,onTouchMove:h,onMouseUp:x,onTouchEnd:x}:{}}),l?.map((b,g)=>{let L=b.points.map((S,k)=>k%2===0?S*e.width+e.x:S*e.height+e.y),C=b.strokeWidth*e.width;return jsx(Line,{points:L,stroke:b.tool==="eraser"?"white":b.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},g)}),d&&jsx(Line,{points:d.points.map((b,g)=>g%2===0?b*e.width+e.x:b*e.height+e.y),stroke:d.tool==="eraser"?"white":d.color,strokeWidth:d.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:d.tool==="eraser"?"destination-out":"source-over",fill:d.isSketch?d.color:void 0,closed:d.isSketch,listening:false},"active")]})});Zd.displayName="ImageWithDrawing";var Ti=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(l=>{let d=o(l);return d?jsx(Zd,{img:l,loadedImage:d,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n},l.id):null})}));Ti.displayName="ImageLayer";var Np=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:l=0,onTransformEnd:d,onDragEnd:u})=>{let m=xe(),f=useRef(null),i=c=>{m(jo(c));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:l,onDragEnd:u,onTransformEnd:d,children:[jsx(Rect,{width:s,height:r,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${s}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:f,src:e,controls:true,autoPlay:true,onClick:()=>i(t),onSeeking:c=>c.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Qd=Np;var Kp=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[l,d]=useState(null),u=useSelector(y=>y.toolbar.selectedTool),m=u==="pen"||u==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let y=new window.Image;y.src=e.thumbnailDataUrl,y.onload=()=>{d(y);};}},[e.thumbnailDataUrl]),!l)return null;let f=e.width/2,i=e.height/2,c=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(c,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:s},ref:y=>{if(n(y),y){let h=y.getStage()?.container();if(h){let x=b=>{let g=y.getStage()?.getPointerPosition();if(g){let L={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=L.x&&g.x<=L.x+L.width&&g.y>=L.y&&g.y<=L.y+L.height&&r(b);}};h.addEventListener("contextmenu",x),y._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",x);};}}},children:[jsx(Image$1,{image:l,width:e.width,height:e.height,listening:!m,...m?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:f,y:i,radius:p,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:f,y:i,radius:p*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:f+p*.1,y:i,sides:3,radius:p*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},tu=Kp;var Di=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(l=>jsxs(be__default.Fragment,{children:[jsx(tu,{video:l,isSelected:!l.isPlaying&&o===l.id,onClick:()=>a(l.id),onDragEnd:d=>s(l.id,d),onTransformEnd:d=>r(l.id,d),onContextMenu:d=>n(d,l.id,"video"),nodeRef:d=>{d?t.current.set(l.id,d):t.current.delete(l.id);}}),l.isPlaying&&(()=>{let d=l.x,u=l.y;if(l.isRecorded){let m=typeof window<"u"?window.innerWidth:l.width,f=typeof window<"u"?window.innerHeight:l.height;d=(m-l.width)/2,u=(f-l.height)/2;}return jsx(Qd,{id:l.id,src:l.objectUrl,x:d,y:u,width:l.width,height:l.height,isSelected:false,rotation:l.rotation,onTransformEnd:m=>r(l.id,m),onDragEnd:m=>s(l.id,m)})})()]},l.id))}));Di.displayName="VideoLayer";var Ri=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n})=>{let l=useSelector(u=>u.toolbar.selectedTool),d=l==="pen"||l==="eraser";return jsx(Fragment,{children:e.map((u,m)=>{let f=u.id||m,i={id:u.id,x:u.x,y:u.y,rotation:u.rotation,draggable:!u.locked&&!d,listening:!d,fill:u.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(u.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radius:u.radius||u.width/2,width:u.width,height:u.width},f);case "star":return jsx(Star,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},numPoints:5,innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},sides:3,radius:u.radius||u.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},sides:u.sides||6,radius:u.radius||u.width/2},f);case "ellipse":return jsx(Ellipse,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radiusX:u.radiusX||u.width/2,radiusY:u.radiusY||u.height/2},f);case "ring":return jsx(Ring,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},f);case "wedge":return jsx(Wedge,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radius:u.radius||u.width/2,angle:u.angle||60},f);case "arrow":return jsx(Arrow,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.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"},f);case "line":return jsx(Line,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},points:u.points||[0,0,u.width,0],stroke:"#000000",strokeWidth:u.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2,angle:u.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...i,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},width:u.width,height:u.height,cornerRadius:u.type==="rounded-rectangle"?10:0},f)}})})});Ri.displayName="ShapeLayer";var ru=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:l})=>{let d=useSelector(m=>m.toolbar.selectedTool),u=d==="pen"||d==="eraser";return jsx(Fragment,{children:e.map(m=>{let f=m.id===l,i=m.fontWeight==="bold",c=i?Math.max(1,m.fontSize/25):0;return jsx(Text,{id:m.id,ref:p=>{p?o.current.set(m.id,p):o.current.delete(m.id);},text:m.text,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:!m.locked&&!f&&!u,listening:!u,fontSize:m.fontSize,fontFamily:m.fontFamily,fontStyle:m.fontStyle,fontWeight:m.fontWeight,textDecoration:m.textDecoration,fill:m.fill,stroke:i?m.fill:void 0,strokeWidth:c,align:m.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...u?{}:{onClick:()=>s(m.id),onTap:()=>s(m.id),onDblClick:()=>n(m.id),onDblTap:()=>n(m.id),onDragEnd:p=>t(p,m.id),onTransformEnd:()=>a(m.id),onContextMenu:p=>{p.evt.preventDefault();let y=p.evt;r(y,m.id,"text");}}},m.id)})})};var gh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:l,nodeRef:d})=>{let[u,m]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{m(h);};}},[e.images,e.currentIndex]),!u||e.images.length===0)return null;let f=8,i=2,c=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(c,32)),y=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:s,ref:h=>{if(d(h),h){let x=h.getStage()?.container();if(x){let b=g=>{let L=h.getStage()?.getPointerPosition();if(L){let C={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=C.x&&L.x<=C.x+C.width&&L.y>=C.y&&L.y<=C.y+C.height&&r(g);}};x.addEventListener("contextmenu",b),h._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",b);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,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:f,stroke:"#E5E7EB",strokeWidth:i,listening:false}),jsx(Image$1,{x:i+4,y:i+4,image:u,width:e.width-(i+4)*2,height:e.height-(i+4)*2,cornerRadius:f-i,onClick:t,onTap:t}),jsx(Rect,{x:i,y:e.height-50,width:e.width-i*2,height:50,cornerRadius:[0,0,f-i,f-i],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:y+p,y:e.height/2,onClick:h=>{h.cancelBubble=true,l();},onTap:h=>{h.cancelBubble=true,l();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-y-p,y:e.height/2,onClick:h=>{h.cancelBubble=true,n();},onTap:h=>{h.cancelBubble=true,n();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},iu=gh;var Bi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:l,onContextMenu:d})=>jsx(Fragment,{children:e.map(u=>jsx(iu,{flashcard:u,isSelected:t===u.id,onClick:()=>r(u.id),onDragEnd:a,onTransformEnd:m=>s(u.id,m),onContextMenu:m=>d(m,u.id,"flashcard"),onNext:()=>n(u.id),onPrevious:()=>l(u.id),nodeRef:m=>{m?o.current.set(u.id,m):o.current.delete(u.id);}},u.id))}));Bi.displayName="FlashcardLayer";var du=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);Q(g=>g.toolbar.selectedTool);let d=Q(g=>g.toolbar.penColor),u=Q(g=>g.toolbar.strokeWidth),m=Q(g=>g.canvas.isSketchMode),f=Q(g=>g.canvas.slides.find(C=>C.id===g.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),i=f?.annotations||[],c=f?.isDrawingMode||false,p=f?.width||1,y=f?.height||1,h=useCallback(g=>{if(!c)return;t.current=true,a.current=false,s.current=[{x:g.x,y:g.y}];let L=g.x/p,C=g.y/y;n({tool:"pen",points:[L,C],color:d,strokeWidth:u/p,isSketch:m});},[c,d,u,m,p,y]),x=useCallback(g=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;s.current.push({x:g.x,y:g.y});let S;if(m)S=Ts(s.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((v,M)=>M%2===0?v/p:v/y);else {let k=g.x/p,v=g.y/y;S=[...r.points,k,v];}n(k=>k?{...k,points:S}:null);},[m,u,r,p,y]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ti({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:i,activeLine:r,isDrawingMode:c,startDrawing:h,draw:x,stopDrawing:b}};var Ih=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:l,cameraStream:d,nodeRef:u})=>{let[m,f]=useState(null),[i,c]=useState(null),p=useRef(null),y=useRef(null),h=useRef(null),x=useRef(null),b=useRef(0),g=33,L=useSelector(q=>q.toolbar.selectedTool),C=L==="pen"||L==="eraser",{annotations:S,activeLine:k,isDrawingMode:v,startDrawing:M,draw:B,stopDrawing:D}=du(e.id);useEffect(()=>{if(!v)return;let q=()=>{D();},_=()=>{D();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",_),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",_);}},[D,v]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;q.src=e.capturedImageUrl,q.onload=()=>{f(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&d){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),y.current||(y.current=document.createElement("canvas"));let q=p.current,_=y.current;q.srcObject=d;let H=()=>{_.width=q.videoWidth||640,_.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",_.width,_.height);let K=te=>{if(te-b.current<g){h.current=requestAnimationFrame(K);return}b.current=te;let Z=_.getContext("2d");if(Z&&q.readyState===q.HAVE_ENOUGH_DATA){Z.drawImage(q,0,0,_.width,_.height);let J=_.toDataURL("image/jpeg",.6),le=new window.Image;le.onload=()=>{c(le);},le.src=J;}h.current=requestAnimationFrame(K);};h.current=requestAnimationFrame(K);};return q.onloadedmetadata=H,q.readyState>=q.HAVE_METADATA&&H(),q.play().catch(K=>console.error("Error playing video:",K)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{c(null),x.current&&(x.current.src="");}},[e.isCapturing,d]);let O=()=>{p.current&&e.isCapturing&&l(p.current);},W=q=>{if(e.capturedImageUrl){if(!v){t();return}let _=q.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);M(Z);}q.cancelBubble=true;}else t();},T=q=>{if(!v||!e.capturedImageUrl)return;let _=q.currentTarget,H=_.getAbsoluteTransform().copy(),te=_.getStage()?.getPointerPosition();if(te){H.invert();let Z=H.point(te);B(Z);}},U=()=>{!v||!e.capturedImageUrl||D();},R=e.isCapturing?i:m,oe=Math.min(e.width,e.height)*.12,V=Math.max(25,Math.min(oe,50)),se=e.width/2,G=e.height/2;return jsxs(Group,{id:e.id,draggable:!v&&!C,listening:true,x:e.x,y:e.y,...C?{}:{onDragEnd:a,onTransformEnd:s},rotation:e.rotation,width:e.width,height:e.height,ref:q=>{if(u(q),q){let _=q.getStage()?.container();if(_){let H=K=>{let te=q.getStage()?.getPointerPosition();if(te){let Z={x:e.x,y:e.y,width:e.width,height:e.height};te.x>=Z.x&&te.x<=Z.x+Z.width&&te.y>=Z.y&&te.y<=Z.y+Z.height&&r(K);}};_.addEventListener("contextmenu",H),q._contextMenuCleanup=()=>{_.removeEventListener("contextmenu",H);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:R?"transparent":"white",strokeWidth:o?0:2,cornerRadius:8,listening:true,onClick:t,onTap:t,shadowColor:"rgba(0,0,0,0.35)",shadowBlur:15,shadowOpacity:.4,shadowOffset:{x:0,y:4}}),R&&jsx(Image$1,{image:R,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:W,onTap:W,onMouseDown:W,onTouchStart:W,onMouseMove:T,onTouchMove:T,onMouseUp:U,onTouchEnd:U,...C?{}:{onDragEnd:a,onTransformEnd:s}}),S?.map((q,_)=>{let H=q.points.map((te,Z)=>Z%2===0?te*e.width:te*e.height),K=q.strokeWidth*e.width;return jsx(Line,{points:H,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:K,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:q.tool==="eraser"?"destination-out":"source-over",fill:q.isSketch?q.color:void 0,closed:q.isSketch,listening:false},_)}),k&&jsx(Line,{points:k.points.map((q,_)=>_%2===0?q*e.width:q*e.height),stroke:k.tool==="eraser"?"white":k.color,strokeWidth:k.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:k.tool==="eraser"?"destination-out":"source-over",fill:k.isSketch?k.color:void 0,closed:k.isSketch,listening:false},"active"),!R&&!e.isCapturing&&jsxs(Fragment,{children:[jsx(Text,{x:10,y:6,width:e.width,text:"Take a Photo",fontSize:22,fontStyle:"bold",fill:"#000000CC",fontFamily:"Arial"}),jsx(Text,{x:12,y:32,width:e.width,text:"Capture a photo to add directly into your canvas.",fontSize:12,fill:"#00000099",fontFamily:"Arial"}),jsx(Rect,{x:0,y:G-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:se-V+6,y:G-60,width:V*1.6,height:V*1.6,radius:V,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?O():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?O():n();}}),jsx(Html,{groupProps:{x:se-12,y:G-40,width:V*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?O():n();}})})]}),jsx(Text,{x:0,y:G,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:G+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:se-24,y:G+104,width:V*1.6,height:V*1.6,radius:V,fill:"#096B76",cornerRadius:V,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?O():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?O():n();}}),jsx(Html,{groupProps:{x:se-8,y:G+120,width:V*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?O():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:se-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),O();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},mu=Ih;var Ui=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:l,cameraStreams:d,onContextMenu:u})=>jsx(Fragment,{children:e.map(m=>jsx(mu,{photoFrame:m,isSelected:t===m.id,onClick:()=>r(m.id),onDragEnd:f=>a(f,m.id),onTransformEnd:f=>s(m.id,f),onContextMenu:f=>u(f,m.id,"photoFrame"),onStartCamera:()=>n(m.id),onCapture:f=>l(m.id,f),cameraStream:d.get(m.id),nodeRef:f=>{f?o.current.set(m.id,f):o.current.delete(m.id);}},m.id))}));Ui.displayName="PhotoFrameLayer";var xu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:l})=>{useEffect(()=>{let f=c=>{l?.current&&!l.current.contains(c.target)&&a();},i=c=>{c.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",i);}},[a]);let d=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(i=>!(i.showForTypes&&!i.showForTypes.includes(s)||i.hideForTypes&&i.hideForTypes.includes(s))),[s,n]),u=(f,i)=>{f==="order"||f==="lock"?t(f,i):(t(f),a());},m=jsx("div",{ref:l,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:d.map((f,i)=>jsxs("button",{onClick:c=>u(f.action,c),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.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"})})]},i))})});return createPortal(m,document.body)};var bu=({x:e,y:o,items:t,onClose:a})=>{let s=useRef(null);return useEffect(()=>{let r=n=>{s.current&&!s.current.contains(n.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:s,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((r,n)=>jsx("button",{onClick:()=>{r.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:r.label})},n))})})};var yu=createContext(null),Wi=()=>useContext(yu);function Yh({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(yu.Provider,{value:s,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function ot(){let e=Wi();return typeof document>"u"?null:e||document.body}var wu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,l]=useState(a),d=useRef(null),u=ot();useEffect(()=>{d.current?.focus();},[]);let m=()=>{s(n),r();},f=c=>{c.key==="Enter"?m():c.key==="Escape"&&r();};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",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:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:d,type:"text",value:n,onChange:c=>l(c.target.value),onKeyDown:f,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:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:m,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),u):null};var Fs=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=ot();useEffect(()=>{let f=i=>{i.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let l=f=>{f.preventDefault(),o(a);},d=(f,i,c)=>{c/=100;let p=i*Math.min(c,1-c)/100,y=h=>{let x=(h+f/30)%12,b=c-p*Math.max(Math.min(x-3,9-x,1),-1);return Math.round(255*b).toString(16).padStart(2,"0")};return `#${y(0)}${y(8)}${y(4)}`},u=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!n)return null;let m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",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:r,className:"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 Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:l,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=>s(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=>s(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 i=parseInt(f.target.value),c=d(i,100,50);s(c);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:u.map(f=>jsx("button",{type:"button",onClick:()=>s(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(m,n)};var hg=({imageSrc:e,onCrop:o})=>{let[t]=Iu(e),a=useRef(null),s=useRef(null),r=useRef(null),n=useMemo(()=>{if(!t)return {width:600,height:400};let p=Math.min(600/t.width,400/t.height);return {width:t.width*p,height:t.height*p}},[t]),l=useMemo(()=>{let i=n.width*.5,c=n.height*.5,p=(n.width-i)/2,y=(n.height-c)/2;return {x:p,y,width:i,height:c}},[n]),[d,u]=useState(l);useEffect(()=>{u(l);},[l]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[d]),useEffect(()=>{o(d.x,d.y,d.width,d.height);},[d,o]);let m=()=>{let i=s.current;if(!i)return;let c=i.scaleX(),p=i.scaleY();i.scaleX(1),i.scaleY(1),u({x:i.x(),y:i.y(),width:Math.max(20,i.width()*c),height:Math.max(20,i.height()*p)});},f=()=>{let i=s.current;i&&u({x:i.x(),y:i.y(),width:i.width(),height:i.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:d.x,y:d.y,width:d.width,height:d.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:d.x,y:d.y,width:d.width,height:d.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:f,onTransformEnd:m,dragBoundFunc:i=>{let c=Math.max(0,Math.min(i.x,n.width-d.width)),p=Math.max(0,Math.min(i.y,n.height-d.height));return {x:c,y:p}}}),jsx(Transformer,{ref:r,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:(i,c)=>c.width<20||c.height<20||c.x<0||c.y<0||c.x+c.width>n.width||c.y+c.height>n.height?i:c})]})})},Cu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=Iu(e),l=ot();useEffect(()=>{let f=i=>{i.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let d=(f,i,c,p)=>{r({x:f,y:i,width:c,height:p});},u=()=>{if(!n)return;let c=Math.min(600/n.width,400/n.height),p=s.x/c,y=s.y/c,h=s.width/c,x=s.height/c,b=document.createElement("canvas");b.width=h,b.height=x;let g=b.getContext("2d");if(!g)return;g.drawImage(n,p,y,h,x,0,0,h,x);let L=b.toDataURL("image/png");o(L);};return l?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",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:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(hg,{imageSrc:e,onCrop:d})}),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:u,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"]})]})]})}),l):null};var dr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let[s,r]=useState(false),[n,l]=useState(null),[d,u]=useState(0),[m,f]=useState(true),i=useRef(null),c=useRef([]),p=useRef(null),y=useRef(null),h=useRef(null),x=useRef(null),b=useRef(null),g=useRef(null);useEffect(()=>()=>{h.current&&cancelAnimationFrame(h.current),p.current&&clearInterval(p.current),y.current&&y.current.getTracks().forEach(v=>v.stop());},[]);let L=async()=>{try{let v,M=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let T=o.current.getLayers();console.log("Konva layers:",T.length),T.forEach((_,H)=>{let K=_.getChildren();console.log(`Layer ${H} children count:`,K.length);});let U=document.createElement("canvas");U.width=o.current.width(),U.height=o.current.height();let R=U.getContext("2d",{willReadFrequently:!1});if(!R){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",U.width,"x",U.height),b.current=U;let oe=()=>{if(R.clearRect(0,0,U.width,U.height),T.forEach(_=>{let H=_.getCanvas()._canvas;H&&R.drawImage(H,0,0);}),a?.current){let _=a.current;R.drawImage(_,0,0);}};g.current=oe,o.current.draw(),oe(),await new Promise(_=>setTimeout(_,100)),console.log("Creating captureStream..."),v=U.captureStream(30),console.log("Canvas stream created, tracks:",v.getTracks().length);let se=v.getVideoTracks()[0];se&&console.log("Video track:",se.label,"state:",se.readyState);let G=0,q=()=>{oe(),o?.current&&(o.current.getLayers().forEach(H=>{H.batchDraw();}),G++,G%60===0&&console.log("Drawing frame:",G)),h.current=requestAnimationFrame(q);};q();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(m)try{M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(T){console.warn("Microphone access denied:",T);}let B=[...v.getVideoTracks()];M&&B.push(...M.getAudioTracks());let D=new MediaStream(B);y.current=D;let O="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?O="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?O="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?O="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(O="video/webm;codecs=vp8"),console.log("Using mimeType:",O);let W=new MediaRecorder(D,{mimeType:O,videoBitsPerSecond:25e5});i.current=W,c.current=[],W.ondataavailable=T=>{console.log("Data available, size:",T.data.size),T.data.size>0&&c.current.push(T.data);},W.onstop=()=>{console.log("Recording stopped, chunks:",c.current.length);let T=new Blob(c.current,{type:O});console.log("Final blob size:",T.size),o?.current&&g.current&&b.current&&(o.current.draw(),o.current.getLayers().forEach(R=>{R.batchDraw();}),g.current(),x.current=b.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",x.current.length)),D.getTracks().forEach(U=>U.stop()),p.current&&clearInterval(p.current),h.current&&(cancelAnimationFrame(h.current),h.current=null),l(T);},W.onerror=T=>{console.error("MediaRecorder error:",T);},console.log("Starting recording..."),W.start(1e3),r(!0),u(0),p.current=setInterval(()=>{u(T=>T+1);},1e3);}catch(v){console.error("Error starting screen recording:",v),alert("Failed to start recording. Please ensure you granted permission.");}},C=()=>{i.current&&s&&(console.log("Stopping recording, state:",i.current.state),i.current.state!=="inactive"&&(i.current.requestData(),setTimeout(()=>{i.current&&i.current.state!=="inactive"&&i.current.stop();},100)),r(false));},S=()=>{if(n){let v=URL.createObjectURL(n),M=document.createElement("a");M.href=v,M.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(v);}},k=v=>{let M=Math.floor(v/60),B=v%60;return `${M.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`};return s?jsxs("div",{className:"fixed top-4 left-1/2 z-102 flex -translate-x-1/2 items-center gap-4 rounded-full border border-gray-200 bg-white px-6 py-3 shadow-2xl",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"h-3 w-3 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-lg font-semibold text-gray-900",children:k(d)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:C,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]}):jsx("div",{className:"fixed inset-0 z-102 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!n&&jsxs("div",{className:"text-start",children:[jsx("p",{className:"mb-4 text-base text-[#00000099]",children:"Record your canvas with voice narration. Everything you draw, type, or add will be captured automatically."}),jsxs("div",{className:"mx-auto mb-4 flex w-full flex-col items-center justify-between gap-4 px-2",children:[jsx("button",{onClick:()=>f(!m),className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-lg font-semibold transition-colors ${m?"text-primary border-[#096B76] bg-[#EBF6F7]":"border-gray-300 bg-[#F5F5F5] text-[#00000099]"}`,children:m?jsxs(Fragment,{children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Microphone On"]}):jsxs(Fragment,{children:[jsx(MicrophoneSlash,{className:"h-5 w-5",weight:"fill"}),"Microphone Off"]})}),jsxs("button",{onClick:L,className:"bg-primary hover:bg-primary/92 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-6 py-4 text-center text-lg font-semibold text-white transition-colors",children:[jsx(Record,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})]})]}),n&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(n),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",k(d)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&n&&x.current&&(t(n,x.current),e());},className:"flex items-center justify-center gap-2 rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Add to Canvas"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:S,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-5 w-5"}),"Download"]}),jsx("button",{onClick:()=>{l(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 Tu=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=ot(),[n,l]=useState(false),[d,u]=useState(null),[m,f]=useState(false),[i,c]=useState(0),p=useRef(null),y=useRef([]),h=useRef(null),x=useRef(null);useEffect(()=>{o&&!d&&fetch(o).then(B=>B.blob()).then(B=>u(B)).catch(B=>console.error("Error loading audio:",B));},[o,d]);let b=async()=>{try{let B=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),D=new MediaRecorder(B);p.current=D,y.current=[],D.ondataavailable=O=>{O.data.size>0&&y.current.push(O.data);},D.onstop=()=>{let O=new Blob(y.current,{type:"audio/webm"});u(O),B.getTracks().forEach(W=>W.stop()),h.current&&clearInterval(h.current);},D.start(),l(!0),c(0),h.current=setInterval(()=>{c(O=>O+1);},1e3);}catch(B){console.error("Error starting audio recording:",B),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{p.current&&n&&(p.current.stop(),l(false));},L=()=>{if(d){let B=URL.createObjectURL(d),D=new Audio(B);x.current=D,D.onended=()=>{f(false),URL.revokeObjectURL(B);},D.play(),f(true);}},C=()=>{x.current&&(x.current.pause(),x.current.currentTime=0,f(false));},S=async()=>{if(d){let B=new FileReader;B.onloadend=()=>{let D=B.result;t(D),s();},B.readAsDataURL(d);}},k=()=>{u(null),a();},v=B=>{let D=Math.floor(B/60),O=B%60;return `${D.toString().padStart(2,"0")}:${O.toString().padStart(2,"0")}`};if(!r)return null;if(n){let B=jsx("div",{className:"pointer-events-none fixed inset-0 z-50",children:jsxs("div",{className:"pointer-events-auto fixed top-[100px] left-1/2 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:v(i)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]})});return createPortal(B,r)}let M=jsx("div",{className:"fixed inset-0 z-50 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:[!d&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:b,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"]})}),d&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?C:L,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"}),m?"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:S,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:s,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"})]})]})});return createPortal(M,r)};var kt=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:l=90,containerRight:d=320})=>{let[u,m]=useState(false),f=useRef(null),i=y=>{if(y.stopPropagation(),u&&f.current)f.current.pause(),f.current.currentTime=0,m(false);else {let h=new Audio(e);f.current=h,h.onended=()=>{m(false);},h.onerror=()=>{console.error("Error playing audio"),m(false);},h.play(),m(true);}},c=(o+a)*s+r-15,p=t*s+n+l-15;return jsx("button",{onClick:i,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${u?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${c}px`,top:`${p}px`,width:"30px",height:"30px",zIndex:99},title:u?"Stop Audio":"Play Audio",children:u?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(),s=Q(he),r=useMemo(()=>{if(!s)return [];let h=[];return s.images?.forEach(x=>{h.push({id:x.id,type:"image",name:"Image",timestamp:x.timestamp||0});}),s.videos?.forEach(x=>{h.push({id:x.id,type:"video",name:"Video",timestamp:x.timestamp||0});}),s.shapes?.forEach(x=>{h.push({id:x.id,type:"shape",name:`${x.type} Shape`,timestamp:x.timestamp||0});}),s.texts?.forEach(x=>{h.push({id:x.id,type:"text",name:x.text.substring(0,20)+(x.text.length>20?"...":""),timestamp:x.timestamp||0});}),s.flashcards?.forEach(x=>{h.push({id:x.id,type:"flashcard",name:`Flashcard (${x.images.length} images)`,timestamp:x.timestamp||0});}),s.photoFrames?.forEach(x=>{h.push({id:x.id,type:"photoFrame",name:"Photo Frame",timestamp:x.timestamp||0});}),s.multipleChoices?.forEach(x=>{h.push({id:x.id,type:"mcq",name:"Multiple Choice",timestamp:x.timestamp||0});}),s.trueFalses?.forEach(x=>{h.push({id:x.id,type:"trueFalse",name:"True/False",timestamp:x.timestamp||0});}),s.shortAnswers?.forEach(x=>{h.push({id:x.id,type:"shortAnswer",name:"Short Answer",timestamp:x.timestamp||0});}),s.LongAnswer?.forEach(x=>{h.push({id:x.id,type:"longAnswer",name:"Long Answer",timestamp:x.timestamp||0});}),s.fillInTheBlanks?.forEach(x=>{h.push({id:x.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:x.timestamp||0});}),s.lines?.forEach(x=>{x.id&&h.push({id:x.id,type:"line",name:"Drawn Line",timestamp:x.timestamp||0});}),h.sort((x,b)=>b.timestamp-x.timestamp)},[s]),[n,l]=useState(r),[d,u]=useState(false);useEffect(()=>{d||l(r);},[r]);let m=h=>{let x="h-5 w-5";switch(h){case "image":return jsx(Image$3,{className:x});case "video":return jsx(VideoCamera,{className:x});case "shape":return jsx(Shapes$1,{className:x});case "text":return jsx(TextT,{className:x});case "flashcard":return jsx(Cards$1,{className:x});case "photoFrame":return jsx(FrameCorners,{className:x});case "line":return jsx(Pen,{className:x});default:return jsx(Question,{className:x})}},c=h=>{u(true),l(h);},p=()=>{u(false);let h=Date.now();n.forEach((x,b)=>{let g=h-b;a(Qo({id:x.id,type:x.type,newTimestamp:g}));});},y=jsxs("div",{className:"konva-editor-root",children:[jsx("div",{className:"fixed inset-0 z-9999 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-10000 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:n.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:n,onReorder:c,className:"space-y-1",children:n.map(h=>{let x=h.id===e;return jsxs(Reorder.Item,{value:h,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${x?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,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-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(h.id,h.type),className:`font-medium ${x?"text-[#096B76]":"text-[#00000099]"}`,children:h.name})}),jsx("div",{className:`${x?"text-[#096B76]":"text-[#00000099]"}`,children:m(h.type)})]},h.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[n.length," Layers"]})]})]})]});return createPortal(y,document.body)};var Ru=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>{let n=useSelector(G=>G.toolbar.selectedTool),l=n==="pen"||n==="eraser",[d,u]=useState(new Set),[m,f]=useState(false),[i,c]=useState(null),p=useRef(null);useEffect(()=>{let G=p.current;if(G)return a.current.set(e.id,G),()=>{a.current.delete(e.id);}},[e.id]);let y=new Set(e.data.responseOptions.correctIndex),h=y.size>1,x=G=>{m||u(h?q=>{let _=new Set(q);return _.has(G)?_.delete(G):_.add(G),_}:new Set([G]));},b=()=>{d.size>0&&f(true);},g=()=>{f(false),u(new Set);},L=d.size===y.size&&Array.from(d).every(G=>y.has(G)),C=Array.from(d).filter(G=>y.has(G)),S=h&&C.length>0&&!L,k=()=>L?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${C.length}/${y.size})`:"\u2717 Try again!",v=()=>L?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},M=55,B=8,D=24,O=60,W=60,T=h&&!m?25:0,U=e.data.feedbackMode==="practice"?48:0,R=12,oe=O+T+(m?W:0),V=e.data.responseOptions.options.length*(M+B),se=oe+V+R+U+D;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...l?{}:{onDragEnd:s,onClick:G=>t(e.id),onTap:G=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:se,width:e.width,onTransformEnd:G=>o(e.id,G),onContextMenu:G=>{G.cancelBubble=true,r(G.evt,e.id,"mcq");}}),jsx(Text,{x:D+8,y:D,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-D*2,listening:false}),h&&!m&&e.data.feedbackMode==="practice"?jsx(Text,{x:D,y:D+35,text:`Select ${y.size} answers (${d.size}/${y.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-D*2,listening:false}):null,m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:D+24,y:O+T,width:e.width-D*2-40,height:W-20,fill:v().bg,cornerRadius:8}),jsx(Text,{x:D,y:O+T,width:e.width-D*2,height:W-20,text:k(),fontSize:16,fontStyle:"bold",fill:v().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((G,q)=>{let _=y.has(q),H=d.has(q),K=oe+q*(M+B),te="#e5e7eb",Z="#ffffff",J="#111827";return m&&_?(te="#22c55e",Z="#dcfce7",J="#1B9D2C"):m&&H&&!_?(te="#ef4444",Z="#fee2e2",J="#ef4444"):H&&(te="#096B76",Z="#ECFFF8",J="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:D+12,y:K+(M-20)/2,width:20,height:20,fill:H?"#096B76":"white",stroke:H?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:le=>{le.cancelBubble=true,x(q);},onTap:le=>{le.cancelBubble=true,x(q);}}),H&&jsx(Text,{x:D+12,y:K+(M-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:M,fill:Z,stroke:te,strokeWidth:2,cornerRadius:8,onClick:le=>{le.cancelBubble=true,x(q);},onTap:le=>{le.cancelBubble=true,x(q);}}),jsx(Text,{x:D+60,y:K,width:e.width-D*2-80,height:M,text:G,fontSize:16,fill:J,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:oe+e.data.responseOptions.options.length*(M+B)+12,children:[jsxs(Group,{onMouseDown:G=>{G.cancelBubble=true,c("check");},onMouseUp:G=>{G.cancelBubble=true,c(null),b();},onMouseLeave:G=>{G.cancelBubble=true,c(null);},onTouchStart:G=>{G.cancelBubble=true,c("check");},onTouchEnd:G=>{G.cancelBubble=true,c(null),b();},scaleX:i==="check"?.95:1,scaleY:i==="check"?.95:1,children:[jsx(Rect,{x:D+14,width:(e.width-D*2-24)/(m?2:1),height:48,fill:d.size===0||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.cancelBubble=true}),jsx(Text,{x:D+14,width:(e.width-D*2-24)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-D*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),g();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),g();},scaleX:i==="reset"?.95:1,scaleY:i==="reset"?.95:1,children:[jsx(Rect,{x:D,width:(e.width-D*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:G=>G.cancelBubble=true,onTap:G=>G.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})]})]})]})});Ru.displayName="MultipleChoice";var Eu=Ru;var _i=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s})=>{let r=useDispatch(),n=useSelector(H=>H.toolbar.selectedTool),l=n==="pen"||n==="eraser",[d,u]=useState(false),[m,f]=useState(new Set),[i,c]=useState(false),[p,y]=useState(false),[h,x]=useState(0),b=340,g=100,L=window.innerWidth*.4,C=window.innerHeight*.5,S=b+20,k=g+60,v=L-40,M=C-300,B=useRef(null);useEffect(()=>{let H=B.current;if(H)return s.current.set(e.id,H),()=>{s.current.delete(e.id);}},[e.id]);let D=H=>{r(ca({id:e.id,x:H.target.x(),y:H.target.y()}));},O=H=>{let K=H.target,te=K.x(),Z=K.y(),J=window.innerWidth*.2,Ie=te+J>S&&te<S+v&&Z+50>k&&Z<k+M;u(Ie);},W=(H,K)=>{let te=K.target,Z=te.x(),J=te.y(),le=window.innerWidth*.2,Y=Z+le>S&&Z<S+v&&J+50>k&&J<k+M;f(Y?Me=>new Set(Me).add(H):Me=>{let Be=new Set(Me);return Be.delete(H),Be}),u(false);},T=()=>{c(true);},U=()=>{c(false),f(new Set),x(H=>H+1);},R=new Set(e.data.responseOptions.correctIndex),oe=m.size===R.size&&Array.from(m).every(H=>R.has(H)),V=Array.from(m).filter(H=>R.has(H)),se=V.length>0&&!oe,G=()=>oe?"\u2713 Correct! Great job!":se?`\u26A0 Partially correct (${V.length}/${R.size})`:"\u2717 Try again!",q=()=>oe?{bg:"#dcfce7",text:"#166534"}:se?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},_=()=>i?oe?"#4CAF50":se?"#f59e0b":"#ef4444":d?"#4CAF50":"#075560";return jsxs(Group,{ref:B,name:"mcq-element",width:L,height:C,draggable:!l,listening:!l,...l?{}:{onClick:H=>a(e.id),onTap:H=>a(e.id),onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:D,children:[jsx(Rect,{fill:"white",stroke:d?"#4CAF50":"#e5e7eb",strokeWidth:d?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?C-100:C-50,width:L,shadowColor:d?"#4CAF50":"transparent",shadowBlur:d?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:v,height:M,fill:"#EBF6F7",stroke:_(),strokeWidth:3,dash:[10,10],cornerRadius:8}),i&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:M+18,width:v-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:M+20,width:v,height:60,text:G(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),m.size===0&&!i&&jsx(Text,{x:20,y:60,width:v,height:M-60,text:R.size>1?`Drop ${R.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:i?C-200:C-160,children:[jsxs(Group,{onMouseDown:()=>{y(true),T();},onMouseUp:()=>y(false),onMouseLeave:()=>y(false),onTouchStart:()=>{y(true),T();},onTouchEnd:()=>y(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:v}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:v,height:40,align:"center",verticalAlign:"middle",listening:false})]}),i&&jsxs(Group,{y:50,onMouseDown:U,onTouchStart:U,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:v}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:v,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((H,K)=>{let te=K%2,Z=Math.floor(K/2),J=window.innerWidth*.2,le=50,Ie=10,Y=m.has(K),Me=R.has(K),Be=i&&Y,Et="transparent";return Be?Et=Me?"#4CAF50":"#ef4444":Y&&(Et="#4CAF50"),jsxs(Group,{x:340+te*(J+Ie),y:g+C-80+Z*(le+Ie),draggable:!i,onDragMove:O,onDragEnd:oo=>W(K,oo),opacity:i&&!Y?.5:1,children:[jsx(Rect,{width:J-20,height:le,fill:"white",stroke:Et,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:J-20,height:le,text:H,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${K}-${h}`)})]})};_i.displayName="MultipleChoiceDragAndDrop";var Fu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Eu,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:l=>s(l,n.id),onContextMenu:r},n.id):jsx(_i,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r},n.id))});var Bu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(R=>R.toolbar.selectedTool),l=n==="pen"||n==="eraser",[d,u]=useState(null),[m,f]=useState(false),[i,c]=useState(null),p=useRef(null);useEffect(()=>{let R=p.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id]);let y=()=>{d!==null&&f(true);},h=()=>{f(false),u(null);},x=e.data.responseOptions.correctAnswer,b=d===x,g=R=>{m||u(R);},L=()=>b?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=70,k=12,v=24,M=60,B=60,D=e.data.feedbackMode==="practice"?48:0,O=12,W=M+(m?B:0),T=2*(S+k),U=W+T+O+D+v;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...l?{}:{onDragEnd:R=>r(R,e.id),onClick:R=>t(e.id),onTap:R=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:U-20,width:e.width,onTransformEnd:R=>o(e.id,R),onContextMenu:R=>{R.cancelBubble=true,s(R.evt,e.id,"trueFalse");}}),jsx(Text,{x:v,y:v,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-v*2,listening:false}),m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:v,y:M,width:e.width-v*2,height:B-10,fill:C().bg,cornerRadius:8}),jsx(Text,{x:v,y:M,width:e.width-v*2,height:B-10,text:L(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((R,oe)=>{let V=x===R.value,se=d===R.value,G=(e.width-v*3)/2,q=v+oe*(G+v),_=W,H=R.value===true,K=H?"#10b981":"#ef4444",te="#ffffff",Z="#ffffff",J="#e5e7eb";return m&&(V?(Z=H?"#f0fdf4":"#fef2f2",J=H?"#86efac":"#fecaca"):se&&!V&&(Z="#fee2e2",J="#ef4444")),se&&!m&&(J="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:_,width:G,height:S+50,fill:Z,stroke:J,strokeWidth:2,cornerRadius:12,onClick:le=>{le.cancelBubble=true,g(R.value);},onTap:le=>{le.cancelBubble=true,g(R.value);}}),jsx(Circle,{x:q+G/2,y:_+40,radius:28,fill:K,listening:false}),H?jsx(Text,{x:q+G/2-14,y:_+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+G/2-14,y:_+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:te,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:q,y:_+85,width:G,height:30,text:R.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},R.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:W+2*(S+k),children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,c("check");},onMouseUp:R=>{R.cancelBubble=true,c(null),y();},onMouseLeave:R=>{R.cancelBubble=true,c(null);},onTouchStart:R=>{R.cancelBubble=true,c("check");},onTouchEnd:R=>{R.cancelBubble=true,c(null),y();},scaleX:i==="check"?.95:1,scaleY:i==="check"?.95:1,children:[jsx(Rect,{x:v,width:(e.width-v*2-8)/(m?2:1),height:48,fill:d===null||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:v,width:(e.width-v*2-8)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-v*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),h();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),h();},scaleX:i==="reset"?.95:1,scaleY:i==="reset"?.95:1,children:[jsx(Rect,{x:v,width:(e.width-v*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:v,width:(e.width-v*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Bu.displayName="TrueFalse";var Ou=Bu;var mx="#FFFFFF",$i=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),s=useSelector(K=>K.toolbar.selectedTool),r=s==="pen"||s==="eraser",[n,l]=useState(false),[d,u]=useState(null),[m,f]=useState(false),[i,c]=useState(false),[p,y]=useState(0),[h,x]=useState(false),b=340,g=100,L=window.innerWidth*.4,C=window.innerHeight*.5,S=L-40,k=C-300,v=20,M=60,B=S,D=k,O=L*.2-40,W=50,T=useRef(null),U=K=>{a(fa({id:e.id,x:K.target.x(),y:K.target.y()}));},R=K=>{let te=K.target,Z=te.x(),J=te.y(),le=Math.max(0,Math.min(Z+O,v+B)-Math.max(Z,v)),Ie=Math.max(0,Math.min(J+W,M+D)-Math.max(J,M)),Y=le*Ie,Me=O*W;l(Y/Me>=.5);},oe=(K,te)=>{let Z=te.target,J=Z.x(),le=Z.y(),Ie=Math.max(0,Math.min(J+O,v+B)-Math.max(J,v)),Y=Math.max(0,Math.min(le+W,M+D)-Math.max(le,M)),Me=Ie*Y,Be=O*W;if(Me/Be>=.5)u(K);else return;l(false);},V=()=>{f(true);},se=()=>{f(false),u(null),y(K=>K+1);},G=e.data.responseOptions.correctAnswer,q=d===G,_=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:T,name:"trueFalse-element",width:L,height:C,draggable:!r,listening:!r,...r?{}:{onContextMenu:K=>{K.evt.preventDefault(),o(K.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:U,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:m?C:e.data.feedbackMode==="practice"?C-50:C-100,width:L,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:S,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:S,height:60,fill:H().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:S,height:60,text:_(),fontSize:18,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle"})]}),d===null&&!m&&jsx(Text,{x:20,y:60,width:S,height:k-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:C-100,children:[jsxs(Group,{onMouseDown:()=>{d!==null&&(c(true),V());},onMouseUp:()=>c(false),onMouseLeave:()=>c(false),onTouchStart:()=>{d!==null&&(c(true),V());},onTouchEnd:()=>c(false),scaleX:i?.95:1,scaleY:i?.95:1,children:[jsx(Rect,{fill:d===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:se,onTouchStart:se,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((K,te)=>{let Z=window.innerWidth*.2,J=50,le=10,Ie=d===K.value,Y=G===K.value,Me=m&&Ie,Be="transparent";return Me?Be=Y?"#4CAF50":"#ef4444":Ie&&(Be="#4CAF50"),jsxs(Group,{x:16+te*(Z+le),y:g+C-300,draggable:!m,onDragMove:R,onDragEnd:Et=>oe(K.value,Et),opacity:m&&!Ie?.5:1,children:[jsx(Rect,{width:Z-40,height:J,fill:"#075560",stroke:Be,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:J,text:K.label,fontSize:18,fontStyle:"bold",fill:mx,align:"center",verticalAlign:"middle",listening:false})]},`${K.value}-${p}`)})]})})};$i.displayName="TrueFalseDragAndDrop";var Nu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Ou,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s},n.id):jsx($i,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r},n.id))});var xa=new WeakMap,ko=new WeakMap,hr={current:[]},Ji=false,pr=0,mr=new Set,Hs=new Map;function Vu(e){let o=Array.from(e).sort((t,a)=>t instanceof qt&&t.options.deps.includes(a)?1:a instanceof qt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(hr.current.includes(t))continue;hr.current.push(t),t.recompute();let a=ko.get(t);if(a)for(let s of a){let r=xa.get(s);r&&Vu(r);}}}function gx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function xx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Us(e){if(pr>0&&!Hs.has(e)&&Hs.set(e,e.prevState),mr.add(e),!(pr>0)&&!Ji)try{for(Ji=!0;mr.size>0;){let o=Array.from(mr);mr.clear();for(let t of o){let a=Hs.get(t)??t.prevState;t.prevState=a,gx(t);}for(let t of o){let a=xa.get(t);a&&(hr.current.push(t),Vu(a));}for(let t of o){let a=xa.get(t);if(a)for(let s of a)xx(s);}}}finally{Ji=false,hr.current=[],Hs.clear();}}function ht(e){pr++;try{e();}finally{if(pr--,pr===0){let o=mr.values().next().value;o&&Us(o);}}}function qu(e){return typeof e=="function"}var jt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var s,r;this.listeners.add(a);let n=(r=(s=this.options)==null?void 0:s.onSubscribe)==null?void 0:r.call(s,a,this);return ()=>{this.listeners.delete(a),n?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,s;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):qu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Us(this);}};var qt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),s=new Array(t);for(let r=0;r<t;r++){let n=this.options.deps[r];a[r]=n.prevState,s[r]=n.state;}return this.lastSeenDepValues=s,{prevDepVals:a,currDepVals:s,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let s=this.getDepVals();this.state=this.options.fn(s),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:s}=this.getDepVals();for(let r=0;r<s.length;r++)if(s[r]!==a[r]){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,s;this.listeners.add(t);let r=(s=(a=this.options).onSubscribe)==null?void 0:s.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},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 jt){let a=xa.get(t);a||(a=new Set,xa.set(t,a)),a.add(this);let s=ko.get(this);s||(s=new Set,ko.set(this,s)),s.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 jt){let a=xa.get(t);a&&a.delete(this);let s=ko.get(this);s&&s.delete(t);}}};function bx(e){return typeof e=="function"}function Zi(e,...o){return bx(e)?e(...o):e}function Hu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ba,st,et,gr,va,Ha,Zt,Mo,xr,Ws,br,To,Ua=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){Pe(this,ba,true);Pe(this,st);Pe(this,et);Pe(this,gr);Pe(this,va);Pe(this,Ha);Pe(this,Zt);Pe(this,Mo);Pe(this,xr,0);Pe(this,Ws,5);Pe(this,br,()=>{this.debugLog("Connected to event bus"),Ce(this,Ha,true),this.debugLog("Emitting queued events",j(this,va)),j(this,va).forEach(o=>this.emitEventToBus(o)),Ce(this,va,[]),this.stopConnectLoop(),j(this,et).call(this).removeEventListener("tanstack-connect-success",j(this,br));});Pe(this,To,()=>{if(j(this,et).call(this).addEventListener("tanstack-connect-success",j(this,br)),j(this,xr)<j(this,Ws)){hd(this,xr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}j(this,et).call(this).removeEventListener("tanstack-connect",j(this,To)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ce(this,st,o),Ce(this,ba,a),Ce(this,et,this.getGlobalTarget),Ce(this,gr,t),this.debugLog(" Initializing event subscription for plugin",j(this,st)),Ce(this,va,[]),Ce(this,Ha,false),Ce(this,Zt,null),Ce(this,Mo,s);}startConnectLoop(){j(this,Zt)!==null||j(this,Ha)||(this.debugLog(`Starting connect loop (every ${j(this,Mo)}ms)`),Ce(this,Zt,setInterval(j(this,To),j(this,Mo))));}stopConnectLoop(){j(this,Zt)!==null&&(clearInterval(j(this,Zt)),Ce(this,Zt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){j(this,gr)&&console.log(`\u{1F334} [tanstack-devtools:${j(this,st)}-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 j(this,st)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});j(this,et).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{j(this,et).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!j(this,ba)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!j(this,Ha)){this.debugLog("Bus not available, will be pushed as soon as connected"),j(this,va).push({type:`${j(this,st)}:${o}`,payload:t,pluginId:j(this,st)}),typeof CustomEvent<"u"&&(j(this,To).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${j(this,st)}:${o}`,payload:t,pluginId:j(this,st)})}on(o,t){let a=`${j(this,st)}:${o}`;if(!j(this,ba))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let s=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return j(this,et).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{j(this,et).call(this).removeEventListener(a,s);}}onAll(o){if(!j(this,ba))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return j(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!j(this,ba))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;j(this,st)&&s.pluginId!==j(this,st)||o(s);};return j(this,et).call(this).addEventListener("tanstack-devtools-global",t),()=>j(this,et).call(this).removeEventListener("tanstack-devtools-global",t)}};ba=new WeakMap,st=new WeakMap,et=new WeakMap,gr=new WeakMap,va=new WeakMap,Ha=new WeakMap,Zt=new WeakMap,Mo=new WeakMap,xr=new WeakMap,Ws=new WeakMap,br=new WeakMap,To=new WeakMap;var Qi=class extends Ua{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Uu=(e,o)=>{el.emit(e,o);},el=new Qi;function Wu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var vx={enabled:true,leading:true,trailing:true,wait:0},ya,gt,Wa,za,Ga,Ao,zs=class{constructor(o,t){Pe(this,ya);Pe(this,gt);Pe(this,Wa);Pe(this,za);Pe(this,Ga);Pe(this,Ao);this.fn=o,this.store=new jt(Wu()),this.setOptions=a=>{this.options={...this.options,...a},j(this,Wa).call(this)||this.cancel();},Ce(this,gt,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:j(this,Wa).call(this)?n?"pending":"idle":"disabled"}}),Uu("Throttler",this);}),Ce(this,Wa,()=>!!Zi(this.options.enabled,this)),Ce(this,za,()=>Zi(this.options.wait,this)),this.maybeExecute=(...a)=>{j(this,gt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=j(this,za).call(this);if(this.options.leading&&r>=n)j(this,Ga).call(this,...a);else if(j(this,gt).call(this,{lastArgs:a}),!j(this,ya)&&this.options.trailing){let l=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,d=n-l;j(this,gt).call(this,{isPending:true}),Ce(this,ya,setTimeout(()=>{let{lastArgs:u}=this.store.state;u!==void 0&&j(this,Ga).call(this,...u);},d));}},Ce(this,Ga,(...a)=>{if(!j(this,Wa).call(this))return;this.fn(...a);let s=Date.now(),r=s+j(this,za).call(this);j(this,Ao).call(this),j(this,gt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:s,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||j(this,gt).call(this,{nextExecutionTime:void 0});},j(this,za).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&j(this,Ga).call(this,...this.store.state.lastArgs);},Ce(this,Ao,()=>{j(this,ya)&&(clearTimeout(j(this,ya)),Ce(this,ya,void 0));}),this.cancel=()=>{j(this,Ao).call(this),j(this,gt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{j(this,gt).call(this,Wu());},this.key=Hu(t.key),this.options={...vx,...t},j(this,gt).call(this,this.options.initialState??{}),el.on("d-Throttler",a=>{a.payload.key===this.key&&(j(this,gt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ya=new WeakMap,gt=new WeakMap,Wa=new WeakMap,za=new WeakMap,Ga=new WeakMap,Ao=new WeakMap;function tl(e,o){return new zs(e,o).maybeExecute}function wa(e,o){return typeof e=="function"?e(o):e}function La(e,o){return js(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Po(e,o,t){let a=js(o);function s(r){if(!a.length)return wa(t,r);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[n]:s(r[n])}):{[n]:s()};if(Array.isArray(r)&&typeof n=="number"){let l=r.slice(0,n);return [...l.length?l:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function ol(e,o){let t=js(o);function a(s){if(!s)return;if(t.length===1){let n=t[0];if(Array.isArray(s)&&typeof n=="number")return s.filter((u,m)=>m!==n);let{[n]:l,...d}=s;return d}let r=t.shift();if(typeof r=="string"&&typeof s=="object")return {...s,[r]:a(s[r])};if(typeof r=="number"&&Array.isArray(s)){if(r>=s.length)return s;let n=s.slice(0,r);return [...n.length?n:new Array(r),a(s[r]),...s.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var yx=/^(\d+)$/gm,wx=/\.(\d+)(?=\.)/gm,Lx=/^(\d+)\./gm,Sx=/\.(\d+$)/gm,Ix=/\.{2,}/gm,al="__int__",Gs=`${al}$1`;function js(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(yx,Gs).replace(wx,`.${Gs}.`).replace(Lx,`${Gs}.`).replace(Sx,`.${Gs}`).replace(Ix,".").split(".").map(o=>{if(o.startsWith(al)){let t=o.substring(al.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function rl(e){return !(Array.isArray(e)&&e.length===0)}function Do(e,o){let t=a=>a.validators.filter(Boolean).map(s=>({cause:s.cause,validate:s.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Ro(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,l=d=>d.validators.filter(Boolean).map(u=>{let m=u?.cause||e,f=n;switch(m){case "change":f=s??n;break;case "blur":f=a??n;break;case "dynamic":f=r??n;break;case "submit":f=0;break}return e==="submit"&&(f=0),{cause:m,validate:u.fn,debounceMs:f}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:l})}var vr=e=>!!e&&typeof e=="object"&&"fields"in e;function Sa(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[s,r]of e)if(!o.has(s)||!Object.is(r,o.get(s)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let s of e)if(!o.has(s))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let s of t)if(!a.includes(s)||!Sa(e[s],o[s]))return false;return true}var Xs=({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},$s=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function _e(e,o){return e==null?o:{...e,...o}}var Ka=256,_s=[],Ks;for(;Ka--;)_s[Ka]=(Ka+256).toString(16).substring(1);function sl(){let e=0,o,t="";if(!Ks||Ka+16>256){for(Ks=new Array(256),e=256;e--;)Ks[e]=256*Math.random()|0;e=0,Ka=0;}for(;e<16;e++)o=Ks[Ka+e],e===6?t+=_s[o&15|64]:e===8?t+=_s[o&63|128]:t+=_s[o],e&1&&e>1&&e<11&&(t+="-");return Ka++,t}var Ia=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"},s={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,s,r,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[s,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function Cx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let l=0;l<s.length;l++){let d=s[l];if(d===void 0)continue;let u=typeof d=="object"?d.key:d,m=Number(u);Array.isArray(r)&&!Number.isNaN(m)?n+=`[${m}]`:n+=(l>0?".":"")+String(u),typeof r=="object"&&r!==null?r=r[u]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var zu=(e,o)=>{let t=Cx(e,o);return {form:t,fields:t}},Ca={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:zu(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:zu(a.issues,e)}},Ys=e=>!!e&&"~standard"in e;var Eo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function yr(e){function o(f,i,c,p){let y=a(f,i,c,p);({insert:()=>l(y,f,i),remove:()=>d(y),swap:()=>p!==void 0&&m(y,f,i,p),move:()=>p!==void 0&&u(y,f,i,p)})[c]();}function t(f,i){return `${f}[${i}]`}function a(f,i,c,p){let y=[t(f,i)];if(c==="swap")y.push(t(f,p));else if(c==="move"){let[h,x]=[Math.min(i,p),Math.max(i,p)];for(let b=h;b<=x;b++)y.push(t(f,b));}else {let h=e.getFieldValue(f),x=Array.isArray(h)?h.length:0;for(let b=i+1;b<x;b++)y.push(t(f,b));}return Object.keys(e.fieldInfo).filter(h=>y.some(x=>h.startsWith(x)))}function s(f,i){return f.replace(/\[(\d+)\]/,(c,p)=>{let y=parseInt(p,10);return `[${i==="up"?y+1:Math.max(0,y-1)}]`})}function r(f,i){(i==="up"?f:[...f].reverse()).forEach(p=>{let y=s(p.toString(),i),h=e.getFieldMeta(y);h?e.setFieldMeta(p,h):e.setFieldMeta(p,n());});}let n=()=>Eo,l=(f,i,c)=>{r(f,"down"),f.forEach(p=>{p.toString().startsWith(t(i,c))&&e.setFieldMeta(p,n());});},d=f=>{r(f,"up");},u=(f,i,c,p)=>{let y=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(i,c))).map(h=>[h,e.getFieldMeta(h)]));r(f,c<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(i,p))).forEach(h=>{let x=h.replace(t(i,p),t(i,c)),b=y.get(x);b&&e.setFieldMeta(h,b);});},m=(f,i,c,p)=>{f.forEach(y=>{if(!y.toString().startsWith(t(i,c)))return;let h=y.toString().replace(t(i,c),t(i,p)),[x,b]=[e.getFieldMeta(y),e.getFieldMeta(h)];x&&e.setFieldMeta(h,x),b&&e.setFieldMeta(y,b);});};return {handleArrayFieldMetaShift:o}}var nl=class extends Ua{constructor(){super({pluginId:"form-devtools"});}},xt=new nl;function il(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Lr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),s=this.store.mount(),r=()=>{a(),s(),xt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let s=this.options;this.options=a;let r=!!a.transform?.deps?.some((d,u)=>d!==this.prevTransformArray[u]),n=a.defaultValues&&!Sa(a.defaultValues,s.defaultValues)&&!this.state.isTouched,l=!Sa(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!l&&!r||(ht(()=>{this.baseStore.setState(()=>il(Object.assign({},this.state,l?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,s)=>{let{fieldMeta:r}=this.state,n=this.resetFieldMeta(r);a&&!s?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>il({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return ht(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let l=n.instance;s.push(Promise.resolve().then(()=>l.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(d=>({...d,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),l=Array.isArray(n)?Math.max(n.length-1,0):null,d=[`${a}[${s}]`];for(let i=s+1;i<=(l??0);i++)d.push(`${a}[${i}]`);let u=Object.keys(this.fieldInfo).filter(i=>d.some(c=>i.startsWith(c))),m=[];return ht(()=>{u.forEach(i=>{m.push(Promise.resolve().then(()=>this.validateField(i,r)));});}),(await Promise.all(m)).flat()},this.validateField=(a,s)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(n=>({...n,isTouched:true})),r.validate(s)):[]},this.validateSync=a=>{let s=Do(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ia}),r=false,n={};return ht(()=>{for(let u of s){if(!u.validate)continue;let m=this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:f,fieldErrors:i}=Js(m),c=wr(u.cause);for(let p of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[p]===void 0)continue;let y=this.getFieldMeta(p);if(!y)continue;let{errorMap:h,errorSourceMap:x}=y,b=i?.[p],{newErrorValue:g,newSource:L}=Xs({newFormValidatorError:b,isPreviousErrorFromFormValidator:x?.[c]==="form",previousErrorValue:h?.[c]});L==="form"&&(n[p]={...n[p],[c]:b}),h?.[c]!==g&&this.setFieldMeta(p,C=>({...C,errorMap:{...C.errorMap,[c]:g},errorSourceMap:{...C.errorSourceMap,[c]:L}}));}this.state.errorMap?.[c]!==f&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[c]:f}})),(f||i)&&(r=!0);}let l=wr("submit");this.state.errorMap?.[l]&&a!=="submit"&&!r&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[l]:void 0}}));let d=wr("server");this.state.errorMap?.[d]&&a!=="server"&&!r&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[d]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Ro(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ia});this.state.isFormValidating||this.baseStore.setState(u=>({...u,isFormValidating:true}));let r=[],n;for(let u of s){if(!u.validate)continue;let m=wr(u.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let i=new AbortController;this.state.validationMetaMap[m]={lastAbortController:i},r.push(new Promise(async c=>{let p;try{p=await new Promise((b,g)=>{setTimeout(async()=>{if(i.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:i.signal},type:"validateAsync"}));}catch(L){g(L);}},u.debounceMs);});}catch(b){p=b;}let{formError:y,fieldErrors:h}=Js(p);h&&(n=n?{...n,...h}:h);let x=wr(u.cause);for(let b of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[b]===void 0)continue;let g=this.getFieldMeta(b);if(!g)continue;let{errorMap:L,errorSourceMap:C}=g,S=n?.[b],{newErrorValue:k,newSource:v}=Xs({newFormValidatorError:S,isPreviousErrorFromFormValidator:C?.[x]==="form",previousErrorValue:L?.[x]});L?.[x]!==k&&this.setFieldMeta(b,M=>({...M,errorMap:{...M.errorMap,[x]:k},errorSourceMap:{...M.errorSourceMap,[x]:v}}));}this.baseStore.setState(b=>({...b,errorMap:{...b.errorMap,[x]:y}})),c(n?{fieldErrors:n,errorMapKey:x}:void 0);}));}let l=[],d={};if(r.length){l=await Promise.all(r);for(let u of l)if(u?.fieldErrors){let{errorMapKey:m}=u;for(let[f,i]of Object.entries(u.fieldErrors)){let p={...d[f]||{},[m]:i};d[f]=p;}}}return this.baseStore.setState(u=>({...u,isFormValidating:false})),d},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>La(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var s;return (s=this.fieldInfo)[a]||(s[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,s)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:wa(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Eo,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,l=r?.dontRunListeners??false,d=r?.dontValidate??false;ht(()=>{n||this.setFieldMeta(a,u=>({...u,isTouched:!0,isDirty:!0,errorMap:{...u?.errorMap,onMount:void 0}})),this.baseStore.setState(u=>({...u,values:Po(u.values,a,s)}));}),l||this.getFieldInfo(a).instance?.triggerOnChangeListener(),d||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let l=a.toString();return n!==l&&n.startsWith(l)}),a];this.baseStore.setState(n=>{let l={...n};return r.forEach(d=>{l.values=ol(l.values,d),delete this.fieldInfo[d],delete l.fieldMetaBase[d];}),l});},this.pushFieldValue=(a,s,r)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],s],r);},this.insertFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,d=>[...d.slice(0,s),r,...d.slice(s)],_e(n,{dontValidate:true}));let l=n?.dontValidate??false;l||await this.validateField(a,"change"),yr(this).handleArrayFieldMetaShift(a,s,"insert"),l||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,d=>d.map((u,m)=>m===s?r:u),_e(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.removeFieldValue=async(a,s,r)=>{let n=this.getFieldValue(a),l=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,u=>u.filter((m,f)=>f!==s),_e(r,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"remove"),l!==null){let u=`${a}[${l}]`;this.deleteField(u);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,d=>{let u=d[s],m=d[r];return Po(Po(d,`${s}`,m),`${r}`,u)},_e(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"swap",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,s,r,n)=>{this.setFieldValue(a,d=>{let u=[...d];return u.splice(r,0,u.splice(s,1)[0]),u},_e(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"move",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,s)=>{let r=this.getFieldValue(a),n=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],_e(s,{dontValidate:true})),n!==null)for(let d=0;d<=n;d++){let u=`${a}[${d}]`;this.deleteField(u);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Eo},values:this.options.defaultValues?Po(s.values,a,La(this.options.defaultValues,a)):s.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[s,r])=>(Object.keys(r).length&&r.errors.length&&(a[s]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ca.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ca.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??sl(),this._devtoolsSubmissionOverride=false,this.baseStore=new jt(il({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new qt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,l=a?.[0],d=s[0],u=0,m={};for(let f of Object.keys(d.fieldMetaBase)){let i=d.fieldMetaBase[f],c=l?.fieldMetaBase[f],p=n?.[f],y=La(d.values,f),h=p?.errors;if(!c||i.errorMap!==c.errorMap){h=Object.values(i.errorMap??{}).filter(C=>C!==void 0);let L=this.getFieldInfo(f)?.instance;L&&!L.options.disableErrorFlat&&(h=h?.flat(1));}let x=!rl(h??[]),b=!i.isDirty,g=Sa(y,La(this.options.defaultValues,f))||Sa(y,this.getFieldInfo(f)?.instance?.options.defaultValue);if(p&&p.isPristine===b&&p.isValid===x&&p.isDefaultValue===g&&p.errors===h&&i===c){m[f]=p,u++;continue}m[f]={...i,errors:h,isPristine:b,isValid:x,isDefaultValue:g};}return Object.keys(d.fieldMetaBase).length&&n&&u===Object.keys(d.fieldMetaBase).length?n:m}}),this.store=new qt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,l=a?.[0],d=s[0],u=s[1],m=Object.values(u).filter(Boolean),f=m.some(T=>T.isValidating),i=m.every(T=>T.isValid),c=m.some(T=>T.isTouched),p=m.some(T=>T.isBlurred),y=m.every(T=>T.isDefaultValue),h=c&&d.errorMap?.onMount,x=m.some(T=>T.isDirty),b=!x,g=!!(d.errorMap?.onMount||m.some(T=>T?.errorMap?.onMount)),L=!!f,C=n?.errors??[];(!l||d.errorMap!==l.errorMap)&&(C=Object.values(d.errorMap).reduce((T,U)=>U===void 0?T:U&&vr(U)?(T.push(U.form),T):(T.push(U),T),[]));let S=C.length===0,k=i&&S,v=this.options.canSubmitWhenInvalid??false,M=d.submissionAttempts===0&&!c&&!g||!L&&!d.isSubmitting&&k||v,B=d.errorMap;if(h&&(C=C.filter(T=>T!==d.errorMap.onMount),B=Object.assign(B,{onMount:void 0})),n&&l&&n.errorMap===B&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===f&&n.isFieldsValid===i&&n.isFormValid===S&&n.isValid===k&&n.canSubmit===M&&n.isTouched===c&&n.isBlurred===p&&n.isPristine===b&&n.isDefaultValue===y&&n.isDirty===x&&Sa(l,d))return n;let D={...d,errorMap:B,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:f,isFieldsValid:i,isFormValid:S,isValid:k,canSubmit:M,isTouched:c,isBlurred:p,isPristine:b,isDefaultValue:y,isDirty:x},O=this.options.transform?.deps??[];if(O.length!==this.prevTransformArray.length||O.some((T,U)=>T!==this.prevTransformArray[U])){let T=Object.assign({},this,{state:D});this.options.transform?.fn(T),D=T.state,this.prevTransformArray=O;}return D}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=tl(a=>xt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),xt.on("request-form-state",a=>{a.payload.id===this._formId&&xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),xt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),xt.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 Ys(o.validate)?Ca[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(s=>({...s,isSubmitted:false,submissionAttempts:s.submissionAttempts+1,isSubmitSuccessful:false})),ht(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance&&(s.instance.state.meta.isTouched||s.instance.setMeta(r=>({...r,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(s=>({...s,isSubmitting:true}));let a=()=>{this.baseStore.setState(s=>({...s,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(s=>s.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ht(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance?.options.listeners?.onSubmit?.({value:s.instance.state.value,fieldApi:s.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ht(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){ht(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(vr(a)){let{formError:r,fieldErrors:n}=Js(a);for(let l of Object.keys(this.fieldInfo))this.getFieldMeta(l)&&this.setFieldMeta(l,u=>({...u,errorMap:{...u.errorMap,[s]:n?.[l]},errorSourceMap:{...u.errorSourceMap,[s]:"form"}}));this.baseStore.setState(l=>({...l,errorMap:{...l.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function Js(e){if(e){if(vr(e)){let o=Js(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function wr(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 Sr=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:s}=this.options.validators||{};if(s){let r=this.runValidator({validate:s,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:r},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let s=La(t.form.options.defaultValues,t.name),r=t.defaultValue??s;a?this.setValue(n=>n||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{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,_e(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,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,_e(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),s=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:n,onBlurListenTo:l}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&l?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Do(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ia}),n=this.getLinkedFields(t).reduce((u,m)=>{let f=Do(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Ia});return f.forEach(i=>{i.field=m;}),u.concat(f)},[]),l=false;ht(()=>{let u=(m,f)=>{let i=Zs(f.cause),c=f.validate?Gu(m.runValidator({validate:f.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,p=a[i],{newErrorValue:y,newSource:h}=$s({formLevelError:p,fieldLevelError:c});m.state.meta.errorMap?.[i]!==y&&m.setMeta(x=>({...x,errorMap:{...x.errorMap,[i]:y},errorSourceMap:{...x.errorSourceMap,[i]:h}})),y&&(l=!0);};for(let m of s)u(this,m);for(let m of n)m.validate&&u(m.field,m);});let d=Zs("submit");return this.state.meta.errorMap?.[d]&&t!=="submit"&&!l&&this.setMeta(u=>({...u,errorMap:{...u.errorMap,[d]:void 0},errorSourceMap:{...u.errorSourceMap,[d]:void 0}})),{hasErrored:l}},this.validateAsync=async(t,a)=>{let s=Ro(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ia}),r=await a,n=this.getLinkedFields(t),l=n.reduce((i,c)=>{let p=Ro(t,{...c.options,form:c.form,validationLogic:c.form.options.validationLogic||Ia});return p.forEach(y=>{y.field=c;}),i.concat(p)},[]);this.state.meta.isValidating||this.setMeta(i=>({...i,isValidating:true}));for(let i of n)i.setMeta(c=>({...c,isValidating:true}));let d=[],u=[],m=(i,c,p)=>{let y=Zs(c.cause);i.getInfo().validationMetaMap[y]?.lastAbortController.abort();let x=new AbortController;this.getInfo().validationMetaMap[y]={lastAbortController:x},p.push(new Promise(async b=>{let g;try{g=await new Promise((v,M)=>{this.timeoutIds.validations[c.cause]&&clearTimeout(this.timeoutIds.validations[c.cause]),this.timeoutIds.validations[c.cause]=setTimeout(async()=>{if(x.signal.aborted)return v(void 0);try{v(await this.runValidator({validate:c.validate,value:{value:i.store.state.value,fieldApi:i,signal:x.signal,validationSource:"field"},type:"validateAsync"}));}catch(B){M(B);}},c.debounceMs);});}catch(v){g=v;}if(x.signal.aborted)return b(void 0);let L=Gu(g),C=r[this.name]?.[y],{newErrorValue:S,newSource:k}=$s({formLevelError:C,fieldLevelError:L});i.setMeta(v=>({...v,errorMap:{...v?.errorMap,[y]:S},errorSourceMap:{...v.errorSourceMap,[y]:k}})),b(S);}));};for(let i of s)i.validate&&m(this,i,d);for(let i of l)i.validate&&m(i.field,i,u);let f=[];(d.length||u.length)&&(f=await Promise.all(d),await Promise.all(u)),this.setMeta(i=>({...i,isValidating:false}));for(let i of n)i.setMeta(c=>({...c,isValidating:false}));return f.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:s}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,s[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Zs(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ca.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ca.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new qt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Eo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Ys(o.validate)?Ca[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 Gu(e){if(e)return e}function Zs(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 Qs(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Mx)}function Mx(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,s]of e)if(!o.has(a)||!Object.is(s,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=Ku(e);if(t.length!==Ku(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 Ku(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Fo=typeof window<"u"?useLayoutEffect:useEffect;function Fx(e){let[o]=useState(()=>{let a=new Sr({...e,form:e.form,name:e.name});return a.Field=ll,a});return Fo(o.mount,[o]),Fo(()=>{o.update(e);}),Qs(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var ll=(({children:e,...o})=>{let t=Fx(o),a=useMemo(()=>wa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Nx({form:e,selector:o,children:t}){let a=Qs(e.store,o);return wa(t,a)}function dl(e){let o=useId(),[t]=useState(()=>{let a=new Lr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(ll,{...n,form:a})},s.Subscribe=function(n){return jsx(Nx,{form:a,selector:n.selector,children:n.children})},s});return Fo(t.mount,[]),Fo(()=>{t.update(e);}),t}function ul({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 jx=({editElement:e})=>{let o=useDispatch(),t=useSelector(he),a=useRef(null),s=ot(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[l,d]=useState(n),u=dl({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:i})=>{if(i.questionType==="true-false"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctAnswer:i.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?fa(c):oi(c));}else if(i.questionType==="multiple-choice"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctIndex:i.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?ca(c):ai(c));}else if(i.questionType==="short-answer"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctShortAnswer:i.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?$o(c):ri(c));}else if(i.questionType==="fill-in-the-blank"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctShortAnswer:i.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?Jo(c):ni(c));}else if(i.questionType==="long-answer"){let c={id:r?e.id:v4(),data:{questionType:i.questionType,responseType:i.responseType,feedbackMode:i.feedbackMode,question:i.question,responseOptions:{options:i.responseOptions.options,correctLongAnswer:i.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?Yo(c):si(c));}o(ma(false));}}),m=()=>{o(ma(false));};if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:i=>{i.preventDefault(),i.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{m();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(u.Field,{name:"questionType",children:i=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:i.name,name:i.name,value:i.state.value,onBlur:i.handleBlur,onChange:c=>{i.handleChange(c.target.value),d(c.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${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-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",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-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(ul,{field:i})]})}),l&&!["short-answer","fill-in-the-blank","long-answer"].includes(l)&&jsx(u.Field,{name:"responseType",children:i=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:i.name,name:i.name,value:i.state.value,onBlur:i.handleBlur,onChange:c=>i.handleChange(c.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",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-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",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(ul,{field:i})]})})]}),jsx(u.Field,{name:"feedbackMode",children:i=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${l==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:l==="long-answer",onClick:()=>i.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${i.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:l==="long-answer",onClick:()=>i.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${i.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),l==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(ul,{field:i})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:i})=>i?void 0:"A question is required"},children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",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-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:i.state.value,onChange:c=>i.handleChange(c.target.value),onBlur:i.handleBlur,placeholder:"Enter Your Question"})}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),l==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:i=>{let c=i.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>i.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),c===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>i.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),c===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),l==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:i})=>{if(i.options.filter(p=>!p.trim()).length>0)return "All options must have text";if(!i.correctIndex||i.correctIndex.length===0)return "Please select at least one correct answer"}},children:i=>{let c=(x,b)=>{let g=[...i.state.value.options];g[x]=b,i.handleChange({...i.state.value,options:g});},p=()=>{if(i.state.value.options.length>=6){alert("Maximum 6 options allowed");return}i.handleChange({...i.state.value,options:[...i.state.value.options,""]});},y=x=>{if(i.state.value.options.length<=2){alert("Minimum 2 options required");return}let b=i.state.value.options.filter((L,C)=>C!==x),g=i.state.value.correctIndex?.filter(L=>L!==x).map(L=>L>x?L-1:L);i.handleChange({...i.state.value,options:b,correctIndex:g});},h=x=>{let b=i.state.value.correctIndex||[];if(b.includes(x))i.handleChange({...i.state.value,correctIndex:b.filter(L=>L!==x)});else {if(b.length>=6){alert("Maximum 6 correct answers allowed");return}i.handleChange({...i.state.value,correctIndex:[...b,x]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:i.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:i.state.value.options.map((x,b)=>{let g=!x.trim(),L=i.state.value.correctIndex?.includes(b),C=i.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>h(b),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${L?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:L&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",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-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${C?"border-red-500 bg-red-50":L?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${b+1}`,value:x,onChange:S=>c(b,S.target.value),onBlur:i.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),i.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>y(b),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},b)})}),jsx("button",{type:"button",onClick:p,disabled:i.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),i.state.value.correctIndex.length===0||i.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:i.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",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(l==="short-answer"||l==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:i.state.value,onChange:c=>{i.handleChange(c.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),l==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:i=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:i.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:i.state.value,onChange:c=>{i.handleChange(c.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),i.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:i.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:i=>[i.canSubmit,i.isSubmitting],children:([i,c])=>jsx("button",{type:"submit",disabled:!i,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:c?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,s)},Xu=jx;var Zu=({text:e,position:o})=>{let t=xe(),a=u=>{t(ce()),t(It({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+u))}));},s=u=>{t(ce()),t(It({id:e.id,fill:u}));},r=()=>{t(ce()),t(It({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ce()),t(It({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},l=()=>{t(ce()),t(It({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},d=u=>{t(ce()),t(It({id:e.id,fontFamily:u}));};return jsxs("div",{className:"fixed z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:u=>u.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:u=>d(u.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",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:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:r,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:n,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:l,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:u=>s(u.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var ec=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{let l=useRef(null),d=useMemo(()=>({fontSize:`${e.fontSize*r}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,r]),u=useCallback(m=>{m.style.height="auto",m.style.height=`${m.scrollHeight}px`;let f=document.createElement("span");f.style.font=window.getComputedStyle(m).font,f.style.fontSize=m.style.fontSize,f.style.fontFamily=m.style.fontFamily,f.style.fontWeight=m.style.fontWeight,f.style.fontStyle=m.style.fontStyle,f.style.visibility="hidden",f.style.position="absolute",f.style.whiteSpace="pre";let i=m.value.split(`
4
- `),c=0;document.body.appendChild(f);for(let y of i){f.textContent=y||" ";let h=f.offsetWidth;h>c&&(c=h);}document.body.removeChild(f);let p=10;m.style.width=`${Math.max(200,c+p+20)}px`;},[]);return useEffect(()=>{let m=l.current;m&&(m.style.fontSize=`${e.fontSize*r}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,u(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,u]),jsx("div",{style:{position:"absolute",top:`${s.top}px`,left:`${s.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(l.current=m,n.current=m,m){m.focus();let f=m.value.length;m.setSelectionRange(f,f),u(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:d},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var tc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(T=>T.toolbar.selectedTool),l=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,i]=useState(false),[c,p]=useState(null);useEffect(()=>{let T=d.current;if(T)return a.current.set(e.id,T),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===y,x=()=>{i(false),m("");},b=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,C=60,S=f?40:0,k=f?54:20,v=50,M=12,B=e.data.feedbackMode==="practice"?48:0,D=12,O=30,W=C+S+O+v+M+D+B+L;return jsxs(Group,{ref:d,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:W,name:"sa-element",...l?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:W,onTransformEnd:T=>t(e.id,T),onContextMenu:T=>{T.cancelBubble=true,s(T.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+S+O-k,width:e.width-L*2+4,height:v+6,fill:"#ffffff",stroke:h?"#22c55e":f?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+S+O-k},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${v}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:T=>m(T.target.value),disabled:f,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:f?"none":"auto"}})}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C+80,width:e.width/2+24,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:36,y:C+80,width:e.width-L*2,height:S,text:b(),fontSize:12,fontStyle:"bold",fill:g().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C+S+O+v+M+D,children:[jsxs(Group,{onMouseDown:T=>{T.cancelBubble=true,p("check");},onMouseUp:T=>{T.cancelBubble=true,p(null),u.length>0&&i(true);},onMouseLeave:T=>{T.cancelBubble=true,p(null);},onTouchStart:T=>{T.cancelBubble=true,p("check");},onTouchEnd:T=>{T.cancelBubble=true,p(null),u.length>0&&i(true);},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(f?2:1),height:48,fill:u.length===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*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-L*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:T=>T.cancelBubble=true,onTap:T=>T.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});tc.displayName="ShortAnswer";var ac=tc;var rc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(ac,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:l=>r(l,n.id)},n.id))});var sc=e=>{let o=useDispatch(),a=useSelector(he)?.fillInTheBlanks||[],s=useRef(new Map),r=useCallback((n,l)=>{let d=n.target;o(Jo({id:l,x:d.x(),y:d.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:s,handleFillInTheBlanksDragEnd:r}};var Tt=24,ml=51,Ar=64,nc=15,an=32,ic=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:s,fibRefs:r})=>{let n=useSelector(v=>v.toolbar.selectedTool),l=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,i]=useState(false),[c,p]=useState(null);useEffect(()=>{let v=d.current;if(v)return r.current.set(e.id,v),()=>{r.current.delete(e.id);}},[e.id,r]);let y=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===y,x=()=>{i(false),m("");},b=()=>{u.length>0&&i(true);},g=e.width-Tt*2,L=(g-nc)/2,C=e.data.feedbackMode==="practice",S=useMemo(()=>{let v=Tt,M=v;v+=60;let B=v;v+=35;let D=v;v+=ml+16;let O=v;f&&(v+=an+16);let W=v;return C&&(v+=Ar),v+=Tt,{questionY:M,helperTextY:B,inputY:D,feedbackY:O,buttonsY:W,totalHeight:v}},[f,C]),k=()=>f?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:d,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...l?{}:{onDragEnd:v=>a(v,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:S.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:v=>t(e.id,v),onContextMenu:v=>{v.cancelBubble=true,s?.(v.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Tt,y:S.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:g,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Tt,y:S.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:g,listening:false}),jsx(Rect,{x:Tt,y:S.inputY,width:g,height:ml,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Tt,y:S.inputY},divProps:{style:{width:`${g}px`,height:`${ml}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:v=>m(v.target.value),disabled:f,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"}})}),f&&jsxs(Group,{y:S.feedbackY,children:[jsx(Rect,{x:Tt,width:h?206:140,height:an,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Tt+10,y:0,width:16,height:an,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Tt+30,y:0,height:an,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),C&&jsxs(Group,{y:S.buttonsY,children:[jsxs(Group,{x:Tt,onMouseDown:v=>{v.cancelBubble=true,p("reset");},onMouseUp:v=>{v.cancelBubble=true,p(null),x();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("reset");},onTouchEnd:v=>{v.cancelBubble=true,p(null),x();},scaleX:c==="reset"?.98:1,scaleY:c==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Tt+L+nc,onMouseDown:v=>{v.cancelBubble=true,p("submit");},onMouseUp:v=>{v.cancelBubble=true,p(null),b();},onMouseLeave:v=>{v.cancelBubble=true,p(null);},onTouchStart:v=>{v.cancelBubble=true,p("submit");},onTouchEnd:v=>{v.cancelBubble=true,p(null),b();},scaleX:c==="submit"?.98:1,scaleY:c==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:u.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});ic.displayName="FillInTheBlanks";var lc=ic;var uc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r})=>jsx(Fragment,{children:e.map(n=>jsx(lc,{fillInTheBlank:n,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r},n.id))});var xl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(W=>W.toolbar.selectedTool),l=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,i]=useState(false),[c,p]=useState(null);useEffect(()=>{let W=d.current;if(W)return a.current.set(e.id,W),()=>{a.current.delete(e.id);}},[e.id,a]);let y=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===y,x=()=>{i(false),m("");},b=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,C=60,S=f?60:0,k=120,v=12,M=48,B=12,D=30,O=C+S+D+k+v+B+M+L;return jsxs(Group,{ref:d,draggable:!l,listening:!l,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...l?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:W=>{let T=d.current?.getStage()?.getPointerPosition();if(!T||!s)return;let U={x:e.x,y:e.y,width:e.width,height:e.height};T.x>=U.x&&T.x<=U.x+U.width&&T.y>=U.y&&T.y<=U.y+U.height&&s(W.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:O,onTransformEnd:W=>t(e.id,W)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:S,text:b(),fontSize:14,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:C+S+v,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+S+D,width:e.width-L*2,height:k,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+S+D},divProps:{style:{width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:f?"none":"auto"}},children:jsx("textarea",{value:u,onChange:W=>m(W.target.value),disabled:f,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,createContext,useState,useMemo,createElement,useContext,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,createSelector,configureStore}from'@reduxjs/toolkit';import Sd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {CameraPlus,Camera,Stop,X as X$1,Microphone,MicrophoneSlash,Record,Download,Cursor,PenNib,Eraser,TextAa,Shapes,Cards,Image as Image$2,Square,Circle as Circle$1,Triangle,Hexagon,Star as Star$1,Pizza,ArrowRight,LineSegment,Circuitry,ListBullets,ToggleRight,Textbox,TextUnderline,MonitorPlay,ArrowCounterClockwise,ArrowClockwise,Trash,Export,CaretLeft,Plus,CaretDown,CaretUp,SidebarSimple,ArrowUpIcon,Lock,LinkIcon,SpeakerHifiIcon,NotePencilIcon,Palette,ScissorsIcon,PencilSimple,CopySimple,Chat,Stack,Check,Play,WarningCircle,SpeakerSimpleSlash,SpeakerHigh,ScribbleLoop,Exam,CheckCircle,XCircle,TextB,TextItalic,Warning,CloudArrowUp,ArrowsDownUp,Shuffle,Pen}from'@phosphor-icons/react/dist/ssr';import {EyeIcon,Stack as Stack$1,X as X$2,DotsSixVertical,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 Iu from'use-image';import {AnimatePresence,motion,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 md=e=>{throw TypeError(e)};var pd=(e,o,t)=>o.has(e)||md("Cannot "+t);var _=(e,o,t)=>(pd(e,o,"read from private field"),t?t.call(e):o.get(e)),Pe=(e,o,t)=>o.has(e)?md("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),Ce=(e,o,t,a)=>(pd(e,o,"write to private field"),o.set(e,t),t);var hd=(e,o,t,a)=>({set _(s){Ce(e,o,s);},get _(){return _(e,o,a)}});var xe=()=>useDispatch(),te=e=>useSelector(e),ot=xe,ct=te;var Bn=20,Nn=e=>({id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:e||`Slide ${Date.now()}`,thumbnail:void 0,backgroundColor:"#ffffff",lines:[],shapes:[],images:[],videos:[],flashcards:[],photoFrames:[],texts:[],activityType:"",multipleChoices:[],trueFalses:[],shortAnswers:[],LongAnswer:[],fillInTheBlanks:[],showMcqForm:false,showFlashcardForm:false,editingActivity:null,editingFlashcard:null,createdAt:Date.now(),updatedAt:Date.now(),isActive:true}),Fn=Nn("Slide 1"),Um={slides:[Fn],currentSlideId:Fn.id,history:{[Fn.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false},gd=createSlice({name:"canvas",initialState:Um,reducers:{addSlide:e=>{if(e.slides.length>=Bn)return;let o=Nn(`Page ${e.slides.length+1}`);e.slides.push(o),e.currentSlideId=o.id,e.history[o.id]={past:[],future:[]};},deleteSlide:(e,o)=>{let{id:t,softDelete:a}=typeof o.payload=="string"?{id:o.payload,softDelete:false}:{id:o.payload.id,softDelete:o.payload.softDelete??false};if(e.slides.filter(i=>i.isActive).length<=1)return;let r=e.slides.findIndex(i=>i.id===t);if(r===-1)return;let n=e.slides[r];if(a?(n.isActive=false,n.updatedAt=Date.now()):(e.slides.splice(r,1),delete e.history[t]),e.currentSlideId===t){let i=e.slides.filter(d=>d.isActive);i.length>0&&(e.currentSlideId=i[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=Bn)return;let t=e.slides.findIndex(r=>r.id===o.payload);if(t===-1)return;let a=e.slides[t],s={...a,id:`slide-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:`${a.name} (Copy)`,createdAt:Date.now(),updatedAt:Date.now(),isActive:true,lines:JSON.parse(JSON.stringify(a.lines)),images:JSON.parse(JSON.stringify(a.images)),videos:JSON.parse(JSON.stringify(a.videos)),shapes:JSON.parse(JSON.stringify(a.shapes)),flashcards:JSON.parse(JSON.stringify(a.flashcards)),photoFrames:JSON.parse(JSON.stringify(a.photoFrames))};e.slides.splice(t+1,0,s),e.currentSlideId=s.id,e.history[s.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[s]=e.slides.splice(t,1);e.slides.splice(a,0,s);},loadSlides:(e,o)=>{e.slides=o.payload.slides.map(t=>({...t,showMcqForm:false,isActive:t.isActive!==void 0?t.isActive:true})),e.currentSlideId=o.payload.currentSlideId,e.history={},o.payload.slides.forEach(t=>{e.history[t.id]={past:[],future:[]};});},addLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a={...o.payload,id:o.payload.id||`line-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:o.payload.timestamp||Date.now(),x:o.payload.x||0,y:o.payload.y||0};t.lines.push(a),t.updatedAt=Date.now();}},removeLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&o.payload>=0&&o.payload<t.lines.length&&(t.lines.splice(o.payload,1),t.updatedAt=Date.now());},updateLastLine:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&t.lines.length>0&&(t.lines[t.lines.length-1].points=o.payload,t.updatedAt=Date.now());},finalizeDrawing:e=>{let o=e.slides.find(t=>t.id===e.currentSlideId);o&&(o.updatedAt=Date.now());},setLines:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);t&&(t.lines=o.payload,t.updatedAt=Date.now());},updateLinePosition:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.lines.find(s=>s.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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),t.updatedAt=Date.now();}}},updateElementOrder:(e,o)=>{let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,newTimestamp:r}=o.payload;switch(s){case "image":let n=t.images.find(b=>b.id===a);n&&(n.timestamp=r);break;case "video":let i=t.videos.find(b=>b.id===a);i&&(i.timestamp=r);break;case "shape":let d=t.shapes.find(b=>b.id===a);d&&(d.timestamp=r);break;case "text":let u=t.texts.find(b=>b.id===a);u&&(u.timestamp=r);break;case "flashcard":let m=t.flashcards.find(b=>b.id===a);m&&(m.timestamp=r);break;case "photoFrame":let f=t.photoFrames.find(b=>b.id===a);f&&(f.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(b=>b.id===a);l&&(l.timestamp=r);break;case "trueFalse":let c=t.trueFalses.find(b=>b.id===a);c&&(c.timestamp=r);break;case "shortAnswer":let p=t.shortAnswers.find(b=>b.id===a);p&&(p.timestamp=r);break;case "longAnswer":let v=t.LongAnswer.find(b=>b.id===a);v&&(v.timestamp=r);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(b=>b.id===a);h&&(h.timestamp=r);break;case "line":let x=t.lines.find(b=>b.id===a);x&&(x.timestamp=r);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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.multipleChoices[t.multipleChoices.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.trueFalses[t.trueFalses.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.shortAnswers[t.shortAnswers.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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 s=t.LongAnswer[t.LongAnswer.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...a,id:`${a.id}-copy-${Date.now()}`,timestamp:Date.now()};t.LongAnswer.push(s),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 s=t.fillInTheBlanks[t.fillInTheBlanks.length-1];a.x=s.x+20,a.y=s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.push(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.push(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.push(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.push(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.push(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.push(n);}}else if(s==="trueFalse"){let r=t.trueFalses.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.trueFalses.splice(r,1);t.trueFalses.push(n);}}else if(s==="shortAnswer"){let r=t.shortAnswers.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shortAnswers.splice(r,1);t.shortAnswers.push(n);}}else if(s==="fillInTheBlanks"){let r=t.fillInTheBlanks.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.fillInTheBlanks.splice(r,1);t.fillInTheBlanks.push(n);}}t.updatedAt=Date.now();}},sendToBack(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload;if(s==="image"){let r=t.images.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.images.splice(r,1);t.images.unshift(n);}}else if(s==="video"){let r=t.videos.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.videos.splice(r,1);t.videos.unshift(n);}}else if(s==="shape"){let r=t.shapes.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.shapes.splice(r,1);t.shapes.unshift(n);}}else if(s==="flashcard"){let r=t.flashcards.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.flashcards.splice(r,1);t.flashcards.unshift(n);}}else if(s==="photoFrame"){let r=t.photoFrames.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.photoFrames.splice(r,1);t.photoFrames.unshift(n);}}else if(s==="text"){let r=t.texts.findIndex(n=>n.id===a);if(r!==-1){let[n]=t.texts.splice(r,1);t.texts.unshift(n);}}t.updatedAt=Date.now();}},toggleLock(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s}=o.payload,n=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(i=>i.id===a);n&&(n.locked=!n.locked,"draggable"in n&&(n.draggable=!n.locked),t.updatedAt=Date.now());}},setLink(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,link:r}=o.payload,i=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="mcq"?t.multipleChoices:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);i&&(i.link=r,t.updatedAt=Date.now());}},setAltText(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,altText:r}=o.payload,i=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);i&&(i.altText=r,t.updatedAt=Date.now());}},setAudioData(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let{id:a,type:s,audioData:r}=o.payload,i=(s==="image"?t.images:s==="video"?t.videos:s==="shape"?t.shapes:s==="flashcard"?t.flashcards:s==="photoFrame"?t.photoFrames:s==="trueFalse"?t.trueFalses:s==="shortAnswer"?t.shortAnswers:s==="fillInTheBlanks"?t.fillInTheBlanks:t.texts).find(d=>d.id===a);i&&(i.audioData=r,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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),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(s=>s.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 s=a.images.map((r,n)=>n).filter(r=>r!==a.currentIndex);if(s.length>0){let r=s[Math.floor(Math.random()*s.length)];a.navigationHistory.push(r),a.currentIndex=r;}}t.updatedAt=Date.now();}}},previousFlashcard(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.flashcards.find(s=>s.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(s=>s.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(s=>s.id===o.payload);if(a){let s={...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(s),t.updatedAt=Date.now();}}},toggleImageDrawingMode(e,o){let t=e.slides.find(a=>a.id===e.currentSlideId);if(t){let a=t.images.find(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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(s=>s.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 s=o.past.pop();e.slides[t]=s;}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 s=o.future.shift();e.slides[t]=s;}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 s=JSON.parse(JSON.stringify(t));a.past.push(s),a.future=[],a.past.length>20&&a.past.shift();}catch(s){console.warn("Failed to save to history - data too large:",s),a.past.length>5&&(a.past=a.past.slice(-5)),a.future=[];}}},toggleSketchMode:e=>{e.isSketchMode=!e.isSketchMode;},setSketchMode:(e,o)=>{e.isSketchMode=o.payload;},setEditingTextId:(e,o)=>{e.editingTextId=o.payload;},setPresentationTitle:(e,o)=>{e.presentationMetadata.title=o.payload;},setPresentationDescription:(e,o)=>{e.presentationMetadata.description=o.payload;},loadPresentationMetadata:(e,o)=>{e.presentationMetadata.title=o.payload.title,e.presentationMetadata.description=o.payload.description,e.metadataLoaded=true;},setMetadataLoaded:(e,o)=>{e.metadataLoaded=o.payload;}}}),{addSlide:Vn,deleteSlide:qn,duplicateSlide:Hn,setCurrentSlide:Un,updateSlideThumbnail:Wn,setBackgroundColor:zn,reorderSlides:Wm,loadSlides:io,addLine:Gn,removeLine:Yr,addImage:Kn,updateImage:lo,deleteImage:Jr,duplicateImage:Zr,addVideo:Qr,updateVideo:es,deleteVideo:ts,duplicateVideo:as,toggleVideoPlaying:jo,addShape:_n,updateShape:uo,duplicateShape:os,deleteShape:rs,addText:jn,updateText:It,deleteText:ss,duplicateText:ns,addFlashcard:Xn,updateFlashcard:co,deleteFlashcard:is,duplicateFlashcard:ls,editFlashcard:Xo,nextFlashcard:$n,previousFlashcard:Yn,addPhotoFrame:Jn,updatePhotoFrame:Ba,deletePhotoFrame:ds,duplicatePhotoFrame:us,toggleImageDrawingMode:Zn,addImageAnnotation:Qn,updateImageAnnotation:zm,clearImageAnnotations:Gm,togglePhotoFrameDrawingMode:ei,addPhotoFrameAnnotation:ti,updatePhotoFrameAnnotation:Km,clearPhotoFrameAnnotations:_m,addMultipleChoice:ai,updateMultipleChoice:ca,editMultipleChoice:jm,deleteMultipleChoice:cs,duplicateMultipleChoice:fs,addTrueFalse:oi,updateTrueFalse:fa,deleteTrueFalse:ms,duplicateTrueFalse:ps,addShortAnswer:ri,updateShortAnswer:$o,deleteShortAnswer:hs,duplicateShortAnswer:gs,addLongAnswer:si,updateLongAnswer:Yo,deleteLongAnswer:xs,duplicateLongAnswer:bs,addFillInTheBlanks:ni,updateFillInTheBlanks:Jo,deleteFillInTheBlanks:vs,duplicateFillInTheBlanks:ys,setShowMcqForm:ma,setShowFlashcardForm:Oa,setActivityType:ii,setEditingActivity:Zo,bringToFront:li,sendToBack:di,toggleLock:ui,setLink:ws,setAltText:Ls,setAudioData:Ss,updateLastLine:Xm,finalizeDrawing:ci,setLines:$m,updateLinePosition:Ym,updateLineTransform:Is,deleteLineById:Cs,duplicateLine:fi,updateElementOrder:Qo,clearCanvas:mi,undo:pi,redo:hi,saveToHistory:ce,toggleSketchMode:Jm,setSketchMode:ft,setEditingTextId:er,setPresentationTitle:gi,setPresentationDescription:xi,loadPresentationMetadata:bi,setMetadataLoaded:ks}=gd.actions;var xd=e=>e.canvas.slides,fo=e=>e.canvas.currentSlideId,he=createSelector([xd,fo],(e,o)=>e.find(t=>t.id===o)),mo=createSelector([xd],e=>e.filter(o=>o.isActive!==false)),vi=e=>e.canvas.slides,yi=createSelector([mo],e=>e.length<Bn),Zm=e=>o=>{let t=o.canvas.slides.findIndex(a=>a.id===e);return t>=0?o.canvas.slides[t]:void 0},tr=e=>e.canvas.presentationMetadata,wi=e=>e.canvas.metadataLoaded,bd=gd.reducer;var yd=e=>{let o=xe(),t=useRef(null),a=useRef(false),s=te(c=>c.toolbar.selectedTool),r=te(c=>c.toolbar.penColor),n=te(c=>c.toolbar.strokeWidth),i=te(c=>c.canvas.isSketchMode),d=te(c=>c.canvas.slides.find(v=>v.id===c.canvas.currentSlideId)?.lines||[]),u=useCallback(c=>{t.current=c;},[]),m=useCallback(c=>{s==="pen"&&t.current&&(o(ce()),t.current.startDrawing(c),a.current=true);},[s,o]),f=useCallback(c=>{!t.current||!a.current||t.current.draw(c);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let c=t.current.stopDrawing();a.current=false,c&&c.points.length>=4&&o(Gn(c)),o(ci()),e?.();},[o,e]);return {lines:d,tool:s,color:r,strokeWidth:n,isSketchMode:i,setCanvasRef:u,startDrawing:m,draw:f,stopDrawing:l}};var Id=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:s,isSketchMode:r,style:n,xOffset:i=0,yOffset:d=0},u)=>{let m=useRef(null),f=useRef(false),l=useRef([]),c=useRef([]),p=useRef(null),v=useRef(t),h=useRef(a),x=useRef(s),b=useRef(r),g=useRef(i),L=useRef(d);useEffect(()=>{v.current=t,h.current=a,x.current=s,b.current=r,g.current=i,L.current=d;},[t,a,s,r,i,d]);let C=useCallback(()=>{let k=m.current;if(!k)return;let y=k.getContext("2d");y&&y.clearRect(0,0,k.width,k.height);},[]),S=useCallback(()=>{let k=m.current,y=c.current;if(!k||y.length<1)return;let A=k.getContext("2d");if(!A)return;if(A.clearRect(0,0,k.width,k.height),v.current==="eraser"?(A.globalCompositeOperation="destination-out",A.fillStyle="rgba(0,0,0,1)"):(A.globalCompositeOperation="source-over",A.fillStyle=h.current),y.length===1){A.beginPath(),A.arc(y[0].x,y[0].y,x.current/2,0,Math.PI*2),A.fill();return}let T=Sd(y,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:V=>V,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(T.length<2)){A.beginPath(),A.moveTo(T[0][0],T[0][1]);for(let V=1;V<T.length;V++)A.lineTo(T[V][0],T[V][1]);A.closePath(),A.fill();}},[]);return useImperativeHandle(u,()=>({startDrawing:k=>{f.current=true;let y={x:k.x-g.current,y:k.y-L.current};l.current=[{x:k.x,y:k.y}],c.current=[y],p.current=k,S();},draw:k=>{if(!f.current||!p.current)return;let y=k.x-p.current.x,A=k.y-p.current.y;if(Math.sqrt(y*y+A*A)<2)return;let T={x:k.x-g.current,y:k.y-L.current};l.current.push({x:k.x,y:k.y}),c.current.push(T),p.current=k,S();},stopDrawing:()=>{if(!f.current)return null;if(f.current=false,l.current.length<2)return l.current=[],c.current=[],p.current=null,C(),null;let y=Sd(l.current,{size:x.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:E=>E,start:{taper:0,cap:true},end:{taper:0,cap:true}}).flatMap(E=>[E[0],E[1]]),A={tool:v.current,points:y,color:h.current,strokeWidth:x.current,isSketch:true};return l.current=[],c.current=[],p.current=null,C(),A},clear:()=>{C(),l.current=[],c.current=[],p.current=null,f.current=false;},isDrawing:()=>f.current,getCanvasElement:()=>m.current}),[C,S]),useEffect(()=>{let k=m.current;k&&(k.width=e,k.height=o);},[e,o]),jsx("canvas",{ref:m,width:e,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:1e3,...n}})});Id.displayName="DirectDrawingCanvas";var Cd=Id;var Md=e=>{let o=xe(),a=te(he)?.images||[],s=useRef(new Map),r=useRef(new Map),n=useRef(new Set);useEffect(()=>{let m=new Set(a.map(f=>f.id));n.current.forEach(f=>{if(!m.has(f)){let l=r.current.get(f);l&&(l.src="",r.current.delete(f)),s.current.delete(f);}}),n.current=m;},[a]),useEffect(()=>()=>{r.current.forEach(m=>{m.src="";}),r.current.clear(),s.current.clear();},[]);let i=useCallback(m=>{if(r.current.has(m.id))return r.current.get(m.id);let f=new window.Image;return (m.src.startsWith("http://")||m.src.startsWith("https://"))&&(f.crossOrigin="anonymous"),f.src=m.src,r.current.set(m.id,f),f},[]),d=useCallback((m,f)=>{let l=m.target,c=l.id();a.find(v=>v.id===c)&&(o(lo({id:c,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),f?.());},[a,o]),u=useCallback((m,f)=>{let l=f.target,c=s.current.get(m);if(!c){console.error("\u274C Image node not found for id:",m);return}let p=l.scaleX(),v=l.scaleY(),h=l.rotation(),x=c.width(),b=c.height(),g=Math.max(5,x*p),L=Math.max(5,b*v);l.scaleX(1),l.scaleY(1),c.width(g),c.height(L),o(lo({id:m,width:g,height:L,x:l.x(),y:l.y(),rotation:h})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:i,imageRefs:s,handleDragEnd:d,handleImageTransformEnd:u}};var Td=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),s=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((i,d)=>{let u=d.target,m=u.scaleX(),f=u.scaleY(),l=u.rotation(),c=Math.max(5,u.width()*m),p=Math.max(5,u.height()*f);u.scaleX(1),u.scaleY(1),u.width(c),u.height(p),o(ca({id:i,width:c,height:p,x:u.x(),y:u.y(),rotation:l})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:s,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(i,d)=>{o(ca({id:d,x:i.target.x(),y:i.target.y()})),e?.();}}};var Ad=e=>{let o=useDispatch(),t=useSelector(he),a=useRef(new Map),s=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((i,d)=>{let u=d.target,m=u.scaleX(),f=u.scaleY(),l=u.rotation(),c=Math.max(5,u.width()*m),p=Math.max(5,u.height()*f);u.scaleX(1),u.scaleY(1),u.width(c),u.height(p),o(fa({id:i,width:c,height:p,x:u.x(),y:u.y(),rotation:l})),u.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:s,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(i,d)=>{o(fa({id:d,x:i.target.x(),y:i.target.y()})),e?.();},trueFalseRefs:a}};var Pd=e=>{let o=xe(),a=te(he)?.videos||[],s=useRef(new Map),r=useCallback(d=>{o(jo(d));},[o]),n=useCallback((d,u)=>{let m=u.target;o(es({id:d,x:m.x(),y:m.y()})),e?.();},[o,e]),i=useCallback((d,u)=>{let m=u.target,f=m.scaleX(),l=m.scaleY(),c=m.rotation(),p=Math.max(5,m.width()*f),v=Math.max(5,m.height()*l);m.scaleX(1),m.scaleY(1),m.width(p),m.height(v),o(es({id:d,width:p,height:v,x:m.x(),y:m.y(),rotation:c})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:s,handleVideoClick:r,handleVideoDragEnd:n,handleVideoTransformEnd:i}};var Ed=e=>{let o=xe(),a=te(he)?.shapes||[],s=useRef(new Map),r=useRef(new Map),[n,i]=useState(false),d=useCallback((m,f)=>{let l=f.target;o(uo({id:m,x:l.x(),y:l.y()})),e?.();},[o,e]),u=useCallback((m,f)=>{let l=f.target,c=a.find(g=>g.id===m);if(!c)return;let p=l.scaleX(),v=l.scaleY(),h=c.type?.toLowerCase();h==="arrow"||h==="line"||(l.scaleX(1),l.scaleY(1));let b={id:m,x:l.x(),y:l.y(),width:Math.max(5,l.width()*p),height:Math.max(5,l.height()*v),rotation:l.rotation()};switch(h){case "circle":b.radius=l.width()*p/2;break;case "star":b.innerRadius=l.width()*p/4,b.outerRadius=l.width()*p/2;break;case "triangle":b.radius=l.width()*p/2;break;case "ellipse":b.radiusX=l.width()*p/2,b.radiusY=l.height()*v/2;break;case "polygon":b.radius=l.width()*p/2;break;case "ring":let g=p;b.innerRadius=c.innerRadius&&c.innerRadius*g,b.outerRadius=c.outerRadius&&c.outerRadius*g;break;case "wedge":b.radius=c.radius&&c.radius*p;break;case "arc":b.innerRadius=c.innerRadius&&c.innerRadius*p,b.outerRadius=c.outerRadius&&c.outerRadius*p;break;case "arrow":case "line":{b.scaleX=p,b.scaleY=v,delete b.width,delete b.height;break}}o(uo(b)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:s,isDragging:n,loadedShapesRef:r,handleShapeDragEnd:d,handleShapeResizeEnd:u}};var Bd=(e,o)=>{let t=ot(),s=te(he)?.texts||[],r=useRef(new Map),[n,i]=useState(null),[d,u]=useState("");return {texts:s,textRefs:r,handleDragEnd:(h,x)=>{let b=h.target;t(ce()),t(It({id:x,x:b.x(),y:b.y()})),e();},handleTransformEnd:h=>{let x=r.current.get(h);if(!x)return;let b=x.scaleX(),g=x.scaleY(),L=s.find(S=>S.id===h);if(!L)return;let C=(b+g)/2;x.scaleX(1),x.scaleY(1),t(ce()),t(It({id:h,x:x.x(),y:x.y(),width:Math.max(5,(L.width||100)*b),height:Math.max(5,(L.height||50)*g),fontSize:Math.round(Math.max(8,L.fontSize*C)),rotation:x.rotation()})),e();},handleDoubleClick:h=>{let x=s.find(b=>b.id===h);x&&!x.locked&&(i(h),u(x.text));},startEditing:h=>{let x=s.find(b=>b.id===h);x&&!x.locked&&(i(h),u(x.text));},editingTextId:n,editingValue:d,handleEditingChange:h=>{u(h);},finishEditing:()=>{if(n){let h=r.current.get(n),x=s.find(g=>g.id===n);t(ce());let b={id:n,text:d};if(x&&(x.fontWeight!==void 0&&(b.fontWeight=x.fontWeight),x.fontStyle!==void 0&&(b.fontStyle=x.fontStyle),x.textDecoration!==void 0&&(b.textDecoration=x.textDecoration)),o?.current&&d.trim()){let g=o.current,L=g.offsetWidth,C=g.offsetHeight,S=1;if(h){let G=h.getStage();G&&(S=G.scaleX());}let k=14,y=(L-k)/S,A=(C-k)/S,E=d.split(`
3
+ `).length,V=s.find(G=>G.id===n)?.fontSize||24,R=E*V*1.2+10;b.width=Math.max(200,y),b.height=Math.max(50,A,R);}else if(h&&d.trim()){let g=h.text(),L=h.width();h.text(d),h.width(void 0);let C=h.width(),S=h.height();h.text(g),h.width(L),b.width=Math.max(200,C+20),b.height=Math.max(50,S+20);}t(It(b)),i(null),u(""),t(er(null)),e();}}}};var Od=e=>{let o=useDispatch(),a=useSelector(he)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,i)=>{let d=n.target;o($o({id:i,x:d.x(),y:d.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var Nd=e=>{let o=useDispatch(),t=useSelector(he),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let i=r.target;o(Yo({id:n,x:i.x(),y:i.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var qd=e=>{let o=xe(),a=te(he)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((f,l)=>{if(r.current.has(l))return r.current.get(l);let c=new window.Image;return c.src=f,r.current.set(l,c),c},[]),i=useCallback((f,l)=>{let c=f.target,p=c.id();a.find(h=>h.id===p)&&(o(co({id:p,x:c.x(),y:c.y()})),l?.());},[a,o]),d=useCallback((f,l)=>{let c=l.target,p=c.scaleX(),v=c.scaleY(),h=c.rotation(),x=Math.max(50,c.width()*p),b=Math.max(50,c.height()*v);c.scaleX(1),c.scaleY(1),c.width(x),c.height(b),o(co({id:f,width:x,height:b,x:c.x(),y:c.y(),rotation:h})),c.getLayer()?.batchDraw(),e?.();},[o,e]),u=useCallback(f=>{o($n(f)),e?.();},[o,e]),m=useCallback(f=>{o(Yn(f)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:i,handleFlashcardTransformEnd:d,handleNext:u,handlePrevious:m}};var Wd=e=>{let o=xe(),a=te(he)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),i=useCallback((c,p)=>{console.log("handleDragEnd"),o(Ba({id:p,x:c.target.x(),y:c.target.y()})),e?.();},[o,e]),d=useCallback((c,p)=>{let v=p.target,h=v.scaleX(),x=v.scaleY(),b=v.rotation(),g=a.find(S=>S.id===c);if(!g)return;let L=Math.max(100,g.width*h),C=Math.max(100,g.height*x);v.scaleX(1),v.scaleY(1),o(Ba({id:c,width:L,height:C,x:v.x(),y:v.y(),rotation:b})),v.getLayer()?.batchDraw(),e?.();},[o,e,a]),u=useCallback(async c=>{try{let p=await navigator.mediaDevices.getUserMedia({video:{width:640,height:480},audio:!1});return n(v=>{let h=new Map(v);return h.set(c,p),h}),o(Ba({id:c,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),m=useCallback(c=>{let p=r.get(c);p&&(p.getTracks().forEach(v=>v.stop()),n(v=>{let h=new Map(v);return h.delete(c),h}),o(Ba({id:c,isCapturing:false})),e?.());},[r,o,e]),f=useCallback((c,p)=>{let v=document.createElement("canvas");v.width=p.videoWidth,v.height=p.videoHeight;let h=v.getContext("2d");if(h){h.drawImage(p,0,0,v.width,v.height);let x=v.toDataURL("image/jpeg",.8);return o(Ba({id:c,capturedImageUrl:x,isCapturing:false})),m(c),e?.(),x}return null},[o,m,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(c=>{c.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:i,handlePhotoFrameTransformEnd:d,startCamera:u,stopCamera:m,capturePhoto:f,cameraStreams:r}};var zd=()=>{let e=useRef(null),o=useMemo(()=>({minWidth:340,minHeight:400,maxWidth:520,maxHeight:600}),[]),t=useCallback((r,n)=>e.current?.nodes()[0]?.name()==="mcq-element"?{...n,width:Math.max(o.minWidth,Math.min(n.width,o.maxWidth)),height:Math.max(o.minHeight,Math.min(n.height,o.maxHeight))}:n,[o]),a=useCallback((r,n,i,d,u,m,f,l=[])=>{if(e.current){if(r&&!l.find(v=>v.id===r)?.isPlaying){let v=n.get(r)||i.get(r)||d.get(r)||u.get(r)||m.get(r)||(f?f.get(r):null);if(v){e.current.boundBoxFunc(t),e.current.nodes([v]),e.current.getLayer()?.batchDraw();return}}e.current.nodes([]),e.current.getLayer()?.batchDraw();}},[t]),s=useCallback(()=>{e.current&&(e.current.nodes([]),e.current.getLayer()?.batchDraw());},[]);return {transformerRef:e,attachTransformer:a,deselectTransformer:s,boundBoxFunc:t}};var kp=(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])},jd=(e,o)=>{let t=ot(),a=useRef(e);useEffect(()=>{a.current=e;},[e]);let s=useCallback(()=>{if(o.current)try{let n=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});n&&n.startsWith("data:")&&t(Wn({id:a.current,thumbnail:n}));}catch(n){console.warn("Could not generate thumbnail (likely CORS issue with images):",n);}},[o,t]),r=kp(s,500);return {generateThumbnail:s,debouncedGenerateThumbnail:r}};var Tp=e=>e.flatMap(o=>[o[0],o[1]]),Ts=(e,o)=>{let t=Sd(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 Tp(t)};var Xd=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),i=te(g=>g.toolbar.selectedTool),d=te(g=>g.toolbar.penColor),u=te(g=>g.toolbar.strokeWidth),m=te(g=>g.canvas.isSketchMode),f=te(g=>g.canvas.slides.find(C=>C.id===g.canvas.currentSlideId)?.images.find(C=>C.id===e)),l=f?.annotations||[],c=f?.isDrawingMode||false,p=f?.width||1,v=f?.height||1,h=useCallback(g=>{if(i!=="pen"&&i!=="eraser")return;t.current=true,a.current=false,s.current=[{x:g.x,y:g.y}];let L=g.x/p,C=g.y/v;n({tool:i,points:[L,C],color:d,strokeWidth:u/p,isSketch:m});},[i,d,u,m,p,v]),x=useCallback(g=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;s.current.push({x:g.x,y:g.y});let S;if(m)S=Ts(s.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,A)=>A%2===0?y/p:y/v);else {let k=g.x/p,y=g.y/v;S=[...r.points,k,y];}n(k=>k?{...k,points:S}:null);},[m,u,r,p,v]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(Qn({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:c,startDrawing:h,draw:x,stopDrawing:b,tool:i}};var Zd=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>{let{annotations:i,activeLine:d,stopDrawing:l,tool:c}=Xd(e.id);useEffect(()=>{let b=t.current.get(e.id);b&&(b.width()!==e.width||b.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:b.width(),konvaHeight:b.height()}),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let v=b=>{{r(e.id);return}},h=b=>{return;},x=b=>{};return jsxs(Group,{listening:c!=="pen"&&c!=="eraser",children:[jsx(Image$1,{id:e.id,ref:b=>{if(b){t.current.set(e.id,b),b.width(e.width),b.height(e.height),b.getLayer()?.batchDraw();let g=b.getStage()?.container();if(g){let L=C=>{let S=b.getStage()?.getPointerPosition();if(S){let k={x:e.x,y:e.y,width:e.width,height:e.height};S.x>=k.x&&S.x<=k.x+k.width&&S.y>=k.y&&S.y<=k.y+k.height&&n(C,e.id,"image");}};g.addEventListener("contextmenu",L),b._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",L);};}}else {let g=t.current.get(e.id);g?._contextMenuCleanup&&g._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:c!=="pen"&&c!=="eraser",onDragEnd:a,onTransformEnd:b=>s(e.id,b),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...c!=="pen"&&c!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onTouchStart:v,onMouseMove:h,onTouchMove:h,onMouseUp:x,onTouchEnd:x}:{}}),i?.map((b,g)=>{let L=b.points.map((S,k)=>k%2===0?S*e.width+e.x:S*e.height+e.y),C=b.strokeWidth*e.width;return jsx(Line,{points:L,stroke:b.tool==="eraser"?"white":b.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:b.tool==="eraser"?"destination-out":"source-over",fill:b.isSketch?b.color:void 0,closed:b.isSketch,listening:false},g)}),d&&jsx(Line,{points:d.points.map((b,g)=>g%2===0?b*e.width+e.x:b*e.height+e.y),stroke:d.tool==="eraser"?"white":d.color,strokeWidth:d.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:d.tool==="eraser"?"destination-out":"source-over",fill:d.isSketch?d.color:void 0,closed:d.isSketch,listening:false},"active")]})});Zd.displayName="ImageWithDrawing";var Ti=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>{let d=o(i);return d?jsx(Zd,{img:i,loadedImage:d,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n},i.id):null})}));Ti.displayName="ImageLayer";var Vp=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:i=0,onTransformEnd:d,onDragEnd:u})=>{let m=xe(),f=useRef(null),l=c=>{m(jo(c));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:i,onDragEnd:u,onTransformEnd:d,children:[jsx(Rect,{width:s,height:r,fill:"black",stroke:n?"#4A90E2":"transparent",strokeWidth:2}),jsx(Html,{divProps:{style:{width:`${s}px`,height:`${r}px`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}},children:jsx("video",{ref:f,src:e,controls:true,autoPlay:true,onClick:()=>l(t),onSeeking:c=>c.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},Qd=Vp;var _p=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[i,d]=useState(null),u=useSelector(v=>v.toolbar.selectedTool),m=u==="pen"||u==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let v=new window.Image;v.src=e.thumbnailDataUrl,v.onload=()=>{d(v);};}},[e.thumbnailDataUrl]),!i)return null;let f=e.width/2,l=e.height/2,c=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(c,80));return jsxs(Group,{draggable:!m,listening:!m,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...m?{}:{onDragEnd:a,onTransformEnd:s},ref:v=>{if(n(v),v){let h=v.getStage()?.container();if(h){let x=b=>{let g=v.getStage()?.getPointerPosition();if(g){let L={x:e.x,y:e.y,width:e.width,height:e.height};g.x>=L.x&&g.x<=L.x+L.width&&g.y>=L.y&&g.y<=L.y+L.height&&r(b);}};h.addEventListener("contextmenu",x),v._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",x);};}}},children:[jsx(Image$1,{image:i,width:e.width,height:e.height,listening:!m,...m?{}:{onClick:t,onTap:t},shadowColor:"black",shadowBlur:o?10:0,shadowOpacity:o?.3:0}),jsx(Circle,{x:f,y:l,radius:p,fill:"white",listening:!m,shadowColor:"black",shadowBlur:20,shadowOpacity:.4,shadowOffsetX:0,shadowOffsetY:2,...m?{}:{onClick:t,onTap:t}}),jsx(Circle,{x:f,y:l,radius:p*.88,fill:"rgba(0, 0, 0, 0.75)",listening:!m,...m?{}:{onClick:t,onTap:t}}),jsx(RegularPolygon,{x:f+p*.1,y:l,sides:3,radius:p*.35,fill:"white",rotation:90,listening:!m,...m?{}:{onClick:t,onTap:t}})]})},tu=_p;var Di=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(i=>jsxs(be__default.Fragment,{children:[jsx(tu,{video:i,isSelected:!i.isPlaying&&o===i.id,onClick:()=>a(i.id),onDragEnd:d=>s(i.id,d),onTransformEnd:d=>r(i.id,d),onContextMenu:d=>n(d,i.id,"video"),nodeRef:d=>{d?t.current.set(i.id,d):t.current.delete(i.id);}}),i.isPlaying&&(()=>{let d=i.x,u=i.y;if(i.isRecorded){let m=typeof window<"u"?window.innerWidth:i.width,f=typeof window<"u"?window.innerHeight:i.height;d=(m-i.width)/2,u=(f-i.height)/2;}return jsx(Qd,{id:i.id,src:i.objectUrl,x:d,y:u,width:i.width,height:i.height,isSelected:false,rotation:i.rotation,onTransformEnd:m=>r(i.id,m),onDragEnd:m=>s(i.id,m)})})()]},i.id))}));Di.displayName="VideoLayer";var Ri=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n})=>{let i=useSelector(u=>u.toolbar.selectedTool),d=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map((u,m)=>{let f=u.id||m,l={id:u.id,x:u.x,y:u.y,rotation:u.rotation,draggable:!u.locked&&!d,listening:!d,fill:u.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(u.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radius:u.radius||u.width/2,width:u.width,height:u.width},f);case "star":return jsx(Star,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},numPoints:5,innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},sides:3,radius:u.radius||u.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},sides:u.sides||6,radius:u.radius||u.width/2},f);case "ellipse":return jsx(Ellipse,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radiusX:u.radiusX||u.width/2,radiusY:u.radiusY||u.height/2},f);case "ring":return jsx(Ring,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2},f);case "wedge":return jsx(Wedge,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},radius:u.radius||u.width/2,angle:u.angle||60},f);case "arrow":return jsx(Arrow,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.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"},f);case "line":return jsx(Line,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,scaleX:u.scaleX||1,scaleY:u.scaleY||1,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},points:u.points||[0,0,u.width,0],stroke:"#000000",strokeWidth:u.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},innerRadius:u.innerRadius||u.width/4,outerRadius:u.outerRadius||u.width/2,angle:u.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:c=>{c?o.current.set(u.id,c):o.current.delete(u.id);},...l,draggable:!u.locked&&!d,...d?{}:{onDragStart:c=>{r?.();},onDragEnd:c=>t(u.id,c),onTransformEnd:c=>a(u.id,c),onClick:()=>s(u.id),onContextMenu:c=>{c.evt.preventDefault(),n(c.evt,u.id,"shape");}},width:u.width,height:u.height,cornerRadius:u.type==="rounded-rectangle"?10:0},f)}})})});Ri.displayName="ShapeLayer";var ru=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:i})=>{let d=useSelector(m=>m.toolbar.selectedTool),u=d==="pen"||d==="eraser";return jsx(Fragment,{children:e.map(m=>{let f=m.id===i,l=m.fontWeight==="bold",c=l?Math.max(1,m.fontSize/25):0;return jsx(Text,{id:m.id,ref:p=>{p?o.current.set(m.id,p):o.current.delete(m.id);},text:m.text,x:m.x,y:m.y,width:m.width,height:m.height,rotation:m.rotation,draggable:!m.locked&&!f&&!u,listening:!u,fontSize:m.fontSize,fontFamily:m.fontFamily,fontStyle:m.fontStyle,fontWeight:m.fontWeight,textDecoration:m.textDecoration,fill:m.fill,stroke:l?m.fill:void 0,strokeWidth:c,align:m.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...u?{}:{onClick:()=>s(m.id),onTap:()=>s(m.id),onDblClick:()=>n(m.id),onDblTap:()=>n(m.id),onDragEnd:p=>t(p,m.id),onTransformEnd:()=>a(m.id),onContextMenu:p=>{p.evt.preventDefault();let v=p.evt;r(v,m.id,"text");}}},m.id)})})};var xh=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:i,nodeRef:d})=>{let[u,m]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{m(h);};}},[e.images,e.currentIndex]),!u||e.images.length===0)return null;let f=8,l=2,c=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(c,32)),v=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:s,ref:h=>{if(d(h),h){let x=h.getStage()?.container();if(x){let b=g=>{let L=h.getStage()?.getPointerPosition();if(L){let C={x:e.x,y:e.y,width:e.width,height:e.height};L.x>=C.x&&L.x<=C.x+C.width&&L.y>=C.y&&L.y<=C.y+C.height&&r(g);}};x.addEventListener("contextmenu",b),h._contextMenuCleanup=()=>{x.removeEventListener("contextmenu",b);};}}},children:[jsx(Rect,{width:e.width,height:e.height,cornerRadius:f,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:f,stroke:"#E5E7EB",strokeWidth:l,listening:false}),jsx(Image$1,{x:l+4,y:l+4,image:u,width:e.width-(l+4)*2,height:e.height-(l+4)*2,cornerRadius:f-l,onClick:t,onTap:t}),jsx(Rect,{x:l,y:e.height-50,width:e.width-l*2,height:50,cornerRadius:[0,0,f-l,f-l],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:v+p,y:e.height/2,onClick:h=>{h.cancelBubble=true,i();},onTap:h=>{h.cancelBubble=true,i();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[-4,-6,-10,0,-4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),e.images.length>1&&jsxs(Group,{x:e.width-v-p,y:e.height/2,onClick:h=>{h.cancelBubble=true,n();},onTap:h=>{h.cancelBubble=true,n();},children:[jsx(Circle,{radius:p,fill:"white",shadowColor:"black",shadowBlur:4,shadowOpacity:.15}),jsx(Line,{points:[4,-6,10,0,4,6],stroke:"#6B7280",strokeWidth:2,lineCap:"round",lineJoin:"round"})]}),jsx(Rect,{x:e.width-60,y:e.height-35,width:50,height:24,cornerRadius:4,fill:"rgba(255, 255, 255, 0.9)"}),jsx(Text,{x:e.width-60,y:e.height-35,width:50,height:24,text:`${e.currentIndex+1}/${e.images.length}`,fontSize:11,fontFamily:"Arial",fill:"#6B7280",align:"center",verticalAlign:"middle"})]})},iu=xh;var Bi=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:i,onContextMenu:d})=>jsx(Fragment,{children:e.map(u=>jsx(iu,{flashcard:u,isSelected:t===u.id,onClick:()=>r(u.id),onDragEnd:a,onTransformEnd:m=>s(u.id,m),onContextMenu:m=>d(m,u.id,"flashcard"),onNext:()=>n(u.id),onPrevious:()=>i(u.id),nodeRef:m=>{m?o.current.set(u.id,m):o.current.delete(u.id);}},u.id))}));Bi.displayName="FlashcardLayer";var du=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);te(g=>g.toolbar.selectedTool);let d=te(g=>g.toolbar.penColor),u=te(g=>g.toolbar.strokeWidth),m=te(g=>g.canvas.isSketchMode),f=te(g=>g.canvas.slides.find(C=>C.id===g.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),l=f?.annotations||[],c=f?.isDrawingMode||false,p=f?.width||1,v=f?.height||1,h=useCallback(g=>{if(!c)return;t.current=true,a.current=false,s.current=[{x:g.x,y:g.y}];let L=g.x/p,C=g.y/v;n({tool:"pen",points:[L,C],color:d,strokeWidth:u/p,isSketch:m});},[c,d,u,m,p,v]),x=useCallback(g=>{if(!t.current||!r)return;a.current=true;let L=s.current[s.current.length-1];if(Math.sqrt(Math.pow(g.x-L.x,2)+Math.pow(g.y-L.y,2))<2)return;s.current.push({x:g.x,y:g.y});let S;if(m)S=Ts(s.current,{size:u*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,A)=>A%2===0?y/p:y/v);else {let k=g.x/p,y=g.y/v;S=[...r.points,k,y];}n(k=>k?{...k,points:S}:null);},[m,u,r,p,v]),b=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ti({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:c,startDrawing:h,draw:x,stopDrawing:b}};var Ch=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:i,cameraStream:d,nodeRef:u})=>{let[m,f]=useState(null),[l,c]=useState(null),p=useRef(null),v=useRef(null),h=useRef(null),x=useRef(null),b=useRef(0),g=33,L=useSelector(q=>q.toolbar.selectedTool),C=L==="pen"||L==="eraser",{annotations:S,activeLine:k,isDrawingMode:y,startDrawing:A,draw:E,stopDrawing:T}=du(e.id);useEffect(()=>{if(!y)return;let q=()=>{T();},j=()=>{T();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",j),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",j);}},[T,y]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;q.src=e.capturedImageUrl,q.onload=()=>{f(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&d){p.current||(p.current=document.createElement("video"),p.current.autoplay=true,p.current.playsInline=true),v.current||(v.current=document.createElement("canvas"));let q=p.current,j=v.current;q.srcObject=d;let H=()=>{j.width=q.videoWidth||640,j.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",j.width,j.height);let U=Y=>{if(Y-b.current<g){h.current=requestAnimationFrame(U);return}b.current=Y;let Z=j.getContext("2d");if(Z&&q.readyState===q.HAVE_ENOUGH_DATA){Z.drawImage(q,0,0,j.width,j.height);let Q=j.toDataURL("image/jpeg",.6),le=new window.Image;le.onload=()=>{c(le);},le.src=Q;}h.current=requestAnimationFrame(U);};h.current=requestAnimationFrame(U);};return q.onloadedmetadata=H,q.readyState>=q.HAVE_METADATA&&H(),q.play().catch(U=>console.error("Error playing video:",U)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{c(null),x.current&&(x.current.src="");}},[e.isCapturing,d]);let V=()=>{p.current&&e.isCapturing&&i(p.current);},z=q=>{if(e.capturedImageUrl){if(!y){t();return}let j=q.currentTarget,H=j.getAbsoluteTransform().copy(),Y=j.getStage()?.getPointerPosition();if(Y){H.invert();let Z=H.point(Y);A(Z);}q.cancelBubble=true;}else t();},R=q=>{if(!y||!e.capturedImageUrl)return;let j=q.currentTarget,H=j.getAbsoluteTransform().copy(),Y=j.getStage()?.getPointerPosition();if(Y){H.invert();let Z=H.point(Y);E(Z);}},G=()=>{!y||!e.capturedImageUrl||T();},D=e.isCapturing?l:m,ee=Math.min(e.width,e.height)*.12,N=Math.max(25,Math.min(ee,50)),se=e.width/2,K=e.height/2;return jsxs(Group,{id:e.id,draggable:!y&&!C,listening:true,x:e.x,y:e.y,...C?{}:{onDragEnd:a,onTransformEnd:s},rotation:e.rotation,width:e.width,height:e.height,ref:q=>{if(u(q),q){let j=q.getStage()?.container();if(j){let H=U=>{let Y=q.getStage()?.getPointerPosition();if(Y){let Z={x:e.x,y:e.y,width:e.width,height:e.height};Y.x>=Z.x&&Y.x<=Z.x+Z.width&&Y.y>=Z.y&&Y.y<=Z.y+Z.height&&r(U);}};j.addEventListener("contextmenu",H),q._contextMenuCleanup=()=>{j.removeEventListener("contextmenu",H);};}}},children:[jsx(Rect,{x:-20,y:-20,width:e.width+50,height:e.height+50,fill:D?"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}}),D&&jsx(Image$1,{image:D,width:e.width,height:e.height,cornerRadius:8,listening:true,onClick:z,onTap:z,onMouseDown:z,onTouchStart:z,onMouseMove:R,onTouchMove:R,onMouseUp:G,onTouchEnd:G,...C?{}:{onDragEnd:a,onTransformEnd:s}}),S?.map((q,j)=>{let H=q.points.map((Y,Z)=>Z%2===0?Y*e.width:Y*e.height),U=q.strokeWidth*e.width;return jsx(Line,{points:H,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:U,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:q.tool==="eraser"?"destination-out":"source-over",fill:q.isSketch?q.color:void 0,closed:q.isSketch,listening:false},j)}),k&&jsx(Line,{points:k.points.map((q,j)=>j%2===0?q*e.width:q*e.height),stroke:k.tool==="eraser"?"white":k.color,strokeWidth:k.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:k.tool==="eraser"?"destination-out":"source-over",fill:k.isSketch?k.color:void 0,closed:k.isSketch,listening:false},"active"),!D&&!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:K-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:se-N+6,y:K-60,width:N*1.6,height:N*1.6,radius:N,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?V():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?V():n();}}),jsx(Html,{groupProps:{x:se-12,y:K-40,width:N*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?V():n();}})})]}),jsx(Text,{x:0,y:K,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:K+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:se-24,y:K+104,width:N*1.6,height:N*1.6,radius:N,fill:"#096B76",cornerRadius:N,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?V():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?V():n();}}),jsx(Html,{groupProps:{x:se-8,y:K+120,width:N*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?V():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:se-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),V();},className:"flex h-[70px] w-[70px] cursor-pointer items-center justify-center rounded-full border-none shadow-lg",children:jsx("div",{className:"flex h-[50px] w-[50px] items-center justify-center rounded-full bg-[#096B76]",children:jsx(Camera,{weight:"fill",color:"white",size:28})})})})]})]})},mu=Ch;var Ui=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:i,cameraStreams:d,onContextMenu:u})=>jsx(Fragment,{children:e.map(m=>jsx(mu,{photoFrame:m,isSelected:t===m.id,onClick:()=>r(m.id),onDragEnd:f=>a(f,m.id),onTransformEnd:f=>s(m.id,f),onContextMenu:f=>u(f,m.id,"photoFrame"),onStartCamera:()=>n(m.id),onCapture:f=>i(m.id,f),cameraStream:d.get(m.id),nodeRef:f=>{f?o.current.set(m.id,f):o.current.delete(m.id);}},m.id))}));Ui.displayName="PhotoFrameLayer";var xu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:i})=>{useEffect(()=>{let f=c=>{i?.current&&!i.current.contains(c.target)&&a();},l=c=>{c.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",l);}},[a]);let d=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label:n?"Exit Drawing Mode":"Draw on Image",icon:jsx(PencilSimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image","photoFrame"]},{action:"duplicate",label:"Duplicate",icon:jsx(CopySimple,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"infinite-clone",label:"Infinite Clone",icon:jsx(Square,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"make-response",label:"Make Response",icon:jsx(Chat,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"accessibility",label:"Accessibility",icon:jsx(EyeIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"layers",label:"Layers",icon:jsx(Stack,{className:"h-5 w-5",weight:"fill",color:"#00000099"})},{action:"delete",label:"Delete",icon:jsx(Trash,{className:"h-5 w-5",weight:"fill",color:"#E92222"}),isDanger:true}].filter(l=>!(l.showForTypes&&!l.showForTypes.includes(s)||l.hideForTypes&&l.hideForTypes.includes(s))),[s,n]),u=(f,l)=>{f==="order"||f==="lock"?t(f,l):(t(f),a());},m=jsx("div",{ref:i,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:d.map((f,l)=>jsxs("button",{onClick:c=>u(f.action,c),className:`flex w-full items-center justify-between rounded-md px-4 py-2 text-left text-sm transition-colors hover:cursor-pointer hover:bg-[#0000000A] ${f.isDanger?"text-red-600 hover:bg-red-50":"text-gray-700"}`,children:[jsxs("div",{className:"flex items-center gap-3",children:[f.icon,jsx("span",{className:`font-medium ${f.isDanger?"text-[#E92222]":"text-[#00000099]"}`,children:f.label})]}),f.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"})})]},l))})});return createPortal(m,document.body)};var bu=({x:e,y:o,items:t,onClose:a})=>{let s=useRef(null);return useEffect(()=>{let r=n=>{s.current&&!s.current.contains(n.target)&&a();};return document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r);}},[a]),jsx("div",{ref:s,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((r,n)=>jsx("button",{onClick:()=>{r.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:r.label})},n))})})};var yu=createContext(null),Wi=()=>useContext(yu);function Jh({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(yu.Provider,{value:s,children:jsxs("div",{className:`konva-editor-root ${o}`.trim(),style:t,children:[e,jsx("div",{ref:a,id:"konva-modal-portal"})]})})}function $e(){let e=Wi();return typeof document>"u"?null:e||document.body}var wu=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,i]=useState(a),d=useRef(null),u=$e();useEffect(()=>{d.current?.focus();},[]);let m=()=>{s(n),r();},f=c=>{c.key==="Enter"?m():c.key==="Escape"&&r();};return u?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex min-h-screen items-center justify-center bg-black/50 p-4",children:jsxs("div",{className:"my-auto w-full max-w-md rounded-lg bg-white p-4 shadow-2xl sm:p-6",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:r,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsxs("div",{className:"mb-6",children:[jsx("label",{className:"mb-2 block text-sm font-medium text-gray-700",children:o}),jsx("input",{ref:d,type:"text",value:n,onChange:c=>i(c.target.value),onKeyDown:f,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:r,className:"rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{onClick:m,className:"rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Save"})]})]})}),u):null};var Fs=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=$e();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let i=f=>{f.preventDefault(),o(a);},d=(f,l,c)=>{c/=100;let p=l*Math.min(c,1-c)/100,v=h=>{let x=(h+f/30)%12,b=c-p*Math.max(Math.min(x-3,9-x,1),-1);return Math.round(255*b).toString(16).padStart(2,"0")};return `#${v(0)}${v(8)}${v(4)}`},u=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#096B76","#2C3E50","#E74C3C","#3498DB","#2ECC71","#F39C12","#9B59B6","#1ABC9C"];if(!n)return null;let m=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",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:r,className:"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 Color"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsxs("form",{onSubmit:i,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=>s(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=>s(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 l=parseInt(f.target.value),c=d(l,100,50);s(c);},className:"h-3 w-full cursor-pointer appearance-none rounded-full",style:{background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)"}})]}),jsxs("div",{children:[jsx("label",{className:"mb-2 block text-xs font-semibold text-gray-500",children:"PRESET COLORS"}),jsx("div",{className:"grid grid-cols-8 gap-2",children:u.map(f=>jsx("button",{type:"button",onClick:()=>s(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(m,n)};var gg=({imageSrc:e,onCrop:o})=>{let[t]=Iu(e),a=useRef(null),s=useRef(null),r=useRef(null),n=useMemo(()=>{if(!t)return {width:600,height:400};let p=Math.min(600/t.width,400/t.height);return {width:t.width*p,height:t.height*p}},[t]),i=useMemo(()=>{let l=n.width*.5,c=n.height*.5,p=(n.width-l)/2,v=(n.height-c)/2;return {x:p,y:v,width:l,height:c}},[n]),[d,u]=useState(i);useEffect(()=>{u(i);},[i]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[d]),useEffect(()=>{o(d.x,d.y,d.width,d.height);},[d,o]);let m=()=>{let l=s.current;if(!l)return;let c=l.scaleX(),p=l.scaleY();l.scaleX(1),l.scaleY(1),u({x:l.x(),y:l.y(),width:Math.max(20,l.width()*c),height:Math.max(20,l.height()*p)});},f=()=>{let l=s.current;l&&u({x:l.x(),y:l.y(),width:l.width(),height:l.height()});};return jsx(Stage,{width:n.width,height:n.height,className:"border border-gray-300",children:jsxs(Layer,{children:[jsx(Image$1,{ref:a,image:t,width:n.width,height:n.height}),jsx(Rect,{x:0,y:0,width:n.width,height:n.height,fill:"rgba(0, 0, 0, 0.5)",globalCompositeOperation:"source-over"}),jsx(Rect,{x:d.x,y:d.y,width:d.width,height:d.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:d.x,y:d.y,width:d.width,height:d.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:f,onTransformEnd:m,dragBoundFunc:l=>{let c=Math.max(0,Math.min(l.x,n.width-d.width)),p=Math.max(0,Math.min(l.y,n.height-d.height));return {x:c,y:p}}}),jsx(Transformer,{ref:r,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:(l,c)=>c.width<20||c.height<20||c.x<0||c.y<0||c.x+c.width>n.width||c.y+c.height>n.height?l:c})]})})},Cu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=Iu(e),i=$e();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let d=(f,l,c,p)=>{r({x:f,y:l,width:c,height:p});},u=()=>{if(!n)return;let c=Math.min(600/n.width,400/n.height),p=s.x/c,v=s.y/c,h=s.width/c,x=s.height/c,b=document.createElement("canvas");b.width=h,b.height=x;let g=b.getContext("2d");if(!g)return;g.drawImage(n,p,v,h,x,0,0,h,x);let L=b.toDataURL("image/png");o(L);};return i?createPortal(jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",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:"max-h-[90vh] w-auto max-w-[90vw] overflow-y-auto rounded-xl border border-gray-200 bg-white p-6 shadow-2xl",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"mb-4 flex items-center justify-between",children:[jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"Crop Image"}),jsx("button",{onClick:t,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("div",{className:"mb-4 text-sm text-gray-600",children:"Drag the corners to resize the crop area, or drag the rectangle to move it."}),jsx("div",{className:"mb-6",children:jsx(gg,{imageSrc:e,onCrop:d})}),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:u,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"]})]})]})}),i):null};var dr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let s=$e(),[r,n]=useState(false),[i,d]=useState(null),[u,m]=useState(0),[f,l]=useState(true),c=useRef(null),p=useRef([]),v=useRef(null),h=useRef(null),x=useRef(null),b=useRef(null),g=useRef(null),L=useRef(null);useEffect(()=>()=>{x.current&&cancelAnimationFrame(x.current),v.current&&clearInterval(v.current),h.current&&h.current.getTracks().forEach(E=>E.stop());},[]);let C=async()=>{try{let E,T=null;if(o?.current){console.log("Creating recording canvas from Konva stage...");let D=o.current.getLayers();console.log("Konva layers:",D.length),D.forEach((U,Y)=>{let Z=U.getChildren();console.log(`Layer ${Y} children count:`,Z.length);});let ee=document.createElement("canvas");ee.width=o.current.width(),ee.height=o.current.height();let N=ee.getContext("2d",{willReadFrequently:!1});if(!N){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",ee.width,"x",ee.height),g.current=ee;let se=()=>{if(N.clearRect(0,0,ee.width,ee.height),D.forEach(U=>{let Y=U.getCanvas()._canvas;Y&&N.drawImage(Y,0,0);}),a?.current){let U=a.current;N.drawImage(U,0,0);}};L.current=se,o.current.draw(),se(),await new Promise(U=>setTimeout(U,100)),console.log("Creating captureStream..."),E=ee.captureStream(30),console.log("Canvas stream created, tracks:",E.getTracks().length);let q=E.getVideoTracks()[0];q&&console.log("Video track:",q.label,"state:",q.readyState);let j=0,H=()=>{se(),o?.current&&(o.current.getLayers().forEach(Y=>{Y.batchDraw();}),j++,j%60===0&&console.log("Drawing frame:",j)),x.current=requestAnimationFrame(H);};H();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{T=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(D){console.warn("Microphone access denied:",D);}let V=[...E.getVideoTracks()];T&&V.push(...T.getAudioTracks());let z=new MediaStream(V);h.current=z;let R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8"),console.log("Using mimeType:",R);let G=new MediaRecorder(z,{mimeType:R,videoBitsPerSecond:25e5});c.current=G,p.current=[],G.ondataavailable=D=>{console.log("Data available, size:",D.data.size),D.data.size>0&&p.current.push(D.data);},G.onstop=()=>{console.log("Recording stopped, chunks:",p.current.length);let D=new Blob(p.current,{type:R});console.log("Final blob size:",D.size),o?.current&&L.current&&g.current&&(o.current.draw(),o.current.getLayers().forEach(N=>{N.batchDraw();}),L.current(),b.current=g.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",b.current.length)),z.getTracks().forEach(ee=>ee.stop()),v.current&&clearInterval(v.current),x.current&&(cancelAnimationFrame(x.current),x.current=null),d(D);},G.onerror=D=>{console.error("MediaRecorder error:",D);},console.log("Starting recording..."),G.start(1e3),n(!0),m(0),v.current=setInterval(()=>{m(D=>D+1);},1e3);}catch(E){console.error("Error starting screen recording:",E),alert("Failed to start recording. Please ensure you granted permission.");}},S=()=>{c.current&&r&&(console.log("Stopping recording, state:",c.current.state),c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),n(false));},k=()=>{if(i){let E=URL.createObjectURL(i),T=document.createElement("a");T.href=E,T.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(E);}},y=E=>{let T=Math.floor(E/60),V=E%60;return `${T.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};if(!s)return null;if(r){let E=jsxs("div",{className:"fixed top-4 left-1/2 z-50 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:y(u)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording canvas..."}),jsxs("button",{onClick:S,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]});return createPortal(E,s)}let A=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-6 shadow-2xl",children:[jsxs("div",{className:"mb-2 flex items-center justify-between",children:[jsx("h2",{className:"text-xl font-bold text-[#000000CC]",children:"Screen Recording"}),jsx("button",{onClick:e,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$1,{className:"h-5 w-5 text-[#00000099]"})})]}),jsxs("div",{className:"mb-6",children:[!i&&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:()=>l(!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:C,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"]})]})]}),i&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(i),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",y(u)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&i&&b.current&&(t(i,b.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:()=>{d(null),m(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."]})})]})});return createPortal(A,s)};var Au=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=$e(),[n,i]=useState(false),[d,u]=useState(null),[m,f]=useState(false),[l,c]=useState(0),p=useRef(null),v=useRef([]),h=useRef(null),x=useRef(null);useEffect(()=>{o&&!d&&fetch(o).then(E=>E.blob()).then(E=>u(E)).catch(E=>console.error("Error loading audio:",E));},[o,d]);let b=async()=>{try{let E=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),T=new MediaRecorder(E);p.current=T,v.current=[],T.ondataavailable=V=>{V.data.size>0&&v.current.push(V.data);},T.onstop=()=>{let V=new Blob(v.current,{type:"audio/webm"});u(V),E.getTracks().forEach(z=>z.stop()),h.current&&clearInterval(h.current);},T.start(),i(!0),c(0),h.current=setInterval(()=>{c(V=>V+1);},1e3);}catch(E){console.error("Error starting audio recording:",E),alert("Failed to start recording. Please allow microphone access.");}},g=()=>{p.current&&n&&(p.current.stop(),i(false));},L=()=>{if(d){let E=URL.createObjectURL(d),T=new Audio(E);x.current=T,T.onended=()=>{f(false),URL.revokeObjectURL(E);},T.play(),f(true);}},C=()=>{x.current&&(x.current.pause(),x.current.currentTime=0,f(false));},S=async()=>{if(d){let E=new FileReader;E.onloadend=()=>{let T=E.result;t(T),s();},E.readAsDataURL(d);}},k=()=>{u(null),a();},y=E=>{let T=Math.floor(E/60),V=E%60;return `${T.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`};if(!r)return null;if(n){let E=jsx("div",{className:"pointer-events-none fixed inset-0 z-50",children:jsxs("div",{className:"pointer-events-auto fixed top-[100px] left-1/2 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:y(l)})]}),jsx("div",{className:"h-6 w-px bg-gray-300"}),jsx("span",{className:"text-sm text-gray-600",children:"Recording audio..."}),jsxs("button",{onClick:g,className:"ml-2 flex items-center gap-2 rounded-full bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700",children:[jsx(Stop,{className:"h-4 w-4",weight:"fill"}),"Stop"]})]})});return createPortal(E,r)}let A=jsx("div",{className:"fixed inset-0 z-50 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:[!d&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:b,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"]})}),d&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?C:L,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"}),m?"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:S,className:"w-full rounded-lg bg-green-600 px-6 py-3 text-white transition-colors hover:bg-green-700",children:"Save Audio"})]}),jsx("button",{onClick:s,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"})]})]})});return createPortal(A,r)};var kt=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:i=90,containerRight:d=320})=>{let[u,m]=useState(false),f=useRef(null),l=v=>{if(v.stopPropagation(),u&&f.current)f.current.pause(),f.current.currentTime=0,m(false);else {let h=new Audio(e);f.current=h,h.onended=()=>{m(false);},h.onerror=()=>{console.error("Error playing audio"),m(false);},h.play(),m(true);}},c=(o+a)*s+r-15,p=t*s+n+i-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${u?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${c}px`,top:`${p}px`,width:"30px",height:"30px",zIndex:99},title:u?"Stop Audio":"Play Audio",children:u?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Ru=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),s=te(he),r=useMemo(()=>{if(!s)return [];let h=[];return s.images?.forEach(x=>{h.push({id:x.id,type:"image",name:"Image",timestamp:x.timestamp||0});}),s.videos?.forEach(x=>{h.push({id:x.id,type:"video",name:"Video",timestamp:x.timestamp||0});}),s.shapes?.forEach(x=>{h.push({id:x.id,type:"shape",name:`${x.type} Shape`,timestamp:x.timestamp||0});}),s.texts?.forEach(x=>{h.push({id:x.id,type:"text",name:x.text.substring(0,20)+(x.text.length>20?"...":""),timestamp:x.timestamp||0});}),s.flashcards?.forEach(x=>{h.push({id:x.id,type:"flashcard",name:`Flashcard (${x.images.length} images)`,timestamp:x.timestamp||0});}),s.photoFrames?.forEach(x=>{h.push({id:x.id,type:"photoFrame",name:"Photo Frame",timestamp:x.timestamp||0});}),s.multipleChoices?.forEach(x=>{h.push({id:x.id,type:"mcq",name:"Multiple Choice",timestamp:x.timestamp||0});}),s.trueFalses?.forEach(x=>{h.push({id:x.id,type:"trueFalse",name:"True/False",timestamp:x.timestamp||0});}),s.shortAnswers?.forEach(x=>{h.push({id:x.id,type:"shortAnswer",name:"Short Answer",timestamp:x.timestamp||0});}),s.LongAnswer?.forEach(x=>{h.push({id:x.id,type:"longAnswer",name:"Long Answer",timestamp:x.timestamp||0});}),s.fillInTheBlanks?.forEach(x=>{h.push({id:x.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:x.timestamp||0});}),s.lines?.forEach(x=>{x.id&&h.push({id:x.id,type:"line",name:"Drawn Line",timestamp:x.timestamp||0});}),h.sort((x,b)=>b.timestamp-x.timestamp)},[s]),[n,i]=useState(r),[d,u]=useState(false);useEffect(()=>{d||i(r);},[r]);let m=h=>{let x="h-5 w-5";switch(h){case "image":return jsx(Image$3,{className:x});case "video":return jsx(VideoCamera,{className:x});case "shape":return jsx(Shapes$1,{className:x});case "text":return jsx(TextT,{className:x});case "flashcard":return jsx(Cards$1,{className:x});case "photoFrame":return jsx(FrameCorners,{className:x});case "line":return jsx(Pen,{className:x});default:return jsx(Question,{className:x})}},c=h=>{u(true),i(h);},p=()=>{u(false);let h=Date.now();n.forEach((x,b)=>{let g=h-b;a(Qo({id:x.id,type:x.type,newTimestamp:g}));});},v=jsxs("div",{className:"konva-editor-root",children:[jsx("div",{className:"fixed inset-0 z-9999 bg-black/30",onClick:o}),jsxs("div",{className:"fixed top-1/2 left-1/2 z-10000 w-96 -translate-x-1/2 -translate-y-1/2 space-y-4 overflow-hidden rounded-lg border border-gray-200 bg-white p-4 shadow-2xl",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2 text-[#00000099]",children:[jsx(Stack$1,{className:"h-5 w-5 text-[#00000099]",weight:"fill"}),jsx("h3",{className:"text-lg font-semibold text-[#00000099]",children:"Layers"})]}),jsx("button",{onClick:o,className:"rounded-lg p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600",children:jsx(X$2,{className:"h-5 w-5 text-[#000000CC]",weight:"bold"})})]}),jsx("div",{className:"max-h-96 overflow-y-auto",children:n.length===0?jsx("div",{className:"p-8 text-center text-sm text-gray-500",children:"No elements on this slide"}):jsx(Reorder.Group,{axis:"y",values:n,onReorder:c,className:"space-y-1",children:n.map(h=>{let x=h.id===e;return jsxs(Reorder.Item,{value:h,onDragEnd:p,className:`flex cursor-grab items-center gap-2 rounded-lg p-3 transition-colors active:cursor-grabbing ${x?"border border-[#096B7633] bg-[#EBF6F7]":"border border-transparent hover:bg-[#0000000A]"}`,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-5 w-5",weight:"bold"})}),jsx("div",{className:"flex flex-1 cursor-pointer items-center gap-2",children:jsx("span",{onClick:()=>t(h.id,h.type),className:`font-medium ${x?"text-[#096B76]":"text-[#00000099]"}`,children:h.name})}),jsx("div",{className:`${x?"text-[#096B76]":"text-[#00000099]"}`,children:m(h.type)})]},h.id)})})}),jsxs("div",{className:"flex items-center justify-between border-t border-[#0000001A] pt-2 font-medium text-[#00000066]",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(WarningCircle,{className:"h-5 w-5",weight:"fill"}),jsx("p",{children:"Drag to reorder"})]}),jsxs("span",{children:[n.length," Layers"]})]})]})]});return createPortal(v,document.body)};var Eu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>{let n=useSelector(K=>K.toolbar.selectedTool),i=n==="pen"||n==="eraser",[d,u]=useState(new Set),[m,f]=useState(false),[l,c]=useState(null),p=useRef(null);useEffect(()=>{let K=p.current;if(K)return a.current.set(e.id,K),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),h=v.size>1,x=K=>{m||u(h?q=>{let j=new Set(q);return j.has(K)?j.delete(K):j.add(K),j}:new Set([K]));},b=()=>{d.size>0&&f(true);},g=()=>{f(false),u(new Set);},L=d.size===v.size&&Array.from(d).every(K=>v.has(K)),C=Array.from(d).filter(K=>v.has(K)),S=h&&C.length>0&&!L,k=()=>L?"\u2713 Correct! Great job! \u{1F389}":S?`\u26A0 Partially correct (${C.length}/${v.size})`:"\u2717 Try again!",y=()=>L?{bg:"#dcfce7",text:"#166534"}:S?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},A=55,E=8,T=24,V=60,z=60,R=h&&!m?25:0,G=e.data.feedbackMode==="practice"?48:0,D=12,ee=V+R+(m?z:0),N=e.data.responseOptions.options.length*(A+E),se=ee+N+D+G+T;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:s,onClick:K=>t(e.id),onTap:K=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:se,width:e.width,onTransformEnd:K=>o(e.id,K),onContextMenu:K=>{K.cancelBubble=true,r(K.evt,e.id,"mcq");}}),jsx(Text,{x:T+8,y:T,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-T*2,listening:false}),h&&!m&&e.data.feedbackMode==="practice"?jsx(Text,{x:T,y:T+35,text:`Select ${v.size} answers (${d.size}/${v.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-T*2,listening:false}):null,m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:T+24,y:V+R,width:e.width-T*2-40,height:z-20,fill:y().bg,cornerRadius:8}),jsx(Text,{x:T,y:V+R,width:e.width-T*2,height:z-20,text:k(),fontSize:16,fontStyle:"bold",fill:y().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((K,q)=>{let j=v.has(q),H=d.has(q),U=ee+q*(A+E),Y="#e5e7eb",Z="#ffffff",Q="#111827";return m&&j?(Y="#22c55e",Z="#dcfce7",Q="#1B9D2C"):m&&H&&!j?(Y="#ef4444",Z="#fee2e2",Q="#ef4444"):H&&(Y="#096B76",Z="#ECFFF8",Q="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:T+12,y:U+(A-20)/2,width:20,height:20,fill:H?"#096B76":"white",stroke:H?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:le=>{le.cancelBubble=true,x(q);},onTap:le=>{le.cancelBubble=true,x(q);}}),H&&jsx(Text,{x:T+12,y:U+(A-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:T+44,y:U,width:e.width-T*2-60,height:A,fill:Z,stroke:Y,strokeWidth:2,cornerRadius:8,onClick:le=>{le.cancelBubble=true,x(q);},onTap:le=>{le.cancelBubble=true,x(q);}}),jsx(Text,{x:T+60,y:U,width:e.width-T*2-80,height:A,text:K,fontSize:16,fill:Q,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:ee+e.data.responseOptions.options.length*(A+E)+12,children:[jsxs(Group,{onMouseDown:K=>{K.cancelBubble=true,c("check");},onMouseUp:K=>{K.cancelBubble=true,c(null),b();},onMouseLeave:K=>{K.cancelBubble=true,c(null);},onTouchStart:K=>{K.cancelBubble=true,c("check");},onTouchEnd:K=>{K.cancelBubble=true,c(null),b();},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:T+14,width:(e.width-T*2-24)/(m?2:1),height:48,fill:d.size===0||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:K=>K.cancelBubble=true,onTap:K=>K.cancelBubble=true}),jsx(Text,{x:T+14,width:(e.width-T*2-24)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-T*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),g();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),g();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:T,width:(e.width-T*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:K=>K.cancelBubble=true,onTap:K=>K.cancelBubble=true}),jsx(Text,{x:T,width:(e.width-T*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Eu.displayName="MultipleChoice";var Fu=Eu;var _i=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s})=>{let r=useDispatch(),n=useSelector(H=>H.toolbar.selectedTool),i=n==="pen"||n==="eraser",[d,u]=useState(false),[m,f]=useState(new Set),[l,c]=useState(false),[p,v]=useState(false),[h,x]=useState(0),b=340,g=100,L=window.innerWidth*.4,C=window.innerHeight*.5,S=b+20,k=g+60,y=L-40,A=C-300,E=useRef(null);useEffect(()=>{let H=E.current;if(H)return s.current.set(e.id,H),()=>{s.current.delete(e.id);}},[e.id]);let T=H=>{r(ca({id:e.id,x:H.target.x(),y:H.target.y()}));},V=H=>{let U=H.target,Y=U.x(),Z=U.y(),Q=window.innerWidth*.2,Ie=Y+Q>S&&Y<S+y&&Z+50>k&&Z<k+A;u(Ie);},z=(H,U)=>{let Y=U.target,Z=Y.x(),Q=Y.y(),le=window.innerWidth*.2,J=Z+le>S&&Z<S+y&&Q+50>k&&Q<k+A;f(J?Me=>new Set(Me).add(H):Me=>{let Be=new Set(Me);return Be.delete(H),Be}),u(false);},R=()=>{c(true);},G=()=>{c(false),f(new Set),x(H=>H+1);},D=new Set(e.data.responseOptions.correctIndex),ee=m.size===D.size&&Array.from(m).every(H=>D.has(H)),N=Array.from(m).filter(H=>D.has(H)),se=N.length>0&&!ee,K=()=>ee?"\u2713 Correct! Great job!":se?`\u26A0 Partially correct (${N.length}/${D.size})`:"\u2717 Try again!",q=()=>ee?{bg:"#dcfce7",text:"#166534"}:se?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},j=()=>l?ee?"#4CAF50":se?"#f59e0b":"#ef4444":d?"#4CAF50":"#075560";return jsxs(Group,{ref:E,name:"mcq-element",width:L,height:C,draggable:!i,listening:!i,...i?{}:{onClick:H=>a(e.id),onTap:H=>a(e.id),onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"mcq");}},children:[jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:T,children:[jsx(Rect,{fill:"white",stroke:d?"#4CAF50":"#e5e7eb",strokeWidth:d?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?C-100:C-50,width:L,shadowColor:d?"#4CAF50":"transparent",shadowBlur:d?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:y,height:A,fill:"#EBF6F7",stroke:j(),strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:A+18,width:y-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:A+20,width:y,height:60,text:K(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),m.size===0&&!l&&jsx(Text,{x:20,y:60,width:y,height:A-60,text:D.size>1?`Drop ${D.size} Correct Answers Here`:"Drop Here",fontSize:28,fontStyle:"bold",fill:"#075560",align:"center",verticalAlign:"middle"}),e.data.feedbackMode==="practice"?jsxs(Group,{x:20,y:l?C-200:C-160,children:[jsxs(Group,{onMouseDown:()=>{v(true),R();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),R();},onTouchEnd:()=>v(false),scaleX:p?.95:1,scaleY:p?.95:1,children:[jsx(Rect,{fill:"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]}),l&&jsxs(Group,{y:50,onMouseDown:G,onTouchStart:G,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:y}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:y,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null]}),e.data.responseOptions.options.map((H,U)=>{let Y=U%2,Z=Math.floor(U/2),Q=window.innerWidth*.2,le=50,Ie=10,J=m.has(U),Me=D.has(U),Be=l&&J,Et="transparent";return Be?Et=Me?"#4CAF50":"#ef4444":J&&(Et="#4CAF50"),jsxs(Group,{x:340+Y*(Q+Ie),y:g+C-80+Z*(le+Ie),draggable:!l,onDragMove:V,onDragEnd:oo=>z(U,oo),opacity:l&&!J?.5:1,children:[jsx(Rect,{width:Q-20,height:le,fill:"white",stroke:Et,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Q-20,height:le,text:H,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${U}-${h}`)})]})};_i.displayName="MultipleChoiceDragAndDrop";var Bu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Fu,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:i=>s(i,n.id),onContextMenu:r},n.id):jsx(_i,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r},n.id))});var Ou=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(D=>D.toolbar.selectedTool),i=n==="pen"||n==="eraser",[d,u]=useState(null),[m,f]=useState(false),[l,c]=useState(null),p=useRef(null);useEffect(()=>{let D=p.current;if(D)return a.current.set(e.id,D),()=>{a.current.delete(e.id);}},[e.id]);let v=()=>{d!==null&&f(true);},h=()=>{f(false),u(null);},x=e.data.responseOptions.correctAnswer,b=d===x,g=D=>{m||u(D);},L=()=>b?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>b?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},S=70,k=12,y=24,A=60,E=60,T=e.data.feedbackMode==="practice"?48:0,V=12,z=A+(m?E:0),R=2*(S+k),G=z+R+V+T+y;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...i?{}:{onDragEnd:D=>r(D,e.id),onClick:D=>t(e.id),onTap:D=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:G-20,width:e.width,onTransformEnd:D=>o(e.id,D),onContextMenu:D=>{D.cancelBubble=true,s(D.evt,e.id,"trueFalse");}}),jsx(Text,{x:y,y,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-y*2,listening:false}),m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:y,y:A,width:e.width-y*2,height:E-10,fill:C().bg,cornerRadius:8}),jsx(Text,{x:y,y:A,width:e.width-y*2,height:E-10,text:L(),fontSize:16,fontStyle:"bold",fill:C().text,align:"center",verticalAlign:"middle",listening:false})]}):null,jsx(Group,{children:[{label:"True",value:true},{label:"False",value:false}].map((D,ee)=>{let N=x===D.value,se=d===D.value,K=(e.width-y*3)/2,q=y+ee*(K+y),j=z,H=D.value===true,U=H?"#10b981":"#ef4444",Y="#ffffff",Z="#ffffff",Q="#e5e7eb";return m&&(N?(Z=H?"#f0fdf4":"#fef2f2",Q=H?"#86efac":"#fecaca"):se&&!N&&(Z="#fee2e2",Q="#ef4444")),se&&!m&&(Q="#096B76",Z="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:j,width:K,height:S+50,fill:Z,stroke:Q,strokeWidth:2,cornerRadius:12,onClick:le=>{le.cancelBubble=true,g(D.value);},onTap:le=>{le.cancelBubble=true,g(D.value);}}),jsx(Circle,{x:q+K/2,y:j+40,radius:28,fill:U,listening:false}),H?jsx(Text,{x:q+K/2-14,y:j+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+K/2-14,y:j+40-14,width:28,height:28,text:"\u2717",fontSize:28,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}),jsx(Text,{x:q,y:j+85,width:K,height:30,text:D.label,fontSize:18,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle",listening:false})]},D.label)})}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:z+2*(S+k),children:[jsxs(Group,{onMouseDown:D=>{D.cancelBubble=true,c("check");},onMouseUp:D=>{D.cancelBubble=true,c(null),v();},onMouseLeave:D=>{D.cancelBubble=true,c(null);},onTouchStart:D=>{D.cancelBubble=true,c("check");},onTouchEnd:D=>{D.cancelBubble=true,c(null),v();},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/(m?2:1),height:48,fill:d===null||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:D=>D.cancelBubble=true,onTap:D=>D.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/(m?2:1),height:48,text:m?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{x:(e.width-y*2)/2+8,onMouseDown:()=>c("reset"),onMouseUp:()=>{c(null),h();},onMouseLeave:()=>c(null),onTouchStart:()=>c("reset"),onTouchEnd:()=>{c(null),h();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:y,width:(e.width-y*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:D=>D.cancelBubble=true,onTap:D=>D.cancelBubble=true}),jsx(Text,{x:y,width:(e.width-y*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Ou.displayName="TrueFalse";var Nu=Ou;var px="#FFFFFF",$i=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),s=useSelector(U=>U.toolbar.selectedTool),r=s==="pen"||s==="eraser",[n,i]=useState(false),[d,u]=useState(null),[m,f]=useState(false),[l,c]=useState(false),[p,v]=useState(0),[h,x]=useState(false),b=340,g=100,L=window.innerWidth*.4,C=window.innerHeight*.5,S=L-40,k=C-300,y=20,A=60,E=S,T=k,V=L*.2-40,z=50,R=useRef(null),G=U=>{a(fa({id:e.id,x:U.target.x(),y:U.target.y()}));},D=U=>{let Y=U.target,Z=Y.x(),Q=Y.y(),le=Math.max(0,Math.min(Z+V,y+E)-Math.max(Z,y)),Ie=Math.max(0,Math.min(Q+z,A+T)-Math.max(Q,A)),J=le*Ie,Me=V*z;i(J/Me>=.5);},ee=(U,Y)=>{let Z=Y.target,Q=Z.x(),le=Z.y(),Ie=Math.max(0,Math.min(Q+V,y+E)-Math.max(Q,y)),J=Math.max(0,Math.min(le+z,A+T)-Math.max(le,A)),Me=Ie*J,Be=V*z;if(Me/Be>=.5)u(U);else return;i(false);},N=()=>{f(true);},se=()=>{f(false),u(null),v(U=>U+1);},K=e.data.responseOptions.correctAnswer,q=d===K,j=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",H=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:R,name:"trueFalse-element",width:L,height:C,draggable:!r,listening:!r,...r?{}:{onContextMenu:U=>{U.evt.preventDefault(),o(U.evt,e.id,"trueFalse");}},children:jsxs(Group,{x:b,y:g,rotation:e.rotation,onDragEnd:G,children:[jsx(Rect,{fill:"white",stroke:n?"#4CAF50":"#e5e7eb",strokeWidth:n?4:2,cornerRadius:12,height:m?C:e.data.feedbackMode==="practice"?C-50:C-100,width:L,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:L-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:S,height:k,fill:"transparent",stroke:n?"#4CAF50":"#075560",strokeWidth:3,dash:[10,10],cornerRadius:8}),m&&jsxs(Fragment,{children:[jsx(Rect,{x:20,y:60,width:S,height:60,fill:H().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:S,height:60,text:j(),fontSize:18,fontStyle:"bold",fill:H().text,align:"center",verticalAlign:"middle"})]}),d===null&&!m&&jsx(Text,{x:20,y:60,width:S,height:k-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:C-100,children:[jsxs(Group,{onMouseDown:()=>{d!==null&&(c(true),N());},onMouseUp:()=>c(false),onMouseLeave:()=>c(false),onTouchStart:()=>{d!==null&&(c(true),N());},onTouchEnd:()=>c(false),scaleX:l?.95:1,scaleY:l?.95:1,children:[jsx(Rect,{fill:d===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:se,onTouchStart:se,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:S}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:S,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((U,Y)=>{let Z=window.innerWidth*.2,Q=50,le=10,Ie=d===U.value,J=K===U.value,Me=m&&Ie,Be="transparent";return Me?Be=J?"#4CAF50":"#ef4444":Ie&&(Be="#4CAF50"),jsxs(Group,{x:16+Y*(Z+le),y:g+C-300,draggable:!m,onDragMove:D,onDragEnd:Et=>ee(U.value,Et),opacity:m&&!Ie?.5:1,children:[jsx(Rect,{width:Z-40,height:Q,fill:"#075560",stroke:Be,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Z-40,height:Q,text:U.label,fontSize:18,fontStyle:"bold",fill:px,align:"center",verticalAlign:"middle",listening:false})]},`${U.value}-${p}`)})]})})};$i.displayName="TrueFalseDragAndDrop";var Vu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Nu,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s},n.id):jsx($i,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r},n.id))});var xa=new WeakMap,ko=new WeakMap,hr={current:[]},Ji=false,pr=0,mr=new Set,Hs=new Map;function qu(e){let o=Array.from(e).sort((t,a)=>t instanceof qt&&t.options.deps.includes(a)?1:a instanceof qt&&a.options.deps.includes(t)?-1:0);for(let t of o){if(hr.current.includes(t))continue;hr.current.push(t),t.recompute();let a=ko.get(t);if(a)for(let s of a){let r=xa.get(s);r&&qu(r);}}}function xx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function bx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Us(e){if(pr>0&&!Hs.has(e)&&Hs.set(e,e.prevState),mr.add(e),!(pr>0)&&!Ji)try{for(Ji=!0;mr.size>0;){let o=Array.from(mr);mr.clear();for(let t of o){let a=Hs.get(t)??t.prevState;t.prevState=a,xx(t);}for(let t of o){let a=xa.get(t);a&&(hr.current.push(t),qu(a));}for(let t of o){let a=xa.get(t);if(a)for(let s of a)bx(s);}}}finally{Ji=false,hr.current=[],Hs.clear();}}function ht(e){pr++;try{e();}finally{if(pr--,pr===0){let o=mr.values().next().value;o&&Us(o);}}}function Hu(e){return typeof e=="function"}var jt=class{constructor(o,t){this.listeners=new Set,this.subscribe=a=>{var s,r;this.listeners.add(a);let n=(r=(s=this.options)==null?void 0:s.onSubscribe)==null?void 0:r.call(s,a,this);return ()=>{this.listeners.delete(a),n?.();}},this.prevState=o,this.state=o,this.options=t;}setState(o){var t,a,s;this.prevState=this.state,(t=this.options)!=null&&t.updateFn?this.state=this.options.updateFn(this.prevState)(o):Hu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Us(this);}};var qt=class e{constructor(o){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{let t=this.options.deps.length,a=new Array(t),s=new Array(t);for(let r=0;r<t;r++){let n=this.options.deps[r];a[r]=n.prevState,s[r]=n.state;}return this.lastSeenDepValues=s,{prevDepVals:a,currDepVals:s,prevVal:this.prevState??void 0}},this.recompute=()=>{var t,a;this.prevState=this.state;let s=this.getDepVals();this.state=this.options.fn(s),(a=(t=this.options).onUpdate)==null||a.call(t);},this.checkIfRecalculationNeededDeeply=()=>{for(let r of this.options.deps)r instanceof e&&r.checkIfRecalculationNeededDeeply();let t=false,a=this.lastSeenDepValues,{currDepVals:s}=this.getDepVals();for(let r=0;r<s.length;r++)if(s[r]!==a[r]){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,s;this.listeners.add(t);let r=(s=(a=this.options).onSubscribe)==null?void 0:s.call(a,t,this);return ()=>{this.listeners.delete(t),r?.();}},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 jt){let a=xa.get(t);a||(a=new Set,xa.set(t,a)),a.add(this);let s=ko.get(this);s||(s=new Set,ko.set(this,s)),s.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 jt){let a=xa.get(t);a&&a.delete(this);let s=ko.get(this);s&&s.delete(t);}}};function vx(e){return typeof e=="function"}function Zi(e,...o){return vx(e)?e(...o):e}function Uu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var ba,st,tt,gr,va,Ha,Zt,Mo,xr,Ws,br,To,Ua=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){Pe(this,ba,true);Pe(this,st);Pe(this,tt);Pe(this,gr);Pe(this,va);Pe(this,Ha);Pe(this,Zt);Pe(this,Mo);Pe(this,xr,0);Pe(this,Ws,5);Pe(this,br,()=>{this.debugLog("Connected to event bus"),Ce(this,Ha,true),this.debugLog("Emitting queued events",_(this,va)),_(this,va).forEach(o=>this.emitEventToBus(o)),Ce(this,va,[]),this.stopConnectLoop(),_(this,tt).call(this).removeEventListener("tanstack-connect-success",_(this,br));});Pe(this,To,()=>{if(_(this,tt).call(this).addEventListener("tanstack-connect-success",_(this,br)),_(this,xr)<_(this,Ws)){hd(this,xr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}_(this,tt).call(this).removeEventListener("tanstack-connect",_(this,To)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});Ce(this,st,o),Ce(this,ba,a),Ce(this,tt,this.getGlobalTarget),Ce(this,gr,t),this.debugLog(" Initializing event subscription for plugin",_(this,st)),Ce(this,va,[]),Ce(this,Ha,false),Ce(this,Zt,null),Ce(this,Mo,s);}startConnectLoop(){_(this,Zt)!==null||_(this,Ha)||(this.debugLog(`Starting connect loop (every ${_(this,Mo)}ms)`),Ce(this,Zt,setInterval(_(this,To),_(this,Mo))));}stopConnectLoop(){_(this,Zt)!==null&&(clearInterval(_(this,Zt)),Ce(this,Zt,null),this.debugLog("Stopped connect loop"));}debugLog(...o){_(this,gr)&&console.log(`\u{1F334} [tanstack-devtools:${_(this,st)}-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,st)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});_(this,tt).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{_(this,tt).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,ba)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!_(this,Ha)){this.debugLog("Bus not available, will be pushed as soon as connected"),_(this,va).push({type:`${_(this,st)}:${o}`,payload:t,pluginId:_(this,st)}),typeof CustomEvent<"u"&&(_(this,To).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${_(this,st)}:${o}`,payload:t,pluginId:_(this,st)})}on(o,t){let a=`${_(this,st)}:${o}`;if(!_(this,ba))return this.debugLog("Event bus client is disabled, not registering event",a),()=>{};let s=r=>{this.debugLog("Received event from bus",r.detail),t(r.detail);};return _(this,tt).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{_(this,tt).call(this).removeEventListener(a,s);}}onAll(o){if(!_(this,ba))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return _(this,tt).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,tt).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!_(this,ba))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;_(this,st)&&s.pluginId!==_(this,st)||o(s);};return _(this,tt).call(this).addEventListener("tanstack-devtools-global",t),()=>_(this,tt).call(this).removeEventListener("tanstack-devtools-global",t)}};ba=new WeakMap,st=new WeakMap,tt=new WeakMap,gr=new WeakMap,va=new WeakMap,Ha=new WeakMap,Zt=new WeakMap,Mo=new WeakMap,xr=new WeakMap,Ws=new WeakMap,br=new WeakMap,To=new WeakMap;var Qi=class extends Ua{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Wu=(e,o)=>{el.emit(e,o);},el=new Qi;function zu(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var yx={enabled:true,leading:true,trailing:true,wait:0},ya,gt,Wa,za,Ga,Ao,zs=class{constructor(o,t){Pe(this,ya);Pe(this,gt);Pe(this,Wa);Pe(this,za);Pe(this,Ga);Pe(this,Ao);this.fn=o,this.store=new jt(zu()),this.setOptions=a=>{this.options={...this.options,...a},_(this,Wa).call(this)||this.cancel();},Ce(this,gt,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:_(this,Wa).call(this)?n?"pending":"idle":"disabled"}}),Wu("Throttler",this);}),Ce(this,Wa,()=>!!Zi(this.options.enabled,this)),Ce(this,za,()=>Zi(this.options.wait,this)),this.maybeExecute=(...a)=>{_(this,gt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=_(this,za).call(this);if(this.options.leading&&r>=n)_(this,Ga).call(this,...a);else if(_(this,gt).call(this,{lastArgs:a}),!_(this,ya)&&this.options.trailing){let i=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,d=n-i;_(this,gt).call(this,{isPending:true}),Ce(this,ya,setTimeout(()=>{let{lastArgs:u}=this.store.state;u!==void 0&&_(this,Ga).call(this,...u);},d));}},Ce(this,Ga,(...a)=>{if(!_(this,Wa).call(this))return;this.fn(...a);let s=Date.now(),r=s+_(this,za).call(this);_(this,Ao).call(this),_(this,gt).call(this,{executionCount:this.store.state.executionCount+1,lastExecutionTime:s,nextExecutionTime:r,isPending:false,lastArgs:void 0}),this.options.onExecute?.(a,this),setTimeout(()=>{this.store.state.isPending||_(this,gt).call(this,{nextExecutionTime:void 0});},_(this,za).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&_(this,Ga).call(this,...this.store.state.lastArgs);},Ce(this,Ao,()=>{_(this,ya)&&(clearTimeout(_(this,ya)),Ce(this,ya,void 0));}),this.cancel=()=>{_(this,Ao).call(this),_(this,gt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{_(this,gt).call(this,zu());},this.key=Uu(t.key),this.options={...yx,...t},_(this,gt).call(this,this.options.initialState??{}),el.on("d-Throttler",a=>{a.payload.key===this.key&&(_(this,gt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};ya=new WeakMap,gt=new WeakMap,Wa=new WeakMap,za=new WeakMap,Ga=new WeakMap,Ao=new WeakMap;function tl(e,o){return new zs(e,o).maybeExecute}function wa(e,o){return typeof e=="function"?e(o):e}function La(e,o){return js(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Po(e,o,t){let a=js(o);function s(r){if(!a.length)return wa(t,r);let n=a.shift();if(typeof n=="string"||typeof n=="number"&&!Array.isArray(r))return typeof r=="object"?(r===null&&(r={}),{...r,[n]:s(r[n])}):{[n]:s()};if(Array.isArray(r)&&typeof n=="number"){let i=r.slice(0,n);return [...i.length?i:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function ol(e,o){let t=js(o);function a(s){if(!s)return;if(t.length===1){let n=t[0];if(Array.isArray(s)&&typeof n=="number")return s.filter((u,m)=>m!==n);let{[n]:i,...d}=s;return d}let r=t.shift();if(typeof r=="string"&&typeof s=="object")return {...s,[r]:a(s[r])};if(typeof r=="number"&&Array.isArray(s)){if(r>=s.length)return s;let n=s.slice(0,r);return [...n.length?n:new Array(r),a(s[r]),...s.slice(r+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}return a(e)}var wx=/^(\d+)$/gm,Lx=/\.(\d+)(?=\.)/gm,Sx=/^(\d+)\./gm,Ix=/\.(\d+$)/gm,Cx=/\.{2,}/gm,al="__int__",Gs=`${al}$1`;function js(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(wx,Gs).replace(Lx,`.${Gs}.`).replace(Sx,`${Gs}.`).replace(Ix,`.${Gs}`).replace(Cx,".").split(".").map(o=>{if(o.startsWith(al)){let t=o.substring(al.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function rl(e){return !(Array.isArray(e)&&e.length===0)}function Do(e,o){let t=a=>a.validators.filter(Boolean).map(s=>({cause:s.cause,validate:s.fn}));return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:false},runValidation:t})}function Ro(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,i=d=>d.validators.filter(Boolean).map(u=>{let m=u?.cause||e,f=n;switch(m){case "change":f=s??n;break;case "blur":f=a??n;break;case "dynamic":f=r??n;break;case "submit":f=0;break}return e==="submit"&&(f=0),{cause:m,validate:u.fn,debounceMs:f}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:i})}var vr=e=>!!e&&typeof e=="object"&&"fields"in e;function Sa(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[s,r]of e)if(!o.has(s)||!Object.is(r,o.get(s)))return false;return true}if(e instanceof Set&&o instanceof Set){if(e.size!==o.size)return false;for(let s of e)if(!o.has(s))return false;return true}let t=Object.keys(e),a=Object.keys(o);if(t.length!==a.length)return false;for(let s of t)if(!a.includes(s)||!Sa(e[s],o[s]))return false;return true}var Xs=({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},$s=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function _e(e,o){return e==null?o:{...e,...o}}var Ka=256,_s=[],Ks;for(;Ka--;)_s[Ka]=(Ka+256).toString(16).substring(1);function sl(){let e=0,o,t="";if(!Ks||Ka+16>256){for(Ks=new Array(256),e=256;e--;)Ks[e]=256*Math.random()|0;e=0,Ka=0;}for(;e<16;e++)o=Ks[Ka+e],e===6?t+=_s[o&15|64]:e===8?t+=_s[o&63|128]:t+=_s[o],e&1&&e>1&&e<11&&(t+="-");return Ka++,t}var Ia=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"},s={fn:o?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},r={fn:o?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},n=o?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case "mount":return e.runValidation({validators:[t],form:e.form});case "submit":return e.runValidation({validators:[a,s,r,n],form:e.form});case "server":return e.runValidation({validators:[],form:e.form});case "blur":return e.runValidation({validators:[s,n],form:e.form});case "change":return e.runValidation({validators:[a,n],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};function kx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let i=0;i<s.length;i++){let d=s[i];if(d===void 0)continue;let u=typeof d=="object"?d.key:d,m=Number(u);Array.isArray(r)&&!Number.isNaN(m)?n+=`[${m}]`:n+=(i>0?".":"")+String(u),typeof r=="object"&&r!==null?r=r[u]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var Gu=(e,o)=>{let t=kx(e,o);return {form:t,fields:t}},Ca={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:Gu(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:Gu(a.issues,e)}},Ys=e=>!!e&&"~standard"in e;var Eo={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function yr(e){function o(f,l,c,p){let v=a(f,l,c,p);({insert:()=>i(v,f,l),remove:()=>d(v),swap:()=>p!==void 0&&m(v,f,l,p),move:()=>p!==void 0&&u(v,f,l,p)})[c]();}function t(f,l){return `${f}[${l}]`}function a(f,l,c,p){let v=[t(f,l)];if(c==="swap")v.push(t(f,p));else if(c==="move"){let[h,x]=[Math.min(l,p),Math.max(l,p)];for(let b=h;b<=x;b++)v.push(t(f,b));}else {let h=e.getFieldValue(f),x=Array.isArray(h)?h.length:0;for(let b=l+1;b<x;b++)v.push(t(f,b));}return Object.keys(e.fieldInfo).filter(h=>v.some(x=>h.startsWith(x)))}function s(f,l){return f.replace(/\[(\d+)\]/,(c,p)=>{let v=parseInt(p,10);return `[${l==="up"?v+1:Math.max(0,v-1)}]`})}function r(f,l){(l==="up"?f:[...f].reverse()).forEach(p=>{let v=s(p.toString(),l),h=e.getFieldMeta(v);h?e.setFieldMeta(p,h):e.setFieldMeta(p,n());});}let n=()=>Eo,i=(f,l,c)=>{r(f,"down"),f.forEach(p=>{p.toString().startsWith(t(l,c))&&e.setFieldMeta(p,n());});},d=f=>{r(f,"up");},u=(f,l,c,p)=>{let v=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,c))).map(h=>[h,e.getFieldMeta(h)]));r(f,c<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,p))).forEach(h=>{let x=h.replace(t(l,p),t(l,c)),b=v.get(x);b&&e.setFieldMeta(h,b);});},m=(f,l,c,p)=>{f.forEach(v=>{if(!v.toString().startsWith(t(l,c)))return;let h=v.toString().replace(t(l,c),t(l,p)),[x,b]=[e.getFieldMeta(v),e.getFieldMeta(h)];x&&e.setFieldMeta(h,x),b&&e.setFieldMeta(v,b);});};return {handleArrayFieldMetaShift:o}}var nl=class extends Ua{constructor(){super({pluginId:"form-devtools"});}},xt=new nl;function il(e){return {values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??false,isSubmitting:e.isSubmitting??false,isValidating:e.isValidating??false,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??false,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Lr=class{constructor(o){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{let a=this.fieldMetaDerived.mount(),s=this.store.mount(),r=()=>{a(),s(),xt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n&&this.validateSync("mount"),r},this.update=a=>{if(!a)return;let s=this.options;this.options=a;let r=!!a.transform?.deps?.some((d,u)=>d!==this.prevTransformArray[u]),n=a.defaultValues&&!Sa(a.defaultValues,s.defaultValues)&&!this.state.isTouched,i=!Sa(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!i&&!r||(ht(()=>{this.baseStore.setState(()=>il(Object.assign({},this.state,i?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}));},this.reset=(a,s)=>{let{fieldMeta:r}=this.state,n=this.resetFieldMeta(r);a&&!s?.keepDefaultValues&&(this.options={...this.options,defaultValues:a}),this.baseStore.setState(()=>il({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return ht(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let i=n.instance;s.push(Promise.resolve().then(()=>i.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(d=>({...d,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null,d=[`${a}[${s}]`];for(let l=s+1;l<=(i??0);l++)d.push(`${a}[${l}]`);let u=Object.keys(this.fieldInfo).filter(l=>d.some(c=>l.startsWith(c))),m=[];return ht(()=>{u.forEach(l=>{m.push(Promise.resolve().then(()=>this.validateField(l,r)));});}),(await Promise.all(m)).flat()},this.validateField=(a,s)=>{let r=this.fieldInfo[a]?.instance;return r?(r.state.meta.isTouched||r.setMeta(n=>({...n,isTouched:true})),r.validate(s)):[]},this.validateSync=a=>{let s=Do(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ia}),r=false,n={};return ht(()=>{for(let u of s){if(!u.validate)continue;let m=this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:f,fieldErrors:l}=Js(m),c=wr(u.cause);for(let p of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[p]===void 0)continue;let v=this.getFieldMeta(p);if(!v)continue;let{errorMap:h,errorSourceMap:x}=v,b=l?.[p],{newErrorValue:g,newSource:L}=Xs({newFormValidatorError:b,isPreviousErrorFromFormValidator:x?.[c]==="form",previousErrorValue:h?.[c]});L==="form"&&(n[p]={...n[p],[c]:b}),h?.[c]!==g&&this.setFieldMeta(p,C=>({...C,errorMap:{...C.errorMap,[c]:g},errorSourceMap:{...C.errorSourceMap,[c]:L}}));}this.state.errorMap?.[c]!==f&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[c]:f}})),(f||l)&&(r=!0);}let i=wr("submit");this.state.errorMap?.[i]&&a!=="submit"&&!r&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[i]:void 0}}));let d=wr("server");this.state.errorMap?.[d]&&a!=="server"&&!r&&this.baseStore.setState(u=>({...u,errorMap:{...u.errorMap,[d]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Ro(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ia});this.state.isFormValidating||this.baseStore.setState(u=>({...u,isFormValidating:true}));let r=[],n;for(let u of s){if(!u.validate)continue;let m=wr(u.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[m]={lastAbortController:l},r.push(new Promise(async c=>{let p;try{p=await new Promise((b,g)=>{setTimeout(async()=>{if(l.signal.aborted)return b(void 0);try{b(await this.runValidator({validate:u.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(L){g(L);}},u.debounceMs);});}catch(b){p=b;}let{formError:v,fieldErrors:h}=Js(p);h&&(n=n?{...n,...h}:h);let x=wr(u.cause);for(let b of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[b]===void 0)continue;let g=this.getFieldMeta(b);if(!g)continue;let{errorMap:L,errorSourceMap:C}=g,S=n?.[b],{newErrorValue:k,newSource:y}=Xs({newFormValidatorError:S,isPreviousErrorFromFormValidator:C?.[x]==="form",previousErrorValue:L?.[x]});L?.[x]!==k&&this.setFieldMeta(b,A=>({...A,errorMap:{...A.errorMap,[x]:k},errorSourceMap:{...A.errorSourceMap,[x]:y}}));}this.baseStore.setState(b=>({...b,errorMap:{...b.errorMap,[x]:v}})),c(n?{fieldErrors:n,errorMapKey:x}:void 0);}));}let i=[],d={};if(r.length){i=await Promise.all(r);for(let u of i)if(u?.fieldErrors){let{errorMapKey:m}=u;for(let[f,l]of Object.entries(u.fieldErrors)){let p={...d[f]||{},[m]:l};d[f]=p;}}}return this.baseStore.setState(u=>({...u,isFormValidating:false})),d},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>La(this.state.values,a),this.getFieldMeta=a=>this.state.fieldMeta[a],this.getFieldInfo=a=>{var s;return (s=this.fieldInfo)[a]||(s[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,s)=>{this.baseStore.setState(r=>({...r,fieldMetaBase:{...r.fieldMetaBase,[a]:wa(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Eo,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,i=r?.dontRunListeners??false,d=r?.dontValidate??false;ht(()=>{n||this.setFieldMeta(a,u=>({...u,isTouched:!0,isDirty:!0,errorMap:{...u?.errorMap,onMount:void 0}})),this.baseStore.setState(u=>({...u,values:Po(u.values,a,s)}));}),i||this.getFieldInfo(a).instance?.triggerOnChangeListener(),d||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let i=a.toString();return n!==i&&n.startsWith(i)}),a];this.baseStore.setState(n=>{let i={...n};return r.forEach(d=>{i.values=ol(i.values,d),delete this.fieldInfo[d],delete i.fieldMetaBase[d];}),i});},this.pushFieldValue=(a,s,r)=>{this.setFieldValue(a,n=>[...Array.isArray(n)?n:[],s],r);},this.insertFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,d=>[...d.slice(0,s),r,...d.slice(s)],_e(n,{dontValidate:true}));let i=n?.dontValidate??false;i||await this.validateField(a,"change"),yr(this).handleArrayFieldMetaShift(a,s,"insert"),i||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,d=>d.map((u,m)=>m===s?r:u),_e(n,{dontValidate:true})),(n?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.removeFieldValue=async(a,s,r)=>{let n=this.getFieldValue(a),i=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,u=>u.filter((m,f)=>f!==s),_e(r,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"remove"),i!==null){let u=`${a}[${i}]`;this.deleteField(u);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,d=>{let u=d[s],m=d[r];return Po(Po(d,`${s}`,m),`${r}`,u)},_e(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"swap",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.moveFieldValues=(a,s,r,n)=>{this.setFieldValue(a,d=>{let u=[...d];return u.splice(r,0,u.splice(s,1)[0]),u},_e(n,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"move",r),(n?.dontValidate??false)||(this.validateField(a,"change"),this.validateField(`${a}[${s}]`,"change"),this.validateField(`${a}[${r}]`,"change"));},this.clearFieldValues=(a,s)=>{let r=this.getFieldValue(a),n=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(a,[],_e(s,{dontValidate:true})),n!==null)for(let d=0;d<=n;d++){let u=`${a}[${d}]`;this.deleteField(u);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Eo},values:this.options.defaultValues?Po(s.values,a,La(this.options.defaultValues,a)):s.values}));},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((a,[s,r])=>(Object.keys(r).length&&r.errors.length&&(a[s]={errors:r.errors,errorMap:r.errorMap}),a),{})}),this.parseValuesWithSchema=a=>Ca.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>Ca.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??sl(),this._devtoolsSubmissionOverride=false,this.baseStore=new jt(il({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new qt({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,i=a?.[0],d=s[0],u=0,m={};for(let f of Object.keys(d.fieldMetaBase)){let l=d.fieldMetaBase[f],c=i?.fieldMetaBase[f],p=n?.[f],v=La(d.values,f),h=p?.errors;if(!c||l.errorMap!==c.errorMap){h=Object.values(l.errorMap??{}).filter(C=>C!==void 0);let L=this.getFieldInfo(f)?.instance;L&&!L.options.disableErrorFlat&&(h=h?.flat(1));}let x=!rl(h??[]),b=!l.isDirty,g=Sa(v,La(this.options.defaultValues,f))||Sa(v,this.getFieldInfo(f)?.instance?.options.defaultValue);if(p&&p.isPristine===b&&p.isValid===x&&p.isDefaultValue===g&&p.errors===h&&l===c){m[f]=p,u++;continue}m[f]={...l,errors:h,isPristine:b,isValid:x,isDefaultValue:g};}return Object.keys(d.fieldMetaBase).length&&n&&u===Object.keys(d.fieldMetaBase).length?n:m}}),this.store=new qt({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,i=a?.[0],d=s[0],u=s[1],m=Object.values(u).filter(Boolean),f=m.some(R=>R.isValidating),l=m.every(R=>R.isValid),c=m.some(R=>R.isTouched),p=m.some(R=>R.isBlurred),v=m.every(R=>R.isDefaultValue),h=c&&d.errorMap?.onMount,x=m.some(R=>R.isDirty),b=!x,g=!!(d.errorMap?.onMount||m.some(R=>R?.errorMap?.onMount)),L=!!f,C=n?.errors??[];(!i||d.errorMap!==i.errorMap)&&(C=Object.values(d.errorMap).reduce((R,G)=>G===void 0?R:G&&vr(G)?(R.push(G.form),R):(R.push(G),R),[]));let S=C.length===0,k=l&&S,y=this.options.canSubmitWhenInvalid??false,A=d.submissionAttempts===0&&!c&&!g||!L&&!d.isSubmitting&&k||y,E=d.errorMap;if(h&&(C=C.filter(R=>R!==d.errorMap.onMount),E=Object.assign(E,{onMount:void 0})),n&&i&&n.errorMap===E&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===f&&n.isFieldsValid===l&&n.isFormValid===S&&n.isValid===k&&n.canSubmit===A&&n.isTouched===c&&n.isBlurred===p&&n.isPristine===b&&n.isDefaultValue===v&&n.isDirty===x&&Sa(i,d))return n;let T={...d,errorMap:E,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:f,isFieldsValid:l,isFormValid:S,isValid:k,canSubmit:A,isTouched:c,isBlurred:p,isPristine:b,isDefaultValue:v,isDirty:x},V=this.options.transform?.deps??[];if(V.length!==this.prevTransformArray.length||V.some((R,G)=>R!==this.prevTransformArray[G])){let R=Object.assign({},this,{state:T});this.options.transform?.fn(R),T=R.state,this.prevTransformArray=V;}return T}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=tl(a=>xt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),xt.on("request-form-state",a=>{a.payload.id===this._formId&&xt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),xt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),xt.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 Ys(o.validate)?Ca[o.type](o.value,o.validate):o.validate(o.value)}async handleSubmit(o){this.baseStore.setState(s=>({...s,isSubmitted:false,submissionAttempts:s.submissionAttempts+1,isSubmitSuccessful:false})),ht(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance&&(s.instance.state.meta.isTouched||s.instance.setMeta(r=>({...r,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(s=>({...s,isSubmitting:true}));let a=()=>{this.baseStore.setState(s=>({...s,isSubmitting:false}));};if(await this.validateAllFields("submit"),!this.state.isFieldsValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(s=>s.errors).flat()});return}if(await this.validate("submit"),!this.state.isValid){a(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}ht(()=>{Object.values(this.fieldInfo).forEach(s=>{s.instance?.options.listeners?.onSubmit?.({value:s.instance.state.value,fieldApi:s.instance});});}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),ht(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),xt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){ht(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(vr(a)){let{formError:r,fieldErrors:n}=Js(a);for(let i of Object.keys(this.fieldInfo))this.getFieldMeta(i)&&this.setFieldMeta(i,u=>({...u,errorMap:{...u.errorMap,[s]:n?.[i]},errorSourceMap:{...u.errorSourceMap,[s]:"form"}}));this.baseStore.setState(i=>({...i,errorMap:{...i.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function Js(e){if(e){if(vr(e)){let o=Js(e.form).formError,t=e.fields;return {formError:o,fieldErrors:t}}return {formError:e}}return {formError:void 0}}function wr(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 Sr=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:s}=this.options.validators||{};if(s){let r=this.runValidator({validate:s,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});r&&this.setMeta(n=>({...n,errorMap:{...n?.errorMap,onMount:r},errorSourceMap:{...n?.errorSourceMap,onMount:"field"}}));}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),t},this.update=t=>{this.options=t;let a=this.name!==t.name;if(this.name=t.name,this.state.value===void 0){let s=La(t.form.options.defaultValues,t.name),r=t.defaultValue??s;a?this.setValue(n=>n||r,{dontUpdateMeta:true}):r!==void 0&&this.setValue(r,{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,_e(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,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,_e(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,_e(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,_e(t,{dontRunListeners:true})),t?.dontRunListeners||this.triggerOnChangeListener();},this.getLinkedFields=t=>{let a=Object.values(this.form.fieldInfo),s=[];for(let r of a){if(!r.instance)continue;let{onChangeListenTo:n,onBlurListenTo:i}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&i?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Do(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ia}),n=this.getLinkedFields(t).reduce((u,m)=>{let f=Do(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Ia});return f.forEach(l=>{l.field=m;}),u.concat(f)},[]),i=false;ht(()=>{let u=(m,f)=>{let l=Zs(f.cause),c=f.validate?Ku(m.runValidator({validate:f.validate,value:{value:m.store.state.value,validationSource:"field",fieldApi:m},type:"validate"})):void 0,p=a[l],{newErrorValue:v,newSource:h}=$s({formLevelError:p,fieldLevelError:c});m.state.meta.errorMap?.[l]!==v&&m.setMeta(x=>({...x,errorMap:{...x.errorMap,[l]:v},errorSourceMap:{...x.errorSourceMap,[l]:h}})),v&&(i=!0);};for(let m of s)u(this,m);for(let m of n)m.validate&&u(m.field,m);});let d=Zs("submit");return this.state.meta.errorMap?.[d]&&t!=="submit"&&!i&&this.setMeta(u=>({...u,errorMap:{...u.errorMap,[d]:void 0},errorSourceMap:{...u.errorSourceMap,[d]:void 0}})),{hasErrored:i}},this.validateAsync=async(t,a)=>{let s=Ro(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ia}),r=await a,n=this.getLinkedFields(t),i=n.reduce((l,c)=>{let p=Ro(t,{...c.options,form:c.form,validationLogic:c.form.options.validationLogic||Ia});return p.forEach(v=>{v.field=c;}),l.concat(p)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of n)l.setMeta(c=>({...c,isValidating:true}));let d=[],u=[],m=(l,c,p)=>{let v=Zs(c.cause);l.getInfo().validationMetaMap[v]?.lastAbortController.abort();let x=new AbortController;this.getInfo().validationMetaMap[v]={lastAbortController:x},p.push(new Promise(async b=>{let g;try{g=await new Promise((y,A)=>{this.timeoutIds.validations[c.cause]&&clearTimeout(this.timeoutIds.validations[c.cause]),this.timeoutIds.validations[c.cause]=setTimeout(async()=>{if(x.signal.aborted)return y(void 0);try{y(await this.runValidator({validate:c.validate,value:{value:l.store.state.value,fieldApi:l,signal:x.signal,validationSource:"field"},type:"validateAsync"}));}catch(E){A(E);}},c.debounceMs);});}catch(y){g=y;}if(x.signal.aborted)return b(void 0);let L=Ku(g),C=r[this.name]?.[v],{newErrorValue:S,newSource:k}=$s({formLevelError:C,fieldLevelError:L});l.setMeta(y=>({...y,errorMap:{...y?.errorMap,[v]:S},errorSourceMap:{...y.errorSourceMap,[v]:k}})),b(S);}));};for(let l of s)l.validate&&m(this,l,d);for(let l of i)l.validate&&m(l.field,l,u);let f=[];(d.length||u.length)&&(f=await Promise.all(d),await Promise.all(u)),this.setMeta(l=>({...l,isValidating:false}));for(let l of n)l.setMeta(c=>({...c,isValidating:false}));return f.filter(Boolean)},this.validate=(t,a)=>{if(!this.state.meta.isTouched)return [];let{fieldsErrorMap:s}=a?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(t),{hasErrored:r}=this.validateSync(t,s[this.name]??{});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Zs(t)]?.lastAbortController.abort(),this.state.meta.errors;let n=a?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(t);return this.validateAsync(t,n)},this.handleChange=t=>{this.setValue(t);},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(a=>({...a,isTouched:true})),this.state.meta.isBlurred||this.setMeta(a=>({...a,isBlurred:true})),this.validate("blur"),this.triggerOnBlurListener();},this.parseValueWithSchema=t=>Ca.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>Ca.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new qt({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Eo,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Ys(o.validate)?Ca[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 Ku(e){if(e)return e}function Zs(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 Qs(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Tx)}function Tx(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,s]of e)if(!o.has(a)||!Object.is(s,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=_u(e);if(t.length!==_u(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 _u(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Fo=typeof window<"u"?useLayoutEffect:useEffect;function Bx(e){let[o]=useState(()=>{let a=new Sr({...e,form:e.form,name:e.name});return a.Field=ll,a});return Fo(o.mount,[o]),Fo(()=>{o.update(e);}),Qs(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var ll=(({children:e,...o})=>{let t=Bx(o),a=useMemo(()=>wa(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function Vx({form:e,selector:o,children:t}){let a=Qs(e.store,o);return wa(t,a)}function dl(e){let o=useId(),[t]=useState(()=>{let a=new Lr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(ll,{...n,form:a})},s.Subscribe=function(n){return jsx(Vx,{form:a,selector:n.selector,children:n.children})},s});return Fo(t.mount,[]),Fo(()=>{t.update(e);}),t}function ul({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 Xx=({editElement:e})=>{let o=useDispatch(),t=useSelector(he),a=useRef(null),s=$e(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[i,d]=useState(n),u=dl({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:l})=>{if(l.questionType==="true-false"){let c={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctAnswer:l.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?fa(c):oi(c));}else if(l.questionType==="multiple-choice"){let c={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctIndex:l.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?ca(c):ai(c));}else if(l.questionType==="short-answer"){let c={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.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?$o(c):ri(c));}else if(l.questionType==="fill-in-the-blank"){let c={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctShortAnswer:l.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?Jo(c):ni(c));}else if(l.questionType==="long-answer"){let c={id:r?e.id:v4(),data:{questionType:l.questionType,responseType:l.responseType,feedbackMode:l.feedbackMode,question:l.question,responseOptions:{options:l.responseOptions.options,correctLongAnswer:l.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?Yo(c):si(c));}o(ma(false));}}),m=()=>{o(ma(false));};if(!s)return null;let f=jsx("div",{className:"fixed inset-0 z-50 flex w-full flex-col items-center justify-center gap-6 rounded-lg bg-black/50 p-2 shadow-lg sm:p-4 md:p-6",children:jsx("div",{ref:a,className:"scrollbar-hide h-fit max-h-[calc(100vh-16px)] w-full max-w-xl overflow-y-auto rounded-lg bg-white p-2 sm:max-h-[calc(100vh-80px)] sm:p-3 md:max-h-[calc(100vh-240px)] md:p-4",children:jsxs("form",{className:"relative flex h-fit max-h-[calc(100vh-50px)] w-full flex-col gap-1 rounded-lg bg-white p-2 sm:p-3 md:p-4",onSubmit:l=>{l.preventDefault(),l.stopPropagation(),u.handleSubmit();},children:[jsxs("div",{className:"flex items-center justify-between pb-2 sm:pb-3 md:pb-4",children:[jsxs("div",{className:"flex flex-col gap-0.5 pr-8 sm:gap-1 sm:pr-10",children:[jsx("h2",{className:"text-lg font-bold text-[#000000CC] sm:text-xl md:text-2xl",children:r?"Edit Question":"Create Question"}),jsx("p",{className:"text-xs font-semibold text-[#00000099] sm:text-sm md:text-base",children:"Design a new question for your lesson slide."})]}),jsx("button",{type:"button",className:"absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded bg-red-500 hover:cursor-pointer hover:bg-red-600 sm:h-8 sm:w-8",onClick:()=>{m();},children:jsx("span",{className:"text-lg text-white sm:text-xl",children:"\u2715"})})]}),jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:mb-4 sm:flex-row sm:gap-4 md:gap-6",children:[jsx(u.Field,{name:"questionType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Question Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:c=>{l.handleChange(c.target.value),d(c.target.value);},disabled:r,className:`outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base ${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-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",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-[10px] text-gray-500 italic sm:text-xs",children:"Question type cannot be changed when editing"}),jsx(ul,{field:l})]})}),i&&!["short-answer","fill-in-the-blank","long-answer"].includes(i)&&jsx(u.Field,{name:"responseType",children:l=>jsxs("div",{className:"flex w-full flex-col gap-1.5 sm:gap-2",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",children:"Response Type"}),jsxs("div",{className:"relative",children:[jsxs("select",{id:l.name,name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:c=>l.handleChange(c.target.value),className:"outline-primary/50 w-full appearance-none rounded-lg border border-gray-300 bg-white px-3 py-2 pr-9 text-xs font-semibold text-[#000000CC] sm:px-4 sm:py-2.5 sm:pr-10 sm:text-sm md:py-3 md:text-base",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-2 -translate-y-1/2 sm:right-3",children:jsx("svg",{className:"h-4 w-4 text-gray-400 sm:h-5 sm:w-5",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(ul,{field:l})]})})]}),jsx(u.Field,{name:"feedbackMode",children:l=>jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsxs("div",{className:`flex w-full items-center gap-1.5 rounded-lg bg-gray-100 p-1 sm:gap-2 sm:p-1.5 ${i==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:i==="long-answer",onClick:()=>l.handleChange("practice"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="practice"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(ScribbleLoop,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Practice Mode"})]}),jsxs("button",{type:"button",disabled:i==="long-answer",onClick:()=>l.handleChange("test"),className:`flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-all sm:gap-2 sm:px-3 sm:py-2 sm:text-sm md:px-4 md:text-base ${l.state.value==="test"?"text-primary bg-white":"text-gray-500"} `,children:[jsx(Exam,{weight:"fill",className:"h-3.5 w-3.5 sm:h-4 sm:w-4"}),jsx("span",{className:"whitespace-nowrap",children:"Assessment Mode"})]})]}),i==="long-answer"&&jsx("p",{className:"text-[10px] text-gray-500 italic sm:text-xs",children:"Long answer questions are only available in Assessment Mode"}),jsx(ul,{field:l})]})}),jsx(u.Field,{name:"question",validators:{onChange:({value:l})=>l?void 0:"A question is required"},children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm",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-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-2.5 sm:text-base md:py-3",value:l.state.value,onChange:c=>l.handleChange(c.target.value),onBlur:l.handleBlur,placeholder:"Enter Your Question"})}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),i==="true-false"&&jsx(u.Field,{name:"responseOptions.correctAnswer",children:l=>{let c=l.state.value;return jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{className:"text-xs font-semibold text-[#00000066] uppercase sm:text-sm md:text-base",children:"Set Correct Answer"}),jsxs("div",{className:"flex gap-2 sm:gap-3 md:gap-4",children:[jsxs("button",{type:"button",onClick:()=>l.handleChange(true),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===true?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(CheckCircle,{weight:"fill",color:"#45B389",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"True"}),c===true&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]}),jsxs("button",{type:"button",onClick:()=>l.handleChange(false),className:`relative flex flex-1 flex-col items-center justify-center rounded-xl border px-3 py-3 transition-all sm:px-4 sm:py-4 md:px-6 md:py-5 ${c===false?"border-green-500 bg-green-50":"border-[#096B76] bg-white hover:border-gray-400"}`,children:[jsx(XCircle,{weight:"fill",color:"#EE5454",className:"h-10 w-10 sm:h-12 sm:w-12 md:h-[52px] md:w-[52px]"}),jsx("span",{className:"mt-1 text-base font-semibold text-black sm:mt-2 sm:text-lg",children:"False"}),c===false&&jsx("span",{className:"absolute top-1.5 right-1.5 rounded-full bg-green-600 px-2 py-0.5 text-[10px] font-medium text-white sm:top-2 sm:right-2 sm:px-3 sm:text-xs",children:"Correct"})]})]}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Select the correct answer for this true/false question"})]})}}),i==="multiple-choice"&&jsx(u.Field,{name:"responseOptions",validators:{onChange:({value:l})=>{if(l.options.filter(p=>!p.trim()).length>0)return "All options must have text";if(!l.correctIndex||l.correctIndex.length===0)return "Please select at least one correct answer"}},children:l=>{let c=(x,b)=>{let g=[...l.state.value.options];g[x]=b,l.handleChange({...l.state.value,options:g});},p=()=>{if(l.state.value.options.length>=6){alert("Maximum 6 options allowed");return}l.handleChange({...l.state.value,options:[...l.state.value.options,""]});},v=x=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let b=l.state.value.options.filter((L,C)=>C!==x),g=l.state.value.correctIndex?.filter(L=>L!==x).map(L=>L>x?L-1:L);l.handleChange({...l.state.value,options:b,correctIndex:g});},h=x=>{let b=l.state.value.correctIndex||[];if(b.includes(x))l.handleChange({...l.state.value,correctIndex:b.filter(L=>L!==x)});else {if(b.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...b,x]});}};return jsxs("div",{className:"mb-3 flex flex-col gap-1.5 sm:mb-4 sm:gap-2",children:[jsx("div",{className:"flex items-center justify-between",children:jsxs("label",{htmlFor:l.name,className:"mb-1.5 text-sm font-semibold text-gray-900 sm:mb-2 sm:text-base",children:["Answer Options",jsx("span",{className:"text-[#00000066]",children:" (At least 2 options required)"})]})}),jsx("div",{className:"mb-2 flex flex-col gap-2 sm:mb-3 sm:gap-3 md:mb-4",children:l.state.value.options.map((x,b)=>{let g=!x.trim(),L=l.state.value.correctIndex?.includes(b),C=l.state.meta.isTouched&&g;return jsxs("div",{className:"flex w-full items-center gap-2 px-0.5 sm:gap-3 sm:px-1",children:[jsx("button",{type:"button",onClick:()=>h(b),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${L?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:L&&jsx("svg",{className:"h-2.5 w-2.5 text-white sm:h-3 sm:w-3",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-3 py-2 transition-colors sm:px-4 sm:py-2.5 md:py-3 ${C?"border-red-500 bg-red-50":L?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${b+1}`,value:x,onChange:S=>c(b,S.target.value),onBlur:l.handleBlur,className:"w-full flex-1 border-none bg-transparent text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base"})}),l.state.value.options.length>2&&jsx("button",{type:"button",onClick:()=>v(b),className:"shrink-0 text-[#00000066] transition-colors hover:cursor-pointer hover:text-red-600",children:jsx(Trash,{weight:"fill",className:"h-5 w-5 sm:h-6 sm:w-6"})})]},b)})}),jsx("button",{type:"button",onClick:p,disabled:l.state.value.options.length>=6,className:"mx-1 cursor-pointer rounded-lg border border-dashed border-[#00000033] px-3 py-2 text-base font-semibold text-[#00000066] disabled:cursor-not-allowed sm:mx-2 sm:py-2.5 sm:text-lg md:py-3",children:"+ Add Option"}),l.state.value.correctIndex.length===0||l.state.meta.errors.length>0?jsx("span",{className:"px-1 text-sm font-semibold text-red-500 sm:px-2 sm:text-base",children:l.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",className:"h-4 w-4 sm:h-5 sm:w-5"}),jsx("p",{className:"text-xs sm:text-sm md:text-base",children:"Correct answer selected"})]})]})}}),(i==="short-answer"||i==="fill-in-the-blank")&&jsx(u.Field,{name:"responseOptions.correctShortAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Correct Short Answer"}),jsx("input",{type:"text",placeholder:"Type the expected correct answer...",value:l.state.value,onChange:c=>{l.handleChange(c.target.value);},className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"Learners must write this answer exactly (case-insensitive)."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),i==="long-answer"&&jsx(u.Field,{name:"responseOptions.correctLongAnswer",children:l=>jsxs("div",{className:"mb-4 flex flex-col gap-1.5 sm:mb-5 sm:gap-2 md:mb-6",children:[jsx("label",{htmlFor:l.name,className:"text-xs font-semibold text-gray-900 sm:text-sm",children:"Expected Long Answer (Optional)"}),jsx("textarea",{placeholder:"Type the expected answer or key points...",value:l.state.value,onChange:c=>{l.handleChange(c.target.value);},rows:6,className:"outline-primary/50 w-full rounded-lg border-2 border-gray-300 bg-white p-2 text-sm text-gray-900 transition-colors sm:p-2.5 sm:text-base md:p-3"}),jsx("p",{className:"text-xs font-semibold text-gray-500 sm:text-sm",children:"This will be used as a reference answer for manual grading."}),l.state.meta.errors.length>0&&jsx("span",{className:"text-xs font-semibold text-red-500 sm:text-sm",children:l.state.meta.errors.join(", ")})]})}),jsx(u.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,c])=>jsx("button",{type:"submit",disabled:!l,className:"mt-1 mb-2 w-full rounded-lg bg-[#096B76] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[#075862] disabled:cursor-not-allowed disabled:opacity-50 sm:mt-2 sm:mb-3 sm:px-5 sm:py-2.5 sm:text-base md:mb-4 md:px-6 md:py-3",children:c?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,s)},$u=Xx;var Qu=({text:e,position:o})=>{let t=xe(),a=u=>{t(ce()),t(It({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+u))}));},s=u=>{t(ce()),t(It({id:e.id,fill:u}));},r=()=>{t(ce()),t(It({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ce()),t(It({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},i=()=>{t(ce()),t(It({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},d=u=>{t(ce()),t(It({id:e.id,fontFamily:u}));};return jsxs("div",{className:"fixed z-1001 flex flex-wrap items-center gap-1 rounded-lg border border-gray-200 bg-white p-1.5 shadow-2xl sm:flex-nowrap sm:p-2",style:{left:"50%",top:`${Math.max(60,o.y-60)}px`,transform:"translateX(-50%)",maxWidth:"calc(100vw - 2rem)"},onClick:u=>u.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:u=>d(u.target.value),className:"rounded border border-gray-300 bg-white px-1.5 py-0.5 text-xs hover:bg-gray-50 sm:px-2 sm:py-1",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:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsx("button",{onClick:()=>a(-2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Decrease font size",children:"\u2212"}),jsx("span",{className:"w-6 text-center text-xs font-medium sm:w-8",children:Math.round(e.fontSize)}),jsx("button",{onClick:()=>a(2),className:"flex h-6 w-6 items-center justify-center rounded text-sm font-bold hover:bg-gray-100 sm:h-7 sm:w-7",title:"Increase font size",children:"+"})]}),jsxs("div",{className:"flex items-center gap-0.5 border-l border-gray-200 pl-1",children:[jsxs("button",{onClick:r,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontWeight==="bold"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Bold",children:[jsx(TextB,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextB,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:n,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.fontStyle==="italic"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Italic",children:[jsx(TextItalic,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextItalic,{size:16,weight:"bold",className:"hidden sm:block"})]}),jsxs("button",{onClick:i,className:`flex h-6 w-6 items-center justify-center rounded transition-colors sm:h-7 sm:w-7 ${e.textDecoration==="underline"?"bg-blue-100 text-blue-600":"text-gray-700 hover:bg-gray-100"}`,title:"Underline",children:[jsx(TextUnderline,{size:14,weight:"bold",className:"sm:hidden"}),jsx(TextUnderline,{size:16,weight:"bold",className:"hidden sm:block"})]})]}),jsx("div",{className:"border-l border-gray-200 pl-1",children:jsx("input",{type:"color",value:e.fill,onChange:u=>s(u.target.value),className:"h-6 w-6 cursor-pointer rounded border border-gray-300 sm:h-7 sm:w-7",title:"Text color",style:{padding:"2px"}})})]})};var tc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{let i=useRef(null),d=useMemo(()=>({fontSize:`${e.fontSize*r}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,r]),u=useCallback(m=>{m.style.height="auto",m.style.height=`${m.scrollHeight}px`;let f=document.createElement("span");f.style.font=window.getComputedStyle(m).font,f.style.fontSize=m.style.fontSize,f.style.fontFamily=m.style.fontFamily,f.style.fontWeight=m.style.fontWeight,f.style.fontStyle=m.style.fontStyle,f.style.visibility="hidden",f.style.position="absolute",f.style.whiteSpace="pre";let l=m.value.split(`
4
+ `),c=0;document.body.appendChild(f);for(let v of l){f.textContent=v||" ";let h=f.offsetWidth;h>c&&(c=h);}document.body.removeChild(f);let p=10;m.style.width=`${Math.max(200,c+p+20)}px`;},[]);return useEffect(()=>{let m=i.current;m&&(m.style.fontSize=`${e.fontSize*r}px`,m.style.fontFamily=e.fontFamily,m.style.fontStyle=e.fontStyle,m.style.fontWeight=e.fontWeight==="bold"?"bold":"normal",m.style.textDecoration=e.textDecoration,m.style.color=e.fill,u(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,u]),jsx("div",{style:{position:"absolute",top:`${s.top}px`,left:`${s.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(i.current=m,n.current=m,m){m.focus();let f=m.value.length;m.setSelectionRange(f,f),u(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:d},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var ac=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(R=>R.toolbar.selectedTool),i=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,l]=useState(false),[c,p]=useState(null);useEffect(()=>{let R=d.current;if(R)return a.current.set(e.id,R),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===v,x=()=>{l(false),m("");},b=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},L=24,C=60,S=f?40:0,k=f?54:20,y=50,A=12,E=e.data.feedbackMode==="practice"?48:0,T=12,V=30,z=C+S+V+y+A+T+E+L;return jsxs(Group,{ref:d,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:z,name:"sa-element",...i?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:z,onTransformEnd:R=>t(e.id,R),onContextMenu:R=>{R.cancelBubble=true,s(R.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:C+S+V-k,width:e.width-L*2+4,height:y+6,fill:"#ffffff",stroke:h?"#22c55e":f?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+S+V-k},divProps:{style:{width:`${e.width-L*2-4}px`,height:`${y}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:R=>m(R.target.value),disabled:f,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:f?"none":"auto"}})}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C+80,width:e.width/2+24,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:36,y:C+80,width:e.width-L*2,height:S,text:b(),fontSize:12,fontStyle:"bold",fill:g().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C+S+V+y+A+T,children:[jsxs(Group,{onMouseDown:R=>{R.cancelBubble=true,p("check");},onMouseUp:R=>{R.cancelBubble=true,p(null),u.length>0&&l(true);},onMouseLeave:R=>{R.cancelBubble=true,p(null);},onTouchStart:R=>{R.cancelBubble=true,p("check");},onTouchEnd:R=>{R.cancelBubble=true,p(null),u.length>0&&l(true);},scaleX:c==="check"?.95:1,scaleY:c==="check"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/(f?2:1),height:48,fill:u.length===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.cancelBubble=true}),jsx(Text,{x:L,width:(e.width-L*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-L*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:(e.width-L*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:R=>R.cancelBubble=true,onTap:R=>R.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})]})]})]})});ac.displayName="ShortAnswer";var oc=ac;var sc=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(oc,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:i=>r(i,n.id)},n.id))});var nc=e=>{let o=useDispatch(),a=useSelector(he)?.fillInTheBlanks||[],s=useRef(new Map),r=useCallback((n,i)=>{let d=n.target;o(Jo({id:i,x:d.x(),y:d.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:s,handleFillInTheBlanksDragEnd:r}};var Tt=24,ml=51,Ar=64,ic=15,an=32,lc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:s,fibRefs:r})=>{let n=useSelector(y=>y.toolbar.selectedTool),i=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,l]=useState(false),[c,p]=useState(null);useEffect(()=>{let y=d.current;if(y)return r.current.set(e.id,y),()=>{r.current.delete(e.id);}},[e.id,r]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===v,x=()=>{l(false),m("");},b=()=>{u.length>0&&l(true);},g=e.width-Tt*2,L=(g-ic)/2,C=e.data.feedbackMode==="practice",S=useMemo(()=>{let y=Tt,A=y;y+=60;let E=y;y+=35;let T=y;y+=ml+16;let V=y;f&&(y+=an+16);let z=y;return C&&(y+=Ar),y+=Tt,{questionY:A,helperTextY:E,inputY:T,feedbackY:V,buttonsY:z,totalHeight:y}},[f,C]),k=()=>f?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:d,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...i?{}:{onDragEnd:y=>a(y,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:S.totalHeight,shadowColor:"rgba(0,0,0,0.1)",shadowBlur:10,shadowOffsetY:2,onTransformEnd:y=>t(e.id,y),onContextMenu:y=>{y.cancelBubble=true,s?.(y.evt,e.id,"fillInTheBlanks");}}),jsx(Text,{text:e.data.question.replace("_____","________"),x:Tt,y:S.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:g,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Tt,y:S.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:g,listening:false}),jsx(Rect,{x:Tt,y:S.inputY,width:g,height:ml,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Tt,y:S.inputY},divProps:{style:{width:`${g}px`,height:`${ml}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:u,onChange:y=>m(y.target.value),disabled:f,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"}})}),f&&jsxs(Group,{y:S.feedbackY,children:[jsx(Rect,{x:Tt,width:h?206:140,height:an,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Tt+10,y:0,width:16,height:an,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Tt+30,y:0,height:an,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),C&&jsxs(Group,{y:S.buttonsY,children:[jsxs(Group,{x:Tt,onMouseDown:y=>{y.cancelBubble=true,p("reset");},onMouseUp:y=>{y.cancelBubble=true,p(null),x();},onMouseLeave:y=>{y.cancelBubble=true,p(null);},onTouchStart:y=>{y.cancelBubble=true,p("reset");},onTouchEnd:y=>{y.cancelBubble=true,p(null),x();},scaleX:c==="reset"?.98:1,scaleY:c==="reset"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u21BB Reset",fontSize:18,fontStyle:"bold",fill:"rgba(0,0,0,0.6)",align:"center",verticalAlign:"middle",listening:false})]}),jsxs(Group,{x:Tt+L+ic,onMouseDown:y=>{y.cancelBubble=true,p("submit");},onMouseUp:y=>{y.cancelBubble=true,p(null),b();},onMouseLeave:y=>{y.cancelBubble=true,p(null);},onTouchStart:y=>{y.cancelBubble=true,p("submit");},onTouchEnd:y=>{y.cancelBubble=true,p(null),b();},scaleX:c==="submit"?.98:1,scaleY:c==="submit"?.98:1,children:[jsx(Rect,{width:L,height:Ar,fill:u.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:L,height:Ar,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});lc.displayName="FillInTheBlanks";var dc=lc;var cc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r})=>jsx(Fragment,{children:e.map(n=>jsx(dc,{fillInTheBlank:n,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r},n.id))});var xl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(z=>z.toolbar.selectedTool),i=n==="pen"||n==="eraser",d=useRef(null),[u,m]=useState(""),[f,l]=useState(false),[c,p]=useState(null);useEffect(()=>{let z=d.current;if(z)return a.current.set(e.id,z),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=f&&u.trim().toLowerCase()===v,x=()=>{l(false),m("");},b=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",g=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},L=24,C=60,S=f?60:0,k=120,y=12,A=48,E=12,T=30,V=C+S+T+k+y+E+A+L;return jsxs(Group,{ref:d,draggable:!i,listening:!i,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...i?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:z=>{let R=d.current?.getStage()?.getPointerPosition();if(!R||!s)return;let G={x:e.x,y:e.y,width:e.width,height:e.height};R.x>=G.x&&R.x<=G.x+G.width&&R.y>=G.y&&R.y<=G.y+G.height&&s(z.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:V,onTransformEnd:z=>t(e.id,z)}),jsx(Text,{text:e.data.question,x:L,y:L,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-L*2,listening:false}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:L,y:C,width:e.width-L*2,height:S,fill:g().bg,cornerRadius:8}),jsx(Text,{x:L,y:C,width:e.width-L*2,height:S,text:b(),fontSize:14,fontStyle:"bold",fill:g().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:L,y:C+S+y,fontSize:14,fill:"#6b7280",width:e.width-L*2,listening:false}),jsx(Rect,{x:L,y:C+S+T,width:e.width-L*2,height:k,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:L,y:C+S+T},divProps:{style:{width:`${e.width-L*2}px`,height:`${k}px`,pointerEvents:f?"none":"auto"}},children:jsx("textarea",{value:u,onChange:z=>m(z.target.value),disabled:f,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:f?"none":"auto"}})}),jsx(Group,{y:C+S+D+k+v+B,children:f&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.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})]})})]})});xl.displayName="LongAnswer";var fc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(xl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:l=>r(l,n.id)},n.id))});var ja=1600,Xa=900,gc=3200,xc=1800,Mb=.4,Tb=1.5,Ab=e=>{let o=0,t=0,a=ja,s=Xa;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:ja,height:Xa};let r=(d,u,m,f)=>{o=Math.min(o,d),t=Math.min(t,u),a=Math.max(a,d+m),s=Math.max(s,u+f);};e.lines?.forEach(d=>{if(d.points&&d.points.length>=2){let u=d.x||0,m=d.y||0,f=d.scaleX||1,i=d.scaleY||1;for(let c=0;c<d.points.length;c+=2){let p=u+d.points[c]*f,y=m+d.points[c+1]*i;o=Math.min(o,p),t=Math.min(t,y),a=Math.max(a,p),s=Math.max(s,y);}}}),e.images?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.videos?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.shapes?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.texts?.forEach(d=>r(d.x,d.y,d.width||200,d.height||d.fontSize||24)),e.flashcards?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.photoFrames?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.multipleChoices?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.trueFalses?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.shortAnswers?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.LongAnswer?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.fillInTheBlanks?.forEach(d=>r(d.x,d.y,d.width,d.height));let n=Math.min(a-o,gc),l=Math.min(s-t,xc);return o=Math.max(o,a-gc),t=Math.max(t,s-xc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:l}},Pb=(e,o,t={minX:0,minY:0,maxX:ja,maxY:Xa,width:ja,height:Xa})=>{let a=Math.max(t.width,ja),s=Math.max(t.height,Xa),r=e/o,n=a/s,l,d,u,f=0;if(r>n){d=s,l=Math.round(d*r),u=o/d;}else {l=a,d=Math.round(l/r),u=e/l;let i=s*u;f=(o-i)/2;}return u=Math.max(Mb,Math.min(Tb,u)),{scale:u,scaleX:u,scaleY:u,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:l,baseHeight:d,contentOffsetX:t.minX,contentOffsetY:t.minY}},bc=(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,contextMenuConfig:s={enabled:true}}={})=>{let r=at(),n=Q(w=>w.toolbar.selectedTool),l=Q(he),d=Q(fo),u=l?.editingActivity,m=l?.showMcqForm,f=l?.lines||[],i=useRef(null),c=useRef(null),[p,y]=useState(null),[h,x]=useState(""),b=useRef(null),[g,L]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:ja,stageHeight:Xa,offsetX:0,offsetY:0,baseWidth:ja,baseHeight:Xa,contentOffsetX:0,contentOffsetY:0}),C=useMemo(()=>Ab(l||null),[d]),[S,k]=useState(null),[v,M]=useState(null),[B,D]=useState(null),[O,W]=useState(null),[T,U]=useState(null),[R,oe]=useState(null),[V,se]=useState(null),[G,q]=useState(false),[_,H]=useState(null),[K,te]=useState(false),Z=useRef(null),J=useRef(null),le=useRef(null),{debouncedGenerateThumbnail:Ie}=jd(d,i);useEffect(()=>{let w=()=>{if(c.current){let P=c.current.getBoundingClientRect(),F=Pb(P.width,P.height,C);L(F);}};w();let I=new ResizeObserver(w);return c.current&&I.observe(c.current),window.addEventListener("resize",w),()=>{I.disconnect(),window.removeEventListener("resize",w);}},[C]),useEffect(()=>{if(i.current){let w=i.current.container();w&&(w.style.cursor="");}},[n]);let Y=useCallback(()=>{i.current&&requestAnimationFrame(()=>{if(!i.current)return;i.current.getLayers().forEach(F=>F.batchDraw());let I=1/6,P=i.current.toDataURL({pixelRatio:I});x(P),Ie();});},[Ie]),Me=useRef(d);useEffect(()=>{Me.current!==d&&(Me.current=d,Y());},[d,Y]);let Be=useRef(null),Et=useRef(true);useEffect(()=>{if(!l)return;let w=(l.lines?.length||0)+(l.images?.length||0)+(l.videos?.length||0)+(l.shapes?.length||0)+(l.texts?.length||0)+(l.flashcards?.length||0)+(l.photoFrames?.length||0)+(l.multipleChoices?.length||0)+(l.trueFalses?.length||0)+(l.shortAnswers?.length||0)+(l.LongAnswer?.length||0)+(l.fillInTheBlanks?.length||0),I=Be.current?.count!==w;!Et.current&&I&&setTimeout(()=>{Y();},100),Be.current={slideId:d,count:w},Et.current=false;},[l,d,Y]),useEffect(()=>{i.current&&e&&e(i);},[e]),useEffect(()=>{le.current&&a&&a(le);},[a]);let{startDrawing:oo,draw:Hr,stopDrawing:Ur,setCanvasRef:In,tool:ro,color:Cn,strokeWidth:kn,isSketchMode:Mn}=yd(Y),ia=useRef(new Map),{images:Tn,getLoadedImage:An,imageRefs:so,handleDragEnd:Wr,handleImageTransformEnd:Pn}=Md(Y),{videos:E,videoRefs:re,handleVideoClick:ye,handleVideoDragEnd:ge,handleVideoTransformEnd:ne}=Pd(Y),{multipleChoice:ue,handleMcqTransform:we,mcqRefs:Ne,handleDragEnd:Ft}=Td(Y),{trueFalse:ut,handleTrueFalseTransform:Te,trueFalseRefs:Ue,handleTrueFalseDragEnd:Jt}=Ad(Y),{shortAnswers:la,saRefs:Ea,handleShortAnswerDragEnd:Dn}=Od(Y),{longAnswers:zr,handleLongAnswerDragEnd:Bt}=Nd(Y),{fillInTheBlanks:da,handleFillInTheBlanksDragEnd:Fa,fibRefs:Gr}=sc(Y),{transformerRef:fe,boundBoxFunc:yt}=zd(),{shapes:um,shapeRefs:Kr,isDragging:od,handleShapeDragEnd:cm,handleShapeResizeEnd:fm}=Ed(Y),{texts:_o,textRefs:ua,handleDragEnd:mm,handleTransformEnd:pm,handleDoubleClick:hm,startEditing:_r,editingTextId:pe,editingValue:rd,handleEditingChange:sd,finishEditing:Rn}=Bd(Y,Z);useEffect(()=>{t&&t(_r);},[t,_r]);let jr=Q(w=>w.canvas.editingTextId);useEffect(()=>{jr&&jr!==pe&&_r(jr);},[jr,pe,_r]);let{flashcards:gm,flashcardRefs:Xr,handleDragEnd:xm,handleFlashcardTransformEnd:bm,handleNext:vm,handlePrevious:ym}=qd(Y),{photoFrames:nd,photoFrameRefs:$r,handleDragEnd:wm,handlePhotoFrameTransformEnd:Lm,startCamera:Sm,capturePhoto:Im,cameraStreams:Cm}=Wd(Y);useEffect(()=>{if(fe.current){if(pe){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(p&&!E.find(P=>P.id===p)?.isPlaying){let P=ia.current.get(p)||so.current.get(p)||re.current.get(p)||Kr.current.get(p)||ua.current.get(p)||Ne.current.get(p)||Xr.current.get(p)||$r.current.get(p)||Ea.current.get(p)||Ue.current.get(p)||Gr.current.get(p);if(P){let F=P.attrs?.locked;if(P.visible()&&F!==true){fe.current.nodes([P]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[p,pe,E,ia,so,re,Kr,ua,Xr,$r,nd,Ne,Ue,Gr,fe]);let Ge=useCallback(w=>{y(w),o?.(w);},[o]),no=useCallback(()=>{y(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),id=useCallback(w=>l?l.lines?.some(I=>I.id===w)?"line":l.images?.some(I=>I.id===w)?"image":l.videos?.some(I=>I.id===w)?"video":l.shapes?.some(I=>I.id===w)?"shape":l.texts?.some(I=>I.id===w)?"text":l.flashcards?.some(I=>I.id===w)?"flashcard":l.photoFrames?.some(I=>I.id===w)?"photoFrame":l.multipleChoices?.some(I=>I.id===w)?"mcq":l.trueFalses?.some(I=>I.id===w)?"trueFalse":l.shortAnswers?.some(I=>I.id===w)?"shortAnswer":l.LongAnswer?.some(I=>I.id===w)?"longAnswer":l.fillInTheBlanks?.some(I=>I.id===w)?"fillInTheBlanks":null:null,[l]),ld=useCallback((w,I)=>{switch(r(ce()),I){case "line":r(Cs(w));break;case "image":r(Jr(w));break;case "video":r(ts(w));break;case "shape":r(rs(w));break;case "text":r(ss(w));break;case "flashcard":r(is(w));break;case "photoFrame":r(ds(w));break;case "mcq":r(cs(w));break;case "trueFalse":r(ms(w));break;case "shortAnswer":r(hs(w));break;case "longAnswer":r(xs(w));break;case "fillInTheBlanks":r(vs(w));break}no(),Y();},[r,no,Y]);useEffect(()=>{let w=I=>{if(I.key!=="Delete"||!p||pe)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;I.preventDefault();let Ae=id(p);Ae&&ld(p,Ae);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[p,pe,id,ld]),useEffect(()=>{let w=fe.current;return ()=>{w&&w.nodes([]);}},[d]),useEffect(()=>{let w=I=>{pe&&I.target.tagName!=="TEXTAREA"&&Rn();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[pe,Rn]),useEffect(()=>{let w=pe||p;if(!w||p&&pe){M(null);return}let I=ua.current.get(w),P=i.current;if(!I||!P){M(null);return}let F=P.container().getBoundingClientRect(),Ae=I.absolutePosition(),Le=P.scaleX();M({x:F.left+(Ae.x+I.width()*Le/2)*Le,y:F.top+Ae.y*Le});},[p,pe,_o,ua]),useEffect(()=>{if(!pe){D(null);return}let w=ua.current.get(pe),I=i.current;if(!w||!I){D(null);return}let P=I.container().getBoundingClientRect(),F=w.absolutePosition(),Ae=I.scaleX();D({top:P.top+F.y*Ae,left:P.left+F.x*Ae,scale:Ae});},[pe,_o,ua]);let dd=useCallback(w=>{let I=w.target.getClassName(),P=w.target===w.target.getStage(),F=I==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",Ae=I==="Image",Le=I==="Text",ae=I==="Group"||w.target.getParent()?.getClassName()==="Group",Ot=I==="Circle"||I==="Star"||I==="RegularPolygon"||I==="Ellipse"||I==="Ring"||I==="Wedge"||I==="Arrow"||I==="Line"||I==="Arc"||I==="Rect"&&w.target.attrs.id,Lt=I==="Group";if(P&&!F&&!Ae&&!Le&&!ae&&!Ot&&!Lt&&no(),!(n==="pen"||n==="eraser")&&(Ae||Le||F||ae||Ot||Lt))return;let Xe=w.target.getStage()?.getPointerPosition();if(!Xe)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let N=bc(Xe,g);oo(N);}},[n,oo,no,g]),ud=useCallback(w=>{if(od)return;let I=w.target.getStage()?.getPointerPosition();if(!I)return;let P=bc(I,g);Hr(P);},[Hr,od,g]),cd=useCallback(()=>{Ur();},[Ur]),km=useCallback(w=>{Wr(w,Y);},[Wr,Y]),Mm=useCallback(w=>{ye(w),Ge(w);},[ye,Ge]),wt=useCallback((w,I,P)=>{if(w.preventDefault(),!s.enabled)return;let F=w.clientX,Ae=w.clientY,Le=b.current?.offsetHeight||450,ae=b.current?.offsetWidth||450,Ot=window.innerHeight,Lt=window.innerWidth,tt=F,Xe=Ae;Ae+Le>Ot&&(Xe=Ae-Le),F+ae>Lt&&(tt=F-ae),k({x:tt,y:Xe,elementId:I,elementType:P}),Ge(I);},[Ge,s.enabled]),fd=useCallback(w=>{r(Zo(w)),r(ma(true));},[r]),Tm=useCallback(w=>{r(Xo(w)),r(Oa(true));},[r]),Am=useCallback((w,I)=>{if(!S)return;let{elementId:P,elementType:F}=S;switch(w){case "order":if(I){let A=I.target.getBoundingClientRect();W({x:A.right+5,y:A.top,type:"order"});}break;case "lock":if(I){let A=I.target.getBoundingClientRect();W({x:A.right+5,y:A.top,type:"lock"});}break;case "link":if(k(null),F==="line")break;let Ae=l?F==="image"?l.images.find(A=>A.id===P):l.videos.find(A=>A.id===P):null;U({type:"link",defaultValue:Ae?.link||""});break;case "voice":if(k(null),F==="line")break;let Le=l?F==="image"?l.images.find(A=>A.id===P):F==="video"?l.videos.find(A=>A.id===P):F==="text"?l.texts.find(A=>A.id===P):F==="flashcard"?l.flashcards.find(A=>A.id===P):F==="photoFrame"?l.photoFrames.find(A=>A.id===P):F==="mcq"?l.multipleChoices.find(A=>A.id===P):F==="fillInTheBlanks"?l.fillInTheBlanks.find(A=>A.id===P):F==="longAnswer"?l.LongAnswer.find(A=>A.id===P):F==="shortAnswer"?l.shortAnswers.find(A=>A.id===P):F==="trueFalse"?l.trueFalses.find(A=>A.id===P):F==="shape"?l.shapes.find(A=>A.id===P):null:null;H({elementId:P,elementType:F,existingAudio:Le?.audioData});break;case "edit":k(null);let ae=null;F==="mcq"?ae=l?.multipleChoices.find(A=>A.id===P):F==="trueFalse"?ae=l?.trueFalses.find(A=>A.id===P):F==="shortAnswer"?ae=l?.shortAnswers.find(A=>A.id===P):F==="longAnswer"?ae=l?.LongAnswer.find(A=>A.id===P):F==="fillInTheBlanks"&&(ae=l?.fillInTheBlanks.find(A=>A.id===P)),ae&&fd(ae);break;case "editFlashcard":k(null);let Ot=l?.flashcards.find(A=>A.id===P);Ot&&Tm(Ot);break;case "color":k(null);let Lt=l?.shapes.find(A=>A.id===P);oe({elementId:P,elementType:"shape",defaultColor:Lt?.color||"#096B76"});break;case "crop":if(k(null),F==="image"){let A=l?.images.find(Om=>Om.id===P);A&&se({elementId:P,imageSrc:A.src});}break;case "draw":k(null),F==="image"?r(Zn(P)):F==="photoFrame"&&r(ei(P));break;case "duplicate":r(ce()),F==="line"?r(fi(P)):F==="image"?r(Zr(P)):F==="video"?r(as(P)):F==="shape"?r(os(P)):F==="text"?r(ns(P)):F==="flashcard"?r(ls(P)):F==="photoFrame"?r(us(P)):F==="mcq"?r(fs(P)):F==="trueFalse"?r(ps(P)):F==="shortAnswer"?r(gs(P)):F==="fillInTheBlanks"?r(ys(P)):F==="longAnswer"&&r(bs(P)),Y();break;case "infinite-clone":r(ce());let tt=5;for(let A=0;A<tt;A++)F==="image"?r(Zr(P)):F==="video"?r(as(P)):F==="shape"?r(os(P)):F==="text"?r(ns(P)):F==="flashcard"?r(ls(P)):F==="photoFrame"?r(us(P)):F==="mcq"?r(fs(P)):F==="trueFalse"?r(ps(P)):F==="shortAnswer"?r(gs(P)):F==="fillInTheBlanks"?r(ys(P)):F==="longAnswer"&&r(bs(P));Y();break;case "make-response":if(k(null),F==="line")break;let Xe=`#response-${P}`;r(ce()),r(ws({id:P,type:F,link:Xe})),(l?F==="image"?l.images.find(A=>A.id===P):F==="video"?l.videos.find(A=>A.id===P):F==="shape"?l.shapes.find(A=>A.id===P):F==="flashcard"?l.flashcards.find(A=>A.id===P):F==="photoFrame"?l.photoFrames.find(A=>A.id===P):l.multipleChoices.find(A=>A.id===P):null)?.altText||r(Ls({id:P,type:F,altText:"Interactive response area"})),Y(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(k(null),F==="line")break;let N=l?F==="image"?l.images.find(A=>A.id===P):F==="video"?l.videos.find(A=>A.id===P):F==="shape"?l.shapes.find(A=>A.id===P):null:null;U({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),k(null),te(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),F==="line"?r(Cs(P)):F==="image"?r(Jr(P)):F==="video"?r(ts(P)):F==="shape"?r(rs(P)):F==="text"?r(ss(P)):F==="flashcard"?r(is(P)):F==="photoFrame"?r(ds(P)):F==="mcq"?r(cs(P)):F==="trueFalse"?r(ms(P)):F==="shortAnswer"?r(hs(P)):F==="longAnswer"?r(xs(P)):F==="fillInTheBlanks"&&r(vs(P)),no(),Y();break}},[S,r,Y,no,l,fd]),Pm=useCallback(()=>{k(null),W(null);},[]),En=useCallback(w=>{if(!S)return;let{elementId:I,elementType:P}=S;switch(r(ce()),w){case "bring-to-front":P!=="line"&&r(li({id:I,type:P}));break;case "send-to-back":P!=="line"&&r(di({id:I,type:P}));break;case "lock":case "unlock":P!=="line"&&r(ui({id:I,type:P}));break}Y(),k(null),W(null);},[S,r,Y]),Dm=useCallback(w=>{if(!S||!T)return;let{elementId:I,elementType:P}=S;r(ce()),T.type==="link"&&P!=="line"?r(ws({id:I,type:P,link:w})):T.type==="altText"&&P!=="line"&&r(Ls({id:I,type:P,altText:w})),Y(),U(null);},[S,T,r,Y]),Rm=useCallback(w=>{if(!_)return;let{elementId:I,elementType:P}=_;r(ce()),r(Ss({id:I,type:P,audioData:w})),Y(),H(null);},[_,r,Y]),Em=useCallback(()=>{if(!_)return;let{elementId:w,elementType:I}=_;r(ce()),r(Ss({id:w,type:I,audioData:""})),Y();},[_,r,Y]),Fm=useCallback(w=>{if(!R)return;let{elementId:I}=R;r(ce()),r(uo({id:I,color:w})),Y(),oe(null);},[R,r,Y]),Bm=useCallback(w=>{if(!V)return;let{elementId:I}=V;r(ce()),r(lo({id:I,src:w})),Y(),se(null);},[V,r,Y]);return jsxs("div",{ref:c,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(Cd,{ref:w=>{if(J.current=w,In(w),w){let I=w.getCanvasElement();I&&(le.current=I,a&&a(le));}},width:g.baseWidth,height:g.baseHeight,tool:ro,color:Cn,strokeWidth:kn/g.scale,isSketchMode:Mn,xOffset:g.contentOffsetX,yOffset:g.contentOffsetY-g.offsetY/g.scale,style:{width:g.stageWidth,height:g.stageHeight}}),jsxs(Stage,{ref:i,width:g.stageWidth,height:g.stageHeight,scaleX:g.scaleX,scaleY:g.scaleY,x:g.offsetX,y:0,onMouseDown:dd,onMouseMove:ud,onMouseUp:cd,onTouchStart:dd,onTouchMove:ud,onTouchEnd:cd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:g.baseWidth,height:g.stageHeight/g.scale,fill:l?.backgroundColor||"white"})}),jsx(Layer,{x:-g.contentOffsetX,y:g.offsetY/g.scale-g.contentOffsetY,children:(()=>{let w=[];return f.forEach((I,P)=>{w.push({type:"line",timestamp:I.timestamp||P,element:{...I,id:I.id??`line-${P}`},index:P});}),um.forEach(I=>{w.push({type:"shape",timestamp:I.timestamp||0,element:I});}),Tn.forEach(I=>{w.push({type:"image",timestamp:I.timestamp||0,element:I});}),E.forEach(I=>{w.push({type:"video",timestamp:I.timestamp||0,element:I});}),_o.forEach(I=>{w.push({type:"text",timestamp:I.timestamp||0,element:I});}),gm.forEach(I=>{w.push({type:"flashcard",timestamp:I.timestamp||0,element:I});}),nd.forEach(I=>{w.push({type:"photoFrame",timestamp:I.timestamp||0,element:I});}),ue.forEach(I=>{w.push({type:"mcq",timestamp:I.timestamp||0,element:I});}),ut.forEach(I=>{w.push({type:"trueFalse",timestamp:I.timestamp||0,element:I});}),la.forEach(I=>{w.push({type:"shortAnswer",timestamp:I.timestamp||0,element:I});}),zr.forEach(I=>{w.push({type:"longAnswer",timestamp:I.timestamp||0,element:I});}),da.forEach(I=>{w.push({type:"fillInTheBlanks",timestamp:I.timestamp||0,element:I});}),w.sort((I,P)=>I.timestamp-P.timestamp),w.map((I,P)=>{let F=`${I.type}-${"id"in I.element&&I.element.id||I.index||P}`,Ae="id"in I.element?I.element.id:void 0,Le=Ae&&p===Ae;switch(I.type){case "line":let ae=I.element,Ot=I.index||0,Lt=ae.tool==="eraser",tt=ae.isSketch&&ae.tool==="pen",Xe=ae.isSketch&&Lt,St=ae.id||`line-${Ot}`;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:tt||Xe?void 0:ae.color,strokeWidth:tt||Xe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Xe?Lt?"black":ae.color:void 0,closed:tt||Xe,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(Yr(Ot));},onTap:()=>{r(ce()),r(Yr(Ot));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:N=>{let A=N.target.getStage();A&&(A.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:N=>{let A=N.target.getStage();A&&(A.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},F):jsxs(be__default.Fragment,{children:[jsx(Group,{id:St,ref:N=>{N?ia.current.set(St,N):ia.current.delete(St);},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:",St),Ge(St));},onTap:()=>{n==="select"&&(console.log("Line tapped:",St),Ge(St));},onDragEnd:N=>{r(ce()),r(Is({id:St,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),Y();},onTransformEnd:N=>{r(ce()),r(Is({id:St,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),Y();},onMouseEnter:N=>{if(n==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="move");}},onMouseLeave:N=>{if(n==="select"){let A=N.target.getStage();A&&(A.container().style.cursor="default");}},onContextMenu:N=>{let A=N.evt;A.preventDefault(),wt(A,St,"line");},children:jsx(Line,{points:ae.points||[],stroke:tt||Xe?void 0:ae.color,strokeWidth:tt||Xe?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:tt||Xe?Lt?"black":ae.color:void 0,closed:tt||Xe,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=ia.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!A),A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Ri,{onSelect:Ge,shapes:[I.element],shapeRefs:Kr,handleShapeDragEnd:cm,handleShapeResizeEnd:fm,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Kr.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "image":return jsxs(be__default.Fragment,{children:[jsx(Ti,{images:[I.element],getLoadedImage:An,imageRefs:so,onDragEnd:km,onTransform:Pn,onSelect:Ge,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=so.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "video":return jsxs(be__default.Fragment,{children:[jsx(Di,{videos:[I.element],selectedId:p,videoRefs:re,onVideoClick:Mm,onDragEnd:ge,onTransformEnd:ne,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=re.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "text":return jsxs(be__default.Fragment,{children:[jsx(ru,{texts:[I.element],textRefs:ua,onDragEnd:mm,onTransformEnd:pm,onSelect:Ge,onContextMenu:wt,onDoubleClick:hm,editingTextId:pe,editingValue:rd,onEditingChange:sd}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=ua.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Bi,{flashcards:[I.element],flashcardRefs:Xr,selectedId:p,onDragEnd:xm,onTransform:bm,onSelect:Ge,onNext:vm,onPrevious:ym,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Xr.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Ui,{photoFrames:[I.element],photoFrameRefs:$r,selectedId:p,onDragEnd:wm,onTransform:Lm,onSelect:Ge,onStartCamera:Sm,onCapture:Im,cameraStreams:Cm,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=$r.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Fu,{handleMcqTransform:we,multipleChoice:[I.element],handleSelect:Ge,mcqRefs:Ne,handleDragEnd:Ft,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ne.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Nu,{trueFalses:[I.element],handleTrueFalseTransform:Te,handleSelect:Ge,trueFalseRefs:Ue,onContextMenu:wt,handleDragEnd:Jt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ue.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(rc,{shortAnswers:[I.element],handleSelect:Ge,handleTransform:we,saRefs:Ea,onContextMenu:wt,handleDragEnd:Dn}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ea.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(fc,{longAnswer:[I.element],handleSelect:Ge,handleTransform:we,saRefs:Ea,onContextMenu:wt,handleDragEnd:Bt}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Ea.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(uc,{fillInTheBlanks:[I.element],handleSelect:Ge,handleTransform:we,onContextMenu:wt,handleDragEnd:Fa,fibRefs:Gr}),Le&&!pe&&p&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let A=Gr.current.get(p);A&&A.visible()&&(N.nodes([A]),N.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},F);default:return null}})})()})]}),S&&jsx(xu,{menuRef:b,x:S.x,y:S.y,type:S.elementType,onAction:Am,onClose:Pm,isDrawingMode:S.elementType==="image"?l?.images.find(w=>w.id===S.elementId)?.isDrawingMode:S.elementType==="photoFrame"?l?.photoFrames.find(w=>w.id===S.elementId)?.isDrawingMode:false}),O&&S&&jsx(bu,{x:O.x,y:O.y,items:O.type==="order"?[{label:"Bring to Front",onClick:()=>En("bring-to-front")},{label:"Send to Back",onClick:()=>En("send-to-back")}]:[{label:l&&(S.elementType==="image"?l.images.find(w=>w.id===S.elementId)?.locked:l.videos.find(w=>w.id===S.elementId)?.locked)?"Unlock":"Lock",onClick:()=>En(l&&(S.elementType==="image"?l.images.find(w=>w.id===S.elementId)?.locked:l.videos.find(w=>w.id===S.elementId)?.locked)?"unlock":"lock")}],onClose:()=>W(null)}),T&&jsx(wu,{title:T.type==="link"?"Add Link":"Add Alt Text",label:T.type==="link"?"URL":"Alternative Text",placeholder:T.type==="link"?"https://example.com":"Describe this image/video",defaultValue:T.defaultValue,onSave:Dm,onClose:()=>U(null)}),R&&jsx(Fs,{defaultColor:R.defaultColor,onConfirm:Fm,onCancel:()=>oe(null)}),V&&jsx(Cu,{imageSrc:V.imageSrc,onConfirm:Bm,onCancel:()=>se(null)}),G&&jsx(dr,{onClose:()=>q(false),stageRef:i}),_&&jsx(Tu,{elementId:_.elementId,elementType:_.elementType,existingAudio:_.existingAudio,onSave:Rm,onDelete:Em,onClose:()=>H(null)}),K&&jsx(Du,{selectedElementId:p||void 0,onClose:()=>te(false),onSelectElement:w=>{Ge(w),te(false);}}),l?.images.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.videos.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.shapes?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.texts?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.flashcards?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),l?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),m&&jsx(Xu,{editElement:u}),v&&(()=>{let w=pe||p;if(!w)return null;let I=_o.find(P=>P.id===w);return I?jsx(Zu,{text:I,position:v}):null})(),B&&pe&&(()=>{let w=_o.find(I=>I.id===pe);return w?jsx(ec,{text:w,editingValue:rd,onEditingChange:sd,onFinish:Rn,position:{top:B.top,left:B.left},scale:B.scale,textareaRef:Z},pe):null})()]})},Rb=Db;function bl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Ye(e,o,{checkForDefaultPrevented:t=true}={}){return function(s){if(e?.(s),t===false||!s.defaultPrevented)return o?.(s)}}function vc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Dr(...e){return o=>{let t=false,a=e.map(s=>{let r=vc(s,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let s=0;s<a.length;s++){let r=a[s];typeof r=="function"?r():vc(e[s],null);}}}}function Dt(...e){return be.useCallback(Dr(...e),e)}function ka(e,o=[]){let t=[];function a(r,n){let l=be.createContext(n),d=t.length;t=[...t,n];let u=f=>{let{scope:i,children:c,...p}=f,y=i?.[e]?.[d]||l,h=be.useMemo(()=>p,Object.values(p));return jsx(y.Provider,{value:h,children:c})};u.displayName=r+"Provider";function m(f,i){let c=i?.[e]?.[d]||l,p=be.useContext(c);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${f}\` must be used within \`${r}\``)}return [u,m]}let s=()=>{let r=t.map(n=>be.createContext(n));return function(l){let d=l?.[e]||r;return be.useMemo(()=>({[`__scope${e}`]:{...l,[e]:d}}),[l,d])}};return s.scopeName=e,[a,Fb(s,...o)]}function Fb(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(r){let n=a.reduce((l,{useScope:d,scopeName:u})=>{let f=d(r)[`__scope${u}`];return {...l,...f}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var Oo=globalThis?.document?be.useLayoutEffect:()=>{};var Bb=be[" useInsertionEffect ".trim().toString()]||Oo;function ea({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=Ob({defaultProp:o,onChange:t}),l=e!==void 0,d=l?e:s;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let f=m.current;f!==l&&console.warn(`${a} is changing from ${f?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=l;},[l,a]);}let u=be.useCallback(m=>{if(l){let f=Nb(m)?m(e):m;f!==e&&n.current?.(f);}else r(m);},[l,e,r,n]);return [d,u]}function Ob({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),s=be.useRef(t),r=be.useRef(o);return Bb(()=>{r.current=o;},[o]),be.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function Nb(e){return typeof e=="function"}var Vb=be.createContext(void 0);function No(e){let o=be.useContext(Vb);return e||o||"ltr"}function Lc(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 Ic(e){let[o,t]=be.useState(void 0);return Oo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;let r=s[0],n,l;if("borderBoxSize"in r){let d=r.borderBoxSize,u=Array.isArray(d)?d[0]:d;n=u.inlineSize,l=u.blockSize;}else n=e.offsetWidth,l=e.offsetHeight;t({width:n,height:l});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function kc(e){let o=qb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,l=be.Children.toArray(r),d=l.find(Ub);if(d){let u=d.props.children,m=l.map(f=>f===d?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(u)?be.cloneElement(u,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function qb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=zb(s),l=Wb(r,s.props);return s.type!==be.Fragment&&(l.ref=a?Dr(a,n):n),be.cloneElement(s,l)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Hb=Symbol("radix.slottable");function Ub(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Hb}function Wb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...l)=>{let d=r(...l);return s(...l),d}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function zb(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 _b=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=_b.reduce((e,o)=>{let t=kc(`Primitive.${o}`),a=be.forwardRef((s,r)=>{let{asChild:n,...l}=s,d=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(d,{...l,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function vl(e){let o=jb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,l=be.Children.toArray(r),d=l.find($b);if(d){let u=d.props.children,m=l.map(f=>f===d?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(u)?be.cloneElement(u,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function jb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=Jb(s),l=Yb(r,s.props);return s.type!==be.Fragment&&(l.ref=a?Dr(a,n):n),be.cloneElement(s,l)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Xb=Symbol("radix.slottable");function $b(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Xb}function Yb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...l)=>{let d=r(...l);return s(...l),d}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function Jb(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 dn(e){let o=e+"CollectionProvider",[t,a]=ka(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=y=>{let{scope:h,children:x}=y,b=be__default.useRef(null),g=be__default.useRef(new Map).current;return jsx(s,{scope:h,itemMap:g,collectionRef:b,children:x})};n.displayName=o;let l=e+"CollectionSlot",d=vl(l),u=be__default.forwardRef((y,h)=>{let{scope:x,children:b}=y,g=r(l,x),L=Dt(h,g.collectionRef);return jsx(d,{ref:L,children:b})});u.displayName=l;let m=e+"CollectionItemSlot",f="data-radix-collection-item",i=vl(m),c=be__default.forwardRef((y,h)=>{let{scope:x,children:b,...g}=y,L=be__default.useRef(null),C=Dt(h,L),S=r(m,x);return be__default.useEffect(()=>(S.itemMap.set(L,{ref:L,...g}),()=>void S.itemMap.delete(L))),jsx(i,{[f]:"",ref:C,children:b})});c.displayName=m;function p(y){let h=r(e+"CollectionConsumer",y);return be__default.useCallback(()=>{let b=h.collectionRef.current;if(!b)return [];let g=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(h.itemMap.values()).sort((S,k)=>g.indexOf(S.ref.current)-g.indexOf(k.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:u,ItemSlot:c},p,a]}var Ac=["PageUp","PageDown"],Pc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Dc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Vo="Slider",[wl,Qb,ev]=dn(Vo),[Rc]=ka(Vo,[ev]),[tv,un]=Rc(Vo),Ec=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:l=false,minStepsBetweenThumbs:d=0,defaultValue:u=[a],value:m,onValueChange:f=()=>{},onValueCommit:i=()=>{},inverted:c=false,form:p,...y}=e,h=be.useRef(new Set),x=be.useRef(0),g=n==="horizontal"?av:ov,[L=[],C]=ea({prop:m,defaultProp:u,onChange:D=>{[...h.current][x.current]?.focus(),f(D);}}),S=be.useRef(L);function k(D){let O=lv(L,D);B(D,O);}function v(D){B(D,x.current);}function M(){let D=S.current[x.current];L[x.current]!==D&&i(L);}function B(D,O,{commit:W}={commit:false}){let T=fv(r),U=mv(Math.round((D-a)/r)*r+a,T),R=bl(U,[a,s]);C((oe=[])=>{let V=nv(oe,R,O);if(cv(V,d*r)){x.current=V.indexOf(R);let se=String(V)!==String(oe);return se&&W&&i(V),se?V:oe}else return oe});}return jsx(tv,{scope:e.__scopeSlider,name:t,disabled:l,min:a,max:s,valueIndexToChangeRef:x,thumbs:h.current,values:L,orientation:n,form:p,children:jsx(wl.Provider,{scope:e.__scopeSlider,children:jsx(wl.Slot,{scope:e.__scopeSlider,children:jsx(g,{"aria-disabled":l,"data-disabled":l?"":void 0,...y,ref:o,onPointerDown:Ye(y.onPointerDown,()=>{l||(S.current=L);}),min:a,max:s,inverted:c,onSlideStart:l?void 0:k,onSlideMove:l?void 0:v,onSlideEnd:l?void 0:M,onHomeKeyDown:()=>!l&&B(a,0,{commit:true}),onEndKeyDown:()=>!l&&B(s,L.length-1,{commit:true}),onStepKeyDown:({event:D,direction:O})=>{if(!l){let U=Ac.includes(D.key)||D.shiftKey&&Pc.includes(D.key)?10:1,R=x.current,oe=L[R],V=r*U*O;B(oe+V,R,{commit:true});}}})})})})});Ec.displayName=Vo;var[Fc,Bc]=Rc(Vo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),av=be.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:l,onSlideEnd:d,onStepKeyDown:u,...m}=e,[f,i]=be.useState(null),c=Dt(o,g=>i(g)),p=be.useRef(void 0),y=No(s),h=y==="ltr",x=h&&!r||!h&&r;function b(g){let L=p.current||f.getBoundingClientRect(),C=[0,L.width],k=Il(C,x?[t,a]:[a,t]);return p.current=L,k(g-L.left)}return jsx(Fc,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:jsx(Oc,{dir:y,"data-orientation":"horizontal",...m,ref:c,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let L=b(g.clientX);n?.(L);},onSlideMove:g=>{let L=b(g.clientX);l?.(L);},onSlideEnd:()=>{p.current=void 0,d?.();},onStepKeyDown:g=>{let C=Dc[x?"from-left":"from-right"].includes(g.key);u?.({event:g,direction:C?-1:1});}})})}),ov=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:l,onStepKeyDown:d,...u}=e,m=be.useRef(null),f=Dt(o,m),i=be.useRef(void 0),c=!s;function p(y){let h=i.current||m.current.getBoundingClientRect(),x=[0,h.height],g=Il(x,c?[a,t]:[t,a]);return i.current=h,g(y-h.top)}return jsx(Fc,{scope:e.__scopeSlider,startEdge:c?"bottom":"top",endEdge:c?"top":"bottom",size:"height",direction:c?1:-1,children:jsx(Oc,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{let h=p(y.clientY);r?.(h);},onSlideMove:y=>{let h=p(y.clientY);n?.(h);},onSlideEnd:()=>{i.current=void 0,l?.();},onStepKeyDown:y=>{let x=Dc[c?"from-bottom":"from-top"].includes(y.key);d?.({event:y,direction:x?-1:1});}})})}),Oc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:l,onStepKeyDown:d,...u}=e,m=un(Vo,t);return jsx(lt.span,{...u,ref:o,onKeyDown:Ye(e.onKeyDown,f=>{f.key==="Home"?(n(f),f.preventDefault()):f.key==="End"?(l(f),f.preventDefault()):Ac.concat(Pc).includes(f.key)&&(d(f),f.preventDefault());}),onPointerDown:Ye(e.onPointerDown,f=>{let i=f.target;i.setPointerCapture(f.pointerId),f.preventDefault(),m.thumbs.has(i)?i.focus():a(f);}),onPointerMove:Ye(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f);}),onPointerUp:Ye(e.onPointerUp,f=>{let i=f.target;i.hasPointerCapture(f.pointerId)&&(i.releasePointerCapture(f.pointerId),r(f));})})}),Nc="SliderTrack",Vc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=un(Nc,t);return jsx(lt.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});Vc.displayName=Nc;var Ll="SliderRange",qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=un(Ll,t),r=Bc(Ll,t),n=be.useRef(null),l=Dt(o,n),d=s.values.length,u=s.values.map(i=>Wc(i,s.min,s.max)),m=d>1?Math.min(...u):0,f=100-Math.max(...u);return jsx(lt.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:l,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:f+"%"}})});qc.displayName=Ll;var Sl="SliderThumb",Hc=be.forwardRef((e,o)=>{let t=Qb(e.__scopeSlider),[a,s]=be.useState(null),r=Dt(o,l=>s(l)),n=be.useMemo(()=>a?t().findIndex(l=>l.ref.current===a):-1,[t,a]);return jsx(rv,{...e,ref:r,index:n})}),rv=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=un(Sl,t),l=Bc(Sl,t),[d,u]=be.useState(null),m=Dt(o,b=>u(b)),f=d?n.form||!!d.closest("form"):true,i=Ic(d),c=n.values[a],p=c===void 0?0:Wc(c,n.min,n.max),y=iv(a,n.values.length),h=i?.[l.size],x=h?dv(h,p,l.direction):0;return be.useEffect(()=>{if(d)return n.thumbs.add(d),()=>{n.thumbs.delete(d);}},[d,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[l.startEdge]:`calc(${p}% + ${x}px)`},children:[jsx(wl.ItemSlot,{scope:e.__scopeSlider,children:jsx(lt.span,{role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":n.min,"aria-valuenow":c,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...r,ref:m,style:c===void 0?{display:"none"}:e.style,onFocus:Ye(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),f&&jsx(Uc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:c},a)]})});Hc.displayName=Sl;var sv="RadioBubbleInput",Uc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=be.useRef(null),r=Dt(s,a),n=Lc(o);return be.useEffect(()=>{let l=s.current;if(!l)return;let d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"value").set;if(n!==o&&m){let f=new Event("input",{bubbles:true});m.call(l,o),l.dispatchEvent(f);}},[n,o]),jsx(lt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});Uc.displayName=sv;function nv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Wc(e,o,t){let r=100/(t-o)*(e-o);return bl(r,[0,100])}function iv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function lv(e,o){if(e.length===1)return 0;let t=e.map(s=>Math.abs(s-o)),a=Math.min(...t);return t.indexOf(a)}function dv(e,o,t){let a=e/2,r=Il([0,50],[0,a]);return (a-r(o)*t)*t}function uv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function cv(e,o){if(o>0){let t=uv(e);return Math.min(...t)>=o}return true}function Il(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 fv(e){return (String(e).split(".")[1]||"").length}function mv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var zc=Ec,Gc=Vc,Kc=qc,_c=Hc;function jc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(o=0;o<s;o++)e[o]&&(t=jc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function cn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=jc(e))&&(a&&(a+=" "),a+=o);return a}var hv=(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},gv=(e,o)=>({classGroupId:e,validator:o}),Zc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Xc=[],xv="arbitrary..",bv=e=>{let o=yv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return vv(n);let l=n.split("-"),d=l[0]===""&&l.length>1?1:0;return Qc(l,d,o)},getConflictingClassGroupIds:(n,l)=>{if(l){let d=a[n],u=t[n];return d?u?hv(u,d):d:u||Xc}return t[n]||Xc}}},Qc=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let u=Qc(e,o+1,r);if(u)return u}let n=t.validators;if(n===null)return;let l=o===0?e.join("-"):e.slice(o).join("-"),d=n.length;for(let u=0;u<d;u++){let m=n[u];if(m.validator(l))return m.classGroupId}},vv=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?xv+a:void 0})(),yv=e=>{let{theme:o,classGroups:t}=e;return wv(t,o)},wv=(e,o)=>{let t=Zc();for(let a in e){let s=e[a];Ml(s,t,a,o);}return t},Ml=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Lv(n,o,t,a);}},Lv=(e,o,t,a)=>{if(typeof e=="string"){Sv(e,o,t);return}if(typeof e=="function"){Iv(e,o,t,a);return}Cv(e,o,t,a);},Sv=(e,o,t)=>{let a=e===""?o:ef(o,e);a.classGroupId=t;},Iv=(e,o,t,a)=>{if(kv(e)){Ml(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(gv(t,e));},Cv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[l,d]=s[n];Ml(d,ef(o,l),t,a);}},ef=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],l=t.nextPart.get(n);l||(l=Zc(),t.nextPart.set(n,l)),t=l;}return t},kv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Mv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),s=(r,n)=>{t[r]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let n=t[r];if(n!==void 0)return n;if((n=a[r])!==void 0)return s(r,n),n},set(r,n){r in t?t[r]=n:s(r,n);}}};var Tv=[],$c=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Av=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,l=0,d=0,u,m=s.length;for(let y=0;y<m;y++){let h=s[y];if(n===0&&l===0){if(h===":"){r.push(s.slice(d,y)),d=y+1;continue}if(h==="/"){u=y;continue}}h==="["?n++:h==="]"?n--:h==="("?l++:h===")"&&l--;}let f=r.length===0?s:s.slice(d),i=f,c=false;f.endsWith("!")?(i=f.slice(0,-1),c=true):f.startsWith("!")&&(i=f.slice(1),c=true);let p=u&&u>d?u-d:void 0;return $c(r,c,i,p)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):$c(Tv,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},Pv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],s=[];for(let r=0;r<t.length;r++){let n=t[r],l=n[0]==="[",d=o.has(n);l||d?(s.length>0&&(s.sort(),a.push(...s),s=[]),a.push(n)):s.push(n);}return s.length>0&&(s.sort(),a.push(...s)),a}},Dv=e=>({cache:Mv(e.cacheSize),parseClassName:Av(e),sortModifiers:Pv(e),...bv(e)}),Rv=/\s+/,Ev=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],l=e.trim().split(Rv),d="";for(let u=l.length-1;u>=0;u-=1){let m=l[u],{isExternal:f,modifiers:i,hasImportantModifier:c,baseClassName:p,maybePostfixModifierPosition:y}=t(m);if(f){d=m+(d.length>0?" "+d:d);continue}let h=!!y,x=a(h?p.substring(0,y):p);if(!x){if(!h){d=m+(d.length>0?" "+d:d);continue}if(x=a(p),!x){d=m+(d.length>0?" "+d:d);continue}h=false;}let b=i.length===0?"":i.length===1?i[0]:r(i).join(":"),g=c?b+"!":b,L=g+x;if(n.indexOf(L)>-1)continue;n.push(L);let C=s(x,h);for(let S=0;S<C.length;++S){let k=C[S];n.push(g+k);}d=m+(d.length>0?" "+d:d);}return d},Fv=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=tf(t))&&(s&&(s+=" "),s+=a);return s},tf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=tf(e[a]))&&(t&&(t+=" "),t+=o);return t},Bv=(e,...o)=>{let t,a,s,r,n=d=>{let u=o.reduce((m,f)=>f(m),e());return t=Dv(u),a=t.cache.get,s=t.cache.set,r=l,l(d)},l=d=>{let u=a(d);if(u)return u;let m=Ev(d,t);return s(d,m),m};return r=n,(...d)=>r(Fv(...d))},Ov=[],He=e=>{let o=t=>t[e]||Ov;return o.isThemeGetter=true,o},af=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,of=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Nv=/^\d+\/\d+$/,Vv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qv=/\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$/,Hv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Uv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Wv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,qo=e=>Nv.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ma=e=>!!e&&Number.isInteger(Number(e)),Cl=e=>e.endsWith("%")&&de(e.slice(0,-1)),ta=e=>Vv.test(e),zv=()=>true,Gv=e=>qv.test(e)&&!Hv.test(e),rf=()=>false,Kv=e=>Uv.test(e),_v=e=>Wv.test(e),jv=e=>!X(e)&&!$(e),Xv=e=>Ho(e,lf,rf),X=e=>af.test(e),Ya=e=>Ho(e,df,Gv),kl=e=>Ho(e,Qv,de),Yc=e=>Ho(e,sf,rf),$v=e=>Ho(e,nf,_v),fn=e=>Ho(e,uf,Kv),$=e=>of.test(e),Rr=e=>Uo(e,df),Yv=e=>Uo(e,ey),Jc=e=>Uo(e,sf),Jv=e=>Uo(e,lf),Zv=e=>Uo(e,nf),mn=e=>Uo(e,uf,true),Ho=(e,o,t)=>{let a=af.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Uo=(e,o,t=false)=>{let a=of.exec(e);return a?a[1]?o(a[1]):t:false},sf=e=>e==="position"||e==="percentage",nf=e=>e==="image"||e==="url",lf=e=>e==="length"||e==="size"||e==="bg-size",df=e=>e==="length",Qv=e=>e==="number",ey=e=>e==="family-name",uf=e=>e==="shadow";var ty=()=>{let e=He("color"),o=He("font"),t=He("text"),a=He("font-weight"),s=He("tracking"),r=He("leading"),n=He("breakpoint"),l=He("container"),d=He("spacing"),u=He("radius"),m=He("shadow"),f=He("inset-shadow"),i=He("text-shadow"),c=He("drop-shadow"),p=He("blur"),y=He("perspective"),h=He("aspect"),x=He("ease"),b=He("animate"),g=()=>["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"],C=()=>[...L(),$,X],S=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],v=()=>[$,X,d],M=()=>[qo,"full","auto",...v()],B=()=>[Ma,"none","subgrid",$,X],D=()=>["auto",{span:["full",Ma,$,X]},Ma,$,X],O=()=>[Ma,"auto",$,X],W=()=>["auto","min","max","fr",$,X],T=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],R=()=>["auto",...v()],oe=()=>[qo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],V=()=>[e,$,X],se=()=>[...L(),Jc,Yc,{position:[$,X]}],G=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",Jv,Xv,{size:[$,X]}],_=()=>[Cl,Rr,Ya],H=()=>["","none","full",u,$,X],K=()=>["",de,Rr,Ya],te=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[de,Cl,Jc,Yc],le=()=>["","none",p,$,X],Ie=()=>["none",de,$,X],Y=()=>["none",de,$,X],Me=()=>[de,$,X],Be=()=>[qo,"full",...v()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ta],breakpoint:[ta],color:[zv],container:[ta],"drop-shadow":[ta],ease:["in","out","in-out"],font:[jv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ta],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ta],shadow:[ta],spacing:["px",de],text:[ta],"text-shadow":[ta],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",qo,X,$,h]}],container:["container"],columns:[{columns:[de,X,$,l]}],"break-after":[{"break-after":g()}],"break-before":[{"break-before":g()}],"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:C()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:M()}],"inset-x":[{"inset-x":M()}],"inset-y":[{"inset-y":M()}],start:[{start:M()}],end:[{end:M()}],top:[{top:M()}],right:[{right:M()}],bottom:[{bottom:M()}],left:[{left:M()}],visibility:["visible","invisible","collapse"],z:[{z:[Ma,"auto",$,X]}],basis:[{basis:[qo,"full","auto",l,...v()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,qo,"auto","initial","none",X]}],grow:[{grow:["",de,$,X]}],shrink:[{shrink:["",de,$,X]}],order:[{order:[Ma,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":B()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":B()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":W()}],"auto-rows":[{"auto-rows":W()}],gap:[{gap:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:[...T(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...T()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":T()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:v()}],px:[{px:v()}],py:[{py:v()}],ps:[{ps:v()}],pe:[{pe:v()}],pt:[{pt:v()}],pr:[{pr:v()}],pb:[{pb:v()}],pl:[{pl:v()}],m:[{m:R()}],mx:[{mx:R()}],my:[{my:R()}],ms:[{ms:R()}],me:[{me:R()}],mt:[{mt:R()}],mr:[{mr:R()}],mb:[{mb:R()}],ml:[{ml:R()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"space-y-reverse":["space-y-reverse"],size:[{size:oe()}],w:[{w:[l,"screen",...oe()]}],"min-w":[{"min-w":[l,"screen","none",...oe()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[n]},...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,Rr,Ya]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,kl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Cl,X]}],"font-family":[{font:[Yv,X,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:[s,$,X]}],"line-clamp":[{"line-clamp":[de,"none",$,kl]}],leading:[{leading:[r,...v()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",$,Ya]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[de,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:v()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:se()}],"bg-repeat":[{bg:G()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ma,$,X],radial:["",$,X],conic:[Ma,$,X]},Zv,$v]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:_()}],"gradient-via-pos":[{via:_()}],"gradient-to-pos":[{to:_()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...te(),"hidden","none"]}],"divide-style":[{divide:[...te(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Rr,Ya]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",m,mn,fn]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",f,mn,fn]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[de,Ya]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",i,mn,fn]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[de,$,X]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"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":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"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":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"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":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"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":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"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":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"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":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"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":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[$,X]}],"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":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:se()}],"mask-repeat":[{mask:G()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:le()}],brightness:[{brightness:[de,$,X]}],contrast:[{contrast:[de,$,X]}],"drop-shadow":[{"drop-shadow":["","none",c,mn,fn]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",de,$,X]}],"hue-rotate":[{"hue-rotate":[de,$,X]}],invert:[{invert:["",de,$,X]}],saturate:[{saturate:[de,$,X]}],sepia:[{sepia:["",de,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[de,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,$,X]}],"backdrop-invert":[{"backdrop-invert":["",de,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":v()}],"border-spacing-x":[{"border-spacing-x":v()}],"border-spacing-y":[{"border-spacing-y":v()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",$,X]}],ease:[{ease:["linear","initial",x,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",b,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,$,X]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Y()}],"scale-x":[{"scale-x":Y()}],"scale-y":[{"scale-y":Y()}],"scale-z":[{"scale-z":Y()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Be()}],"translate-x":[{"translate-x":Be()}],"translate-y":[{"translate-y":Be()}],"translate-z":[{"translate-z":Be()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":v()}],"scroll-mx":[{"scroll-mx":v()}],"scroll-my":[{"scroll-my":v()}],"scroll-ms":[{"scroll-ms":v()}],"scroll-me":[{"scroll-me":v()}],"scroll-mt":[{"scroll-mt":v()}],"scroll-mr":[{"scroll-mr":v()}],"scroll-mb":[{"scroll-mb":v()}],"scroll-ml":[{"scroll-ml":v()}],"scroll-p":[{"scroll-p":v()}],"scroll-px":[{"scroll-px":v()}],"scroll-py":[{"scroll-py":v()}],"scroll-ps":[{"scroll-ps":v()}],"scroll-pe":[{"scroll-pe":v()}],"scroll-pt":[{"scroll-pt":v()}],"scroll-pr":[{"scroll-pr":v()}],"scroll-pb":[{"scroll-pb":v()}],"scroll-pl":[{"scroll-pl":v()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,X]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[de,Rr,Ya,kl]}],stroke:[{stroke:["none",...V()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}};var cf=Bv(ty);function Ta(...e){return cf(cn(e))}function pn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:l,...d}){let u=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(zc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Ta("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),...d,children:[jsx(Gc,{"data-slot":"slider-track",className:Ta("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(Kc,{"data-slot":"slider-range",className:Ta("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:u.length},(m,f)=>jsx(_c,{"data-slot":"slider-thumb",className:Ta("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",l)},f))]})}var oy="SchooplaVideoStorage";var $t="videos",hn=()=>new Promise((e,o)=>{let t=indexedDB.open(oy,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains($t)||s.createObjectStore($t,{keyPath:"id"});};}),Ja=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await hn(),r=a.transaction([$t],"readwrite").objectStore($t),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((l,d)=>{let u=r.put(n);u.onsuccess=()=>l(!0),u.onerror=()=>d(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 mf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await hn(),t=e.transaction([$t],"readonly").objectStore($t);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,l=new Map;n.forEach(d=>{l.set(d.id,{blob:d.blob,thumbnailDataUrl:d.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${l.size} video blobs from IndexedDB`),a(l);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Al=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await hn(),a=o.transaction([$t],"readwrite").objectStore($t);await new Promise((s,r)=>{let n=a.delete(e);n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},pf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await hn(),t=e.transaction([$t],"readwrite").objectStore($t);await new Promise((a,s)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>s(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},hf=e=>URL.createObjectURL(e);var ry=be[" useId ".trim().toString()]||(()=>{}),sy=0;function gf(e){let[o,t]=be.useState(ry());return Oo(()=>{t(a=>a??String(sy++));},[e]),(o?`radix-${o}`:"")}function xf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Dl="rovingFocusGroup.onEntryFocus",ny={bubbles:false,cancelable:true},Er="RovingFocusGroup",[Rl,bf,iy]=dn(Er),[ly,El]=ka(Er,[iy]),[dy,uy]=ly(Er),vf=be.forwardRef((e,o)=>jsx(Rl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Rl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(cy,{...e,ref:o})})}));vf.displayName=Er;var cy=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:m=false,...f}=e,i=be.useRef(null),c=Dt(o,i),p=No(r),[y,h]=ea({prop:n,defaultProp:l??null,onChange:d,caller:Er}),[x,b]=be.useState(false),g=xf(u),L=bf(t),C=be.useRef(false),[S,k]=be.useState(0);return be.useEffect(()=>{let v=i.current;if(v)return v.addEventListener(Dl,g),()=>v.removeEventListener(Dl,g)},[g]),jsx(dy,{scope:t,orientation:a,dir:p,loop:s,currentTabStopId:y,onItemFocus:be.useCallback(v=>h(v),[h]),onItemShiftTab:be.useCallback(()=>b(true),[]),onFocusableItemAdd:be.useCallback(()=>k(v=>v+1),[]),onFocusableItemRemove:be.useCallback(()=>k(v=>v-1),[]),children:jsx(lt.div,{tabIndex:x||S===0?-1:0,"data-orientation":a,...f,ref:c,style:{outline:"none",...e.style},onMouseDown:Ye(e.onMouseDown,()=>{C.current=true;}),onFocus:Ye(e.onFocus,v=>{let M=!C.current;if(v.target===v.currentTarget&&M&&!x){let B=new CustomEvent(Dl,ny);if(v.currentTarget.dispatchEvent(B),!B.defaultPrevented){let D=L().filter(R=>R.focusable),O=D.find(R=>R.active),W=D.find(R=>R.id===y),U=[O,W,...D].filter(Boolean).map(R=>R.ref.current);Lf(U,m);}}C.current=false;}),onBlur:Ye(e.onBlur,()=>b(false))})})}),yf="RovingFocusGroupItem",wf=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...l}=e,d=gf(),u=r||d,m=uy(yf,t),f=m.currentTabStopId===u,i=bf(t),{onFocusableItemAdd:c,onFocusableItemRemove:p,currentTabStopId:y}=m;return be.useEffect(()=>{if(a)return c(),()=>p()},[a,c,p]),jsx(Rl.ItemSlot,{scope:t,id:u,focusable:a,active:s,children:jsx(lt.span,{tabIndex:f?0:-1,"data-orientation":m.orientation,...l,ref:o,onMouseDown:Ye(e.onMouseDown,h=>{a?m.onItemFocus(u):h.preventDefault();}),onFocus:Ye(e.onFocus,()=>m.onItemFocus(u)),onKeyDown:Ye(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let x=py(h,m.orientation,m.dir);if(x!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let g=i().filter(L=>L.focusable).map(L=>L.ref.current);if(x==="last")g.reverse();else if(x==="prev"||x==="next"){x==="prev"&&g.reverse();let L=g.indexOf(h.currentTarget);g=m.loop?hy(g,L+1):g.slice(L+1);}setTimeout(()=>Lf(g));}}),children:typeof n=="function"?n({isCurrentTabStop:f,hasTabStop:y!=null}):n})})});wf.displayName=yf;var fy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function my(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function py(e,o,t){let a=my(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return fy[a]}function Lf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function hy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var Sf=vf,If=wf;var kf="Toggle",Fl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,l]=ea({prop:t,onChange:s,defaultProp:a??false,caller:kf});return jsx(lt.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:Ye(e.onClick,()=>{e.disabled||l(!n);})})});Fl.displayName=kf;var Aa="ToggleGroup",[Tf]=ka(Aa,[El]),Af=El(),Bl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(by,{...a,ref:o});if(t==="multiple")return jsx(vy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Aa}\``)});Bl.displayName=Aa;var[Pf,Df]=Tf(Aa),by=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,l]=ea({prop:t,defaultProp:a??"",onChange:s,caller:Aa});return jsx(Pf,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:l,onItemDeactivate:be__default.useCallback(()=>l(""),[l]),children:jsx(Rf,{...r,ref:o})})}),vy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,l]=ea({prop:t,defaultProp:a??[],onChange:s,caller:Aa}),d=be__default.useCallback(m=>l((f=[])=>[...f,m]),[l]),u=be__default.useCallback(m=>l((f=[])=>f.filter(i=>i!==m)),[l]);return jsx(Pf,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:d,onItemDeactivate:u,children:jsx(Rf,{...r,ref:o})})});Bl.displayName=Aa;var[yy,wy]=Tf(Aa),Rf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:l=true,...d}=e,u=Af(t),m=No(n),f={role:"group",dir:m,...d};return jsx(yy,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(Sf,{asChild:true,...u,orientation:r,dir:m,loop:l,children:jsx(lt.div,{...f,ref:o})}):jsx(lt.div,{...f,ref:o})})}),gn="ToggleGroupItem",Ly=be__default.forwardRef((e,o)=>{let t=Df(gn,e.__scopeToggleGroup),a=wy(gn,e.__scopeToggleGroup),s=Af(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,l={...e,pressed:r,disabled:n},d=be__default.useRef(null);return a.rovingFocus?jsx(If,{asChild:true,...s,focusable:!n,active:r,ref:d,children:jsx(Mf,{...l,ref:o})}):jsx(Mf,{...l,ref:o})});Ly.displayName=gn;var Mf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Df(gn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},l=r.type==="single"?n:void 0;return jsx(Fl,{...l,...s,ref:o,onPressedChange:d=>{d?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Ef=Bl;var Cy=be.createContext({size:"default",variant:"default",spacing:0});function Pa({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Ef,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ta("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Cy.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var My={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Vf=createSlice({name:"toolbar",initialState:My,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:zt,setPenColor:zo,setStrokeWidth:Fr,setFontSize:nD,setFontFamily:iD,setFontStyle:lD,setFontWeight:dD,setTextDecoration:uD,setTextColor:cD}=Vf.actions,qf=Vf.reducer;var Hf=({onClose:e,onRecordingComplete:o})=>{let t=ot(),[a,s]=useState(false),[r,n]=useState(null),[l,d]=useState(0),[u,m]=useState(null),[f,i]=useState(false),c=useRef(null),p=useRef([]),y=useRef(null),h=useRef(null),x=useRef(null);useEffect(()=>((async()=>{try{let M=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(M),i(!0),x.current&&(x.current.srcObject=M);}catch(M){console.error("Error accessing camera:",M),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{y.current&&clearInterval(y.current),u&&u.getTracks().forEach(M=>M.stop());}),[]);let b=()=>{u&&(u.getTracks().forEach(v=>v.stop()),m(null),i(false));},g=async()=>{try{let v=null,M=null;try{v=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(T){console.error("Error accessing camera for recording:",T),alert("Failed to access camera for recording.");return}try{M=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(T){console.warn("Microphone access denied:",T);}let B=[...v.getVideoTracks()];M&&B.push(...M.getAudioTracks());let D=new MediaStream(B),O="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?O="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?O="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?O="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(O="video/webm;codecs=vp8");let W=new MediaRecorder(D,{mimeType:O,videoBitsPerSecond:25e5});c.current=W,p.current=[],W.ondataavailable=T=>{T.data.size>0&&p.current.push(T.data);},W.onstop=()=>{let T=new Blob(p.current,{type:O}),U=document.createElement("video");U.src=URL.createObjectURL(T),U.muted=!0,U.currentTime=.1,U.onseeked=()=>{let R=document.createElement("canvas");R.width=U.videoWidth,R.height=U.videoHeight;let oe=R.getContext("2d");oe&&(oe.drawImage(U,0,0),h.current=R.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(U.src);},D.getTracks().forEach(R=>R.stop()),v&&v.getTracks().forEach(R=>R.stop()),M&&M.getTracks().forEach(R=>R.stop()),y.current&&clearInterval(y.current),n(T),b();},W.onerror=T=>{console.error("MediaRecorder error:",T);},W.start(1e3),s(!0),d(0),y.current=setInterval(()=>{d(T=>T+1);},1e3);}catch(v){console.error("Error starting camera recording:",v),alert("Failed to start recording. Please check permissions.");}},L=()=>{c.current&&a&&(c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),s(false));},C=()=>{if(r){let v=URL.createObjectURL(r),M=document.createElement("a");M.href=v,M.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(v);}},S=v=>{let M=Math.floor(v/60),B=v%60;return `${M.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:v=>{v.target===v.currentTarget&&e(),v.stopPropagation();},onMouseUp:v=>v.stopPropagation(),onMouseMove:v=>v.stopPropagation(),onTouchStart:v=>v.stopPropagation(),onTouchMove:v=>v.stopPropagation(),onTouchEnd:v=>v.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:v=>v.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:x,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,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"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:L,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:S(l)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",S(l)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),d(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:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&h.current&&(o(r,h.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,t)};var aa=40,Wf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[l,d]=useState(false),u=useRef(null),m=ot(),f=useRef(null);useEffect(()=>{let g=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let i=g=>{let L=g.target.files;if(!L||L.length===0)return;let C=aa-a.length;if(C<=0){alert(`You can only upload a maximum of ${aa} images`);return}let S=Array.from(L).slice(0,C);S.length<L.length&&alert(`Only ${C} more images can be added (max ${aa} total)`);let k=S.map(v=>new Promise((M,B)=>{let D=new FileReader;D.onload=O=>{O.target?.result?M(O.target.result):B(new Error("Failed to read file"));},D.onerror=B,D.readAsDataURL(v);}));Promise.all(k).then(v=>{s(M=>[...M,...v]),f.current&&(f.current.value="");});},c=g=>{g.preventDefault(),d(false);let L=Array.from(g.dataTransfer.files).filter(v=>v.type.startsWith("image/"));if(L.length===0)return;let C=aa-a.length;if(C<=0){alert(`You can only upload a maximum of ${aa} images`);return}let S=L.slice(0,C);S.length<L.length&&alert(`Only ${C} more images can be added (max ${aa} total)`);let k=S.map(v=>new Promise((M,B)=>{let D=new FileReader;D.onload=O=>{O.target?.result?M(O.target.result):B(new Error("Failed to read file"));},D.onerror=B,D.readAsDataURL(v);}));Promise.all(k).then(v=>{s(M=>[...M,...v]);});},p=g=>{g.preventDefault(),d(true);},y=()=>{d(false);},h=g=>{s(L=>L.filter((C,S)=>S!==g));},x=g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!m)return null;let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:u,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x,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:i,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:c,onDragOver:p,onDragLeave:y,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${l?"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:l?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="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 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="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 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>h(L),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:L+1})]},L))})]}),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(b,m)};var xn={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}},zy={enabled:true};function ql(e){return e?{tools:{...xn.tools,...e.tools},actions:{...xn.actions,...e.actions}}:xn}var Gy={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}},Ky={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 vw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=xe(),n=Q(E=>E.canvas.slides.find(re=>re.id===E.canvas.currentSlideId)),l=n?.videos||[],d=n?.editingFlashcard,u=Q(E=>E.toolbar.selectedTool),m=Q(E=>E.toolbar.penColor),f=Q(E=>E.toolbar.strokeWidth),i=n?.showMcqForm,c=n?.showFlashcardForm,p=useRef(null),y=useMemo(()=>ql(s),[s]),{tools:h,actions:x}=y,b=l.some(E=>E.isRecorded&&E.isPlaying),g=Q(E=>E.toolbar.fontSize),L=Q(E=>E.toolbar.fontFamily),C=Q(E=>E.toolbar.fontStyle),S=Q(E=>E.toolbar.fontWeight),k=Q(E=>E.toolbar.textDecoration),v=Q(E=>E.toolbar.textColor),[M,B]=useState(false),[D,O]=useState(false),[W,T]=useState(false),[U,R]=useState(false),[oe,V]=useState(false),[se,G]=useState(false),[q,_]=useState(false),H=useRef(null),K=useRef(null),te=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"}],[]),J=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"}],[]),le=useMemo(()=>te.filter(E=>{let re=h[E.configKey];return typeof re=="boolean"?re:Array.isArray(re)?re.length>0:true}),[h,te]),Ie=useMemo(()=>{let E=h.shapes;return E===false?[]:E===true?Z:Array.isArray(E)?Z.filter(re=>E.includes(re.name)):Z},[h.shapes,Z]),Y=useMemo(()=>{let E=h.activities;return E===false?[]:E===true?J:Array.isArray(E)?J.filter(re=>E.includes(re.name)):J},[h.activities,J]),Me=useMemo(()=>{let E=h.media;return E===false?{photoFrame:false,image:false,video:false}:E===true?{photoFrame:true,image:true,video:true}:Array.isArray(E)?{photoFrame:E.includes("photo-frame"),image:E.includes("image"),video:E.includes("video")}:{photoFrame:true,image:true,video:true}},[h.media]),Be=useMemo(()=>{let E=h.activities;return E===false?false:E===true?true:Array.isArray(E)?E.includes("flashcard"):true},[h.activities]),Et=E=>{let re=E.target.files;!re||re.length===0||(r(zt("select")),r(ft(false)),R(false),Array.from(re).forEach(ye=>{let ge=new FileReader;ge.onload=ne=>{let ue=new window.Image;ue.src=ne.target?.result,ue.onload=()=>{let we=ue.width/ue.height,Ne=300,Ft=300,ut=ue.width,Te=ue.height;ut>Ne&&(ut=Ne,Te=ut/we),Te>Ft&&(Te=Ft,ut=Te*we),r(ce());let Ue=960-ut/2,Jt=540-Te/2;r(Kn({id:v4(),src:ue.src,x:Ue,y:Jt,width:ut,height:Te,draggable:true,rotation:0}));};},ge.readAsDataURL(ye);}),E.target.value="");},oo=async E=>{let re=E.target.files;if(!(!re||re.length===0)){console.log("files",E),r(zt("select")),r(ft(false)),R(false);for(let ye of Array.from(re))try{let ge=URL.createObjectURL(ye),ne=document.createElement("video");console.log("video",ne),ne.src=ge,ne.muted=!0,ne.playsInline=!0,ne.preload="auto",ne.load(),await new Promise((Bt,da)=>{let Fa=setTimeout(()=>da(new Error("Metadata load timeout")),1e4);ne.onloadedmetadata=()=>{clearTimeout(Fa),Bt();},ne.onerror=()=>{clearTimeout(Fa),da(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ne.duration,width:ne.videoWidth,height:ne.videoHeight}),await new Promise((Bt,da)=>{let Fa=setTimeout(()=>da(new Error("Video load timeout")),1e4);ne.readyState>=2?(clearTimeout(Fa),Bt()):ne.onloadeddata=()=>{clearTimeout(Fa),Bt();};});let ue=Math.min(.8,ne.duration/2);console.log("Seeking to:",ue),ne.currentTime=ue,await new Promise(Bt=>{let da=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Bt();},5e3);ne.onseeked=()=>{clearTimeout(da),console.log("Seek completed"),Bt();};});let we=document.createElement("canvas"),Ne=ne.videoWidth/ne.videoHeight,Ft=400,ut=400,Te=ne.videoWidth,Ue=ne.videoHeight;Te>Ft&&(Te=Ft,Ue=Te/Ne),Ue>ut&&(Ue=ut,Te=Ue*Ne),we.width=Te,we.height=Ue;let Jt=we.getContext("2d",{willReadFrequently:!1});if(!Jt)throw new Error("Failed to get canvas context");if(await new Promise(Bt=>setTimeout(Bt,100)),ne.videoWidth===0||ne.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Te,height:Ue}),Jt.drawImage(ne,0,0,Te,Ue);let la=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",la.length),r(ce());let Ea=960-Te/2,Dn=540-Ue/2,zr=v4();await Ja(zr,ye,la),r(Qr({id:zr,objectUrl:ge,thumbnailDataUrl:la,videoBlob:ye,x:Ea,y:Dn,width:Te,height:Ue,draggable:!0,isPlaying:!1,rotation:0})),ne.src="",ne.load(),console.log(`Video uploaded: ${ye.name}`);}catch(ge){console.error("Error processing video:",ge),alert(`Failed to process video: ${ye.name}`);}E.target.value="";}},Hr=(E,re,ye)=>{r(ce()),r(zt("select")),r(ft(false));let ge=300,ne=300,ue=960-ge/2,we=540-ne/2;r(ye?co({id:ye,images:E,order:re,x:ue,y:we,width:ge,height:ne,rotation:0,draggable:true}):Xn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:E,currentIndex:0,order:re,x:ue,y:we,width:ge,height:ne,rotation:0,draggable:true})),r(Oa(false));},Ur=()=>{r(ce()),r(zt("select")),r(ft(false));let E=400,re=300,ye=800-E/2,ge=450-re/2;if(t?.current){let ne=t.current,ue=ne.scaleX()||1,we=ne.scaleY()||1,Ne=ne.width()/ue,Ft=ne.height()/we;ye=Ne/2-E/2,ge=Ft/2-re/2;}r(Jn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ye,y:ge,width:E,height:re,rotation:0,draggable:true,isCapturing:false})),V(false);},In=E=>{let ue={};switch(E.name){case "circle":case "ring":case "wedge":case "arc":ue.radius=50,(E.name==="ring"||E.name==="arc")&&(ue.innerRadius=25,ue.outerRadius=50),(E.name==="wedge"||E.name==="arc")&&(ue.angle=E.name==="wedge"?60:90);break;case "ellipse":ue.radiusX=60,ue.radiusY=40;break;case "triangle":ue.radius=50,ue.sides=3;break;case "polygon":ue.radius=50,ue.sides=6;break;case "star":ue.innerRadius=25,ue.outerRadius=50,ue.numPoints=5;break;case "arrow":case "line":ue.points=[0,0,100,0],E.name==="arrow"&&(ue.pointerLength=10,ue.pointerWidth=10);break}let we={id:`shape-${Date.now()}`,type:E.name,x:910,y:490,width:100,height:100,rotation:0,color:m,...ue};r(ce()),r(ft(false)),r(zt(E.name)),r(_n(we));},ro=E=>{if(r(zt(E)),E==="select")r(ft(false));else if(E==="text"){r(ft(false)),r(ce());let re=200,ye=50,ge=960-re/2,ne=540-ye/2,we=window.innerWidth<768?Math.max(g,32):g,Ne=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(jn({id:Ne,text:"",x:ge,y:ne,width:re,height:ye,rotation:0,draggable:true,fontSize:we,fontFamily:L,fontStyle:C,fontWeight:S,textDecoration:k,fill:v,align:"left"})),setTimeout(()=>{r(er(Ne));},100),a&&a(Ne);}else r(ft(true));},Cn=()=>{r(mi()),r(zt("select")),r(ft(false));},kn=()=>{o?o():t?B(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Mn=()=>{O(true);},ia=async(E,re)=>{try{r(zt("select")),r(ft(!1));let ye=URL.createObjectURL(E),ge=document.createElement("video");ge.src=ye,ge.muted=!0,ge.playsInline=!0,ge.preload="auto",await new Promise((Ue,Jt)=>{let la=setTimeout(()=>Jt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(la),Ue();},ge.onerror=()=>{clearTimeout(la),Jt(new Error("Failed to load video"));};});let ne=640,ue=ge.videoWidth/ge.videoHeight,we=ne,Ne=we/ue;r(ce());let Ft=960-we/2,ut=540-Ne/2,Te=v4();await Ja(Te,E,re),r(Qr({id:Te,objectUrl:ye,thumbnailDataUrl:re,videoBlob:E,x:Ft,y:ut,width:we,height:Ne,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),B(!1),O(!1);}catch(ye){console.error("Error adding recorded video to canvas:",ye),alert("Failed to add video to canvas. Please try again.");}},Tn=E=>{r(zt("select")),r(ft(false)),r(Zo(null)),E&&r(ii(E)),r(ma(!i));},An=()=>{r(Xo(null)),r(Oa(true)),V(false);},so=()=>{T(!W);},Wr=()=>{R(!U);},Pn=()=>{V(!oe);};return useEffect(()=>{if(!q)return;let E=re=>{p.current&&!p.current.contains(re.target)&&_(false);};return document.addEventListener("mousedown",E),()=>{document.removeEventListener("mousedown",E);}},[q]),b?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(Pa,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:le.map((E,re)=>jsx("div",{title:E.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${E.name===u?"bg-primary/10":""}`,onClick:()=>{if(E.name==="image"){Wr(),T(false),V(false),ro(E.name);return}else if(E.name==="shapes"){so(),R(false),V(false),ro(E.name);return}else if(E.name==="activities"){ro(E.name),Pn(),T(false),R(false);return}ro(E.name),T(false),R(false),V(false);},children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl"})},re))}),W&&jsx(Pa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:Ie.map((E,re)=>jsx("div",{title:E.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>In(E),children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl"})},re))}),U&&jsxs(Pa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Ur,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Me.image&&jsx("div",{title:"Image",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Me.video&&jsx("div",{title:"Video",onClick:()=>K.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),oe&&jsxs(Pa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Be&&jsx("div",{title:"Flashcard",onClick:()=>An(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Y.map((E,re)=>jsx("div",{title:E.label,onClick:()=>Tn(E.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(E.icon,{weight:"fill",className:"text-primary text-xl"})},re))]})]}),(x.undo||x.redo||x.screenRecord||x.cameraRecord||x.clear)&&jsxs(Pa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[x.undo&&jsx("button",{value:"undo",onClick:()=>r(pi()),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"})}),x.redo&&jsx("button",{value:"redo",onClick:()=>r(hi()),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"})}),x.screenRecord&&jsx("button",{value:"screen-record",onClick:kn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>G(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:m},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:m}})}),jsxs("div",{ref:p,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>_(!q),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${q?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:f})})}),q&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(pn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[f],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:E=>r(Fr(E[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),x.cameraRecord&&jsx("button",{value:"camera-record",onClick:Mn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),x.clear&&jsx("button",{value:"clear",onClick:()=>Cn(),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"})})]})]}),jsx("input",{ref:H,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Et}),jsx("input",{ref:K,type:"file",accept:"video/*",className:"hidden",onChange:oo}),!o&&M&&t&&jsx(dr,{onClose:()=>B(false),stageRef:t,onRecordingComplete:ia}),D&&jsx(Hf,{onClose:()=>O(false),onRecordingComplete:ia}),c&&jsx(Wf,{editingFlashcard:d,onConfirm:Hr,onCancel:()=>r(Oa(false))}),se&&jsx(Fs,{defaultColor:m,onConfirm:E=>{r(zo(E)),G(false);},onCancel:()=>G(false)})]})},yw=vw;var Gl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=ct(mo),r=ct(vi),n=a?r:s,l=ct(tr),m=(ct(b=>b.canvas.slides.find(g=>g.id===b.canvas.currentSlideId))?.videos||[]).some(b=>b.isRecorded&&b.isPlaying),[f,i]=useState(false),[c,p]=useState(null),[y,h]=useState(null),x=async()=>{if(s.length===0){h({type:"error",message:"No slides to publish"});return}if(!e){h({type:"error",message:"No publish handler provided"});return}i(true),h(null);try{let b=await e(n,l,g=>{p(g);});b.success?h({type:"success",message:b.message}):h({type:"error",message:b.message});}catch(b){h({type:"error",message:b instanceof Error?b.message:"An unexpected error occurred"});}finally{i(false),setTimeout(()=>{p(null),h(null);},3e3);}};return m?null:jsxs("button",{onClick:x,disabled:f||s.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 Cw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:l=true,editableTitle:d=true,editableDescription:u=true,className:m="",rightContent:f,leftContent:i,includeInactiveSlides:c=false})=>{let p=at(),y=ct(tr),h=ct(wi),x=e??(h?y.title:"")??"Untitled",b=o??(h?y.description:"")??"Add a description...",[g,L]=useState(false),[C,S]=useState(false),[k,v]=useState(x),[M,B]=useState(b),D=useRef(null),O=useRef(null);useEffect(()=>{v(x);},[x]),useEffect(()=>{B(b);},[b]),useEffect(()=>{g&&D.current&&(D.current.focus(),D.current.select());},[g]),useEffect(()=>{C&&O.current&&(O.current.focus(),O.current.select());},[C]);let W=()=>{d&&L(true);},T=()=>{u&&S(true);},U=()=>{L(false),k.trim()&&k!==x?s?s(k.trim()):p(gi(k.trim())):k.trim()||v(x);},R=()=>{S(false),M.trim()&&M!==b?r?r(M.trim()):p(xi(M.trim())):M.trim()||B(b);},oe=se=>{se.key==="Enter"?U():se.key==="Escape"&&(v(x),L(false));},V=se=>{se.key==="Enter"?R():se.key==="Escape"&&(B(b),S(false));};return jsxs("div",{className:`fixed top-0 left-0 z-100 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${m}`,children:[i||jsxs("div",{className:"flex items-center gap-6",children:[l&&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:[g?jsx("input",{ref:D,type:"text",value:k,onChange:se=>v(se.target.value),onBlur:U,onKeyDown:oe,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:W,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${d?"hover:border-primary cursor-text":""}`,children:k}),C?jsx("input",{ref:O,type:"text",value:M,onChange:se=>B(se.target.value),onBlur:R,onKeyDown:V,className:"border-primary w-full rounded-sm border-2 bg-transparent text-sm font-medium text-[#63748A] outline-none md:text-base"}):jsx("span",{onClick:T,title:M,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:M})]})]}),f||n&&a&&jsx(Gl,{onPublish:a,includeInactiveSlides:c})]})};var Dw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Rw=({colors:e=Dw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),l=Q(he),d=Q(i=>i.toolbar.penColor),u=Q(i=>i.toolbar.strokeWidth),m=l?.backgroundColor,f=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${s}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between 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(pn,{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",value:[u],onValueChange:i=>f(Fr(i[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Pa,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(i=>jsx("button",{value:i.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${d===i.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:i.value},onClick:()=>f(zo(i.value))},i.value)),jsxs("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-[#ffff] text-xl text-[#00000099] lg:h-12 lg:w-12",children:[jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>f(zo(i.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:i=>f(zn(i.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var _f=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ew=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),_l=e=>{let o=Ew(e);return o.charAt(0).toUpperCase()+o.slice(1)},wn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),jf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Xf={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 Yf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...l},d)=>createElement("svg",{ref:d,...Xf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:wn("lucide",s),...!r&&!jf(l)&&{"aria-hidden":"true"},...l},[...n.map(([u,m])=>createElement(u,m)),...Array.isArray(r)?r:[r]]));var Ln=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(Yf,{ref:r,iconNode:o,className:wn(`lucide-${_f(_l(e))}`,`lucide-${e}`,a),...s}));return t.displayName=_l(e),t};var Nw=[["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"}]],Nr=Ln("copy",Nw);var Vw=[["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"}]],Vr=Ln("trash-2",Vw);var Zf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:s,onDuplicate:r,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:s,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:l=>{l.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Nr,{size:14})}),!a&&jsx("button",{onClick:l=>{l.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Vr,{size:14})})]}),jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-gray-100",children:e.thumbnail?jsx("img",{src:e.thumbnail,alt:`Page ${o+1}`,className:"h-full w-full object-contain"}):jsx("div",{className:"text-sm text-gray-400",children:"No preview"})}),jsx("div",{className:"truncate bg-white p-2 text-xs text-gray-700",children:e.name})]});var Ww=({softDelete:e=false})=>{let o=at(),t=ct(mo),a=ct(fo),s=ct(yi),[r,n]=useState(true),u=(ct(p=>p.canvas.slides.find(y=>y.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),m=()=>{s&&o(Vn());},f=p=>{o(Un(p));},i=p=>{o(Hn(p));},c=p=>{t.length>1&&o(qn({id:p,softDelete:e}));};return u?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] 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:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((p,y)=>jsx(Zf,{slide:p,index:y,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>f(p.id),onDuplicate:()=>i(p.id),onDelete:()=>c(p.id)},p.id))}),jsxs("button",{onClick:m,disabled:!s,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${s?"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 zw="SchooplaEditorDB",Gw=1,Da="slides",Ra="metadata",jl="schoopla_current_slide_id",tm="presentation_metadata",qr=()=>new Promise((e,o)=>{let t=indexedDB.open(zw,Gw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Da)||s.createObjectStore(Da,{keyPath:"id"}),s.objectStoreNames.contains(Ra)||s.createObjectStore(Ra,{keyPath:"id"});};}),Xl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await qr(),a=o.transaction([Da],"readwrite").objectStore(Da);await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);});for(let s of e)await new Promise((r,n)=>{let l=a.add(s);l.onsuccess=()=>r(!0),l.onerror=()=>n(l.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);}}},$l=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await qr(),t=e.transaction([Da],"readonly").objectStore(Da);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(l=>({id:l.id,width:l.width,height:l.height,x:l.x,y:l.y}))),a(n.length>0?n:null);},r.onerror=()=>{e.close(),s(r.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}}},Sn=async()=>{try{let e=await qr(),o=e.transaction([Da,Ra],"readwrite"),t=o.objectStore(Da),a=o.objectStore(Ra);await new Promise((s,r)=>{let n=t.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(jl),localStorage.removeItem("schoopla_presentation_metadata"),await pf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Yl=e=>{try{localStorage.setItem(jl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Jl=()=>{try{return localStorage.getItem(jl)}catch(e){return console.error("Error loading current slide ID:",e),null}},Zl=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Ql=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await qr(),a=o.transaction([Ra],"readwrite").objectStore(Ra);await new Promise((s,r)=>{let n=a.put({id:tm,...e});n.onsuccess=()=>s(!0),n.onerror=()=>r(n.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);}}},ed=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await qr(),t=e.transaction([Ra],"readonly").objectStore(Ra);return new Promise((a,s)=>{let r=t.get(tm);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:l,...d}=n;console.log("\u2705 Loaded presentation metadata:",d),a(d);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),s(r.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 Kw=["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","canvas/updateSlideThumbnail"],_w=["canvas/clearCanvas"],jw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],Xw=Zl((e,o)=>{Xl(e),Yl(o);},500),$w=Zl(e=>{Ql(e);},500),Yw=(e,o)=>{Xl(e),Yl(o);},td=false,am=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let s=t.payload;Al(s).catch(r=>{console.error("Error deleting video blob:",r);});}if(t.type==="canvas/deleteSlide"&&t.payload){let s=t.payload,n=e.getState().canvas.slides.find(l=>l.id===s);n&&n.videos&&n.videos.length>0&&n.videos.forEach(l=>{Al(l.id).catch(d=>{console.error("Error deleting video blob:",d);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let s=t.payload,r=e.getState(),l=r.canvas.slides.find(d=>d.id===r.canvas.currentSlideId)?.videos.find(d=>d.id===s);l&&l.videoBlob&&setTimeout(()=>{let d=e.getState(),m=d.canvas.slides.find(f=>f.id===d.canvas.currentSlideId)?.videos.find(f=>f.id!==s&&f.x===l.x+20&&f.y===l.y+20);m&&l.videoBlob&&Ja(m.id,l.videoBlob,m.thumbnailDataUrl).catch(f=>{console.error("Error saving duplicated video blob:",f);});},0);}let a=o(t);if(t.type&&_w.includes(t.type)){if(!td){td=true;try{let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;Yw(r,n);}finally{setTimeout(()=>{td=false;},0);}}}else if(t.type&&Kw.includes(t.type)){let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;Xw(r,n);}else if(t.type&&jw.includes(t.type)){let s=e.getState(),{presentationMetadata:r}=s.canvas;$w(r);}return a});new QueryClient;var Qw=configureStore({reducer:{toolbar:qf,canvas:bd},middleware:e=>e({serializableCheck:false}).concat(am)});var eL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2,fileName:r=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",l=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),d=document.createElement("a");d.download=`${r}.${t}`,d.href=l,document.body.appendChild(d),d.click(),document.body.removeChild(d);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},tL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let l=t==="png"?"image/png":"image/jpeg",d=e.toDataURL({mimeType:l,quality:a,pixelRatio:s});fetch(d).then(u=>u.blob()).then(u=>r(u)).catch(u=>n(u));}catch(l){n(l);}})},aL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:s})};var oL=(e,o,t)=>{let a=t.x-o.x,s=t.y-o.y;if(a===0&&s===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+s*s,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*s)/r)),l=o.x+n*a,d=o.y+n*s;return Math.sqrt(Math.pow(e.x-l,2)+Math.pow(e.y-d,2))},ad=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,s=e[0],r=e[e.length-1];for(let n=1;n<e.length-1;n++){let l=oL(e[n],s,r);l>t&&(t=l,a=n);}if(t>o){let n=ad(e.slice(0,a+1),o),l=ad(e.slice(a),o);return [...n.slice(0,-1),...l]}return [s,r]},rL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},sL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},om=(e,o=1.5)=>{if(e.length<=4)return e;let t=rL(e),a=ad(t,o);return sL(a)},rm=(e,o=1.5)=>({...e,points:om(e.points,o)}),nL=(e,o=1.5)=>e.map(t=>rm(t,o)),iL=(e,o)=>{let t=e.length/2,a=o.length/2,s=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${s}%`}};var lL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var sm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{let l=new Image;l.onload=()=>{let{width:d,height:u}=l;if(d>t||u>a){let p=d/u;d>u?(d=Math.min(d,t),u=d/p):(u=Math.min(u,a),d=u*p);}let m=document.createElement("canvas");m.width=d,m.height=u;let f=m.getContext("2d");if(!f){n(new Error("Failed to get canvas context"));return}f.drawImage(l,0,0,d,u);let i=lL(e),c=m.toDataURL(i,s);r(c);},l.onerror=n,l.src=e;})};var ao=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer},Go=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Ko=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",dL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],l=0;for(let d of e){let u=[],m=[],f=[];for(let i of d.images){let c=i.src;if(t&&c.startsWith("data:"))try{c=await sm(c,{maxWidth:a,maxHeight:s,quality:r});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(c.startsWith("data:")){let p=ao(c),y=Go(c);l+=p.byteLength;let h={id:i.id,x:i.x,y:i.y,width:i.width,height:i.height,draggable:i.draggable,rotation:i.rotation,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,buffer:p,mimeType:y};if(i.audioData&&i.audioData.startsWith("data:")){let x=ao(i.audioData),b=Go(i.audioData);l+=x.byteLength,h.audioBuffer=x,h.audioMimeType=b;}u.push(h);}}for(let i of d.videos){let c,p;if(i.videoBlob)c=await i.videoBlob.arrayBuffer(),p=i.videoBlob.type;else if(i.videoData&&i.videoData.startsWith("data:"))c=ao(i.videoData),p=Go(i.videoData);else {console.warn(`Video ${i.id} has no blob or videoData, skipping`);continue}l+=c.byteLength;let y={id:i.id,thumbnailDataUrl:i.thumbnailDataUrl,x:i.x,y:i.y,width:i.width,height:i.height,draggable:i.draggable,isPlaying:i.isPlaying,rotation:i.rotation,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,isRecorded:i.isRecorded,buffer:c,mimeType:p};if(i.audioData&&i.audioData.startsWith("data:")){let h=ao(i.audioData),x=Go(i.audioData);l+=h.byteLength,y.audioBuffer=h,y.audioMimeType=x;}m.push(y);}for(let i of d.photoFrames){let c={id:i.id,x:i.x,y:i.y,width:i.width,height:i.height,rotation:i.rotation,draggable:i.draggable,locked:i.locked,link:i.link,altText:i.altText,zIndex:i.zIndex,isCapturing:i.isCapturing};if(i.capturedImageUrl&&i.capturedImageUrl.startsWith("data:")){let p=ao(i.capturedImageUrl),y=Go(i.capturedImageUrl);l+=p.byteLength,c.buffer=p,c.mimeType=y;}if(i.audioData&&i.audioData.startsWith("data:")){let p=ao(i.audioData),y=Go(i.audioData);l+=p.byteLength,c.audioBuffer=p,c.audioMimeType=y;}f.push(c);}n.push({...d,images:u,videos:m,photoFrames:f});}return {slides:n,totalSize:l}},uL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},cL=e=>{let o=new FormData,t=e.slides.map((a,s)=>({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((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${s}_image_${n}`,audioFileKey:r.audioBuffer?`slide_${s}_image_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${s}_video_${n}`,thumbnailFileKey:`slide_${s}_video_${n}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${s}_video_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${s}_photoframe_${n}`:void 0,audioFileKey:r.audioBuffer?`slide_${s}_photoframe_${n}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,s)=>{a.images.forEach((r,n)=>{let l=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,l,d),r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,u,m);}}),a.videos.forEach((r,n)=>{let l=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,l,d),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let u=ao(r.thumbnailDataUrl),m=new Blob([u],{type:"image/jpeg"}),f=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,m,f);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,u,m);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let l=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,l,d);}if(r.audioBuffer&&r.audioMimeType){let l=new Blob([r.audioBuffer],{type:r.audioMimeType}),d=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,l,d);}});}),o};var pL=()=>{let e=at(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await $l(),r=Jl(),n=await ed();if(s&&s.length>0){let l=await mf(),d=s.map(m=>{if(m.videos&&m.videos.length>0){let f=m.videos.map(i=>{let c=l.get(i.id);if(c){let p=hf(c.blob);return {...i,objectUrl:p,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return i});return {...m,videos:f}}return m}),u=r&&d.find(m=>m.id===r)?r:d[0].id;e(io({slides:d,currentSlideId:u}));}e(n?bi({title:n.title,description:n.description}):ks(!0));}catch(s){console.error("Error loading persisted slides:",s),e(ks(true));}finally{t(false);}})();},[e]),{isLoading:o}};var im=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||""})),lm=new WeakSet,dm=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 Ja(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},hL=()=>{let e=at(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||lm.has(a))return;lm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(u){console.error("Error clearing local data:",u);}let l=r&&s.find(u=>u.id===r)?r:s[0].id,d=im(s);e(io({slides:d,currentSlideId:l})),await dm(d);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(u){console.error("Error clearing local data:",u);}let l=r&&s.find(u=>u.id===r)?r:s[0].id,d=im(s);e(io({slides:d,currentSlideId:l})),await dm(d);},[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:f?"none":"auto"}})}),jsx(Group,{y:C+S+T+k+y+E,children:f&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),x();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),x();},scaleX:c==="reset"?.95:1,scaleY:c==="reset"?.95:1,children:[jsx(Rect,{x:L,width:e.width-L*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.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})]})})]})});xl.displayName="LongAnswer";var mc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(xl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:i=>r(i,n.id)},n.id))});var ja=1600,Xa=900,xc=3200,bc=1800,Tb=.4,Ab=1.5,Pb=e=>{let o=0,t=0,a=ja,s=Xa;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:ja,height:Xa};let r=(d,u,m,f)=>{o=Math.min(o,d),t=Math.min(t,u),a=Math.max(a,d+m),s=Math.max(s,u+f);};e.lines?.forEach(d=>{if(d.points&&d.points.length>=2){let u=d.x||0,m=d.y||0,f=d.scaleX||1,l=d.scaleY||1;for(let c=0;c<d.points.length;c+=2){let p=u+d.points[c]*f,v=m+d.points[c+1]*l;o=Math.min(o,p),t=Math.min(t,v),a=Math.max(a,p),s=Math.max(s,v);}}}),e.images?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.videos?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.shapes?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.texts?.forEach(d=>r(d.x,d.y,d.width||200,d.height||d.fontSize||24)),e.flashcards?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.photoFrames?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.multipleChoices?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.trueFalses?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.shortAnswers?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.LongAnswer?.forEach(d=>r(d.x,d.y,d.width,d.height)),e.fillInTheBlanks?.forEach(d=>r(d.x,d.y,d.width,d.height));let n=Math.min(a-o,xc),i=Math.min(s-t,bc);return o=Math.max(o,a-xc),t=Math.max(t,s-bc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:i}},Db=(e,o,t={minX:0,minY:0,maxX:ja,maxY:Xa,width:ja,height:Xa})=>{let a=Math.max(t.width,ja),s=Math.max(t.height,Xa),r=e/o,n=a/s,i,d,u,f=0;if(r>n){d=s,i=Math.round(d*r),u=o/d;}else {i=a,d=Math.round(i/r),u=e/i;let l=s*u;f=(o-l)/2;}return u=Math.max(Tb,Math.min(Ab,u)),{scale:u,scaleX:u,scaleY:u,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:i,baseHeight:d,contentOffsetX:t.minX,contentOffsetY:t.minY}},vc=(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}},Rb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=ot(),n=te(w=>w.toolbar.selectedTool),i=te(he),d=te(fo),u=i?.editingActivity,m=i?.showMcqForm,f=i?.lines||[],l=useRef(null),c=useRef(null),[p,v]=useState(null),[h,x]=useState(""),b=useRef(null),[g,L]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:ja,stageHeight:Xa,offsetX:0,offsetY:0,baseWidth:ja,baseHeight:Xa,contentOffsetX:0,contentOffsetY:0}),C=useMemo(()=>Pb(i||null),[d]),[S,k]=useState(null),[y,A]=useState(null),[E,T]=useState(null),[V,z]=useState(null),[R,G]=useState(null),[D,ee]=useState(null),[N,se]=useState(null),[K,q]=useState(false),[j,H]=useState(null),[U,Y]=useState(false),Z=useRef(null),Q=useRef(null),le=useRef(null),{debouncedGenerateThumbnail:Ie}=jd(d,l);useEffect(()=>{let w=()=>{if(c.current){let P=c.current.getBoundingClientRect(),B=Db(P.width,P.height,C);L(B);}};w();let I=new ResizeObserver(w);return c.current&&I.observe(c.current),window.addEventListener("resize",w),()=>{I.disconnect(),window.removeEventListener("resize",w);}},[C]),useEffect(()=>{if(l.current){let w=l.current.container();w&&(w.style.cursor="");}},[n]);let J=useCallback(()=>{l.current&&requestAnimationFrame(()=>{if(!l.current)return;l.current.getLayers().forEach(B=>B.batchDraw());let I=1/6,P=l.current.toDataURL({pixelRatio:I});x(P),Ie();});},[Ie]),Me=useRef(d);useEffect(()=>{Me.current!==d&&(Me.current=d,J());},[d,J]);let Be=useRef(null),Et=useRef(true);useEffect(()=>{if(!i)return;let w=(i.lines?.length||0)+(i.images?.length||0)+(i.videos?.length||0)+(i.shapes?.length||0)+(i.texts?.length||0)+(i.flashcards?.length||0)+(i.photoFrames?.length||0)+(i.multipleChoices?.length||0)+(i.trueFalses?.length||0)+(i.shortAnswers?.length||0)+(i.LongAnswer?.length||0)+(i.fillInTheBlanks?.length||0),I=Be.current?.count!==w;!Et.current&&I&&setTimeout(()=>{J();},100),Be.current={slideId:d,count:w},Et.current=false;},[i,d,J]),useEffect(()=>{l.current&&e&&e(l);},[e]),useEffect(()=>{le.current&&a&&a(le);},[a]);let{startDrawing:oo,draw:Hr,stopDrawing:Ur,setCanvasRef:In,tool:ro,color:Cn,strokeWidth:kn,isSketchMode:Mn}=yd(J),ia=useRef(new Map),{images:Tn,getLoadedImage:An,imageRefs:so,handleDragEnd:Wr,handleImageTransformEnd:Pn}=Md(J),{videos:F,videoRefs:re,handleVideoClick:ye,handleVideoDragEnd:ge,handleVideoTransformEnd:ne}=Pd(J),{multipleChoice:ue,handleMcqTransform:we,mcqRefs:Ne,handleDragEnd:Ft}=Td(J),{trueFalse:ut,handleTrueFalseTransform:Te,trueFalseRefs:Ue,handleTrueFalseDragEnd:Jt}=Ad(J),{shortAnswers:la,saRefs:Ea,handleShortAnswerDragEnd:Dn}=Od(J),{longAnswers:zr,handleLongAnswerDragEnd:Bt}=Nd(J),{fillInTheBlanks:da,handleFillInTheBlanksDragEnd:Fa,fibRefs:Gr}=nc(J),{transformerRef:fe,boundBoxFunc:yt}=zd(),{shapes:cm,shapeRefs:Kr,isDragging:od,handleShapeDragEnd:fm,handleShapeResizeEnd:mm}=Ed(J),{texts:_o,textRefs:ua,handleDragEnd:pm,handleTransformEnd:hm,handleDoubleClick:gm,startEditing:_r,editingTextId:pe,editingValue:rd,handleEditingChange:sd,finishEditing:Rn}=Bd(J,Z);useEffect(()=>{t&&t(_r);},[t,_r]);let jr=te(w=>w.canvas.editingTextId);useEffect(()=>{jr&&jr!==pe&&_r(jr);},[jr,pe,_r]);let{flashcards:xm,flashcardRefs:Xr,handleDragEnd:bm,handleFlashcardTransformEnd:vm,handleNext:ym,handlePrevious:wm}=qd(J),{photoFrames:nd,photoFrameRefs:$r,handleDragEnd:Lm,handlePhotoFrameTransformEnd:Sm,startCamera:Im,capturePhoto:Cm,cameraStreams:km}=Wd(J);useEffect(()=>{if(fe.current){if(pe){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(p&&!F.find(P=>P.id===p)?.isPlaying){let P=ia.current.get(p)||so.current.get(p)||re.current.get(p)||Kr.current.get(p)||ua.current.get(p)||Ne.current.get(p)||Xr.current.get(p)||$r.current.get(p)||Ea.current.get(p)||Ue.current.get(p)||Gr.current.get(p);if(P){let B=P.attrs?.locked;if(P.visible()&&B!==true){fe.current.nodes([P]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[p,pe,F,ia,so,re,Kr,ua,Xr,$r,nd,Ne,Ue,Gr,fe]);let Ge=useCallback(w=>{v(w),o?.(w);},[o]),no=useCallback(()=>{v(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),id=useCallback(w=>i?i.lines?.some(I=>I.id===w)?"line":i.images?.some(I=>I.id===w)?"image":i.videos?.some(I=>I.id===w)?"video":i.shapes?.some(I=>I.id===w)?"shape":i.texts?.some(I=>I.id===w)?"text":i.flashcards?.some(I=>I.id===w)?"flashcard":i.photoFrames?.some(I=>I.id===w)?"photoFrame":i.multipleChoices?.some(I=>I.id===w)?"mcq":i.trueFalses?.some(I=>I.id===w)?"trueFalse":i.shortAnswers?.some(I=>I.id===w)?"shortAnswer":i.LongAnswer?.some(I=>I.id===w)?"longAnswer":i.fillInTheBlanks?.some(I=>I.id===w)?"fillInTheBlanks":null:null,[i]),ld=useCallback((w,I)=>{switch(r(ce()),I){case "line":r(Cs(w));break;case "image":r(Jr(w));break;case "video":r(ts(w));break;case "shape":r(rs(w));break;case "text":r(ss(w));break;case "flashcard":r(is(w));break;case "photoFrame":r(ds(w));break;case "mcq":r(cs(w));break;case "trueFalse":r(ms(w));break;case "shortAnswer":r(hs(w));break;case "longAnswer":r(xs(w));break;case "fillInTheBlanks":r(vs(w));break}no(),J();},[r,no,J]);useEffect(()=>{let w=I=>{if(I.key!=="Delete"||!p||pe)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;I.preventDefault();let Ae=id(p);Ae&&ld(p,Ae);};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[p,pe,id,ld]),useEffect(()=>{let w=fe.current;return ()=>{w&&w.nodes([]);}},[d]),useEffect(()=>{let w=I=>{pe&&I.target.tagName!=="TEXTAREA"&&Rn();};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w);}},[pe,Rn]),useEffect(()=>{let w=pe||p;if(!w||p&&pe){A(null);return}let I=ua.current.get(w),P=l.current;if(!I||!P){A(null);return}let B=P.container().getBoundingClientRect(),Ae=I.absolutePosition(),Le=P.scaleX();A({x:B.left+(Ae.x+I.width()*Le/2)*Le,y:B.top+Ae.y*Le});},[p,pe,_o,ua]),useEffect(()=>{if(!pe){T(null);return}let w=ua.current.get(pe),I=l.current;if(!w||!I){T(null);return}let P=I.container().getBoundingClientRect(),B=w.absolutePosition(),Ae=I.scaleX();T({top:P.top+B.y*Ae,left:P.left+B.x*Ae,scale:Ae});},[pe,_o,ua]);let dd=useCallback(w=>{let I=w.target.getClassName(),P=w.target===w.target.getStage(),B=I==="Transformer"||w.target.getParent()?.getClassName()==="Transformer",Ae=I==="Image",Le=I==="Text",oe=I==="Group"||w.target.getParent()?.getClassName()==="Group",Ot=I==="Circle"||I==="Star"||I==="RegularPolygon"||I==="Ellipse"||I==="Ring"||I==="Wedge"||I==="Arrow"||I==="Line"||I==="Arc"||I==="Rect"&&w.target.attrs.id,Lt=I==="Group";if(P&&!B&&!Ae&&!Le&&!oe&&!Ot&&!Lt&&no(),!(n==="pen"||n==="eraser")&&(Ae||Le||B||oe||Ot||Lt))return;let Xe=w.target.getStage()?.getPointerPosition();if(!Xe)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(n)){let O=vc(Xe,g);oo(O);}},[n,oo,no,g]),ud=useCallback(w=>{if(od)return;let I=w.target.getStage()?.getPointerPosition();if(!I)return;let P=vc(I,g);Hr(P);},[Hr,od,g]),cd=useCallback(()=>{Ur();},[Ur]),Mm=useCallback(w=>{Wr(w,J);},[Wr,J]),Tm=useCallback(w=>{ye(w),Ge(w);},[ye,Ge]),wt=useCallback((w,I,P)=>{if(w.preventDefault(),!s.enabled)return;let B=w.clientX,Ae=w.clientY,Le=b.current?.offsetHeight||450,oe=b.current?.offsetWidth||450,Ot=window.innerHeight,Lt=window.innerWidth,at=B,Xe=Ae;Ae+Le>Ot&&(Xe=Ae-Le),B+oe>Lt&&(at=B-oe),k({x:at,y:Xe,elementId:I,elementType:P}),Ge(I);},[Ge,s.enabled]),fd=useCallback(w=>{r(Zo(w)),r(ma(true));},[r]),Am=useCallback(w=>{r(Xo(w)),r(Oa(true));},[r]),Pm=useCallback((w,I)=>{if(!S)return;let{elementId:P,elementType:B}=S;switch(w){case "order":if(I){let M=I.target.getBoundingClientRect();z({x:M.right+5,y:M.top,type:"order"});}break;case "lock":if(I){let M=I.target.getBoundingClientRect();z({x:M.right+5,y:M.top,type:"lock"});}break;case "link":if(k(null),B==="line")break;let Ae=i?B==="image"?i.images.find(M=>M.id===P):i.videos.find(M=>M.id===P):null;G({type:"link",defaultValue:Ae?.link||""});break;case "voice":if(k(null),B==="line")break;let Le=i?B==="image"?i.images.find(M=>M.id===P):B==="video"?i.videos.find(M=>M.id===P):B==="text"?i.texts.find(M=>M.id===P):B==="flashcard"?i.flashcards.find(M=>M.id===P):B==="photoFrame"?i.photoFrames.find(M=>M.id===P):B==="mcq"?i.multipleChoices.find(M=>M.id===P):B==="fillInTheBlanks"?i.fillInTheBlanks.find(M=>M.id===P):B==="longAnswer"?i.LongAnswer.find(M=>M.id===P):B==="shortAnswer"?i.shortAnswers.find(M=>M.id===P):B==="trueFalse"?i.trueFalses.find(M=>M.id===P):B==="shape"?i.shapes.find(M=>M.id===P):null:null;H({elementId:P,elementType:B,existingAudio:Le?.audioData});break;case "edit":k(null);let oe=null;B==="mcq"?oe=i?.multipleChoices.find(M=>M.id===P):B==="trueFalse"?oe=i?.trueFalses.find(M=>M.id===P):B==="shortAnswer"?oe=i?.shortAnswers.find(M=>M.id===P):B==="longAnswer"?oe=i?.LongAnswer.find(M=>M.id===P):B==="fillInTheBlanks"&&(oe=i?.fillInTheBlanks.find(M=>M.id===P)),oe&&fd(oe);break;case "editFlashcard":k(null);let Ot=i?.flashcards.find(M=>M.id===P);Ot&&Am(Ot);break;case "color":k(null);let Lt=i?.shapes.find(M=>M.id===P);ee({elementId:P,elementType:"shape",defaultColor:Lt?.color||"#096B76"});break;case "crop":if(k(null),B==="image"){let M=i?.images.find(Nm=>Nm.id===P);M&&se({elementId:P,imageSrc:M.src});}break;case "draw":k(null),B==="image"?r(Zn(P)):B==="photoFrame"&&r(ei(P));break;case "duplicate":r(ce()),B==="line"?r(fi(P)):B==="image"?r(Zr(P)):B==="video"?r(as(P)):B==="shape"?r(os(P)):B==="text"?r(ns(P)):B==="flashcard"?r(ls(P)):B==="photoFrame"?r(us(P)):B==="mcq"?r(fs(P)):B==="trueFalse"?r(ps(P)):B==="shortAnswer"?r(gs(P)):B==="fillInTheBlanks"?r(ys(P)):B==="longAnswer"&&r(bs(P)),J();break;case "infinite-clone":r(ce());let at=5;for(let M=0;M<at;M++)B==="image"?r(Zr(P)):B==="video"?r(as(P)):B==="shape"?r(os(P)):B==="text"?r(ns(P)):B==="flashcard"?r(ls(P)):B==="photoFrame"?r(us(P)):B==="mcq"?r(fs(P)):B==="trueFalse"?r(ps(P)):B==="shortAnswer"?r(gs(P)):B==="fillInTheBlanks"?r(ys(P)):B==="longAnswer"&&r(bs(P));J();break;case "make-response":if(k(null),B==="line")break;let Xe=`#response-${P}`;r(ce()),r(ws({id:P,type:B,link:Xe})),(i?B==="image"?i.images.find(M=>M.id===P):B==="video"?i.videos.find(M=>M.id===P):B==="shape"?i.shapes.find(M=>M.id===P):B==="flashcard"?i.flashcards.find(M=>M.id===P):B==="photoFrame"?i.photoFrames.find(M=>M.id===P):i.multipleChoices.find(M=>M.id===P):null)?.altText||r(Ls({id:P,type:B,altText:"Interactive response area"})),J(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(k(null),B==="line")break;let O=i?B==="image"?i.images.find(M=>M.id===P):B==="video"?i.videos.find(M=>M.id===P):B==="shape"?i.shapes.find(M=>M.id===P):null:null;G({type:"altText",defaultValue:O?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),k(null),Y(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),B==="line"?r(Cs(P)):B==="image"?r(Jr(P)):B==="video"?r(ts(P)):B==="shape"?r(rs(P)):B==="text"?r(ss(P)):B==="flashcard"?r(is(P)):B==="photoFrame"?r(ds(P)):B==="mcq"?r(cs(P)):B==="trueFalse"?r(ms(P)):B==="shortAnswer"?r(hs(P)):B==="longAnswer"?r(xs(P)):B==="fillInTheBlanks"&&r(vs(P)),no(),J();break}},[S,r,J,no,i,fd]),Dm=useCallback(()=>{k(null),z(null);},[]),En=useCallback(w=>{if(!S)return;let{elementId:I,elementType:P}=S;switch(r(ce()),w){case "bring-to-front":P!=="line"&&r(li({id:I,type:P}));break;case "send-to-back":P!=="line"&&r(di({id:I,type:P}));break;case "lock":case "unlock":P!=="line"&&r(ui({id:I,type:P}));break}J(),k(null),z(null);},[S,r,J]),Rm=useCallback(w=>{if(!S||!R)return;let{elementId:I,elementType:P}=S;r(ce()),R.type==="link"&&P!=="line"?r(ws({id:I,type:P,link:w})):R.type==="altText"&&P!=="line"&&r(Ls({id:I,type:P,altText:w})),J(),G(null);},[S,R,r,J]),Em=useCallback(w=>{if(!j)return;let{elementId:I,elementType:P}=j;r(ce()),r(Ss({id:I,type:P,audioData:w})),J(),H(null);},[j,r,J]),Fm=useCallback(()=>{if(!j)return;let{elementId:w,elementType:I}=j;r(ce()),r(Ss({id:w,type:I,audioData:""})),J();},[j,r,J]),Bm=useCallback(w=>{if(!D)return;let{elementId:I}=D;r(ce()),r(uo({id:I,color:w})),J(),ee(null);},[D,r,J]),Om=useCallback(w=>{if(!N)return;let{elementId:I}=N;r(ce()),r(lo({id:I,src:w})),J(),se(null);},[N,r,J]);return jsxs("div",{ref:c,className:"fixed inset-0",style:{cursor:n==="pen"?"crosshair":n==="eraser"?"":"default"},children:[n==="pen"&&jsx(Cd,{ref:w=>{if(Q.current=w,In(w),w){let I=w.getCanvasElement();I&&(le.current=I,a&&a(le));}},width:g.baseWidth,height:g.baseHeight,tool:ro,color:Cn,strokeWidth:kn/g.scale,isSketchMode:Mn,xOffset:g.contentOffsetX,yOffset:g.contentOffsetY-g.offsetY/g.scale,style:{width:g.stageWidth,height:g.stageHeight}}),jsxs(Stage,{ref:l,width:g.stageWidth,height:g.stageHeight,scaleX:g.scaleX,scaleY:g.scaleY,x:g.offsetX,y:0,onMouseDown:dd,onMouseMove:ud,onMouseUp:cd,onTouchStart:dd,onTouchMove:ud,onTouchEnd:cd,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:g.baseWidth,height:g.stageHeight/g.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-g.contentOffsetX,y:g.offsetY/g.scale-g.contentOffsetY,children:(()=>{let w=[];return f.forEach((I,P)=>{w.push({type:"line",timestamp:I.timestamp||P,element:{...I,id:I.id??`line-${P}`},index:P});}),cm.forEach(I=>{w.push({type:"shape",timestamp:I.timestamp||0,element:I});}),Tn.forEach(I=>{w.push({type:"image",timestamp:I.timestamp||0,element:I});}),F.forEach(I=>{w.push({type:"video",timestamp:I.timestamp||0,element:I});}),_o.forEach(I=>{w.push({type:"text",timestamp:I.timestamp||0,element:I});}),xm.forEach(I=>{w.push({type:"flashcard",timestamp:I.timestamp||0,element:I});}),nd.forEach(I=>{w.push({type:"photoFrame",timestamp:I.timestamp||0,element:I});}),ue.forEach(I=>{w.push({type:"mcq",timestamp:I.timestamp||0,element:I});}),ut.forEach(I=>{w.push({type:"trueFalse",timestamp:I.timestamp||0,element:I});}),la.forEach(I=>{w.push({type:"shortAnswer",timestamp:I.timestamp||0,element:I});}),zr.forEach(I=>{w.push({type:"longAnswer",timestamp:I.timestamp||0,element:I});}),da.forEach(I=>{w.push({type:"fillInTheBlanks",timestamp:I.timestamp||0,element:I});}),w.sort((I,P)=>I.timestamp-P.timestamp),w.map((I,P)=>{let B=`${I.type}-${"id"in I.element&&I.element.id||I.index||P}`,Ae="id"in I.element?I.element.id:void 0,Le=Ae&&p===Ae;switch(I.type){case "line":let oe=I.element,Ot=I.index||0,Lt=oe.tool==="eraser",at=oe.isSketch&&oe.tool==="pen",Xe=oe.isSketch&&Lt,St=oe.id||`line-${Ot}`;return oe.x===void 0&&(oe.x=0),oe.y===void 0&&(oe.y=0),oe.scaleX===void 0&&(oe.scaleX=1),oe.scaleY===void 0&&(oe.scaleY=1),oe.rotation===void 0&&(oe.rotation=0),n==="eraser"?jsx(Group,{x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,children:jsx(Line,{points:oe.points||[],stroke:at||Xe?void 0:oe.color,strokeWidth:at||Xe?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:at||Xe?Lt?"black":oe.color:void 0,closed:at||Xe,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(Yr(Ot));},onTap:()=>{r(ce()),r(Yr(Ot));},hitStrokeWidth:Math.max(20,(oe.strokeWidth??0)*2),onMouseEnter:O=>{let M=O.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:O=>{let M=O.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`);}})},B):jsxs(be__default.Fragment,{children:[jsx(Group,{id:St,ref:O=>{O?ia.current.set(St,O):ia.current.delete(St);},x:oe.x||0,y:oe.y||0,scaleX:oe.scaleX||1,scaleY:oe.scaleY||1,rotation:oe.rotation||0,draggable:n==="select",listening:n==="select",onClick:()=>{n==="select"&&(console.log("Line clicked:",St),Ge(St));},onTap:()=>{n==="select"&&(console.log("Line tapped:",St),Ge(St));},onDragEnd:O=>{r(ce()),r(Is({id:St,x:O.target.x(),y:O.target.y(),scaleX:O.target.scaleX(),scaleY:O.target.scaleY(),rotation:O.target.rotation()})),J();},onTransformEnd:O=>{r(ce()),r(Is({id:St,x:O.target.x(),y:O.target.y(),scaleX:O.target.scaleX(),scaleY:O.target.scaleY(),rotation:O.target.rotation()})),J();},onMouseEnter:O=>{if(n==="select"){let M=O.target.getStage();M&&(M.container().style.cursor="move");}},onMouseLeave:O=>{if(n==="select"){let M=O.target.getStage();M&&(M.container().style.cursor="default");}},onContextMenu:O=>{let M=O.evt;M.preventDefault(),wt(M,St,"line");},children:jsx(Line,{points:oe.points||[],stroke:at||Xe?void 0:oe.color,strokeWidth:at||Xe?0:oe.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:at||Xe?Lt?"black":oe.color:void 0,closed:at||Xe,tension:0,globalCompositeOperation:Lt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=ia.current.get(p);console.log("Line Transformer - selectedId:",p,"node found:",!!M),M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Ri,{onSelect:Ge,shapes:[I.element],shapeRefs:Kr,handleShapeDragEnd:fm,handleShapeResizeEnd:mm,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=Kr.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "image":return jsxs(be__default.Fragment,{children:[jsx(Ti,{images:[I.element],getLoadedImage:An,imageRefs:so,onDragEnd:Mm,onTransform:Pn,onSelect:Ge,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=so.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "video":return jsxs(be__default.Fragment,{children:[jsx(Di,{videos:[I.element],selectedId:p,videoRefs:re,onVideoClick:Tm,onDragEnd:ge,onTransformEnd:ne,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=re.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "text":return jsxs(be__default.Fragment,{children:[jsx(ru,{texts:[I.element],textRefs:ua,onDragEnd:pm,onTransformEnd:hm,onSelect:Ge,onContextMenu:wt,onDoubleClick:gm,editingTextId:pe,editingValue:rd,onEditingChange:sd}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=ua.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Bi,{flashcards:[I.element],flashcardRefs:Xr,selectedId:p,onDragEnd:bm,onTransform:vm,onSelect:Ge,onNext:ym,onPrevious:wm,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=Xr.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Ui,{photoFrames:[I.element],photoFrameRefs:$r,selectedId:p,onDragEnd:Lm,onTransform:Sm,onSelect:Ge,onStartCamera:Im,onCapture:Cm,cameraStreams:km,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=$r.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Bu,{handleMcqTransform:we,multipleChoice:[I.element],handleSelect:Ge,mcqRefs:Ne,handleDragEnd:Ft,onContextMenu:wt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=Ne.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Vu,{trueFalses:[I.element],handleTrueFalseTransform:Te,handleSelect:Ge,trueFalseRefs:Ue,onContextMenu:wt,handleDragEnd:Jt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=Ue.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(sc,{shortAnswers:[I.element],handleSelect:Ge,handleTransform:we,saRefs:Ea,onContextMenu:wt,handleDragEnd:Dn}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=Ea.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(mc,{longAnswer:[I.element],handleSelect:Ge,handleTransform:we,saRefs:Ea,onContextMenu:wt,handleDragEnd:Bt}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=Ea.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(cc,{fillInTheBlanks:[I.element],handleSelect:Ge,handleTransform:we,onContextMenu:wt,handleDragEnd:Fa,fibRefs:Gr}),Le&&!pe&&p&&jsx(Transformer,{ref:O=>{if(O&&fe.current!==O){fe.current=O;let M=Gr.current.get(p);M&&M.visible()&&(O.nodes([M]),O.getLayer()?.batchDraw());}},boundBoxFunc:yt,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},B);default:return null}})})()})]}),S&&jsx(xu,{menuRef:b,x:S.x,y:S.y,type:S.elementType,onAction:Pm,onClose:Dm,isDrawingMode:S.elementType==="image"?i?.images.find(w=>w.id===S.elementId)?.isDrawingMode:S.elementType==="photoFrame"?i?.photoFrames.find(w=>w.id===S.elementId)?.isDrawingMode:false}),V&&S&&jsx(bu,{x:V.x,y:V.y,items:V.type==="order"?[{label:"Bring to Front",onClick:()=>En("bring-to-front")},{label:"Send to Back",onClick:()=>En("send-to-back")}]:[{label:i&&(S.elementType==="image"?i.images.find(w=>w.id===S.elementId)?.locked:i.videos.find(w=>w.id===S.elementId)?.locked)?"Unlock":"Lock",onClick:()=>En(i&&(S.elementType==="image"?i.images.find(w=>w.id===S.elementId)?.locked:i.videos.find(w=>w.id===S.elementId)?.locked)?"unlock":"lock")}],onClose:()=>z(null)}),R&&jsx(wu,{title:R.type==="link"?"Add Link":"Add Alt Text",label:R.type==="link"?"URL":"Alternative Text",placeholder:R.type==="link"?"https://example.com":"Describe this image/video",defaultValue:R.defaultValue,onSave:Rm,onClose:()=>G(null)}),D&&jsx(Fs,{defaultColor:D.defaultColor,onConfirm:Bm,onCancel:()=>ee(null)}),N&&jsx(Cu,{imageSrc:N.imageSrc,onConfirm:Om,onCancel:()=>se(null)}),K&&jsx(dr,{onClose:()=>q(false),stageRef:l}),j&&jsx(Au,{elementId:j.elementId,elementType:j.elementType,existingAudio:j.existingAudio,onSave:Em,onDelete:Fm,onClose:()=>H(null)}),U&&jsx(Ru,{selectedElementId:p||void 0,onClose:()=>Y(false),onSelectElement:w=>{Ge(w),Y(false);}}),i?.images.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.videos.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shapes?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.texts?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.flashcards?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.photoFrames?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.multipleChoices?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.trueFalses?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.shortAnswers?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.LongAnswer?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),i?.fillInTheBlanks?.filter(w=>w.audioData).map(w=>jsx(kt,{audioData:w.audioData,x:w.x,y:w.y,width:w.width,scale:g.scale,offsetX:g.offsetX,offsetY:g.offsetY},`audio-${w.id}`)),m&&jsx($u,{editElement:u}),y&&(()=>{let w=pe||p;if(!w)return null;let I=_o.find(P=>P.id===w);return I?jsx(Qu,{text:I,position:y}):null})(),E&&pe&&(()=>{let w=_o.find(I=>I.id===pe);return w?jsx(tc,{text:w,editingValue:rd,onEditingChange:sd,onFinish:Rn,position:{top:E.top,left:E.left},scale:E.scale,textareaRef:Z},pe):null})()]})},Eb=Rb;function bl(e,[o,t]){return Math.min(t,Math.max(o,e))}function Je(e,o,{checkForDefaultPrevented:t=true}={}){return function(s){if(e?.(s),t===false||!s.defaultPrevented)return o?.(s)}}function yc(e,o){if(typeof e=="function")return e(o);e!=null&&(e.current=o);}function Dr(...e){return o=>{let t=false,a=e.map(s=>{let r=yc(s,o);return !t&&typeof r=="function"&&(t=true),r});if(t)return ()=>{for(let s=0;s<a.length;s++){let r=a[s];typeof r=="function"?r():yc(e[s],null);}}}}function Dt(...e){return be.useCallback(Dr(...e),e)}function ka(e,o=[]){let t=[];function a(r,n){let i=be.createContext(n),d=t.length;t=[...t,n];let u=f=>{let{scope:l,children:c,...p}=f,v=l?.[e]?.[d]||i,h=be.useMemo(()=>p,Object.values(p));return jsx(v.Provider,{value:h,children:c})};u.displayName=r+"Provider";function m(f,l){let c=l?.[e]?.[d]||i,p=be.useContext(c);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${f}\` must be used within \`${r}\``)}return [u,m]}let s=()=>{let r=t.map(n=>be.createContext(n));return function(i){let d=i?.[e]||r;return be.useMemo(()=>({[`__scope${e}`]:{...i,[e]:d}}),[i,d])}};return s.scopeName=e,[a,Bb(s,...o)]}function Bb(...e){let o=e[0];if(e.length===1)return o;let t=()=>{let a=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(r){let n=a.reduce((i,{useScope:d,scopeName:u})=>{let f=d(r)[`__scope${u}`];return {...i,...f}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var Oo=globalThis?.document?be.useLayoutEffect:()=>{};var Ob=be[" useInsertionEffect ".trim().toString()]||Oo;function ea({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=Nb({defaultProp:o,onChange:t}),i=e!==void 0,d=i?e:s;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let f=m.current;f!==i&&console.warn(`${a} is changing from ${f?"controlled":"uncontrolled"} to ${i?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=i;},[i,a]);}let u=be.useCallback(m=>{if(i){let f=Vb(m)?m(e):m;f!==e&&n.current?.(f);}else r(m);},[i,e,r,n]);return [d,u]}function Nb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),s=be.useRef(t),r=be.useRef(o);return Ob(()=>{r.current=o;},[o]),be.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function Vb(e){return typeof e=="function"}var qb=be.createContext(void 0);function No(e){let o=be.useContext(qb);return e||o||"ltr"}function Sc(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 Cc(e){let[o,t]=be.useState(void 0);return Oo(()=>{if(e){t({width:e.offsetWidth,height:e.offsetHeight});let a=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;let r=s[0],n,i;if("borderBoxSize"in r){let d=r.borderBoxSize,u=Array.isArray(d)?d[0]:d;n=u.inlineSize,i=u.blockSize;}else n=e.offsetWidth,i=e.offsetHeight;t({width:n,height:i});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Mc(e){let o=Hb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,i=be.Children.toArray(r),d=i.find(Wb);if(d){let u=d.props.children,m=i.map(f=>f===d?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(u)?be.cloneElement(u,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function Hb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=Gb(s),i=zb(r,s.props);return s.type!==be.Fragment&&(i.ref=a?Dr(a,n):n),be.cloneElement(s,i)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Ub=Symbol("radix.slottable");function Wb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ub}function zb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...i)=>{let d=r(...i);return s(...i),d}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function Gb(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 jb=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=jb.reduce((e,o)=>{let t=Mc(`Primitive.${o}`),a=be.forwardRef((s,r)=>{let{asChild:n,...i}=s,d=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(d,{...i,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function vl(e){let o=Xb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,i=be.Children.toArray(r),d=i.find(Yb);if(d){let u=d.props.children,m=i.map(f=>f===d?be.Children.count(u)>1?be.Children.only(null):be.isValidElement(u)?u.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(u)?be.cloneElement(u,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function Xb(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=Zb(s),i=Jb(r,s.props);return s.type!==be.Fragment&&(i.ref=a?Dr(a,n):n),be.cloneElement(s,i)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var $b=Symbol("radix.slottable");function Yb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$b}function Jb(e,o){let t={...o};for(let a in o){let s=e[a],r=o[a];/^on[A-Z]/.test(a)?s&&r?t[a]=(...i)=>{let d=r(...i);return s(...i),d}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function Zb(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 dn(e){let o=e+"CollectionProvider",[t,a]=ka(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=v=>{let{scope:h,children:x}=v,b=be__default.useRef(null),g=be__default.useRef(new Map).current;return jsx(s,{scope:h,itemMap:g,collectionRef:b,children:x})};n.displayName=o;let i=e+"CollectionSlot",d=vl(i),u=be__default.forwardRef((v,h)=>{let{scope:x,children:b}=v,g=r(i,x),L=Dt(h,g.collectionRef);return jsx(d,{ref:L,children:b})});u.displayName=i;let m=e+"CollectionItemSlot",f="data-radix-collection-item",l=vl(m),c=be__default.forwardRef((v,h)=>{let{scope:x,children:b,...g}=v,L=be__default.useRef(null),C=Dt(h,L),S=r(m,x);return be__default.useEffect(()=>(S.itemMap.set(L,{ref:L,...g}),()=>void S.itemMap.delete(L))),jsx(l,{[f]:"",ref:C,children:b})});c.displayName=m;function p(v){let h=r(e+"CollectionConsumer",v);return be__default.useCallback(()=>{let b=h.collectionRef.current;if(!b)return [];let g=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(h.itemMap.values()).sort((S,k)=>g.indexOf(S.ref.current)-g.indexOf(k.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:u,ItemSlot:c},p,a]}var Pc=["PageUp","PageDown"],Dc=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Rc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Vo="Slider",[wl,ev,tv]=dn(Vo),[Ec]=ka(Vo,[tv]),[av,un]=Ec(Vo),Fc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:i=false,minStepsBetweenThumbs:d=0,defaultValue:u=[a],value:m,onValueChange:f=()=>{},onValueCommit:l=()=>{},inverted:c=false,form:p,...v}=e,h=be.useRef(new Set),x=be.useRef(0),g=n==="horizontal"?ov:rv,[L=[],C]=ea({prop:m,defaultProp:u,onChange:T=>{[...h.current][x.current]?.focus(),f(T);}}),S=be.useRef(L);function k(T){let V=dv(L,T);E(T,V);}function y(T){E(T,x.current);}function A(){let T=S.current[x.current];L[x.current]!==T&&l(L);}function E(T,V,{commit:z}={commit:false}){let R=mv(r),G=pv(Math.round((T-a)/r)*r+a,R),D=bl(G,[a,s]);C((ee=[])=>{let N=iv(ee,D,V);if(fv(N,d*r)){x.current=N.indexOf(D);let se=String(N)!==String(ee);return se&&z&&l(N),se?N:ee}else return ee});}return jsx(av,{scope:e.__scopeSlider,name:t,disabled:i,min:a,max:s,valueIndexToChangeRef:x,thumbs:h.current,values:L,orientation:n,form:p,children:jsx(wl.Provider,{scope:e.__scopeSlider,children:jsx(wl.Slot,{scope:e.__scopeSlider,children:jsx(g,{"aria-disabled":i,"data-disabled":i?"":void 0,...v,ref:o,onPointerDown:Je(v.onPointerDown,()=>{i||(S.current=L);}),min:a,max:s,inverted:c,onSlideStart:i?void 0:k,onSlideMove:i?void 0:y,onSlideEnd:i?void 0:A,onHomeKeyDown:()=>!i&&E(a,0,{commit:true}),onEndKeyDown:()=>!i&&E(s,L.length-1,{commit:true}),onStepKeyDown:({event:T,direction:V})=>{if(!i){let G=Pc.includes(T.key)||T.shiftKey&&Dc.includes(T.key)?10:1,D=x.current,ee=L[D],N=r*G*V;E(ee+N,D,{commit:true});}}})})})})});Fc.displayName=Vo;var[Bc,Oc]=Ec(Vo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),ov=be.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:i,onSlideEnd:d,onStepKeyDown:u,...m}=e,[f,l]=be.useState(null),c=Dt(o,g=>l(g)),p=be.useRef(void 0),v=No(s),h=v==="ltr",x=h&&!r||!h&&r;function b(g){let L=p.current||f.getBoundingClientRect(),C=[0,L.width],k=Il(C,x?[t,a]:[a,t]);return p.current=L,k(g-L.left)}return jsx(Bc,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:jsx(Nc,{dir:v,"data-orientation":"horizontal",...m,ref:c,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:g=>{let L=b(g.clientX);n?.(L);},onSlideMove:g=>{let L=b(g.clientX);i?.(L);},onSlideEnd:()=>{p.current=void 0,d?.();},onStepKeyDown:g=>{let C=Rc[x?"from-left":"from-right"].includes(g.key);u?.({event:g,direction:C?-1:1});}})})}),rv=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:i,onStepKeyDown:d,...u}=e,m=be.useRef(null),f=Dt(o,m),l=be.useRef(void 0),c=!s;function p(v){let h=l.current||m.current.getBoundingClientRect(),x=[0,h.height],g=Il(x,c?[a,t]:[t,a]);return l.current=h,g(v-h.top)}return jsx(Bc,{scope:e.__scopeSlider,startEdge:c?"bottom":"top",endEdge:c?"top":"bottom",size:"height",direction:c?1:-1,children:jsx(Nc,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:v=>{let h=p(v.clientY);r?.(h);},onSlideMove:v=>{let h=p(v.clientY);n?.(h);},onSlideEnd:()=>{l.current=void 0,i?.();},onStepKeyDown:v=>{let x=Rc[c?"from-bottom":"from-top"].includes(v.key);d?.({event:v,direction:x?-1:1});}})})}),Nc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:i,onStepKeyDown:d,...u}=e,m=un(Vo,t);return jsx(lt.span,{...u,ref:o,onKeyDown:Je(e.onKeyDown,f=>{f.key==="Home"?(n(f),f.preventDefault()):f.key==="End"?(i(f),f.preventDefault()):Pc.concat(Dc).includes(f.key)&&(d(f),f.preventDefault());}),onPointerDown:Je(e.onPointerDown,f=>{let l=f.target;l.setPointerCapture(f.pointerId),f.preventDefault(),m.thumbs.has(l)?l.focus():a(f);}),onPointerMove:Je(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f);}),onPointerUp:Je(e.onPointerUp,f=>{let l=f.target;l.hasPointerCapture(f.pointerId)&&(l.releasePointerCapture(f.pointerId),r(f));})})}),Vc="SliderTrack",qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=un(Vc,t);return jsx(lt.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});qc.displayName=Vc;var Ll="SliderRange",Hc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=un(Ll,t),r=Oc(Ll,t),n=be.useRef(null),i=Dt(o,n),d=s.values.length,u=s.values.map(l=>zc(l,s.min,s.max)),m=d>1?Math.min(...u):0,f=100-Math.max(...u);return jsx(lt.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:i,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:f+"%"}})});Hc.displayName=Ll;var Sl="SliderThumb",Uc=be.forwardRef((e,o)=>{let t=ev(e.__scopeSlider),[a,s]=be.useState(null),r=Dt(o,i=>s(i)),n=be.useMemo(()=>a?t().findIndex(i=>i.ref.current===a):-1,[t,a]);return jsx(sv,{...e,ref:r,index:n})}),sv=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=un(Sl,t),i=Oc(Sl,t),[d,u]=be.useState(null),m=Dt(o,b=>u(b)),f=d?n.form||!!d.closest("form"):true,l=Cc(d),c=n.values[a],p=c===void 0?0:zc(c,n.min,n.max),v=lv(a,n.values.length),h=l?.[i.size],x=h?uv(h,p,i.direction):0;return be.useEffect(()=>{if(d)return n.thumbs.add(d),()=>{n.thumbs.delete(d);}},[d,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${p}% + ${x}px)`},children:[jsx(wl.ItemSlot,{scope:e.__scopeSlider,children:jsx(lt.span,{role:"slider","aria-label":e["aria-label"]||v,"aria-valuemin":n.min,"aria-valuenow":c,"aria-valuemax":n.max,"aria-orientation":n.orientation,"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,tabIndex:n.disabled?void 0:0,...r,ref:m,style:c===void 0?{display:"none"}:e.style,onFocus:Je(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),f&&jsx(Wc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:c},a)]})});Uc.displayName=Sl;var nv="RadioBubbleInput",Wc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=be.useRef(null),r=Dt(s,a),n=Sc(o);return be.useEffect(()=>{let i=s.current;if(!i)return;let d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"value").set;if(n!==o&&m){let f=new Event("input",{bubbles:true});m.call(i,o),i.dispatchEvent(f);}},[n,o]),jsx(lt.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});Wc.displayName=nv;function iv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function zc(e,o,t){let r=100/(t-o)*(e-o);return bl(r,[0,100])}function lv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function dv(e,o){if(e.length===1)return 0;let t=e.map(s=>Math.abs(s-o)),a=Math.min(...t);return t.indexOf(a)}function uv(e,o,t){let a=e/2,r=Il([0,50],[0,a]);return (a-r(o)*t)*t}function cv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function fv(e,o){if(o>0){let t=cv(e);return Math.min(...t)>=o}return true}function Il(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 mv(e){return (String(e).split(".")[1]||"").length}function pv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var Gc=Fc,Kc=qc,_c=Hc,jc=Uc;function Xc(e){var o,t,a="";if(typeof e=="string"||typeof e=="number")a+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(o=0;o<s;o++)e[o]&&(t=Xc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function cn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=Xc(e))&&(a&&(a+=" "),a+=o);return a}var gv=(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},xv=(e,o)=>({classGroupId:e,validator:o}),Qc=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var $c=[],bv="arbitrary..",vv=e=>{let o=wv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return yv(n);let i=n.split("-"),d=i[0]===""&&i.length>1?1:0;return ef(i,d,o)},getConflictingClassGroupIds:(n,i)=>{if(i){let d=a[n],u=t[n];return d?u?gv(u,d):d:u||$c}return t[n]||$c}}},ef=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let u=ef(e,o+1,r);if(u)return u}let n=t.validators;if(n===null)return;let i=o===0?e.join("-"):e.slice(o).join("-"),d=n.length;for(let u=0;u<d;u++){let m=n[u];if(m.validator(i))return m.classGroupId}},yv=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?bv+a:void 0})(),wv=e=>{let{theme:o,classGroups:t}=e;return Lv(t,o)},Lv=(e,o)=>{let t=Qc();for(let a in e){let s=e[a];Ml(s,t,a,o);}return t},Ml=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Sv(n,o,t,a);}},Sv=(e,o,t,a)=>{if(typeof e=="string"){Iv(e,o,t);return}if(typeof e=="function"){Cv(e,o,t,a);return}kv(e,o,t,a);},Iv=(e,o,t)=>{let a=e===""?o:tf(o,e);a.classGroupId=t;},Cv=(e,o,t,a)=>{if(Mv(e)){Ml(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(xv(t,e));},kv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[i,d]=s[n];Ml(d,tf(o,i),t,a);}},tf=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],i=t.nextPart.get(n);i||(i=Qc(),t.nextPart.set(n,i)),t=i;}return t},Mv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,Tv=e=>{if(e<1)return {get:()=>{},set:()=>{}};let o=0,t=Object.create(null),a=Object.create(null),s=(r,n)=>{t[r]=n,o++,o>e&&(o=0,a=t,t=Object.create(null));};return {get(r){let n=t[r];if(n!==void 0)return n;if((n=a[r])!==void 0)return s(r,n),n},set(r,n){r in t?t[r]=n:s(r,n);}}};var Av=[],Yc=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Pv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,i=0,d=0,u,m=s.length;for(let v=0;v<m;v++){let h=s[v];if(n===0&&i===0){if(h===":"){r.push(s.slice(d,v)),d=v+1;continue}if(h==="/"){u=v;continue}}h==="["?n++:h==="]"?n--:h==="("?i++:h===")"&&i--;}let f=r.length===0?s:s.slice(d),l=f,c=false;f.endsWith("!")?(l=f.slice(0,-1),c=true):f.startsWith("!")&&(l=f.slice(1),c=true);let p=u&&u>d?u-d:void 0;return Yc(r,c,l,p)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):Yc(Av,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},Dv=e=>{let o=new Map;return e.orderSensitiveModifiers.forEach((t,a)=>{o.set(t,1e6+a);}),t=>{let a=[],s=[];for(let r=0;r<t.length;r++){let n=t[r],i=n[0]==="[",d=o.has(n);i||d?(s.length>0&&(s.sort(),a.push(...s),s=[]),a.push(n)):s.push(n);}return s.length>0&&(s.sort(),a.push(...s)),a}},Rv=e=>({cache:Tv(e.cacheSize),parseClassName:Pv(e),sortModifiers:Dv(e),...vv(e)}),Ev=/\s+/,Fv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],i=e.trim().split(Ev),d="";for(let u=i.length-1;u>=0;u-=1){let m=i[u],{isExternal:f,modifiers:l,hasImportantModifier:c,baseClassName:p,maybePostfixModifierPosition:v}=t(m);if(f){d=m+(d.length>0?" "+d:d);continue}let h=!!v,x=a(h?p.substring(0,v):p);if(!x){if(!h){d=m+(d.length>0?" "+d:d);continue}if(x=a(p),!x){d=m+(d.length>0?" "+d:d);continue}h=false;}let b=l.length===0?"":l.length===1?l[0]:r(l).join(":"),g=c?b+"!":b,L=g+x;if(n.indexOf(L)>-1)continue;n.push(L);let C=s(x,h);for(let S=0;S<C.length;++S){let k=C[S];n.push(g+k);}d=m+(d.length>0?" "+d:d);}return d},Bv=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=af(t))&&(s&&(s+=" "),s+=a);return s},af=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=af(e[a]))&&(t&&(t+=" "),t+=o);return t},Ov=(e,...o)=>{let t,a,s,r,n=d=>{let u=o.reduce((m,f)=>f(m),e());return t=Rv(u),a=t.cache.get,s=t.cache.set,r=i,i(d)},i=d=>{let u=a(d);if(u)return u;let m=Fv(d,t);return s(d,m),m};return r=n,(...d)=>r(Bv(...d))},Nv=[],He=e=>{let o=t=>t[e]||Nv;return o.isThemeGetter=true,o},of=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,rf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Vv=/^\d+\/\d+$/,qv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Hv=/\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$/,Uv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Wv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,zv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,qo=e=>Vv.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ma=e=>!!e&&Number.isInteger(Number(e)),Cl=e=>e.endsWith("%")&&de(e.slice(0,-1)),ta=e=>qv.test(e),Gv=()=>true,Kv=e=>Hv.test(e)&&!Uv.test(e),sf=()=>false,_v=e=>Wv.test(e),jv=e=>zv.test(e),Xv=e=>!X(e)&&!$(e),$v=e=>Ho(e,df,sf),X=e=>of.test(e),Ya=e=>Ho(e,uf,Kv),kl=e=>Ho(e,ey,de),Jc=e=>Ho(e,nf,sf),Yv=e=>Ho(e,lf,jv),fn=e=>Ho(e,cf,_v),$=e=>rf.test(e),Rr=e=>Uo(e,uf),Jv=e=>Uo(e,ty),Zc=e=>Uo(e,nf),Zv=e=>Uo(e,df),Qv=e=>Uo(e,lf),mn=e=>Uo(e,cf,true),Ho=(e,o,t)=>{let a=of.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Uo=(e,o,t=false)=>{let a=rf.exec(e);return a?a[1]?o(a[1]):t:false},nf=e=>e==="position"||e==="percentage",lf=e=>e==="image"||e==="url",df=e=>e==="length"||e==="size"||e==="bg-size",uf=e=>e==="length",ey=e=>e==="number",ty=e=>e==="family-name",cf=e=>e==="shadow";var ay=()=>{let e=He("color"),o=He("font"),t=He("text"),a=He("font-weight"),s=He("tracking"),r=He("leading"),n=He("breakpoint"),i=He("container"),d=He("spacing"),u=He("radius"),m=He("shadow"),f=He("inset-shadow"),l=He("text-shadow"),c=He("drop-shadow"),p=He("blur"),v=He("perspective"),h=He("aspect"),x=He("ease"),b=He("animate"),g=()=>["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"],C=()=>[...L(),$,X],S=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],y=()=>[$,X,d],A=()=>[qo,"full","auto",...y()],E=()=>[Ma,"none","subgrid",$,X],T=()=>["auto",{span:["full",Ma,$,X]},Ma,$,X],V=()=>[Ma,"auto",$,X],z=()=>["auto","min","max","fr",$,X],R=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],G=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...y()],ee=()=>[qo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...y()],N=()=>[e,$,X],se=()=>[...L(),Zc,Jc,{position:[$,X]}],K=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",Zv,$v,{size:[$,X]}],j=()=>[Cl,Rr,Ya],H=()=>["","none","full",u,$,X],U=()=>["",de,Rr,Ya],Y=()=>["solid","dashed","dotted","double"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[de,Cl,Zc,Jc],le=()=>["","none",p,$,X],Ie=()=>["none",de,$,X],J=()=>["none",de,$,X],Me=()=>[de,$,X],Be=()=>[qo,"full",...y()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ta],breakpoint:[ta],color:[Gv],container:[ta],"drop-shadow":[ta],ease:["in","out","in-out"],font:[Xv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ta],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ta],shadow:[ta],spacing:["px",de],text:[ta],"text-shadow":[ta],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",qo,X,$,h]}],container:["container"],columns:[{columns:[de,X,$,i]}],"break-after":[{"break-after":g()}],"break-before":[{"break-before":g()}],"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:C()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],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:[Ma,"auto",$,X]}],basis:[{basis:[qo,"full","auto",i,...y()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,qo,"auto","initial","none",X]}],grow:[{grow:["",de,$,X]}],shrink:[{shrink:["",de,$,X]}],order:[{order:[Ma,"first","last","none",$,X]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:T()}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:T()}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":z()}],"auto-rows":[{"auto-rows":z()}],gap:[{gap:y()}],"gap-x":[{"gap-x":y()}],"gap-y":[{"gap-y":y()}],"justify-content":[{justify:[...R(),"normal"]}],"justify-items":[{"justify-items":[...G(),"normal"]}],"justify-self":[{"justify-self":["auto",...G()]}],"align-content":[{content:["normal",...R()]}],"align-items":[{items:[...G(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...G(),{baseline:["","last"]}]}],"place-content":[{"place-content":R()}],"place-items":[{"place-items":[...G(),"baseline"]}],"place-self":[{"place-self":["auto",...G()]}],p:[{p:y()}],px:[{px:y()}],py:[{py:y()}],ps:[{ps:y()}],pe:[{pe:y()}],pt:[{pt:y()}],pr:[{pr:y()}],pb:[{pb:y()}],pl:[{pl:y()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":y()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":y()}],"space-y-reverse":["space-y-reverse"],size:[{size:ee()}],w:[{w:[i,"screen",...ee()]}],"min-w":[{"min-w":[i,"screen","none",...ee()]}],"max-w":[{"max-w":[i,"screen","none","prose",{screen:[n]},...ee()]}],h:[{h:["screen","lh",...ee()]}],"min-h":[{"min-h":["screen","lh","none",...ee()]}],"max-h":[{"max-h":["screen","lh",...ee()]}],"font-size":[{text:["base",t,Rr,Ya]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,$,kl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Cl,X]}],"font-family":[{font:[Jv,X,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:[s,$,X]}],"line-clamp":[{"line-clamp":[de,"none",$,kl]}],leading:[{leading:[r,...y()]}],"list-image":[{"list-image":["none",$,X]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,X]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",$,Ya]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[de,"auto",$,X]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:y()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,X]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",$,X]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:se()}],"bg-repeat":[{bg:K()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ma,$,X],radial:["",$,X],conic:[Ma,$,X]},Qv,Yv]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:j()}],"gradient-via-pos":[{via:j()}],"gradient-to-pos":[{to:j()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:H()}],"rounded-s":[{"rounded-s":H()}],"rounded-e":[{"rounded-e":H()}],"rounded-t":[{"rounded-t":H()}],"rounded-r":[{"rounded-r":H()}],"rounded-b":[{"rounded-b":H()}],"rounded-l":[{"rounded-l":H()}],"rounded-ss":[{"rounded-ss":H()}],"rounded-se":[{"rounded-se":H()}],"rounded-ee":[{"rounded-ee":H()}],"rounded-es":[{"rounded-es":H()}],"rounded-tl":[{"rounded-tl":H()}],"rounded-tr":[{"rounded-tr":H()}],"rounded-br":[{"rounded-br":H()}],"rounded-bl":[{"rounded-bl":H()}],"border-w":[{border:U()}],"border-w-x":[{"border-x":U()}],"border-w-y":[{"border-y":U()}],"border-w-s":[{"border-s":U()}],"border-w-e":[{"border-e":U()}],"border-w-t":[{"border-t":U()}],"border-w-r":[{"border-r":U()}],"border-w-b":[{"border-b":U()}],"border-w-l":[{"border-l":U()}],"divide-x":[{"divide-x":U()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":U()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"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:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,$,X]}],"outline-w":[{outline:["",de,Rr,Ya]}],"outline-color":[{outline:N()}],shadow:[{shadow:["","none",m,mn,fn]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":["none",f,mn,fn]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:U()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[de,Ya]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":U()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":["none",l,mn,fn]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[de,$,X]}],"mix-blend":[{"mix-blend":[...Z(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Z()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[$,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":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":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":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:se()}],"mask-repeat":[{mask:K()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,X]}],filter:[{filter:["","none",$,X]}],blur:[{blur:le()}],brightness:[{brightness:[de,$,X]}],contrast:[{contrast:[de,$,X]}],"drop-shadow":[{"drop-shadow":["","none",c,mn,fn]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:["",de,$,X]}],"hue-rotate":[{"hue-rotate":[de,$,X]}],invert:[{invert:["",de,$,X]}],saturate:[{saturate:[de,$,X]}],sepia:[{sepia:["",de,$,X]}],"backdrop-filter":[{"backdrop-filter":["","none",$,X]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[de,$,X]}],"backdrop-contrast":[{"backdrop-contrast":[de,$,X]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,$,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,$,X]}],"backdrop-invert":[{"backdrop-invert":["",de,$,X]}],"backdrop-opacity":[{"backdrop-opacity":[de,$,X]}],"backdrop-saturate":[{"backdrop-saturate":[de,$,X]}],"backdrop-sepia":[{"backdrop-sepia":["",de,$,X]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":y()}],"border-spacing-x":[{"border-spacing-x":y()}],"border-spacing-y":[{"border-spacing-y":y()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,X]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",$,X]}],ease:[{ease:["linear","initial",x,$,X]}],delay:[{delay:[de,$,X]}],animate:[{animate:["none",b,$,X]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[v,$,X]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:J()}],"scale-x":[{"scale-x":J()}],"scale-y":[{"scale-y":J()}],"scale-z":[{"scale-z":J()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[$,X,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Be()}],"translate-x":[{"translate-x":Be()}],"translate-y":[{"translate-y":Be()}],"translate-z":[{"translate-z":Be()}],"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",$,X]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":y()}],"scroll-mx":[{"scroll-mx":y()}],"scroll-my":[{"scroll-my":y()}],"scroll-ms":[{"scroll-ms":y()}],"scroll-me":[{"scroll-me":y()}],"scroll-mt":[{"scroll-mt":y()}],"scroll-mr":[{"scroll-mr":y()}],"scroll-mb":[{"scroll-mb":y()}],"scroll-ml":[{"scroll-ml":y()}],"scroll-p":[{"scroll-p":y()}],"scroll-px":[{"scroll-px":y()}],"scroll-py":[{"scroll-py":y()}],"scroll-ps":[{"scroll-ps":y()}],"scroll-pe":[{"scroll-pe":y()}],"scroll-pt":[{"scroll-pt":y()}],"scroll-pr":[{"scroll-pr":y()}],"scroll-pb":[{"scroll-pb":y()}],"scroll-pl":[{"scroll-pl":y()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,X]}],fill:[{fill:["none",...N()]}],"stroke-w":[{stroke:[de,Rr,Ya,kl]}],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 ff=Ov(ay);function Ta(...e){return ff(cn(e))}function pn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:i,...d}){let u=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(Gc,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Ta("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),...d,children:[jsx(Kc,{"data-slot":"slider-track",className:Ta("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(_c,{"data-slot":"slider-range",className:Ta("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:u.length},(m,f)=>jsx(jc,{"data-slot":"slider-thumb",className:Ta("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",i)},f))]})}var ry="SchooplaVideoStorage";var $t="videos",hn=()=>new Promise((e,o)=>{let t=indexedDB.open(ry,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains($t)||s.createObjectStore($t,{keyPath:"id"});};}),Ja=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await hn(),r=a.transaction([$t],"readwrite").objectStore($t),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((i,d)=>{let u=r.put(n);u.onsuccess=()=>i(!0),u.onerror=()=>d(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 pf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await hn(),t=e.transaction([$t],"readonly").objectStore($t);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,i=new Map;n.forEach(d=>{i.set(d.id,{blob:d.blob,thumbnailDataUrl:d.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${i.size} video blobs from IndexedDB`),a(i);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Al=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await hn(),a=o.transaction([$t],"readwrite").objectStore($t);await new Promise((s,r)=>{let n=a.delete(e);n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),o.close(),console.log("\u2705 Video blob deleted successfully:",e);}catch(o){throw console.error("Error deleting video blob from IndexedDB:",o),o}},hf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await hn(),t=e.transaction([$t],"readwrite").objectStore($t);await new Promise((a,s)=>{let r=t.clear();r.onsuccess=()=>a(!0),r.onerror=()=>s(r.error);}),e.close(),console.log("\u2705 All video blobs cleared successfully");}catch(e){throw console.error("Error clearing video blobs from IndexedDB:",e),e}},gf=e=>URL.createObjectURL(e);var sy=be[" useId ".trim().toString()]||(()=>{}),ny=0;function xf(e){let[o,t]=be.useState(sy());return Oo(()=>{t(a=>a??String(ny++));},[e]),(o?`radix-${o}`:"")}function bf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var Dl="rovingFocusGroup.onEntryFocus",iy={bubbles:false,cancelable:true},Er="RovingFocusGroup",[Rl,vf,ly]=dn(Er),[dy,El]=ka(Er,[ly]),[uy,cy]=dy(Er),yf=be.forwardRef((e,o)=>jsx(Rl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Rl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(fy,{...e,ref:o})})}));yf.displayName=Er;var fy=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:m=false,...f}=e,l=be.useRef(null),c=Dt(o,l),p=No(r),[v,h]=ea({prop:n,defaultProp:i??null,onChange:d,caller:Er}),[x,b]=be.useState(false),g=bf(u),L=vf(t),C=be.useRef(false),[S,k]=be.useState(0);return be.useEffect(()=>{let y=l.current;if(y)return y.addEventListener(Dl,g),()=>y.removeEventListener(Dl,g)},[g]),jsx(uy,{scope:t,orientation:a,dir:p,loop:s,currentTabStopId:v,onItemFocus:be.useCallback(y=>h(y),[h]),onItemShiftTab:be.useCallback(()=>b(true),[]),onFocusableItemAdd:be.useCallback(()=>k(y=>y+1),[]),onFocusableItemRemove:be.useCallback(()=>k(y=>y-1),[]),children:jsx(lt.div,{tabIndex:x||S===0?-1:0,"data-orientation":a,...f,ref:c,style:{outline:"none",...e.style},onMouseDown:Je(e.onMouseDown,()=>{C.current=true;}),onFocus:Je(e.onFocus,y=>{let A=!C.current;if(y.target===y.currentTarget&&A&&!x){let E=new CustomEvent(Dl,iy);if(y.currentTarget.dispatchEvent(E),!E.defaultPrevented){let T=L().filter(D=>D.focusable),V=T.find(D=>D.active),z=T.find(D=>D.id===v),G=[V,z,...T].filter(Boolean).map(D=>D.ref.current);Sf(G,m);}}C.current=false;}),onBlur:Je(e.onBlur,()=>b(false))})})}),wf="RovingFocusGroupItem",Lf=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...i}=e,d=xf(),u=r||d,m=cy(wf,t),f=m.currentTabStopId===u,l=vf(t),{onFocusableItemAdd:c,onFocusableItemRemove:p,currentTabStopId:v}=m;return be.useEffect(()=>{if(a)return c(),()=>p()},[a,c,p]),jsx(Rl.ItemSlot,{scope:t,id:u,focusable:a,active:s,children:jsx(lt.span,{tabIndex:f?0:-1,"data-orientation":m.orientation,...i,ref:o,onMouseDown:Je(e.onMouseDown,h=>{a?m.onItemFocus(u):h.preventDefault();}),onFocus:Je(e.onFocus,()=>m.onItemFocus(u)),onKeyDown:Je(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let x=hy(h,m.orientation,m.dir);if(x!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let g=l().filter(L=>L.focusable).map(L=>L.ref.current);if(x==="last")g.reverse();else if(x==="prev"||x==="next"){x==="prev"&&g.reverse();let L=g.indexOf(h.currentTarget);g=m.loop?gy(g,L+1):g.slice(L+1);}setTimeout(()=>Sf(g));}}),children:typeof n=="function"?n({isCurrentTabStop:f,hasTabStop:v!=null}):n})})});Lf.displayName=wf;var my={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function py(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function hy(e,o,t){let a=py(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return my[a]}function Sf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function gy(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var If=yf,Cf=Lf;var Mf="Toggle",Fl=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,i]=ea({prop:t,onChange:s,defaultProp:a??false,caller:Mf});return jsx(lt.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":e.disabled?"":void 0,...r,ref:o,onClick:Je(e.onClick,()=>{e.disabled||i(!n);})})});Fl.displayName=Mf;var Aa="ToggleGroup",[Af]=ka(Aa,[El]),Pf=El(),Bl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(vy,{...a,ref:o});if(t==="multiple")return jsx(yy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Aa}\``)});Bl.displayName=Aa;var[Df,Rf]=Af(Aa),vy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,i]=ea({prop:t,defaultProp:a??"",onChange:s,caller:Aa});return jsx(Df,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:i,onItemDeactivate:be__default.useCallback(()=>i(""),[i]),children:jsx(Ef,{...r,ref:o})})}),yy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,i]=ea({prop:t,defaultProp:a??[],onChange:s,caller:Aa}),d=be__default.useCallback(m=>i((f=[])=>[...f,m]),[i]),u=be__default.useCallback(m=>i((f=[])=>f.filter(l=>l!==m)),[i]);return jsx(Df,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:d,onItemDeactivate:u,children:jsx(Ef,{...r,ref:o})})});Bl.displayName=Aa;var[wy,Ly]=Af(Aa),Ef=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:i=true,...d}=e,u=Pf(t),m=No(n),f={role:"group",dir:m,...d};return jsx(wy,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(If,{asChild:true,...u,orientation:r,dir:m,loop:i,children:jsx(lt.div,{...f,ref:o})}):jsx(lt.div,{...f,ref:o})})}),gn="ToggleGroupItem",Sy=be__default.forwardRef((e,o)=>{let t=Rf(gn,e.__scopeToggleGroup),a=Ly(gn,e.__scopeToggleGroup),s=Pf(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,i={...e,pressed:r,disabled:n},d=be__default.useRef(null);return a.rovingFocus?jsx(Cf,{asChild:true,...s,focusable:!n,active:r,ref:d,children:jsx(Tf,{...i,ref:o})}):jsx(Tf,{...i,ref:o})});Sy.displayName=gn;var Tf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Rf(gn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=r.type==="single"?n:void 0;return jsx(Fl,{...i,...s,ref:o,onPressedChange:d=>{d?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Ff=Bl;var ky=be.createContext({size:"default",variant:"default",spacing:0});function Pa({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Ff,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Ta("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(ky.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var Ty={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},qf=createSlice({name:"toolbar",initialState:Ty,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:zt,setPenColor:zo,setStrokeWidth:Fr,setFontSize:dD,setFontFamily:uD,setFontStyle:cD,setFontWeight:fD,setTextDecoration:mD,setTextColor:pD}=qf.actions,Hf=qf.reducer;var Uf=({onClose:e,onRecordingComplete:o})=>{let t=$e(),[a,s]=useState(false),[r,n]=useState(null),[i,d]=useState(0),[u,m]=useState(null),[f,l]=useState(false),c=useRef(null),p=useRef([]),v=useRef(null),h=useRef(null),x=useRef(null);useEffect(()=>((async()=>{try{let A=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(A),l(!0),x.current&&(x.current.srcObject=A);}catch(A){console.error("Error accessing camera:",A),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{v.current&&clearInterval(v.current),u&&u.getTracks().forEach(A=>A.stop());}),[]);let b=()=>{u&&(u.getTracks().forEach(y=>y.stop()),m(null),l(false));},g=async()=>{try{let y=null,A=null;try{y=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(R){console.error("Error accessing camera for recording:",R),alert("Failed to access camera for recording.");return}try{A=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(R){console.warn("Microphone access denied:",R);}let E=[...y.getVideoTracks()];A&&E.push(...A.getAudioTracks());let T=new MediaStream(E),V="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?V="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?V="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?V="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(V="video/webm;codecs=vp8");let z=new MediaRecorder(T,{mimeType:V,videoBitsPerSecond:25e5});c.current=z,p.current=[],z.ondataavailable=R=>{R.data.size>0&&p.current.push(R.data);},z.onstop=()=>{let R=new Blob(p.current,{type:V}),G=document.createElement("video");G.src=URL.createObjectURL(R),G.muted=!0,G.currentTime=.1,G.onseeked=()=>{let D=document.createElement("canvas");D.width=G.videoWidth,D.height=G.videoHeight;let ee=D.getContext("2d");ee&&(ee.drawImage(G,0,0),h.current=D.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(G.src);},T.getTracks().forEach(D=>D.stop()),y&&y.getTracks().forEach(D=>D.stop()),A&&A.getTracks().forEach(D=>D.stop()),v.current&&clearInterval(v.current),n(R),b();},z.onerror=R=>{console.error("MediaRecorder error:",R);},z.start(1e3),s(!0),d(0),v.current=setInterval(()=>{d(R=>R+1);},1e3);}catch(y){console.error("Error starting camera recording:",y),alert("Failed to start recording. Please check permissions.");}},L=()=>{c.current&&a&&(c.current.state!=="inactive"&&(c.current.requestData(),setTimeout(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop();},100)),s(false));},C=()=>{if(r){let y=URL.createObjectURL(r),A=document.createElement("a");A.href=y,A.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(y);}},S=y=>{let A=Math.floor(y/60),E=y%60;return `${A.toString().padStart(2,"0")}:${E.toString().padStart(2,"0")}`};if(!t)return null;let k=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onMouseDown:y=>{y.target===y.currentTarget&&e(),y.stopPropagation();},onMouseUp:y=>y.stopPropagation(),onMouseMove:y=>y.stopPropagation(),onTouchStart:y=>y.stopPropagation(),onTouchMove:y=>y.stopPropagation(),onTouchEnd:y=>y.stopPropagation(),children:jsxs("div",{className:"pointer-events-auto relative w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:y=>y.stopPropagation(),children:[jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 rounded-full bg-white/90 p-2 text-gray-600 transition-colors hover:bg-white hover:text-gray-900",children:jsx(X$1,{className:"h-5 w-5"})}),jsxs("div",{className:"relative aspect-video bg-gray-900",children:[!r&&jsxs(Fragment,{children:[jsx("video",{ref:x,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:g,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"})})]}),a&&jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[jsx("button",{onClick:L,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:S(i)})]})]})]}),r&&jsxs(Fragment,{children:[jsx("video",{src:URL.createObjectURL(r),controls:true,className:"h-full w-full object-cover"}),jsxs("div",{className:"absolute right-0 bottom-0 left-0 bg-linear-to-t from-black/80 via-black/50 to-transparent p-6",children:[jsxs("p",{className:"mb-3 text-center text-sm text-white/80",children:["Duration: ",S(i)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),d(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:C,className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700",children:[jsx(Download,{className:"h-4 w-4"}),"Download"]}),jsx("button",{onClick:()=>{o&&r&&h.current&&(o(r,h.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,t)};var aa=40,zf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[i,d]=useState(false),u=useRef(null),m=$e(),f=useRef(null);useEffect(()=>{let g=L=>{L.key==="Escape"&&o();};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[o]);let l=g=>{let L=g.target.files;if(!L||L.length===0)return;let C=aa-a.length;if(C<=0){alert(`You can only upload a maximum of ${aa} images`);return}let S=Array.from(L).slice(0,C);S.length<L.length&&alert(`Only ${C} more images can be added (max ${aa} total)`);let k=S.map(y=>new Promise((A,E)=>{let T=new FileReader;T.onload=V=>{V.target?.result?A(V.target.result):E(new Error("Failed to read file"));},T.onerror=E,T.readAsDataURL(y);}));Promise.all(k).then(y=>{s(A=>[...A,...y]),f.current&&(f.current.value="");});},c=g=>{g.preventDefault(),d(false);let L=Array.from(g.dataTransfer.files).filter(y=>y.type.startsWith("image/"));if(L.length===0)return;let C=aa-a.length;if(C<=0){alert(`You can only upload a maximum of ${aa} images`);return}let S=L.slice(0,C);S.length<L.length&&alert(`Only ${C} more images can be added (max ${aa} total)`);let k=S.map(y=>new Promise((A,E)=>{let T=new FileReader;T.onload=V=>{V.target?.result?A(V.target.result):E(new Error("Failed to read file"));},T.onerror=E,T.readAsDataURL(y);}));Promise.all(k).then(y=>{s(A=>[...A,...y]);});},p=g=>{g.preventDefault(),d(true);},v=()=>{d(false);},h=g=>{s(L=>L.filter((C,S)=>S!==g));},x=g=>{if(g.preventDefault(),a.length<2){alert("Please upload at least 2 images for the flashcard");return}e(a,r,t?.id);};if(!m)return null;let b=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:g=>{g.target===g.currentTarget&&o(),g.stopPropagation();},onMouseUp:g=>g.stopPropagation(),onMouseMove:g=>g.stopPropagation(),onTouchStart:g=>g.stopPropagation(),onTouchMove:g=>g.stopPropagation(),onTouchEnd:g=>g.stopPropagation(),children:jsxs("div",{ref:u,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:g=>g.stopPropagation(),children:[jsxs("div",{className:"px-6 pt-4 pb-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"text-xl font-bold text-[#000000CC]",children:t?"Edit Flashcard":"Create Flashcard"}),jsx("button",{onClick:o,className:"cursor-pointer text-[#00000099]",children:jsx(X$1,{size:20,weight:"bold"})})]}),jsx("p",{className:"text-sm font-normal text-[#00000099]",children:"Add images to create an interactive study set."})]}),jsxs("form",{onSubmit:x,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:l,className:"hidden",id:"flashcard-file-input"}),jsxs("label",{htmlFor:"flashcard-file-input",onDrop:c,onDragOver:p,onDragLeave:v,className:`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${i?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:i?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>n("sequential"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="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 ${r==="sequential"?"bg-primary/8 text-primary":""}`,children:jsx(ArrowsDownUp,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Sequential"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})}),jsx("button",{type:"button",onClick:()=>n("random"),className:`cursor-pointer rounded-lg border-2 p-4 transition-all ${r==="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 ${r==="random"?"bg-primary/8 text-primary":""}`,children:jsx(Shuffle,{size:20})}),jsxs("div",{className:"text-left",children:[jsx("p",{className:"text-sm font-medium",children:"Random"}),jsx("p",{className:"mt-0.5 text-xs opacity-70",children:"Students navigate through cards in a fixed, specific order."})]})]})})]})]}),a.length>0&&jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between px-2 text-sm font-medium text-gray-900",children:[jsx("span",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Your Cards"}),jsxs("span",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:[a.length," card",a.length!==1?"s":""]})]}),jsx("div",{className:"grid max-h-72 grid-cols-3 gap-3 overflow-y-auto rounded-lg p-3",children:a.map((g,L)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:g,alt:`Flashcard ${L+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>h(L),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:L+1})]},L))})]}),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(b,m)};var xn={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}},Gy={enabled:true};function ql(e){return e?{tools:{...xn.tools,...e.tools},actions:{...xn.actions,...e.actions}}:xn}var Ky={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}},_y={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 yw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=xe(),n=te(F=>F.canvas.slides.find(re=>re.id===F.canvas.currentSlideId)),i=n?.videos||[],d=n?.editingFlashcard,u=te(F=>F.toolbar.selectedTool),m=te(F=>F.toolbar.penColor),f=te(F=>F.toolbar.strokeWidth),l=n?.showMcqForm,c=n?.showFlashcardForm,p=useRef(null),v=useMemo(()=>ql(s),[s]),{tools:h,actions:x}=v,b=i.some(F=>F.isRecorded&&F.isPlaying),g=te(F=>F.toolbar.fontSize),L=te(F=>F.toolbar.fontFamily),C=te(F=>F.toolbar.fontStyle),S=te(F=>F.toolbar.fontWeight),k=te(F=>F.toolbar.textDecoration),y=te(F=>F.toolbar.textColor),[A,E]=useState(false),[T,V]=useState(false),[z,R]=useState(false),[G,D]=useState(false),[ee,N]=useState(false),[se,K]=useState(false),[q,j]=useState(false),H=useRef(null),U=useRef(null),Y=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"}],[]),Q=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"}],[]),le=useMemo(()=>Y.filter(F=>{let re=h[F.configKey];return typeof re=="boolean"?re:Array.isArray(re)?re.length>0:true}),[h,Y]),Ie=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?Z:Array.isArray(F)?Z.filter(re=>F.includes(re.name)):Z},[h.shapes,Z]),J=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?Q:Array.isArray(F)?Q.filter(re=>F.includes(re.name)):Q},[h.activities,Q]),Me=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]),Be=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),Et=F=>{let re=F.target.files;!re||re.length===0||(r(zt("select")),r(ft(false)),D(false),Array.from(re).forEach(ye=>{let ge=new FileReader;ge.onload=ne=>{let ue=new window.Image;ue.src=ne.target?.result,ue.onload=()=>{let we=ue.width/ue.height,Ne=300,Ft=300,ut=ue.width,Te=ue.height;ut>Ne&&(ut=Ne,Te=ut/we),Te>Ft&&(Te=Ft,ut=Te*we),r(ce());let Ue=960-ut/2,Jt=540-Te/2;r(Kn({id:v4(),src:ue.src,x:Ue,y:Jt,width:ut,height:Te,draggable:true,rotation:0}));};},ge.readAsDataURL(ye);}),F.target.value="");},oo=async F=>{let re=F.target.files;if(!(!re||re.length===0)){console.log("files",F),r(zt("select")),r(ft(false)),D(false);for(let ye of Array.from(re))try{let ge=URL.createObjectURL(ye),ne=document.createElement("video");console.log("video",ne),ne.src=ge,ne.muted=!0,ne.playsInline=!0,ne.preload="auto",ne.load(),await new Promise((Bt,da)=>{let Fa=setTimeout(()=>da(new Error("Metadata load timeout")),1e4);ne.onloadedmetadata=()=>{clearTimeout(Fa),Bt();},ne.onerror=()=>{clearTimeout(Fa),da(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:ne.duration,width:ne.videoWidth,height:ne.videoHeight}),await new Promise((Bt,da)=>{let Fa=setTimeout(()=>da(new Error("Video load timeout")),1e4);ne.readyState>=2?(clearTimeout(Fa),Bt()):ne.onloadeddata=()=>{clearTimeout(Fa),Bt();};});let ue=Math.min(.8,ne.duration/2);console.log("Seeking to:",ue),ne.currentTime=ue,await new Promise(Bt=>{let da=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),Bt();},5e3);ne.onseeked=()=>{clearTimeout(da),console.log("Seek completed"),Bt();};});let we=document.createElement("canvas"),Ne=ne.videoWidth/ne.videoHeight,Ft=400,ut=400,Te=ne.videoWidth,Ue=ne.videoHeight;Te>Ft&&(Te=Ft,Ue=Te/Ne),Ue>ut&&(Ue=ut,Te=Ue*Ne),we.width=Te,we.height=Ue;let Jt=we.getContext("2d",{willReadFrequently:!1});if(!Jt)throw new Error("Failed to get canvas context");if(await new Promise(Bt=>setTimeout(Bt,100)),ne.videoWidth===0||ne.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Te,height:Ue}),Jt.drawImage(ne,0,0,Te,Ue);let la=we.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",la.length),r(ce());let Ea=960-Te/2,Dn=540-Ue/2,zr=v4();await Ja(zr,ye,la),r(Qr({id:zr,objectUrl:ge,thumbnailDataUrl:la,videoBlob:ye,x:Ea,y:Dn,width:Te,height:Ue,draggable:!0,isPlaying:!1,rotation:0})),ne.src="",ne.load(),console.log(`Video uploaded: ${ye.name}`);}catch(ge){console.error("Error processing video:",ge),alert(`Failed to process video: ${ye.name}`);}F.target.value="";}},Hr=(F,re,ye)=>{r(ce()),r(zt("select")),r(ft(false));let ge=300,ne=300,ue=960-ge/2,we=540-ne/2;r(ye?co({id:ye,images:F,order:re,x:ue,y:we,width:ge,height:ne,rotation:0,draggable:true}):Xn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:re,x:ue,y:we,width:ge,height:ne,rotation:0,draggable:true})),r(Oa(false));},Ur=()=>{r(ce()),r(zt("select")),r(ft(false));let F=400,re=300,ye=800-F/2,ge=450-re/2;if(t?.current){let ne=t.current,ue=ne.scaleX()||1,we=ne.scaleY()||1,Ne=ne.width()/ue,Ft=ne.height()/we;ye=Ne/2-F/2,ge=Ft/2-re/2;}r(Jn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:ye,y:ge,width:F,height:re,rotation:0,draggable:true,isCapturing:false})),N(false);},In=F=>{let ue={};switch(F.name){case "circle":case "ring":case "wedge":case "arc":ue.radius=50,(F.name==="ring"||F.name==="arc")&&(ue.innerRadius=25,ue.outerRadius=50),(F.name==="wedge"||F.name==="arc")&&(ue.angle=F.name==="wedge"?60:90);break;case "ellipse":ue.radiusX=60,ue.radiusY=40;break;case "triangle":ue.radius=50,ue.sides=3;break;case "polygon":ue.radius=50,ue.sides=6;break;case "star":ue.innerRadius=25,ue.outerRadius=50,ue.numPoints=5;break;case "arrow":case "line":ue.points=[0,0,100,0],F.name==="arrow"&&(ue.pointerLength=10,ue.pointerWidth=10);break}let we={id:`shape-${Date.now()}`,type:F.name,x:910,y:490,width:100,height:100,rotation:0,color:m,...ue};r(ce()),r(ft(false)),r(zt(F.name)),r(_n(we));},ro=F=>{if(r(zt(F)),F==="select")r(ft(false));else if(F==="text"){r(ft(false)),r(ce());let re=200,ye=50,ge=960-re/2,ne=540-ye/2,we=window.innerWidth<768?Math.max(g,32):g,Ne=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r(jn({id:Ne,text:"",x:ge,y:ne,width:re,height:ye,rotation:0,draggable:true,fontSize:we,fontFamily:L,fontStyle:C,fontWeight:S,textDecoration:k,fill:y,align:"left"})),setTimeout(()=>{r(er(Ne));},100),a&&a(Ne);}else r(ft(true));},Cn=()=>{r(mi()),r(zt("select")),r(ft(false));},kn=()=>{o?o():t?E(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Mn=()=>{V(true);},ia=async(F,re)=>{try{r(zt("select")),r(ft(!1));let ye=URL.createObjectURL(F),ge=document.createElement("video");ge.src=ye,ge.muted=!0,ge.playsInline=!0,ge.preload="auto",await new Promise((Ue,Jt)=>{let la=setTimeout(()=>Jt(new Error("Metadata load timeout")),1e4);ge.onloadedmetadata=()=>{clearTimeout(la),Ue();},ge.onerror=()=>{clearTimeout(la),Jt(new Error("Failed to load video"));};});let ne=640,ue=ge.videoWidth/ge.videoHeight,we=ne,Ne=we/ue;r(ce());let Ft=960-we/2,ut=540-Ne/2,Te=v4();await Ja(Te,F,re),r(Qr({id:Te,objectUrl:ye,thumbnailDataUrl:re,videoBlob:F,x:Ft,y:ut,width:we,height:Ne,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),E(!1),V(!1);}catch(ye){console.error("Error adding recorded video to canvas:",ye),alert("Failed to add video to canvas. Please try again.");}},Tn=F=>{r(zt("select")),r(ft(false)),r(Zo(null)),F&&r(ii(F)),r(ma(!l));},An=()=>{r(Xo(null)),r(Oa(true)),N(false);},so=()=>{R(!z);},Wr=()=>{D(!G);},Pn=()=>{N(!ee);};return useEffect(()=>{if(!q)return;let F=re=>{p.current&&!p.current.contains(re.target)&&j(false);};return document.addEventListener("mousedown",F),()=>{document.removeEventListener("mousedown",F);}},[q]),b?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(Pa,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:le.map((F,re)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${F.name===u?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){Wr(),R(false),N(false),ro(F.name);return}else if(F.name==="shapes"){so(),D(false),N(false),ro(F.name);return}else if(F.name==="activities"){ro(F.name),Pn(),R(false),D(false);return}ro(F.name),R(false),D(false),N(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},re))}),z&&jsx(Pa,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:Ie.map((F,re)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>In(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},re))}),G&&jsxs(Pa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Me.photoFrame&&jsx("div",{title:"Photo frame",onClick:Ur,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Me.image&&jsx("div",{title:"Image",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Me.video&&jsx("div",{title:"Video",onClick:()=>U.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),ee&&jsxs(Pa,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Be&&jsx("div",{title:"Flashcard",onClick:()=>An(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),J.map((F,re)=>jsx("div",{title:F.label,onClick:()=>Tn(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},re))]})]}),(x.undo||x.redo||x.screenRecord||x.cameraRecord||x.clear)&&jsxs(Pa,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[x.undo&&jsx("button",{value:"undo",onClick:()=>r(pi()),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"})}),x.redo&&jsx("button",{value:"redo",onClick:()=>r(hi()),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"})}),x.screenRecord&&jsx("button",{value:"screen-record",onClick:kn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6279F8] md:block",title:"Screen Record",children:jsx(Record,{weight:"fill",className:"text-xl"})}),jsx("button",{title:"Pen Color",onClick:()=>K(true),className:"relative mx-4 my-2 flex cursor-pointer items-center justify-center rounded-full border border-[#00000099] bg-white text-xl md:hidden",style:{borderColor:m},children:jsx("div",{className:"h-5 w-5 rounded-full border-2 border-white shadow-sm",style:{backgroundColor:m}})}),jsxs("div",{ref:p,className:"relative md:hidden",children:[jsx("button",{title:"Pen Size",onClick:()=>j(!q),className:`hover:bg-primary/10 cursor-pointer rounded-md px-2 py-2 ${q?"bg-primary/10":""}`,children:jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border-2 border-[#FFFFFF80] bg-[#000000CC]",children:jsx("span",{className:"text-xs font-semibold text-white",children:f})})}),q&&jsxs("div",{className:"absolute top-1/2 left-full z-50 ml-2 w-48 -translate-y-1/2 rounded-lg border bg-white p-4 shadow-xl",children:[jsx("p",{className:"mb-3 text-xs font-semibold text-black/40",children:"PEN SIZE"}),jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"h-2 w-2 shrink-0 rounded-full bg-black"}),jsx(pn,{defaultValue:[12],max:28,min:6,step:1,className:"w-full",value:[f],rangeClassName:"bg-[#8290A133]",thumbClassName:"bg-[#8290A1] border-none h-5 w-5",onValueChange:F=>r(Fr(F[0]))}),jsx("div",{className:"h-5 w-5 shrink-0 rounded-full bg-black"})]})]})]}),x.cameraRecord&&jsx("button",{value:"camera-record",onClick:Mn,className:"hover:bg-primary/10 hidden cursor-pointer rounded-md px-4 py-3 text-[#6BBB93] md:block",title:"Camera Record",children:jsx(Camera,{weight:"fill",className:"text-xl"})}),x.clear&&jsx("button",{value:"clear",onClick:()=>Cn(),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"})})]})]}),jsx("input",{ref:H,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:Et}),jsx("input",{ref:U,type:"file",accept:"video/*",className:"hidden",onChange:oo}),!o&&A&&t&&jsx(dr,{onClose:()=>E(false),stageRef:t,onRecordingComplete:ia}),T&&jsx(Uf,{onClose:()=>V(false),onRecordingComplete:ia}),c&&jsx(zf,{editingFlashcard:d,onConfirm:Hr,onCancel:()=>r(Oa(false))}),se&&jsx(Fs,{defaultColor:m,onConfirm:F=>{r(zo(F)),K(false);},onCancel:()=>K(false)})]})},ww=yw;var Gl=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=ct(mo),r=ct(vi),n=a?r:s,i=ct(tr),m=(ct(b=>b.canvas.slides.find(g=>g.id===b.canvas.currentSlideId))?.videos||[]).some(b=>b.isRecorded&&b.isPlaying),[f,l]=useState(false),[c,p]=useState(null),[v,h]=useState(null),x=async()=>{if(s.length===0){h({type:"error",message:"No slides to publish"});return}if(!e){h({type:"error",message:"No publish handler provided"});return}l(true),h(null);try{let b=await e(n,i,g=>{p(g);});b.success?h({type:"success",message:b.message}):h({type:"error",message:b.message});}catch(b){h({type:"error",message:b instanceof Error?b.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{p(null),h(null);},3e3);}};return m?null:jsxs("button",{onClick:x,disabled:f||s.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 kw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:i=true,editableTitle:d=true,editableDescription:u=true,className:m="",rightContent:f,leftContent:l,includeInactiveSlides:c=false})=>{let p=ot(),v=ct(tr),h=ct(wi),x=e??(h?v.title:"")??"Untitled",b=o??(h?v.description:"")??"Add a description...",[g,L]=useState(false),[C,S]=useState(false),[k,y]=useState(x),[A,E]=useState(b),T=useRef(null),V=useRef(null);useEffect(()=>{y(x);},[x]),useEffect(()=>{E(b);},[b]),useEffect(()=>{g&&T.current&&(T.current.focus(),T.current.select());},[g]),useEffect(()=>{C&&V.current&&(V.current.focus(),V.current.select());},[C]);let z=()=>{d&&L(true);},R=()=>{u&&S(true);},G=()=>{L(false),k.trim()&&k!==x?s?s(k.trim()):p(gi(k.trim())):k.trim()||y(x);},D=()=>{S(false),A.trim()&&A!==b?r?r(A.trim()):p(xi(A.trim())):A.trim()||E(b);},ee=se=>{se.key==="Enter"?G():se.key==="Escape"&&(y(x),L(false));},N=se=>{se.key==="Enter"?D():se.key==="Escape"&&(E(b),S(false));};return jsxs("div",{className:`fixed top-0 left-0 z-40 flex h-[90px] w-full items-center justify-between border-b border-b-gray-200 bg-white px-4 shadow-sm md:px-6 ${m}`,children:[l||jsxs("div",{className:"flex items-center gap-6",children:[i&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[g?jsx("input",{ref:T,type:"text",value:k,onChange:se=>y(se.target.value),onBlur:G,onKeyDown:ee,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:z,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${d?"hover:border-primary cursor-text":""}`,children:k}),C?jsx("input",{ref:V,type:"text",value:A,onChange:se=>E(se.target.value),onBlur:D,onKeyDown:N,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:R,title:A,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:A})]})]}),f||n&&a&&jsx(Gl,{onPublish:a,includeInactiveSlides:c})]})};var Rw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Ew=({colors:e=Rw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),i=te(he),d=te(l=>l.toolbar.penColor),u=te(l=>l.toolbar.strokeWidth),m=i?.backgroundColor,f=xe();return jsx(Fragment,{children:jsx(AnimatePresence,{mode:"wait",initial:false,children:r?jsxs(motion.div,{initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:{type:"tween",duration:.3,ease:[.4,0,.2,1]},className:`fixed bottom-6 left-1/2 z-50 hidden h-fit w-fit -translate-x-1/2 gap-4 rounded-2xl border bg-white p-5 shadow-2xl md:flex 2xl:px-8 2xl:py-6 ${s}`,children:[o&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between 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(pn,{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",value:[u],onValueChange:l=>f(Fr(l[0]))}),jsx("div",{className:"h-7 w-7 rounded-full bg-black lg:h-8 lg:w-8"})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),t&&jsxs(Fragment,{children:[jsxs("div",{className:"flex flex-col items-start justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-sm font-semibold text-[#00000066]",children:"COLOR"}),jsxs(Pa,{type:"single",className:"flex gap-3 px-2 2xl:px-4",children:[e.map(l=>jsx("button",{value:l.value,className:`h-10 w-10 rounded-full border hover:cursor-pointer lg:h-12 lg:w-12 ${d===l.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:l.value},onClick:()=>f(zo(l.value))},l.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:l=>f(zo(l.target.value))}),jsx(Plus,{color:"#00000099"})]})]})]}),jsx("div",{className:"border bg-[#0000001A]"})]}),a&&jsx(Fragment,{children:jsxs("div",{className:"flex flex-col items-center justify-between px-2 2xl:px-4",children:[jsx("p",{className:"mb-4 text-xs font-semibold whitespace-nowrap text-[#00000066] 2xl:text-sm",children:"BG-COLOR"}),jsx("label",{className:"relative flex h-10 w-10 cursor-pointer items-center justify-center rounded-md border text-xl text-[#00000033] lg:h-12 lg:w-12",style:{backgroundColor:m},children:jsx("input",{type:"color",className:"absolute inset-0 cursor-pointer opacity-0",onChange:l=>f(zn(l.target.value))})})]})}),jsx("div",{className:"absolute -top-4 left-1/2 flex flex-col items-center justify-between px-2",children:jsx("button",{onClick:()=>n(false),className:"flex items-center justify-center rounded-full border border-gray-300 bg-white p-2 transition-all hover:bg-gray-100 hover:shadow-md",children:jsx(CaretDown,{size:20,weight:"bold",className:"text-gray-600"})})})]},"toolbar"):jsx(motion.button,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2,delay:.1},onClick:()=>n(true),className:"fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center justify-center rounded-full border bg-white p-2 shadow-2xl transition-all hover:scale-105 hover:shadow-xl","aria-label":"Show Bottom Toolbar",children:jsx(CaretUp,{size:20,weight:"bold",className:"text-gray-600"})},"popup-button")})})};var jf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Fw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),_l=e=>{let o=Fw(e);return o.charAt(0).toUpperCase()+o.slice(1)},wn=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Xf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var $f={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 Jf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...i},d)=>createElement("svg",{ref:d,...$f,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:wn("lucide",s),...!r&&!Xf(i)&&{"aria-hidden":"true"},...i},[...n.map(([u,m])=>createElement(u,m)),...Array.isArray(r)?r:[r]]));var Ln=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(Jf,{ref:r,iconNode:o,className:wn(`lucide-${jf(_l(e))}`,`lucide-${e}`,a),...s}));return t.displayName=_l(e),t};var Vw=[["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"}]],Nr=Ln("copy",Vw);var qw=[["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"}]],Vr=Ln("trash-2",qw);var Qf=({slide:e,index:o,isSelected:t,isSingleSlide:a,onSelect:s,onDuplicate:r,onDelete:n})=>jsxs("div",{className:`group relative cursor-pointer overflow-hidden rounded-lg border-2 transition-all ${t?"border-primary":"border-gray-300 bg-white hover:border-gray-400"}`,onClick:s,children:[jsx("div",{className:"bg-opacity-60 absolute top-2 left-2 z-10 rounded bg-black px-2 py-1 text-xs text-white",children:o+1}),jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[jsx("button",{onClick:i=>{i.stopPropagation(),r();},className:"rounded bg-[#3B75E0] p-1.5 text-white shadow-md transition-colors",title:"Duplicate slide",children:jsx(Nr,{size:14})}),!a&&jsx("button",{onClick:i=>{i.stopPropagation(),n();},className:"rounded bg-red-500 p-1.5 text-white shadow-md transition-colors hover:bg-red-600",title:"Delete slide",children:jsx(Vr,{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 zw=({softDelete:e=false})=>{let o=ot(),t=ct(mo),a=ct(fo),s=ct(yi),[r,n]=useState(true),u=(ct(p=>p.canvas.slides.find(v=>v.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),m=()=>{s&&o(Vn());},f=p=>{o(Un(p));},l=p=>{o(Hn(p));},c=p=>{t.length>1&&o(qn({id:p,softDelete:e}));};return u?null:jsxs("div",{className:"pointer-events-none fixed top-[90px] right-0 bottom-0 z-40 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:[t.length,"/20"]})]})}),jsxs("div",{className:"flex flex-1 flex-col gap-4 overflow-hidden bg-white p-4",children:[jsx("div",{className:"flex-1 space-y-3 overflow-y-auto",children:t.map((p,v)=>jsx(Qf,{slide:p,index:v,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>f(p.id),onDuplicate:()=>l(p.id),onDelete:()=>c(p.id)},p.id))}),jsxs("button",{onClick:m,disabled:!s,className:`flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors ${s?"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 Gw="SchooplaEditorDB",Kw=1,Da="slides",Ra="metadata",jl="schoopla_current_slide_id",am="presentation_metadata",qr=()=>new Promise((e,o)=>{let t=indexedDB.open(Gw,Kw);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Da)||s.createObjectStore(Da,{keyPath:"id"}),s.objectStoreNames.contains(Ra)||s.createObjectStore(Ra,{keyPath:"id"});};}),Xl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await qr(),a=o.transaction([Da],"readwrite").objectStore(Da);await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);});for(let s of e)await new Promise((r,n)=>{let i=a.add(s);i.onsuccess=()=>r(!0),i.onerror=()=>n(i.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},$l=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await qr(),t=e.transaction([Da],"readonly").objectStore(Da);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result;console.log("\u2705 Loaded from IndexedDB:",n.length,"slides"),n.length>0&&n[0].images&&console.log("First slide images:",n[0].images.map(i=>({id:i.id,width:i.width,height:i.height,x:i.x,y:i.y}))),a(n.length>0?n:null);},r.onerror=()=>{e.close(),s(r.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}}},Sn=async()=>{try{let e=await qr(),o=e.transaction([Da,Ra],"readwrite"),t=o.objectStore(Da),a=o.objectStore(Ra);await new Promise((s,r)=>{let n=t.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),await new Promise((s,r)=>{let n=a.clear();n.onsuccess=()=>s(!0),n.onerror=()=>r(n.error);}),e.close(),localStorage.removeItem("schoopla_slides_backup"),localStorage.removeItem(jl),localStorage.removeItem("schoopla_presentation_metadata"),await hf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Yl=e=>{try{localStorage.setItem(jl,e);}catch(o){console.error("Error saving current slide ID:",o);}},Jl=()=>{try{return localStorage.getItem(jl)}catch(e){return console.error("Error loading current slide ID:",e),null}},Zl=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},Ql=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await qr(),a=o.transaction([Ra],"readwrite").objectStore(Ra);await new Promise((s,r)=>{let n=a.put({id:am,...e});n.onsuccess=()=>s(!0),n.onerror=()=>r(n.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);}}},ed=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await qr(),t=e.transaction([Ra],"readonly").objectStore(Ra);return new Promise((a,s)=>{let r=t.get(am);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:i,...d}=n;console.log("\u2705 Loaded presentation metadata:",d),a(d);}else console.log("No presentation metadata found"),a(null);},r.onerror=()=>{e.close(),s(r.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 _w=["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","canvas/updateSlideThumbnail"],jw=["canvas/clearCanvas"],Xw=["canvas/setPresentationTitle","canvas/setPresentationDescription"],$w=Zl((e,o)=>{Xl(e),Yl(o);},500),Yw=Zl(e=>{Ql(e);},500),Jw=(e,o)=>{Xl(e),Yl(o);},td=false,om=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let s=t.payload;Al(s).catch(r=>{console.error("Error deleting video blob:",r);});}if(t.type==="canvas/deleteSlide"&&t.payload){let s=t.payload,n=e.getState().canvas.slides.find(i=>i.id===s);n&&n.videos&&n.videos.length>0&&n.videos.forEach(i=>{Al(i.id).catch(d=>{console.error("Error deleting video blob:",d);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let s=t.payload,r=e.getState(),i=r.canvas.slides.find(d=>d.id===r.canvas.currentSlideId)?.videos.find(d=>d.id===s);i&&i.videoBlob&&setTimeout(()=>{let d=e.getState(),m=d.canvas.slides.find(f=>f.id===d.canvas.currentSlideId)?.videos.find(f=>f.id!==s&&f.x===i.x+20&&f.y===i.y+20);m&&i.videoBlob&&Ja(m.id,i.videoBlob,m.thumbnailDataUrl).catch(f=>{console.error("Error saving duplicated video blob:",f);});},0);}let a=o(t);if(t.type&&jw.includes(t.type)){if(!td){td=true;try{let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;Jw(r,n);}finally{setTimeout(()=>{td=false;},0);}}}else if(t.type&&_w.includes(t.type)){let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;$w(r,n);}else if(t.type&&Xw.includes(t.type)){let s=e.getState(),{presentationMetadata:r}=s.canvas;Yw(r);}return a});new QueryClient;var eL=configureStore({reducer:{toolbar:Hf,canvas:bd},middleware:e=>e({serializableCheck:false}).concat(om)});var tL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2,fileName:r=`slide-${Date.now()}`}=o;try{let n=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),d=document.createElement("a");d.download=`${r}.${t}`,d.href=i,document.body.appendChild(d),d.click(),document.body.removeChild(d);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},aL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let i=t==="png"?"image/png":"image/jpeg",d=e.toDataURL({mimeType:i,quality:a,pixelRatio:s});fetch(d).then(u=>u.blob()).then(u=>r(u)).catch(u=>n(u));}catch(i){n(i);}})},oL=(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o,r=t==="png"?"image/png":"image/jpeg";return e.toDataURL({mimeType:r,quality:a,pixelRatio:s})};var rL=(e,o,t)=>{let a=t.x-o.x,s=t.y-o.y;if(a===0&&s===0)return Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2));let r=a*a+s*s,n=Math.max(0,Math.min(1,((e.x-o.x)*a+(e.y-o.y)*s)/r)),i=o.x+n*a,d=o.y+n*s;return Math.sqrt(Math.pow(e.x-i,2)+Math.pow(e.y-d,2))},ad=(e,o)=>{if(e.length<=2)return e;let t=0,a=0,s=e[0],r=e[e.length-1];for(let n=1;n<e.length-1;n++){let i=rL(e[n],s,r);i>t&&(t=i,a=n);}if(t>o){let n=ad(e.slice(0,a+1),o),i=ad(e.slice(a),o);return [...n.slice(0,-1),...i]}return [s,r]},sL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},nL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},rm=(e,o=1.5)=>{if(e.length<=4)return e;let t=sL(e),a=ad(t,o);return nL(a)},sm=(e,o=1.5)=>({...e,points:rm(e.points,o)}),iL=(e,o=1.5)=>e.map(t=>sm(t,o)),lL=(e,o)=>{let t=e.length/2,a=o.length/2,s=((1-a/t)*100).toFixed(1);return {originalPoints:t,simplifiedPoints:a,reduction:`${s}%`}};var dL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var nm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{let i=new Image;i.onload=()=>{let{width:d,height:u}=i;if(d>t||u>a){let p=d/u;d>u?(d=Math.min(d,t),u=d/p):(u=Math.min(u,a),d=u*p);}let m=document.createElement("canvas");m.width=d,m.height=u;let f=m.getContext("2d");if(!f){n(new Error("Failed to get canvas context"));return}f.drawImage(i,0,0,d,u);let l=dL(e),c=m.toDataURL(l,s);r(c);},i.onerror=n,i.src=e;})};var ao=e=>{let o=e.split(",")[1],t=atob(o),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer},Go=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Ko=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",uL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],i=0;for(let d of e){let u=[],m=[],f=[];for(let l of d.images){let c=l.src;if(t&&c.startsWith("data:"))try{c=await nm(c,{maxWidth:a,maxHeight:s,quality:r});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(c.startsWith("data:")){let p=ao(c),v=Go(c);i+=p.byteLength;let h={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,buffer:p,mimeType:v};if(l.audioData&&l.audioData.startsWith("data:")){let x=ao(l.audioData),b=Go(l.audioData);i+=x.byteLength,h.audioBuffer=x,h.audioMimeType=b;}u.push(h);}}for(let l of d.videos){let c,p;if(l.videoBlob)c=await l.videoBlob.arrayBuffer(),p=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))c=ao(l.videoData),p=Go(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}i+=c.byteLength;let v={id:l.id,thumbnailDataUrl:l.thumbnailDataUrl,x:l.x,y:l.y,width:l.width,height:l.height,draggable:l.draggable,isPlaying:l.isPlaying,rotation:l.rotation,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isRecorded:l.isRecorded,buffer:c,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let h=ao(l.audioData),x=Go(l.audioData);i+=h.byteLength,v.audioBuffer=h,v.audioMimeType=x;}m.push(v);}for(let l of d.photoFrames){let c={id:l.id,x:l.x,y:l.y,width:l.width,height:l.height,rotation:l.rotation,draggable:l.draggable,locked:l.locked,link:l.link,altText:l.altText,zIndex:l.zIndex,isCapturing:l.isCapturing};if(l.capturedImageUrl&&l.capturedImageUrl.startsWith("data:")){let p=ao(l.capturedImageUrl),v=Go(l.capturedImageUrl);i+=p.byteLength,c.buffer=p,c.mimeType=v;}if(l.audioData&&l.audioData.startsWith("data:")){let p=ao(l.audioData),v=Go(l.audioData);i+=p.byteLength,c.audioBuffer=p,c.audioMimeType=v;}f.push(c);}n.push({...d,images:u,videos:m,photoFrames:f});}return {slides:n,totalSize:i}},cL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},fL=e=>{let o=new FormData,t=e.slides.map((a,s)=>({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((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,mimeType:r.mimeType,fileKey:`slide_${s}_image_${n}`,audioFileKey:r.audioBuffer?`slide_${s}_image_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),videos:a.videos.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,draggable:r.draggable,isPlaying:r.isPlaying,rotation:r.rotation,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isRecorded:r.isRecorded,mimeType:r.mimeType,fileKey:`slide_${s}_video_${n}`,thumbnailFileKey:`slide_${s}_video_${n}_thumbnail`,audioFileKey:r.audioBuffer?`slide_${s}_video_${n}_audio`:void 0,audioMimeType:r.audioMimeType})),photoFrames:a.photoFrames.map((r,n)=>({id:r.id,x:r.x,y:r.y,width:r.width,height:r.height,rotation:r.rotation,draggable:r.draggable,locked:r.locked,link:r.link,altText:r.altText,zIndex:r.zIndex,isCapturing:r.isCapturing,mimeType:r.mimeType,fileKey:r.buffer?`slide_${s}_photoframe_${n}`:void 0,audioFileKey:r.audioBuffer?`slide_${s}_photoframe_${n}_audio`:void 0,audioMimeType:r.audioMimeType}))}));return o.append("metadata",JSON.stringify({slides:t,totalSize:e.totalSize,timestamp:Date.now()})),e.slides.forEach((a,s)=>{a.images.forEach((r,n)=>{let i=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,i,d),r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,u,m);}}),a.videos.forEach((r,n)=>{let i=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,i,d),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let u=ao(r.thumbnailDataUrl),m=new Blob([u],{type:"image/jpeg"}),f=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,m,f);}if(r.audioBuffer&&r.audioMimeType){let u=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,u,m);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let i=new Blob([r.buffer],{type:r.mimeType}),d=`${r.id}.${Ko(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,i,d);}if(r.audioBuffer&&r.audioMimeType){let i=new Blob([r.audioBuffer],{type:r.audioMimeType}),d=`${r.id}_audio.${Ko(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,i,d);}});}),o};var hL=()=>{let e=ot(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await $l(),r=Jl(),n=await ed();if(s&&s.length>0){let i=await pf(),d=s.map(m=>{if(m.videos&&m.videos.length>0){let f=m.videos.map(l=>{let c=i.get(l.id);if(c){let p=gf(c.blob);return {...l,objectUrl:p,thumbnailDataUrl:c.thumbnailDataUrl,videoBlob:c.blob}}else return l});return {...m,videos:f}}return m}),u=r&&d.find(m=>m.id===r)?r:d[0].id;e(io({slides:d,currentSlideId:u}));}e(n?bi({title:n.title,description:n.description}):ks(!0));}catch(s){console.error("Error loading persisted slides:",s),e(ks(true));}finally{t(false);}})();},[e]),{isLoading:o}};var lm=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||""})),dm=new WeakSet,um=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 Ja(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},gL=()=>{let e=ot(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||dm.has(a))return;dm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(u){console.error("Error clearing local data:",u);}let i=r&&s.find(u=>u.id===r)?r:s[0].id,d=lm(s);e(io({slides:d,currentSlideId:i})),await um(d);},[e]),t=useCallback(async a=>{if(!a.slides||a.slides.length===0)return;let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await Sn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(u){console.error("Error clearing local data:",u);}let i=r&&s.find(u=>u.id===r)?r:s[0].id,d=lm(s);e(io({slides:d,currentSlideId:i})),await um(d);},[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{Ky as BASIC_EDITOR_TOOLBAR_CONFIG,Rw as BottomToolbar,Rb as Canvas,zy as DEFAULT_CONTEXT_MENU_CONFIG,xn as DEFAULT_TOOLBAR_CONFIG,Yh as EditorRoot,Gl as PublishButton,dr as ScreenRecorder,Ww as SlideNavigation,yw as Toolbar,Cw as TopNavBar,Gy as VIEWER_TOOLBAR_CONFIG,ni as addFillInTheBlanks,Xn as addFlashcard,Kn as addImage,Qn as addImageAnnotation,Gn as addLine,si as addLongAnswer,ai as addMultipleChoice,Jn as addPhotoFrame,ti as addPhotoFrameAnnotation,_n as addShape,ri as addShortAnswer,Vn as addSlide,jn as addText,oi as addTrueFalse,Qr as addVideo,uL as arrayBufferToBase64,li as bringToFront,mi as clearCanvas,zm as clearImageAnnotations,Sn as clearLocalData,Km as clearPhotoFrameAnnotations,Nn as createEmptySlide,vs as deleteFillInTheBlanks,is as deleteFlashcard,Jr as deleteImage,Cs as deleteLineById,xs as deleteLongAnswer,cs as deleteMultipleChoice,ds as deletePhotoFrame,rs as deleteShape,hs as deleteShortAnswer,qn as deleteSlide,ss as deleteText,ms as deleteTrueFalse,ts as deleteVideo,ys as duplicateFillInTheBlanks,ls as duplicateFlashcard,Zr as duplicateImage,fi as duplicateLine,bs as duplicateLongAnswer,fs as duplicateMultipleChoice,us as duplicatePhotoFrame,os as duplicateShape,gs as duplicateShortAnswer,Hn as duplicateSlide,ns as duplicateText,ps as duplicateTrueFalse,as as duplicateVideo,Xo as editFlashcard,_m as editMultipleChoice,tL as exportSlideAsBlob,eL as exportSlideAsImage,ci as finalizeDrawing,iL as getCompressionStats,aL as getSlideDataURL,Jl as loadCurrentSlideId,$l as loadFromIndexedDB,bi as loadPresentationMetadata,ed as loadPresentationMetadataFromDB,io as loadSlides,ql as mergeToolbarConfig,$n as nextFlashcard,cL as prepareFormData,dL as prepareSlidesForPublishing,Yn as previousFlashcard,hi as redo,Yr as removeLine,Um as reorderSlides,Ql as savePresentationMetadata,ce as saveToHistory,mo as selectAllSlides,vi as selectAllSlidesIncludingInactive,yi as selectCanAddSlide,he as selectCurrentSlide,fo as selectCurrentSlideId,wi as selectMetadataLoaded,tr as selectPresentationMetadata,Jm as selectSlideById,di as sendToBack,ii as setActivityType,Ls as setAltText,Ss as setAudioData,zn as setBackgroundColor,Un as setCurrentSlide,Zo as setEditingActivity,er as setEditingTextId,Xm as setLines,ws as setLink,ks as setMetadataLoaded,zo as setPenColor,xi as setPresentationDescription,gi as setPresentationTitle,Oa as setShowFlashcardForm,ma as setShowMcqForm,ft as setSketchMode,Fr as setStrokeWidth,zt as setTool,om as simplifyFlatPoints,rm as simplifyLine,nL as simplifyLines,Qw as store,Zn as toggleImageDrawingMode,ui as toggleLock,ei as togglePhotoFrameDrawingMode,Ym as toggleSketchMode,jo as toggleVideoPlaying,pi as undo,Qo as updateElementOrder,Jo as updateFillInTheBlanks,co as updateFlashcard,lo as updateImage,Wm as updateImageAnnotation,jm as updateLastLine,$m as updateLinePosition,Is as updateLineTransform,Yo as updateLongAnswer,ca as updateMultipleChoice,Ba as updatePhotoFrame,Gm as updatePhotoFrameAnnotation,uo as updateShape,$o as updateShortAnswer,Wn as updateSlideThumbnail,It as updateText,fa as updateTrueFalse,es as updateVideo,xe as useDispatch,hL as useInitialSlides,Wi as useModalPortal,Q as useSelector,pL as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
+ */export{_y as BASIC_EDITOR_TOOLBAR_CONFIG,Ew as BottomToolbar,Eb as Canvas,Gy as DEFAULT_CONTEXT_MENU_CONFIG,xn as DEFAULT_TOOLBAR_CONFIG,Jh as EditorRoot,Gl as PublishButton,dr as ScreenRecorder,zw as SlideNavigation,ww as Toolbar,kw as TopNavBar,Ky as VIEWER_TOOLBAR_CONFIG,ni as addFillInTheBlanks,Xn as addFlashcard,Kn as addImage,Qn as addImageAnnotation,Gn as addLine,si as addLongAnswer,ai as addMultipleChoice,Jn as addPhotoFrame,ti as addPhotoFrameAnnotation,_n as addShape,ri as addShortAnswer,Vn as addSlide,jn as addText,oi as addTrueFalse,Qr as addVideo,cL as arrayBufferToBase64,li as bringToFront,mi as clearCanvas,Gm as clearImageAnnotations,Sn as clearLocalData,_m as clearPhotoFrameAnnotations,Nn as createEmptySlide,vs as deleteFillInTheBlanks,is as deleteFlashcard,Jr as deleteImage,Cs as deleteLineById,xs as deleteLongAnswer,cs as deleteMultipleChoice,ds as deletePhotoFrame,rs as deleteShape,hs as deleteShortAnswer,qn as deleteSlide,ss as deleteText,ms as deleteTrueFalse,ts as deleteVideo,ys as duplicateFillInTheBlanks,ls as duplicateFlashcard,Zr as duplicateImage,fi as duplicateLine,bs as duplicateLongAnswer,fs as duplicateMultipleChoice,us as duplicatePhotoFrame,os as duplicateShape,gs as duplicateShortAnswer,Hn as duplicateSlide,ns as duplicateText,ps as duplicateTrueFalse,as as duplicateVideo,Xo as editFlashcard,jm as editMultipleChoice,aL as exportSlideAsBlob,tL as exportSlideAsImage,ci as finalizeDrawing,lL as getCompressionStats,oL as getSlideDataURL,Jl as loadCurrentSlideId,$l as loadFromIndexedDB,bi as loadPresentationMetadata,ed as loadPresentationMetadataFromDB,io as loadSlides,ql as mergeToolbarConfig,$n as nextFlashcard,fL as prepareFormData,uL as prepareSlidesForPublishing,Yn as previousFlashcard,hi as redo,Yr as removeLine,Wm as reorderSlides,Ql as savePresentationMetadata,ce as saveToHistory,mo as selectAllSlides,vi as selectAllSlidesIncludingInactive,yi as selectCanAddSlide,he as selectCurrentSlide,fo as selectCurrentSlideId,wi as selectMetadataLoaded,tr as selectPresentationMetadata,Zm as selectSlideById,di as sendToBack,ii as setActivityType,Ls as setAltText,Ss as setAudioData,zn as setBackgroundColor,Un as setCurrentSlide,Zo as setEditingActivity,er as setEditingTextId,$m as setLines,ws as setLink,ks as setMetadataLoaded,zo as setPenColor,xi as setPresentationDescription,gi as setPresentationTitle,Oa as setShowFlashcardForm,ma as setShowMcqForm,ft as setSketchMode,Fr as setStrokeWidth,zt as setTool,rm as simplifyFlatPoints,sm as simplifyLine,iL as simplifyLines,eL as store,Zn as toggleImageDrawingMode,ui as toggleLock,ei as togglePhotoFrameDrawingMode,Jm as toggleSketchMode,jo as toggleVideoPlaying,pi as undo,Qo as updateElementOrder,Jo as updateFillInTheBlanks,co as updateFlashcard,lo as updateImage,zm as updateImageAnnotation,Xm as updateLastLine,Ym as updateLinePosition,Is as updateLineTransform,Yo as updateLongAnswer,ca as updateMultipleChoice,Ba as updatePhotoFrame,Km as updatePhotoFrameAnnotation,uo as updateShape,$o as updateShortAnswer,Wn as updateSlideThumbnail,It as updateText,fa as updateTrueFalse,es as updateVideo,xe as useDispatch,gL as useInitialSlides,Wi as useModalPortal,te as useSelector,hL as useSlidesPersistence};//# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map