@turnix-co/konva-editor 3.0.30 → 3.0.32

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 {createPortal}from'react-dom';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';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 {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import Cd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {EyeIcon,Stack as Stack$1,X as X$2,DotsSixVertical,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import ku 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 hd=e=>{throw TypeError(e)};var gd=(e,o,t)=>o.has(e)||hd("Cannot "+t);var K=(e,o,t)=>(gd(e,o,"read from private field"),t?t.call(e):o.get(e)),De=(e,o,t)=>o.has(e)?hd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),ke=(e,o,t,a)=>(gd(e,o,"write to private field"),o.set(e,t),t);var xd=(e,o,t,a)=>({set _(s){ke(e,o,s);},get _(){return K(e,o,a)}});var xe=()=>useDispatch(),ee=e=>useSelector(e),it=xe,et=ee;var Nn=20,qn=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}),On=qn("Slide 1"),Xm={slides:[On],currentSlideId:On.id,history:{[On.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false},bd=createSlice({name:"canvas",initialState:Xm,reducers:{addSlide:e=>{if(e.slides.length>=Nn)return;let o=qn(`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(c=>c.isActive).length<=1)return;let r=e.slides.findIndex(c=>c.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 c=e.slides.filter(i=>i.isActive);c.length>0&&(e.currentSlideId=c[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=Nn)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);},setViewerMode:(e,o)=>{e.viewerMode=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(x=>x.id===a);n&&(n.timestamp=r);break;case "video":let c=t.videos.find(x=>x.id===a);c&&(c.timestamp=r);break;case "shape":let i=t.shapes.find(x=>x.id===a);i&&(i.timestamp=r);break;case "text":let d=t.texts.find(x=>x.id===a);d&&(d.timestamp=r);break;case "flashcard":let m=t.flashcards.find(x=>x.id===a);m&&(m.timestamp=r);break;case "photoFrame":let f=t.photoFrames.find(x=>x.id===a);f&&(f.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(x=>x.id===a);l&&(l.timestamp=r);break;case "trueFalse":let u=t.trueFalses.find(x=>x.id===a);u&&(u.timestamp=r);break;case "shortAnswer":let p=t.shortAnswers.find(x=>x.id===a);p&&(p.timestamp=r);break;case "longAnswer":let v=t.LongAnswer.find(x=>x.id===a);v&&(v.timestamp=r);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(x=>x.id===a);h&&(h.timestamp=r);break;case "line":let g=t.lines.find(x=>x.id===a);g&&(g.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(c=>c.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,c=(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(i=>i.id===a);c&&(c.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,c=(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);c&&(c.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,c=(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);c&&(c.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:Hn,deleteSlide:Un,duplicateSlide:zn,setCurrentSlide:Wn,setViewerMode:$m,updateSlideThumbnail:Gn,setBackgroundColor:Kn,reorderSlides:Ym,loadSlides:no,addLine:_n,removeLine:Zr,addImage:jn,updateImage:io,deleteImage:Qr,duplicateImage:es,addVideo:ts,updateVideo:as,deleteVideo:os,duplicateVideo:rs,toggleVideoPlaying:Oa,addShape:Xn,updateShape:lo,duplicateShape:ss,deleteShape:ns,addText:$n,updateText:Tt,deleteText:is,duplicateText:ls,addFlashcard:Yn,updateFlashcard:uo,deleteFlashcard:ds,duplicateFlashcard:us,editFlashcard:Xo,nextFlashcard:Jn,previousFlashcard:Zn,addPhotoFrame:Qn,updatePhotoFrame:Na,deletePhotoFrame:cs,duplicatePhotoFrame:fs,toggleImageDrawingMode:ei,addImageAnnotation:ti,updateImageAnnotation:Jm,clearImageAnnotations:Zm,togglePhotoFrameDrawingMode:ai,addPhotoFrameAnnotation:oi,updatePhotoFrameAnnotation:Qm,clearPhotoFrameAnnotations:ep,addMultipleChoice:ri,updateMultipleChoice:fa,editMultipleChoice:tp,deleteMultipleChoice:ms,duplicateMultipleChoice:ps,addTrueFalse:si,updateTrueFalse:ma,deleteTrueFalse:hs,duplicateTrueFalse:gs,addShortAnswer:ni,updateShortAnswer:$o,deleteShortAnswer:xs,duplicateShortAnswer:bs,addLongAnswer:ii,updateLongAnswer:Yo,deleteLongAnswer:vs,duplicateLongAnswer:ys,addFillInTheBlanks:li,updateFillInTheBlanks:Jo,deleteFillInTheBlanks:ws,duplicateFillInTheBlanks:Ls,setShowMcqForm:pa,setShowFlashcardForm:Va,setActivityType:di,setEditingActivity:Zo,bringToFront:ui,sendToBack:ci,toggleLock:fi,setLink:Ss,setAltText:Is,setAudioData:Cs,updateLastLine:ap,finalizeDrawing:mi,setLines:op,updateLinePosition:rp,updateLineTransform:ks,deleteLineById:Ms,duplicateLine:pi,updateElementOrder:Qo,clearCanvas:hi,undo:gi,redo:xi,saveToHistory:ce,toggleSketchMode:sp,setSketchMode:pt,setEditingTextId:er,setPresentationTitle:bi,setPresentationDescription:vi,loadPresentationMetadata:yi,setMetadataLoaded:Ts}=bd.actions;var vd=e=>e.canvas.slides,co=e=>e.canvas.currentSlideId,ge=createSelector([vd,co],(e,o)=>e.find(t=>t.id===o)),fo=createSelector([vd],e=>e.filter(o=>o.isActive!==false)),wi=e=>e.canvas.slides,Li=createSelector([fo],e=>e.length<Nn),np=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,Si=e=>e.canvas.metadataLoaded,As=e=>e.canvas.viewerMode,yd=bd.reducer;var Ld=e=>{let o=xe(),t=useRef(null),a=useRef(false),s=ee(u=>u.toolbar.selectedTool),r=ee(u=>u.toolbar.penColor),n=ee(u=>u.toolbar.strokeWidth),c=ee(u=>u.canvas.isSketchMode),i=ee(u=>u.canvas.slides.find(v=>v.id===u.canvas.currentSlideId)?.lines||[]),d=useCallback(u=>{t.current=u;},[]),m=useCallback(u=>{s==="pen"&&t.current&&(o(ce()),t.current.startDrawing(u),a.current=true);},[s,o]),f=useCallback(u=>{!t.current||!a.current||t.current.draw(u);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let u=t.current.stopDrawing();a.current=false,u&&u.points.length>=4&&o(_n(u)),o(mi()),e?.();},[o,e]);return {lines:i,tool:s,color:r,strokeWidth:n,isSketchMode:c,setCanvasRef:d,startDrawing:m,draw:f,stopDrawing:l}};var kd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:s,isSketchMode:r,style:n,xOffset:c=0,yOffset:i=0},d)=>{let m=useRef(null),f=useRef(false),l=useRef([]),u=useRef([]),p=useRef(null),v=useRef(t),h=useRef(a),g=useRef(s),x=useRef(r),w=useRef(c),b=useRef(i);useEffect(()=>{v.current=t,h.current=a,g.current=s,x.current=r,w.current=c,b.current=i;},[t,a,s,r,c,i]);let C=useCallback(()=>{let k=m.current;if(!k)return;let y=k.getContext("2d");y&&y.clearRect(0,0,k.width,k.height);},[]),M=useCallback(()=>{let k=m.current,y=u.current;if(!k||y.length<1)return;let S=k.getContext("2d");if(!S)return;if(S.clearRect(0,0,k.width,k.height),v.current==="eraser"?(S.globalCompositeOperation="destination-out",S.fillStyle="rgba(0,0,0,1)"):(S.globalCompositeOperation="source-over",S.fillStyle=h.current),y.length===1){S.beginPath(),S.arc(y[0].x,y[0].y,g.current/2,0,Math.PI*2),S.fill();return}let A=Cd(y,{size:g.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:R=>R,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(A.length<2)){S.beginPath(),S.moveTo(A[0][0],A[0][1]);for(let R=1;R<A.length;R++)S.lineTo(A[R][0],A[R][1]);S.closePath(),S.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:k=>{f.current=true;let y={x:k.x-w.current,y:k.y-b.current};l.current=[{x:k.x,y:k.y}],u.current=[y],p.current=k,M();},draw:k=>{if(!f.current||!p.current)return;let y=k.x-p.current.x,S=k.y-p.current.y;if(Math.sqrt(y*y+S*S)<2)return;let A={x:k.x-w.current,y:k.y-b.current};l.current.push({x:k.x,y:k.y}),u.current.push(A),p.current=k,M();},stopDrawing:()=>{if(!f.current)return null;if(f.current=false,l.current.length<2)return l.current=[],u.current=[],p.current=null,C(),null;let y=Cd(l.current,{size:g.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]]),S={tool:v.current,points:y,color:h.current,strokeWidth:g.current,isSketch:true};return l.current=[],u.current=[],p.current=null,C(),S},clear:()=>{C(),l.current=[],u.current=[],p.current=null,f.current=false;},isDrawing:()=>f.current,getCanvasElement:()=>m.current}),[C,M]),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}})});kd.displayName="DirectDrawingCanvas";var Md=kd;var Ad=e=>{let o=xe(),a=ee(ge)?.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 c=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},[]),i=useCallback((m,f)=>{let l=m.target,u=l.id();a.find(v=>v.id===u)&&(o(io({id:u,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),f?.());},[a,o]),d=useCallback((m,f)=>{let l=f.target,u=s.current.get(m);if(!u){console.error("\u274C Image node not found for id:",m);return}let p=l.scaleX(),v=l.scaleY(),h=l.rotation(),g=u.width(),x=u.height(),w=Math.max(5,g*p),b=Math.max(5,x*v);l.scaleX(1),l.scaleY(1),u.width(w),u.height(b),o(io({id:m,width:w,height:b,x:l.x(),y:l.y(),rotation:h})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:c,imageRefs:s,handleDragEnd:i,handleImageTransformEnd:d}};var Pd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),s=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((c,i)=>{let d=i.target,m=d.scaleX(),f=d.scaleY(),l=d.rotation(),u=Math.max(5,d.width()*m),p=Math.max(5,d.height()*f);d.scaleX(1),d.scaleY(1),d.width(u),d.height(p),o(fa({id:c,width:u,height:p,x:d.x(),y:d.y(),rotation:l})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:s,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(c,i)=>{o(fa({id:i,x:c.target.x(),y:c.target.y()})),e?.();}}};var Dd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),s=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((c,i)=>{let d=i.target,m=d.scaleX(),f=d.scaleY(),l=d.rotation(),u=Math.max(5,d.width()*m),p=Math.max(5,d.height()*f);d.scaleX(1),d.scaleY(1),d.width(u),d.height(p),o(ma({id:c,width:u,height:p,x:d.x(),y:d.y(),rotation:l})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:s,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(c,i)=>{o(ma({id:i,x:c.target.x(),y:c.target.y()})),e?.();},trueFalseRefs:a}};var Rd=e=>{let o=xe(),a=ee(ge)?.videos||[],s=useRef(new Map),r=useCallback(i=>{o(Oa(i));},[o]),n=useCallback((i,d)=>{let m=d.target;o(as({id:i,x:m.x(),y:m.y()})),e?.();},[o,e]),c=useCallback((i,d)=>{let m=d.target,f=m.scaleX(),l=m.scaleY(),u=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(as({id:i,width:p,height:v,x:m.x(),y:m.y(),rotation:u})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:s,handleVideoClick:r,handleVideoDragEnd:n,handleVideoTransformEnd:c}};var Bd=e=>{let o=xe(),a=ee(ge)?.shapes||[],s=useRef(new Map),r=useRef(new Map),[n,c]=useState(false),i=useCallback((m,f)=>{let l=f.target;o(lo({id:m,x:l.x(),y:l.y()})),e?.();},[o,e]),d=useCallback((m,f)=>{let l=f.target,u=a.find(w=>w.id===m);if(!u)return;let p=l.scaleX(),v=l.scaleY(),h=u.type?.toLowerCase();h==="arrow"||h==="line"||(l.scaleX(1),l.scaleY(1));let x={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":x.radius=l.width()*p/2;break;case "star":x.innerRadius=l.width()*p/4,x.outerRadius=l.width()*p/2;break;case "triangle":x.radius=l.width()*p/2;break;case "ellipse":x.radiusX=l.width()*p/2,x.radiusY=l.height()*v/2;break;case "polygon":x.radius=l.width()*p/2;break;case "ring":let w=p;x.innerRadius=u.innerRadius&&u.innerRadius*w,x.outerRadius=u.outerRadius&&u.outerRadius*w;break;case "wedge":x.radius=u.radius&&u.radius*p;break;case "arc":x.innerRadius=u.innerRadius&&u.innerRadius*p,x.outerRadius=u.outerRadius&&u.outerRadius*p;break;case "arrow":case "line":{x.scaleX=p,x.scaleY=v,delete x.width,delete x.height;break}}o(lo(x)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:s,isDragging:n,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:d}};var Nd=(e,o)=>{let t=it(),s=ee(ge)?.texts||[],r=useRef(new Map),[n,c]=useState(null),[i,d]=useState("");return {texts:s,textRefs:r,handleDragEnd:(h,g)=>{let x=h.target;t(ce()),t(Tt({id:g,x:x.x(),y:x.y()})),e();},handleTransformEnd:h=>{let g=r.current.get(h);if(!g)return;let x=g.scaleX(),w=g.scaleY(),b=s.find(M=>M.id===h);if(!b)return;let C=(x+w)/2;g.scaleX(1),g.scaleY(1),t(ce()),t(Tt({id:h,x:g.x(),y:g.y(),width:Math.max(5,(b.width||100)*x),height:Math.max(5,(b.height||50)*w),fontSize:Math.round(Math.max(8,b.fontSize*C)),rotation:g.rotation()})),e();},handleDoubleClick:h=>{let g=s.find(x=>x.id===h);g&&!g.locked&&(c(h),d(g.text));},startEditing:h=>{let g=s.find(x=>x.id===h);g&&!g.locked&&(c(h),d(g.text));},editingTextId:n,editingValue:i,handleEditingChange:h=>{d(h);},finishEditing:()=>{if(n){let h=r.current.get(n),g=s.find(w=>w.id===n);t(ce());let x={id:n,text:i};if(g&&(g.fontWeight!==void 0&&(x.fontWeight=g.fontWeight),g.fontStyle!==void 0&&(x.fontStyle=g.fontStyle),g.textDecoration!==void 0&&(x.textDecoration=g.textDecoration)),o?.current&&i.trim()){let w=o.current,b=w.offsetWidth,C=w.offsetHeight,M=1;if(h){let _=h.getStage();_&&(M=_.scaleX());}let k=14,y=(b-k)/M,S=(C-k)/M,B=i.split(`
3
- `).length,R=s.find(_=>_.id===n)?.fontSize||24,E=B*R*1.2+10;x.width=Math.max(200,y),x.height=Math.max(50,S,E);}else if(h&&i.trim()){let w=h.text(),b=h.width();h.text(i),h.width(void 0);let C=h.width(),M=h.height();h.text(w),h.width(b),x.width=Math.max(200,C+20),x.height=Math.max(50,M+20);}t(Tt(x)),c(null),d(""),t(er(null)),e();}}}};var Vd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,c)=>{let i=n.target;o($o({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var qd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let c=r.target;o(Yo({id:n,x:c.x(),y:c.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var Ud=e=>{let o=xe(),a=ee(ge)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((f,l)=>{if(r.current.has(l))return r.current.get(l);let u=new window.Image;return u.src=f,r.current.set(l,u),u},[]),c=useCallback((f,l)=>{let u=f.target,p=u.id();a.find(h=>h.id===p)&&(o(uo({id:p,x:u.x(),y:u.y()})),l?.());},[a,o]),i=useCallback((f,l)=>{let u=l.target,p=u.scaleX(),v=u.scaleY(),h=u.rotation(),g=Math.max(50,u.width()*p),x=Math.max(50,u.height()*v);u.scaleX(1),u.scaleY(1),u.width(g),u.height(x),o(uo({id:f,width:g,height:x,x:u.x(),y:u.y(),rotation:h})),u.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(f=>{o(Jn(f)),e?.();},[o,e]),m=useCallback(f=>{o(Zn(f)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:c,handleFlashcardTransformEnd:i,handleNext:d,handlePrevious:m}};var Gd=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),c=useCallback((u,p)=>{console.log("handleDragEnd"),o(Na({id:p,x:u.target.x(),y:u.target.y()})),e?.();},[o,e]),i=useCallback((u,p)=>{let v=p.target,h=v.scaleX(),g=v.scaleY(),x=v.rotation(),w=a.find(M=>M.id===u);if(!w)return;let b=Math.max(100,w.width*h),C=Math.max(100,w.height*g);v.scaleX(1),v.scaleY(1),o(Na({id:u,width:b,height:C,x:v.x(),y:v.y(),rotation:x})),v.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async u=>{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(u,p),h}),o(Na({id:u,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),m=useCallback(u=>{let p=r.get(u);p&&(p.getTracks().forEach(v=>v.stop()),n(v=>{let h=new Map(v);return h.delete(u),h}),o(Na({id:u,isCapturing:false})),e?.());},[r,o,e]),f=useCallback((u,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 g=v.toDataURL("image/jpeg",.8);return o(Na({id:u,capturedImageUrl:g,isCapturing:false})),m(u),e?.(),g}return null},[o,m,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(u=>{u.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:c,handlePhotoFrameTransformEnd:i,startCamera:d,stopCamera:m,capturePhoto:f,cameraStreams:r}};var Kd=()=>{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,c,i,d,m,f,l=[])=>{if(e.current){if(r&&!l.find(v=>v.id===r)?.isPlaying){let v=n.get(r)||c.get(r)||i.get(r)||d.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 Fp=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},$d=(e,o)=>{let t=it(),a=et(As),s=useRef(e);useEffect(()=>{s.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let c=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});c&&c.startsWith("data:")&&t(Gn({id:s.current,thumbnail:c}));}catch(c){console.warn("Could not generate thumbnail (likely CORS issue with images):",c);}},[o,t,a]),n=Fp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var Op=e=>e.flatMap(o=>[o[0],o[1]]),Ds=(e,o)=>{let t=Cd(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 Op(t)};var Yd=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),c=ee(w=>w.toolbar.selectedTool),i=ee(w=>w.toolbar.penColor),d=ee(w=>w.toolbar.strokeWidth),m=ee(w=>w.canvas.isSketchMode),f=ee(w=>w.canvas.slides.find(C=>C.id===w.canvas.currentSlideId)?.images.find(C=>C.id===e)),l=f?.annotations||[],u=f?.isDrawingMode||false,p=f?.width||1,v=f?.height||1,h=useCallback(w=>{if(c!=="pen"&&c!=="eraser")return;t.current=true,a.current=false,s.current=[{x:w.x,y:w.y}];let b=w.x/p,C=w.y/v;n({tool:c,points:[b,C],color:i,strokeWidth:d/p,isSketch:m});},[c,i,d,m,p,v]),g=useCallback(w=>{if(!t.current||!r)return;a.current=true;let b=s.current[s.current.length-1];if(Math.sqrt(Math.pow(w.x-b.x,2)+Math.pow(w.y-b.y,2))<2)return;s.current.push({x:w.x,y:w.y});let M;if(m)M=Ds(s.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,S)=>S%2===0?y/p:y/v);else {let k=w.x/p,y=w.y/v;M=[...r.points,k,y];}n(k=>k?{...k,points:M}:null);},[m,d,r,p,v]),x=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ti({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:u,startDrawing:h,draw:g,stopDrawing:x,tool:c}};var eu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>{let{annotations:c,activeLine:i,stopDrawing:l,tool:u}=Yd(e.id);useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let v=x=>{{r(e.id);return}},h=x=>{return;},g=x=>{};return jsxs(Group,{listening:u!=="pen"&&u!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x){t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();let w=x.getStage()?.container();if(w){let b=C=>{let M=x.getStage()?.getPointerPosition();if(M){let k={x:e.x,y:e.y,width:e.width,height:e.height};M.x>=k.x&&M.x<=k.x+k.width&&M.y>=k.y&&M.y<=k.y+k.height&&n(C,e.id,"image");}};w.addEventListener("contextmenu",b),x._contextMenuCleanup=()=>{w.removeEventListener("contextmenu",b);};}}else {let w=t.current.get(e.id);w?._contextMenuCleanup&&w._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:u!=="pen"&&u!=="eraser",onDragEnd:a,onTransformEnd:x=>s(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...u!=="pen"&&u!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onTouchStart:v,onMouseMove:h,onTouchMove:h,onMouseUp:g,onTouchEnd:g}:{}}),c?.map((x,w)=>{let b=x.points.map((M,k)=>k%2===0?M*e.width+e.x:M*e.height+e.y),C=x.strokeWidth*e.width;return jsx(Line,{points:b,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},w)}),i&&jsx(Line,{points:i.points.map((x,w)=>w%2===0?x*e.width+e.x:x*e.height+e.y),stroke:i.tool==="eraser"?"white":i.color,strokeWidth:i.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:i.tool==="eraser"?"destination-out":"source-over",fill:i.isSketch?i.color:void 0,closed:i.isSketch,listening:false},"active")]})});eu.displayName="ImageWithDrawing";var Pi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(c=>{let i=o(c);return i?jsx(eu,{img:c,loadedImage:i,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n},c.id):null})}));Pi.displayName="ImageLayer";var _p=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:c=0,onTransformEnd:i,onDragEnd:d})=>{let m=xe(),f=useRef(null),l=u=>{m(Oa(u));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:c,onDragEnd:d,onTransformEnd:i,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:u=>u.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},tu=_p;var eh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[c,i]=useState(null),d=useSelector(v=>v.toolbar.selectedTool),m=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let v=new window.Image;v.src=e.thumbnailDataUrl,v.onload=()=>{i(v);};}},[e.thumbnailDataUrl]),!c)return null;let f=e.width/2,l=e.height/2,u=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(u,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 g=x=>{let w=v.getStage()?.getPointerPosition();if(w){let b={x:e.x,y:e.y,width:e.width,height:e.height};w.x>=b.x&&w.x<=b.x+b.width&&w.y>=b.y&&w.y<=b.y+b.height&&r(x);}};h.addEventListener("contextmenu",g),v._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",g);};}}},children:[jsx(Image$1,{image:c,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}})]})},ou=eh;var Ei=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(c=>jsxs(be__default.Fragment,{children:[jsx(ou,{video:c,isSelected:!c.isPlaying&&o===c.id,onClick:()=>a(c.id),onDragEnd:i=>s(c.id,i),onTransformEnd:i=>r(c.id,i),onContextMenu:i=>n(i,c.id,"video"),nodeRef:i=>{i?t.current.set(c.id,i):t.current.delete(c.id);}}),c.isPlaying&&!c.isRecorded&&jsx(tu,{id:c.id,src:c.objectUrl,x:c.x,y:c.y,width:c.width,height:c.height,isSelected:false,rotation:c.rotation,onTransformEnd:i=>r(c.id,i),onDragEnd:i=>s(c.id,i)})]},c.id))}));Ei.displayName="VideoLayer";var Fi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n})=>{let c=useSelector(d=>d.toolbar.selectedTool),i=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map((d,m)=>{let f=d.id||m,l={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!i,listening:!i,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});Fi.displayName="ShapeLayer";var nu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:c})=>{let i=useSelector(m=>m.toolbar.selectedTool),d=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map(m=>{let f=m.id===c,l=m.fontWeight==="bold",u=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&&!d,listening:!d,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:u,align:m.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...d?{}:{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 Ch=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:c,nodeRef:i})=>{let[d,m]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image;h.src=e.images[e.currentIndex],h.onload=()=>{m(h);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let f=8,l=2,u=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(u,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(i(h),h){let g=h.getStage()?.container();if(g){let x=w=>{let b=h.getStage()?.getPointerPosition();if(b){let C={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=C.x&&b.x<=C.x+C.width&&b.y>=C.y&&b.y<=C.y+C.height&&r(w);}};g.addEventListener("contextmenu",x),h._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",x);};}}},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:d,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,c();},onTap:h=>{h.cancelBubble=true,c();},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"})]})},du=Ch;var Ni=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:c,onContextMenu:i})=>jsx(Fragment,{children:e.map(d=>jsx(du,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:a,onTransformEnd:m=>s(d.id,m),onContextMenu:m=>i(m,d.id,"flashcard"),onNext:()=>n(d.id),onPrevious:()=>c(d.id),nodeRef:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);}},d.id))}));Ni.displayName="FlashcardLayer";var cu=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);ee(w=>w.toolbar.selectedTool);let i=ee(w=>w.toolbar.penColor),d=ee(w=>w.toolbar.strokeWidth),m=ee(w=>w.canvas.isSketchMode),f=ee(w=>w.canvas.slides.find(C=>C.id===w.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),l=f?.annotations||[],u=f?.isDrawingMode||false,p=f?.width||1,v=f?.height||1,h=useCallback(w=>{if(!u)return;t.current=true,a.current=false,s.current=[{x:w.x,y:w.y}];let b=w.x/p,C=w.y/v;n({tool:"pen",points:[b,C],color:i,strokeWidth:d/p,isSketch:m});},[u,i,d,m,p,v]),g=useCallback(w=>{if(!t.current||!r)return;a.current=true;let b=s.current[s.current.length-1];if(Math.sqrt(Math.pow(w.x-b.x,2)+Math.pow(w.y-b.y,2))<2)return;s.current.push({x:w.x,y:w.y});let M;if(m)M=Ds(s.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,S)=>S%2===0?y/p:y/v);else {let k=w.x/p,y=w.y/v;M=[...r.points,k,y];}n(k=>k?{...k,points:M}:null);},[m,d,r,p,v]),x=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(oi({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:u,startDrawing:h,draw:g,stopDrawing:x}};var Eh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:c,cameraStream:i,nodeRef:d})=>{let[m,f]=useState(null),[l,u]=useState(null),p=useRef(null),v=useRef(null),h=useRef(null),g=useRef(null),x=useRef(0),w=33,b=useSelector(q=>q.toolbar.selectedTool),C=b==="pen"||b==="eraser",{annotations:M,activeLine:k,isDrawingMode:y,startDrawing:S,draw:B,stopDrawing:A}=cu(e.id);useEffect(()=>{if(!y)return;let q=()=>{A();},$=()=>{A();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",$),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",$);}},[A,y]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;q.src=e.capturedImageUrl,q.onload=()=>{f(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){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,$=v.current;q.srcObject=i;let z=()=>{$.width=q.videoWidth||640,$.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",$.width,$.height);let H=Y=>{if(Y-x.current<w){h.current=requestAnimationFrame(H);return}x.current=Y;let Q=$.getContext("2d");if(Q&&q.readyState===q.HAVE_ENOUGH_DATA){Q.drawImage(q,0,0,$.width,$.height);let Z=$.toDataURL("image/jpeg",.6),re=new window.Image;re.onload=()=>{u(re);},re.src=Z;}h.current=requestAnimationFrame(H);};h.current=requestAnimationFrame(H);};return q.onloadedmetadata=z,q.readyState>=q.HAVE_METADATA&&z(),q.play().catch(H=>console.error("Error playing video:",H)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{u(null),g.current&&(g.current.src="");}},[e.isCapturing,i]);let R=()=>{p.current&&e.isCapturing&&c(p.current);},U=q=>{if(e.capturedImageUrl){if(!y){t();return}let $=q.currentTarget,z=$.getAbsoluteTransform().copy(),Y=$.getStage()?.getPointerPosition();if(Y){z.invert();let Q=z.point(Y);S(Q);}q.cancelBubble=true;}else t();},E=q=>{if(!y||!e.capturedImageUrl)return;let $=q.currentTarget,z=$.getAbsoluteTransform().copy(),Y=$.getStage()?.getPointerPosition();if(Y){z.invert();let Q=z.point(Y);B(Q);}},_=()=>{!y||!e.capturedImageUrl||A();},D=e.isCapturing?l:m,te=Math.min(e.width,e.height)*.12,V=Math.max(25,Math.min(te,50)),oe=e.width/2,W=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(d(q),q){let $=q.getStage()?.container();if($){let z=H=>{let Y=q.getStage()?.getPointerPosition();if(Y){let Q={x:e.x,y:e.y,width:e.width,height:e.height};Y.x>=Q.x&&Y.x<=Q.x+Q.width&&Y.y>=Q.y&&Y.y<=Q.y+Q.height&&r(H);}};$.addEventListener("contextmenu",z),q._contextMenuCleanup=()=>{$.removeEventListener("contextmenu",z);};}}},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:U,onTap:U,onMouseDown:U,onTouchStart:U,onMouseMove:E,onTouchMove:E,onMouseUp:_,onTouchEnd:_,...C?{}:{onDragEnd:a,onTransformEnd:s}}),M?.map((q,$)=>{let z=q.points.map((Y,Q)=>Q%2===0?Y*e.width:Y*e.height),H=q.strokeWidth*e.width;return jsx(Line,{points:z,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:H,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"),!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:W-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:oe-V+6,y:W-60,width:V*1.6,height:V*1.6,radius:V,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?R():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?R():n();}}),jsx(Html,{groupProps:{x:oe-12,y:W-40,width:V*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?R():n();}})})]}),jsx(Text,{x:0,y:W,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:W+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:oe-24,y:W+104,width:V*1.6,height:V*1.6,radius:V,fill:"#096B76",cornerRadius:V,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?R():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?R():n();}}),jsx(Html,{groupProps:{x:oe-8,y:W+120,width:V*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?R():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:oe-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),R();},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})})})})]})]})},hu=Eh;var Wi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:c,cameraStreams:i,onContextMenu:d})=>jsx(Fragment,{children:e.map(m=>jsx(hu,{photoFrame:m,isSelected:t===m.id,onClick:()=>r(m.id),onDragEnd:f=>a(f,m.id),onTransformEnd:f=>s(m.id,f),onContextMenu:f=>d(f,m.id,"photoFrame"),onStartCamera:()=>n(m.id),onCapture:f=>c(m.id,f),cameraStream:i.get(m.id),nodeRef:f=>{f?o.current.set(m.id,f):o.current.delete(m.id);}},m.id))}));Wi.displayName="PhotoFrameLayer";var vu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:c})=>{useEffect(()=>{let f=u=>{c?.current&&!c.current.contains(u.target)&&a();},l=u=>{u.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",l);}},[a]);let i=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label: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]),d=(f,l)=>{f==="order"||f==="lock"?t(f,l):(t(f),a());},m=jsx("div",{ref:c,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:i.map((f,l)=>jsxs("button",{onClick:u=>d(f.action,u),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 yu=({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 Lu=createContext(null),Gi=()=>useContext(Lu);function sg({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Lu.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 ze(){let e=Gi();return typeof document>"u"?null:e||document.body}var Su=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,c]=useState(a),i=useRef(null),d=ze();useEffect(()=>{i.current?.focus();},[]);let m=()=>{s(n),r();},f=u=>{u.key==="Enter"?m():u.key==="Escape"&&r();};return d?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:i,type:"text",value:n,onChange:u=>c(u.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"})]})]})}),d):null};var Ns=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=ze();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let c=f=>{f.preventDefault(),o(a);},i=(f,l,u)=>{u/=100;let p=l*Math.min(u,1-u)/100,v=h=>{let g=(h+f/30)%12,x=u-p*Math.max(Math.min(g-3,9-g,1),-1);return Math.round(255*x).toString(16).padStart(2,"0")};return `#${v(0)}${v(8)}${v(4)}`},d=["#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:c,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),u=i(l,100,50);s(u);},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:d.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 Ig=({imageSrc:e,onCrop:o})=>{let[t]=ku(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]),c=useMemo(()=>{let l=n.width*.5,u=n.height*.5,p=(n.width-l)/2,v=(n.height-u)/2;return {x:p,y:v,width:l,height:u}},[n]),[i,d]=useState(c);useEffect(()=>{d(c);},[c]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let m=()=>{let l=s.current;if(!l)return;let u=l.scaleX(),p=l.scaleY();l.scaleX(1),l.scaleY(1),d({x:l.x(),y:l.y(),width:Math.max(20,l.width()*u),height:Math.max(20,l.height()*p)});},f=()=>{let l=s.current;l&&d({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:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:f,onTransformEnd:m,dragBoundFunc:l=>{let u=Math.max(0,Math.min(l.x,n.width-i.width)),p=Math.max(0,Math.min(l.y,n.height-i.height));return {x:u,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,u)=>u.width<20||u.height<20||u.x<0||u.y<0||u.x+u.width>n.width||u.y+u.height>n.height?l:u})]})})},Mu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=ku(e),c=ze();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let i=(f,l,u,p)=>{r({x:f,y:l,width:u,height:p});},d=()=>{if(!n)return;let u=Math.min(600/n.width,400/n.height),p=s.x/u,v=s.y/u,h=s.width/u,g=s.height/u,x=document.createElement("canvas");x.width=h,x.height=g;let w=x.getContext("2d");if(!w)return;w.drawImage(n,p,v,h,g,0,0,h,g);let b=x.toDataURL("image/png");o(b);};return c?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(Ig,{imageSrc:e,onCrop:i})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:d,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"]})]})]})}),c):null};var dr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let s=ze(),[r,n]=useState(false),[c,i]=useState(null),[d,m]=useState(0),[f,l]=useState(true),u=useRef(null),p=useRef([]),v=useRef(null),h=useRef(null),g=useRef(null),x=useRef(null),w=useRef(null),b=useRef(null);useEffect(()=>()=>{g.current&&cancelAnimationFrame(g.current),v.current&&clearInterval(v.current),h.current&&h.current.getTracks().forEach(B=>B.stop());},[]);let C=async()=>{try{let B,A=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((H,Y)=>{let Q=H.getChildren();console.log(`Layer ${Y} children count:`,Q.length);});let te=document.createElement("canvas");te.width=o.current.width(),te.height=o.current.height();let V=te.getContext("2d",{willReadFrequently:!1});if(!V){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",te.width,"x",te.height),w.current=te;let oe=()=>{if(V.clearRect(0,0,te.width,te.height),D.forEach(H=>{let Y=H.getCanvas()._canvas;Y&&V.drawImage(Y,0,0);}),a?.current){let H=a.current;V.drawImage(H,0,0);}};b.current=oe,o.current.draw(),oe(),await new Promise(H=>setTimeout(H,100)),console.log("Creating captureStream..."),B=te.captureStream(30),console.log("Canvas stream created, tracks:",B.getTracks().length);let q=B.getVideoTracks()[0];q&&console.log("Video track:",q.label,"state:",q.readyState);let $=0,z=()=>{oe(),o?.current&&(o.current.getLayers().forEach(Y=>{Y.batchDraw();}),$++,$%60===0&&console.log("Drawing frame:",$)),g.current=requestAnimationFrame(z);};z();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{A=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(D){console.warn("Microphone access denied:",D);}let R=[...B.getVideoTracks()];A&&R.push(...A.getAudioTracks());let U=new MediaStream(R);h.current=U;let E="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?E="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?E="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?E="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(E="video/webm;codecs=vp8"),console.log("Using mimeType:",E);let _=new MediaRecorder(U,{mimeType:E,videoBitsPerSecond:25e5});u.current=_,p.current=[],_.ondataavailable=D=>{console.log("Data available, size:",D.data.size),D.data.size>0&&p.current.push(D.data);},_.onstop=()=>{console.log("Recording stopped, chunks:",p.current.length);let D=new Blob(p.current,{type:E});console.log("Final blob size:",D.size),o?.current&&b.current&&w.current&&(o.current.draw(),o.current.getLayers().forEach(V=>{V.batchDraw();}),b.current(),x.current=w.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",x.current.length)),U.getTracks().forEach(te=>te.stop()),v.current&&clearInterval(v.current),g.current&&(cancelAnimationFrame(g.current),g.current=null),i(D);},_.onerror=D=>{console.error("MediaRecorder error:",D);},console.log("Starting recording..."),_.start(1e3),n(!0),m(0),v.current=setInterval(()=>{m(D=>D+1);},1e3);}catch(B){console.error("Error starting screen recording:",B),alert("Failed to start recording. Please ensure you granted permission.");}},M=()=>{u.current&&r&&(console.log("Stopping recording, state:",u.current.state),u.current.state!=="inactive"&&(u.current.requestData(),setTimeout(()=>{u.current&&u.current.state!=="inactive"&&u.current.stop();},100)),n(false));},k=()=>{if(c){let B=URL.createObjectURL(c),A=document.createElement("a");A.href=B,A.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(B);}},y=B=>{let A=Math.floor(B/60),R=B%60;return `${A.toString().padStart(2,"0")}:${R.toString().padStart(2,"0")}`};if(!s)return null;if(r){let B=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(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:M,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,s)}let S=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:[!c&&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"]})]})]}),c&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(c),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",y(d)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&c&&x.current&&(t(c,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: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:()=>{i(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(S,s)};var Du=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=ze(),[n,c]=useState(false),[i,d]=useState(null),[m,f]=useState(false),[l,u]=useState(0),p=useRef(null),v=useRef([]),h=useRef(null),g=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(B=>B.blob()).then(B=>d(B)).catch(B=>console.error("Error loading audio:",B));},[o,i]);let x=async()=>{try{let B=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),A=new MediaRecorder(B);p.current=A,v.current=[],A.ondataavailable=R=>{R.data.size>0&&v.current.push(R.data);},A.onstop=()=>{let R=new Blob(v.current,{type:"audio/webm"});d(R),B.getTracks().forEach(U=>U.stop()),h.current&&clearInterval(h.current);},A.start(),c(!0),u(0),h.current=setInterval(()=>{u(R=>R+1);},1e3);}catch(B){console.error("Error starting audio recording:",B),alert("Failed to start recording. Please allow microphone access.");}},w=()=>{p.current&&n&&(p.current.stop(),c(false));},b=()=>{if(i){let B=URL.createObjectURL(i),A=new Audio(B);g.current=A,A.onended=()=>{f(false),URL.revokeObjectURL(B);},A.play(),f(true);}},C=()=>{g.current&&(g.current.pause(),g.current.currentTime=0,f(false));},M=async()=>{if(i){let B=new FileReader;B.onloadend=()=>{let A=B.result;t(A),s();},B.readAsDataURL(i);}},k=()=>{d(null),a();},y=B=>{let A=Math.floor(B/60),R=B%60;return `${A.toString().padStart(2,"0")}:${R.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: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:w,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 S=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:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:x,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?C:b,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),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:M,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(S,r)};var Pt=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:c=90,containerRight:i=320})=>{let[d,m]=useState(false),f=useRef(null),l=v=>{if(v.stopPropagation(),d&&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);}},u=(o+a)*s+r-15,p=t*s+n+c-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${d?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${u}px`,top:`${p}px`,width:"30px",height:"30px",zIndex:99},title:d?"Stop Audio":"Play Audio",children:d?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Fu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),s=ee(ge),r=useMemo(()=>{if(!s)return [];let h=[];return s.images?.forEach(g=>{h.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),s.videos?.forEach(g=>{h.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),s.shapes?.forEach(g=>{h.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),s.texts?.forEach(g=>{h.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),s.flashcards?.forEach(g=>{h.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),s.photoFrames?.forEach(g=>{h.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),s.multipleChoices?.forEach(g=>{h.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),s.trueFalses?.forEach(g=>{h.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),s.shortAnswers?.forEach(g=>{h.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),s.LongAnswer?.forEach(g=>{h.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),s.fillInTheBlanks?.forEach(g=>{h.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),s.lines?.forEach(g=>{g.id&&h.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),h.sort((g,x)=>x.timestamp-g.timestamp)},[s]),[n,c]=useState(r),[i,d]=useState(false);useEffect(()=>{i||c(r);},[r]);let m=h=>{let g="h-5 w-5";switch(h){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},u=h=>{d(true),c(h);},p=()=>{d(false);let h=Date.now();n.forEach((g,x)=>{let w=h-x;a(Qo({id:g.id,type:g.type,newTimestamp:w}));});},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:u,className:"space-y-1",children:n.map(h=>{let g=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 ${g?"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 ${g?"text-[#096B76]":"text-[#00000099]"}`,children:h.name})}),jsx("div",{className:`${g?"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 Bu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>{let n=useSelector(W=>W.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(new Set),[m,f]=useState(false),[l,u]=useState(null),p=useRef(null);useEffect(()=>{let W=p.current;if(W)return a.current.set(e.id,W),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),h=v.size>1,g=W=>{m||d(h?q=>{let $=new Set(q);return $.has(W)?$.delete(W):$.add(W),$}:new Set([W]));},x=()=>{i.size>0&&f(true);},w=()=>{f(false),d(new Set);},b=i.size===v.size&&Array.from(i).every(W=>v.has(W)),C=Array.from(i).filter(W=>v.has(W)),M=h&&C.length>0&&!b,k=()=>b?"\u2713 Correct! Great job! \u{1F389}":M?`\u26A0 Partially correct (${C.length}/${v.size})`:"\u2717 Try again!",y=()=>b?{bg:"#dcfce7",text:"#166534"}:M?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},S=55,B=8,A=24,R=60,U=60,E=h&&!m?25:0,_=e.data.feedbackMode==="practice"?48:0,D=12,te=R+E+(m?U:0),V=e.data.responseOptions.options.length*(S+B),oe=te+V+D+_+A;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:s,onClick:W=>t(e.id),onTap:W=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:oe,width:e.width,onTransformEnd:W=>o(e.id,W),onContextMenu:W=>{W.cancelBubble=true,r(W.evt,e.id,"mcq");}}),jsx(Text,{x:A+8,y:A,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-A*2,listening:false}),h&&!m&&e.data.feedbackMode==="practice"?jsx(Text,{x:A,y:A+35,text:`Select ${v.size} answers (${i.size}/${v.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-A*2,listening:false}):null,m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:A+24,y:R+E,width:e.width-A*2-40,height:U-20,fill:y().bg,cornerRadius:8}),jsx(Text,{x:A,y:R+E,width:e.width-A*2,height:U-20,text:k(),fontSize:16,fontStyle:"bold",fill:y().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((W,q)=>{let $=v.has(q),z=i.has(q),H=te+q*(S+B),Y="#e5e7eb",Q="#ffffff",Z="#111827";return m&&$?(Y="#22c55e",Q="#dcfce7",Z="#1B9D2C"):m&&z&&!$?(Y="#ef4444",Q="#fee2e2",Z="#ef4444"):z&&(Y="#096B76",Q="#ECFFF8",Z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:A+12,y:H+(S-20)/2,width:20,height:20,fill:z?"#096B76":"white",stroke:z?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:re=>{re.cancelBubble=true,g(q);},onTap:re=>{re.cancelBubble=true,g(q);}}),z&&jsx(Text,{x:A+12,y:H+(S-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:A+44,y:H,width:e.width-A*2-60,height:S,fill:Q,stroke:Y,strokeWidth:2,cornerRadius:8,onClick:re=>{re.cancelBubble=true,g(q);},onTap:re=>{re.cancelBubble=true,g(q);}}),jsx(Text,{x:A+60,y:H,width:e.width-A*2-80,height:S,text:W,fontSize:16,fill:Z,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:te+e.data.responseOptions.options.length*(S+B)+12,children:[jsxs(Group,{onMouseDown:W=>{W.cancelBubble=true,u("check");},onMouseUp:W=>{W.cancelBubble=true,u(null),x();},onMouseLeave:W=>{W.cancelBubble=true,u(null);},onTouchStart:W=>{W.cancelBubble=true,u("check");},onTouchEnd:W=>{W.cancelBubble=true,u(null),x();},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:A+14,width:(e.width-A*2-24)/(m?2:1),height:48,fill:i.size===0||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:A+14,width:(e.width-A*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-A*2)/2+8,onMouseDown:()=>u("reset"),onMouseUp:()=>{u(null),w();},onMouseLeave:()=>u(null),onTouchStart:()=>u("reset"),onTouchEnd:()=>{u(null),w();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:A,width:(e.width-A*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:W=>W.cancelBubble=true,onTap:W=>W.cancelBubble=true}),jsx(Text,{x:A,width:(e.width-A*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Bu.displayName="MultipleChoice";var Ou=Bu;var Xi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s})=>{let r=useDispatch(),n=useSelector(z=>z.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(false),[m,f]=useState(new Set),[l,u]=useState(false),[p,v]=useState(false),[h,g]=useState(0),x=340,w=100,b=window.innerWidth*.4,C=window.innerHeight*.5,M=x+20,k=w+60,y=b-40,S=C-300,B=useRef(null);useEffect(()=>{let z=B.current;if(z)return s.current.set(e.id,z),()=>{s.current.delete(e.id);}},[e.id]);let A=z=>{r(fa({id:e.id,x:z.target.x(),y:z.target.y()}));},R=z=>{let H=z.target,Y=H.x(),Q=H.y(),Z=window.innerWidth*.2,ye=Y+Z>M&&Y<M+y&&Q+50>k&&Q<k+S;d(ye);},U=(z,H)=>{let Y=H.target,Q=Y.x(),Z=Y.y(),re=window.innerWidth*.2,Be=Q+re>M&&Q<M+y&&Z+50>k&&Z<k+S;f(Be?Ce=>new Set(Ce).add(z):Ce=>{let Oe=new Set(Ce);return Oe.delete(z),Oe}),d(false);},E=()=>{u(true);},_=()=>{u(false),f(new Set),g(z=>z+1);},D=new Set(e.data.responseOptions.correctIndex),te=m.size===D.size&&Array.from(m).every(z=>D.has(z)),V=Array.from(m).filter(z=>D.has(z)),oe=V.length>0&&!te,W=()=>te?"\u2713 Correct! Great job!":oe?`\u26A0 Partially correct (${V.length}/${D.size})`:"\u2717 Try again!",q=()=>te?{bg:"#dcfce7",text:"#166534"}:oe?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},$=()=>l?te?"#4CAF50":oe?"#f59e0b":"#ef4444":i?"#4CAF50":"#075560";return jsxs(Group,{ref:B,name:"mcq-element",width:b,height:C,draggable:!c,listening:!c,...c?{}:{onClick:z=>a(e.id),onTap:z=>a(e.id),onContextMenu:z=>{z.evt.preventDefault(),o(z.evt,e.id,"mcq");}},children:[jsxs(Group,{x,y:w,rotation:e.rotation,onDragEnd:A,children:[jsx(Rect,{fill:"white",stroke:i?"#4CAF50":"#e5e7eb",strokeWidth:i?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?C-100:C-50,width:b,shadowColor:i?"#4CAF50":"transparent",shadowBlur:i?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:b-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:y,height:S,fill:"#EBF6F7",stroke:$(),strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:S+18,width:y-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:S+20,width:y,height:60,text:W(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),m.size===0&&!l&&jsx(Text,{x:20,y:60,width:y,height:S-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),E();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),E();},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:_,onTouchStart:_,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((z,H)=>{let Y=H%2,Q=Math.floor(H/2),Z=window.innerWidth*.2,re=50,ye=10,Be=m.has(H),Ce=D.has(H),Oe=l&&Be,jt="transparent";return Oe?jt=Ce?"#4CAF50":"#ef4444":Be&&(jt="#4CAF50"),jsxs(Group,{x:340+Y*(Z+ye),y:w+C-80+Q*(re+ye),draggable:!l,onDragMove:R,onDragEnd:da=>U(H,da),opacity:l&&!Be?.5:1,children:[jsx(Rect,{width:Z-20,height:re,fill:"white",stroke:jt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Z-20,height:re,text:z,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${H}-${h}`)})]})};Xi.displayName="MultipleChoiceDragAndDrop";var Nu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Ou,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:c=>s(c,n.id),onContextMenu:r},n.id):jsx(Xi,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r},n.id))});var Vu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(D=>D.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(null),[m,f]=useState(false),[l,u]=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=()=>{i!==null&&f(true);},h=()=>{f(false),d(null);},g=e.data.responseOptions.correctAnswer,x=i===g,w=D=>{m||d(D);},b=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},M=70,k=12,y=24,S=60,B=60,A=e.data.feedbackMode==="practice"?48:0,R=12,U=S+(m?B:0),E=2*(M+k),_=U+E+R+A+y;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{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:_-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:S,width:e.width-y*2,height:B-10,fill:C().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:B-10,text:b(),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,te)=>{let V=g===D.value,oe=i===D.value,W=(e.width-y*3)/2,q=y+te*(W+y),$=U,z=D.value===true,H=z?"#10b981":"#ef4444",Y="#ffffff",Q="#ffffff",Z="#e5e7eb";return m&&(V?(Q=z?"#f0fdf4":"#fef2f2",Z=z?"#86efac":"#fecaca"):oe&&!V&&(Q="#fee2e2",Z="#ef4444")),oe&&!m&&(Z="#096B76",Q="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:$,width:W,height:M+50,fill:Q,stroke:Z,strokeWidth:2,cornerRadius:12,onClick:re=>{re.cancelBubble=true,w(D.value);},onTap:re=>{re.cancelBubble=true,w(D.value);}}),jsx(Circle,{x:q+W/2,y:$+40,radius:28,fill:H,listening:false}),z?jsx(Text,{x:q+W/2-14,y:$+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+W/2-14,y:$+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:$+85,width:W,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:U+2*(M+k),children:[jsxs(Group,{onMouseDown:D=>{D.cancelBubble=true,u("check");},onMouseUp:D=>{D.cancelBubble=true,u(null),v();},onMouseLeave:D=>{D.cancelBubble=true,u(null);},onTouchStart:D=>{D.cancelBubble=true,u("check");},onTouchEnd:D=>{D.cancelBubble=true,u(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:i===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:()=>u("reset"),onMouseUp:()=>{u(null),h();},onMouseLeave:()=>u(null),onTouchStart:()=>u("reset"),onTouchEnd:()=>{u(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})]})]})]})});Vu.displayName="TrueFalse";var qu=Vu;var Lx="#FFFFFF",Ji=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),s=useSelector(H=>H.toolbar.selectedTool),r=s==="pen"||s==="eraser",[n,c]=useState(false),[i,d]=useState(null),[m,f]=useState(false),[l,u]=useState(false),[p,v]=useState(0),[h,g]=useState(false),x=340,w=100,b=window.innerWidth*.4,C=window.innerHeight*.5,M=b-40,k=C-300,y=20,S=60,B=M,A=k,R=b*.2-40,U=50,E=useRef(null),_=H=>{a(ma({id:e.id,x:H.target.x(),y:H.target.y()}));},D=H=>{let Y=H.target,Q=Y.x(),Z=Y.y(),re=Math.max(0,Math.min(Q+R,y+B)-Math.max(Q,y)),ye=Math.max(0,Math.min(Z+U,S+A)-Math.max(Z,S)),Be=re*ye,Ce=R*U;c(Be/Ce>=.5);},te=(H,Y)=>{let Q=Y.target,Z=Q.x(),re=Q.y(),ye=Math.max(0,Math.min(Z+R,y+B)-Math.max(Z,y)),Be=Math.max(0,Math.min(re+U,S+A)-Math.max(re,S)),Ce=ye*Be,Oe=R*U;if(Ce/Oe>=.5)d(H);else return;c(false);},V=()=>{f(true);},oe=()=>{f(false),d(null),v(H=>H+1);},W=e.data.responseOptions.correctAnswer,q=i===W,$=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",z=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:E,name:"trueFalse-element",width:b,height:C,draggable:!r,listening:!r,...r?{}:{onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:w,rotation:e.rotation,onDragEnd:_,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:b,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:b-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:M,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:M,height:60,fill:z().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:M,height:60,text:$(),fontSize:18,fontStyle:"bold",fill:z().text,align:"center",verticalAlign:"middle"})]}),i===null&&!m&&jsx(Text,{x:20,y:60,width:M,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:()=>{i!==null&&(u(true),V());},onMouseUp:()=>u(false),onMouseLeave:()=>u(false),onTouchStart:()=>{i!==null&&(u(true),V());},onTouchEnd:()=>u(false),scaleX:l?.95:1,scaleY:l?.95:1,children:[jsx(Rect,{fill:i===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:M}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:M,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:oe,onTouchStart:oe,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:M}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:M,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((H,Y)=>{let Q=window.innerWidth*.2,Z=50,re=10,ye=i===H.value,Be=W===H.value,Ce=m&&ye,Oe="transparent";return Ce?Oe=Be?"#4CAF50":"#ef4444":ye&&(Oe="#4CAF50"),jsxs(Group,{x:16+Y*(Q+re),y:w+C-300,draggable:!m,onDragMove:D,onDragEnd:jt=>te(H.value,jt),opacity:m&&!ye?.5:1,children:[jsx(Rect,{width:Q-40,height:Z,fill:"#075560",stroke:Oe,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Q-40,height:Z,text:H.label,fontSize:18,fontStyle:"bold",fill:Lx,align:"center",verticalAlign:"middle",listening:false})]},`${H.value}-${p}`)})]})})};Ji.displayName="TrueFalseDragAndDrop";var Hu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(qu,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s},n.id):jsx(Ji,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r},n.id))});var ba=new WeakMap,Co=new WeakMap,hr={current:[]},Qi=false,pr=0,mr=new Set,Ws=new Map;function Uu(e){let o=Array.from(e).sort((t,a)=>t instanceof Ut&&t.options.deps.includes(a)?1:a instanceof Ut&&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=Co.get(t);if(a)for(let s of a){let r=ba.get(s);r&&Uu(r);}}}function Cx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function kx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Gs(e){if(pr>0&&!Ws.has(e)&&Ws.set(e,e.prevState),mr.add(e),!(pr>0)&&!Qi)try{for(Qi=!0;mr.size>0;){let o=Array.from(mr);mr.clear();for(let t of o){let a=Ws.get(t)??t.prevState;t.prevState=a,Cx(t);}for(let t of o){let a=ba.get(t);a&&(hr.current.push(t),Uu(a));}for(let t of o){let a=ba.get(t);if(a)for(let s of a)kx(s);}}}finally{Qi=false,hr.current=[],Ws.clear();}}function xt(e){pr++;try{e();}finally{if(pr--,pr===0){let o=mr.values().next().value;o&&Gs(o);}}}function zu(e){return typeof e=="function"}var Yt=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):zu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Gs(this);}};var Ut=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 Yt){let a=ba.get(t);a||(a=new Set,ba.set(t,a)),a.add(this);let s=Co.get(this);s||(s=new Set,Co.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 Yt){let a=ba.get(t);a&&a.delete(this);let s=Co.get(this);s&&s.delete(t);}}};function Mx(e){return typeof e=="function"}function el(e,...o){return Mx(e)?e(...o):e}function Wu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var va,dt,ot,gr,ya,za,ea,ko,xr,Ks,br,Mo,Wa=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){De(this,va,true);De(this,dt);De(this,ot);De(this,gr);De(this,ya);De(this,za);De(this,ea);De(this,ko);De(this,xr,0);De(this,Ks,5);De(this,br,()=>{this.debugLog("Connected to event bus"),ke(this,za,true),this.debugLog("Emitting queued events",K(this,ya)),K(this,ya).forEach(o=>this.emitEventToBus(o)),ke(this,ya,[]),this.stopConnectLoop(),K(this,ot).call(this).removeEventListener("tanstack-connect-success",K(this,br));});De(this,Mo,()=>{if(K(this,ot).call(this).addEventListener("tanstack-connect-success",K(this,br)),K(this,xr)<K(this,Ks)){xd(this,xr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}K(this,ot).call(this).removeEventListener("tanstack-connect",K(this,Mo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});ke(this,dt,o),ke(this,va,a),ke(this,ot,this.getGlobalTarget),ke(this,gr,t),this.debugLog(" Initializing event subscription for plugin",K(this,dt)),ke(this,ya,[]),ke(this,za,false),ke(this,ea,null),ke(this,ko,s);}startConnectLoop(){K(this,ea)!==null||K(this,za)||(this.debugLog(`Starting connect loop (every ${K(this,ko)}ms)`),ke(this,ea,setInterval(K(this,Mo),K(this,ko))));}stopConnectLoop(){K(this,ea)!==null&&(clearInterval(K(this,ea)),ke(this,ea,null),this.debugLog("Stopped connect loop"));}debugLog(...o){K(this,gr)&&console.log(`\u{1F334} [tanstack-devtools:${K(this,dt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return K(this,dt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});K(this,ot).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{K(this,ot).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!K(this,va)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!K(this,za)){this.debugLog("Bus not available, will be pushed as soon as connected"),K(this,ya).push({type:`${K(this,dt)}:${o}`,payload:t,pluginId:K(this,dt)}),typeof CustomEvent<"u"&&(K(this,Mo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${K(this,dt)}:${o}`,payload:t,pluginId:K(this,dt)})}on(o,t){let a=`${K(this,dt)}:${o}`;if(!K(this,va))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 K(this,ot).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{K(this,ot).call(this).removeEventListener(a,s);}}onAll(o){if(!K(this,va))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return K(this,ot).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,ot).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!K(this,va))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;K(this,dt)&&s.pluginId!==K(this,dt)||o(s);};return K(this,ot).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,ot).call(this).removeEventListener("tanstack-devtools-global",t)}};va=new WeakMap,dt=new WeakMap,ot=new WeakMap,gr=new WeakMap,ya=new WeakMap,za=new WeakMap,ea=new WeakMap,ko=new WeakMap,xr=new WeakMap,Ks=new WeakMap,br=new WeakMap,Mo=new WeakMap;var tl=class extends Wa{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Gu=(e,o)=>{al.emit(e,o);},al=new tl;function Ku(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Tx={enabled:true,leading:true,trailing:true,wait:0},wa,bt,Ga,Ka,_a,To,_s=class{constructor(o,t){De(this,wa);De(this,bt);De(this,Ga);De(this,Ka);De(this,_a);De(this,To);this.fn=o,this.store=new Yt(Ku()),this.setOptions=a=>{this.options={...this.options,...a},K(this,Ga).call(this)||this.cancel();},ke(this,bt,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:K(this,Ga).call(this)?n?"pending":"idle":"disabled"}}),Gu("Throttler",this);}),ke(this,Ga,()=>!!el(this.options.enabled,this)),ke(this,Ka,()=>el(this.options.wait,this)),this.maybeExecute=(...a)=>{K(this,bt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=K(this,Ka).call(this);if(this.options.leading&&r>=n)K(this,_a).call(this,...a);else if(K(this,bt).call(this,{lastArgs:a}),!K(this,wa)&&this.options.trailing){let c=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,i=n-c;K(this,bt).call(this,{isPending:true}),ke(this,wa,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&K(this,_a).call(this,...d);},i));}},ke(this,_a,(...a)=>{if(!K(this,Ga).call(this))return;this.fn(...a);let s=Date.now(),r=s+K(this,Ka).call(this);K(this,To).call(this),K(this,bt).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||K(this,bt).call(this,{nextExecutionTime:void 0});},K(this,Ka).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&K(this,_a).call(this,...this.store.state.lastArgs);},ke(this,To,()=>{K(this,wa)&&(clearTimeout(K(this,wa)),ke(this,wa,void 0));}),this.cancel=()=>{K(this,To).call(this),K(this,bt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{K(this,bt).call(this,Ku());},this.key=Wu(t.key),this.options={...Tx,...t},K(this,bt).call(this,this.options.initialState??{}),al.on("d-Throttler",a=>{a.payload.key===this.key&&(K(this,bt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};wa=new WeakMap,bt=new WeakMap,Ga=new WeakMap,Ka=new WeakMap,_a=new WeakMap,To=new WeakMap;function ol(e,o){return new _s(e,o).maybeExecute}function La(e,o){return typeof e=="function"?e(o):e}function Sa(e,o){return Ys(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Ao(e,o,t){let a=Ys(o);function s(r){if(!a.length)return La(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 c=r.slice(0,n);return [...c.length?c:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function sl(e,o){let t=Ys(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((d,m)=>m!==n);let{[n]:c,...i}=s;return i}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 Ax=/^(\d+)$/gm,Px=/\.(\d+)(?=\.)/gm,Dx=/^(\d+)\./gm,Rx=/\.(\d+$)/gm,Ex=/\.{2,}/gm,rl="__int__",js=`${rl}$1`;function Ys(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(Ax,js).replace(Px,`.${js}.`).replace(Dx,`${js}.`).replace(Rx,`.${js}`).replace(Ex,".").split(".").map(o=>{if(o.startsWith(rl)){let t=o.substring(rl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function nl(e){return !(Array.isArray(e)&&e.length===0)}function Po(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 Do(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,c=i=>i.validators.filter(Boolean).map(d=>{let m=d?.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:d.fn,debounceMs:f}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:c})}var vr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ia(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)||!Ia(e[s],o[s]))return false;return true}var Js=({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},Zs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function je(e,o){return e==null?o:{...e,...o}}var ja=256,$s=[],Xs;for(;ja--;)$s[ja]=(ja+256).toString(16).substring(1);function il(){let e=0,o,t="";if(!Xs||ja+16>256){for(Xs=new Array(256),e=256;e--;)Xs[e]=256*Math.random()|0;e=0,ja=0;}for(;e<16;e++)o=Xs[ja+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 ja++,t}var Ca=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 Fx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let c=0;c<s.length;c++){let i=s[c];if(i===void 0)continue;let d=typeof i=="object"?i.key:i,m=Number(d);Array.isArray(r)&&!Number.isNaN(m)?n+=`[${m}]`:n+=(c>0?".":"")+String(d),typeof r=="object"&&r!==null?r=r[d]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var _u=(e,o)=>{let t=Fx(e,o);return {form:t,fields:t}},ka={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:_u(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:_u(a.issues,e)}},Qs=e=>!!e&&"~standard"in e;var Ro={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function yr(e){function o(f,l,u,p){let v=a(f,l,u,p);({insert:()=>c(v,f,l),remove:()=>i(v),swap:()=>p!==void 0&&m(v,f,l,p),move:()=>p!==void 0&&d(v,f,l,p)})[u]();}function t(f,l){return `${f}[${l}]`}function a(f,l,u,p){let v=[t(f,l)];if(u==="swap")v.push(t(f,p));else if(u==="move"){let[h,g]=[Math.min(l,p),Math.max(l,p)];for(let x=h;x<=g;x++)v.push(t(f,x));}else {let h=e.getFieldValue(f),g=Array.isArray(h)?h.length:0;for(let x=l+1;x<g;x++)v.push(t(f,x));}return Object.keys(e.fieldInfo).filter(h=>v.some(g=>h.startsWith(g)))}function s(f,l){return f.replace(/\[(\d+)\]/,(u,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=()=>Ro,c=(f,l,u)=>{r(f,"down"),f.forEach(p=>{p.toString().startsWith(t(l,u))&&e.setFieldMeta(p,n());});},i=f=>{r(f,"up");},d=(f,l,u,p)=>{let v=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,u))).map(h=>[h,e.getFieldMeta(h)]));r(f,u<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,p))).forEach(h=>{let g=h.replace(t(l,p),t(l,u)),x=v.get(g);x&&e.setFieldMeta(h,x);});},m=(f,l,u,p)=>{f.forEach(v=>{if(!v.toString().startsWith(t(l,u)))return;let h=v.toString().replace(t(l,u),t(l,p)),[g,x]=[e.getFieldMeta(v),e.getFieldMeta(h)];g&&e.setFieldMeta(h,g),x&&e.setFieldMeta(v,x);});};return {handleArrayFieldMetaShift:o}}var ll=class extends Wa{constructor(){super({pluginId:"form-devtools"});}},vt=new ll;function dl(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(),vt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return vt.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((i,d)=>i!==this.prevTransformArray[d]),n=a.defaultValues&&!Ia(a.defaultValues,s.defaultValues)&&!this.state.isTouched,c=!Ia(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!c&&!r||(xt(()=>{this.baseStore.setState(()=>dl(Object.assign({},this.state,c?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),vt.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(()=>dl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return xt(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let c=n.instance;s.push(Promise.resolve().then(()=>c.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),c=Array.isArray(n)?Math.max(n.length-1,0):null,i=[`${a}[${s}]`];for(let l=s+1;l<=(c??0);l++)i.push(`${a}[${l}]`);let d=Object.keys(this.fieldInfo).filter(l=>i.some(u=>l.startsWith(u))),m=[];return xt(()=>{d.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=Po(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ca}),r=false,n={};return xt(()=>{for(let d of s){if(!d.validate)continue;let m=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:f,fieldErrors:l}=en(m),u=wr(d.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:g}=v,x=l?.[p],{newErrorValue:w,newSource:b}=Js({newFormValidatorError:x,isPreviousErrorFromFormValidator:g?.[u]==="form",previousErrorValue:h?.[u]});b==="form"&&(n[p]={...n[p],[u]:x}),h?.[u]!==w&&this.setFieldMeta(p,C=>({...C,errorMap:{...C.errorMap,[u]:w},errorSourceMap:{...C.errorSourceMap,[u]:b}}));}this.state.errorMap?.[u]!==f&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[u]:f}})),(f||l)&&(r=!0);}let c=wr("submit");this.state.errorMap?.[c]&&a!=="submit"&&!r&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[c]:void 0}}));let i=wr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Do(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ca});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let r=[],n;for(let d of s){if(!d.validate)continue;let m=wr(d.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[m]={lastAbortController:l},r.push(new Promise(async u=>{let p;try{p=await new Promise((x,w)=>{setTimeout(async()=>{if(l.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(b){w(b);}},d.debounceMs);});}catch(x){p=x;}let{formError:v,fieldErrors:h}=en(p);h&&(n=n?{...n,...h}:h);let g=wr(d.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let w=this.getFieldMeta(x);if(!w)continue;let{errorMap:b,errorSourceMap:C}=w,M=n?.[x],{newErrorValue:k,newSource:y}=Js({newFormValidatorError:M,isPreviousErrorFromFormValidator:C?.[g]==="form",previousErrorValue:b?.[g]});b?.[g]!==k&&this.setFieldMeta(x,S=>({...S,errorMap:{...S.errorMap,[g]:k},errorSourceMap:{...S.errorSourceMap,[g]:y}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[g]:v}})),u(n?{fieldErrors:n,errorMapKey:g}:void 0);}));}let c=[],i={};if(r.length){c=await Promise.all(r);for(let d of c)if(d?.fieldErrors){let{errorMapKey:m}=d;for(let[f,l]of Object.entries(d.fieldErrors)){let p={...i[f]||{},[m]:l};i[f]=p;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Sa(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]:La(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Ro,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,c=r?.dontRunListeners??false,i=r?.dontValidate??false;xt(()=>{n||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Ao(d.values,a,s)}));}),c||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let c=a.toString();return n!==c&&n.startsWith(c)}),a];this.baseStore.setState(n=>{let c={...n};return r.forEach(i=>{c.values=sl(c.values,i),delete this.fieldInfo[i],delete c.fieldMetaBase[i];}),c});},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,i=>[...i.slice(0,s),r,...i.slice(s)],je(n,{dontValidate:true}));let c=n?.dontValidate??false;c||await this.validateField(a,"change"),yr(this).handleArrayFieldMetaShift(a,s,"insert"),c||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>i.map((d,m)=>m===s?r:d),je(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),c=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,d=>d.filter((m,f)=>f!==s),je(r,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"remove"),c!==null){let d=`${a}[${c}]`;this.deleteField(d);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let d=i[s],m=i[r];return Ao(Ao(i,`${s}`,m),`${r}`,d)},je(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,i=>{let d=[...i];return d.splice(r,0,d.splice(s,1)[0]),d},je(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,[],je(s,{dontValidate:true})),n!==null)for(let i=0;i<=n;i++){let d=`${a}[${i}]`;this.deleteField(d);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Ro},values:this.options.defaultValues?Ao(s.values,a,Sa(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=>ka.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ka.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??il(),this._devtoolsSubmissionOverride=false,this.baseStore=new Yt(dl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Ut({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,c=a?.[0],i=s[0],d=0,m={};for(let f of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[f],u=c?.fieldMetaBase[f],p=n?.[f],v=Sa(i.values,f),h=p?.errors;if(!u||l.errorMap!==u.errorMap){h=Object.values(l.errorMap??{}).filter(C=>C!==void 0);let b=this.getFieldInfo(f)?.instance;b&&!b.options.disableErrorFlat&&(h=h?.flat(1));}let g=!nl(h??[]),x=!l.isDirty,w=Ia(v,Sa(this.options.defaultValues,f))||Ia(v,this.getFieldInfo(f)?.instance?.options.defaultValue);if(p&&p.isPristine===x&&p.isValid===g&&p.isDefaultValue===w&&p.errors===h&&l===u){m[f]=p,d++;continue}m[f]={...l,errors:h,isPristine:x,isValid:g,isDefaultValue:w};}return Object.keys(i.fieldMetaBase).length&&n&&d===Object.keys(i.fieldMetaBase).length?n:m}}),this.store=new Ut({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,c=a?.[0],i=s[0],d=s[1],m=Object.values(d).filter(Boolean),f=m.some(E=>E.isValidating),l=m.every(E=>E.isValid),u=m.some(E=>E.isTouched),p=m.some(E=>E.isBlurred),v=m.every(E=>E.isDefaultValue),h=u&&i.errorMap?.onMount,g=m.some(E=>E.isDirty),x=!g,w=!!(i.errorMap?.onMount||m.some(E=>E?.errorMap?.onMount)),b=!!f,C=n?.errors??[];(!c||i.errorMap!==c.errorMap)&&(C=Object.values(i.errorMap).reduce((E,_)=>_===void 0?E:_&&vr(_)?(E.push(_.form),E):(E.push(_),E),[]));let M=C.length===0,k=l&&M,y=this.options.canSubmitWhenInvalid??false,S=i.submissionAttempts===0&&!u&&!w||!b&&!i.isSubmitting&&k||y,B=i.errorMap;if(h&&(C=C.filter(E=>E!==i.errorMap.onMount),B=Object.assign(B,{onMount:void 0})),n&&c&&n.errorMap===B&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===f&&n.isFieldsValid===l&&n.isFormValid===M&&n.isValid===k&&n.canSubmit===S&&n.isTouched===u&&n.isBlurred===p&&n.isPristine===x&&n.isDefaultValue===v&&n.isDirty===g&&Ia(c,i))return n;let A={...i,errorMap:B,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:f,isFieldsValid:l,isFormValid:M,isValid:k,canSubmit:S,isTouched:u,isBlurred:p,isPristine:x,isDefaultValue:v,isDirty:g},R=this.options.transform?.deps??[];if(R.length!==this.prevTransformArray.length||R.some((E,_)=>E!==this.prevTransformArray[_])){let E=Object.assign({},this,{state:A});this.options.transform?.fn(E),A=E.state,this.prevTransformArray=R;}return A}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=ol(a=>vt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),vt.on("request-form-state",a=>{a.payload.id===this._formId&&vt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),vt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),vt.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 Qs(o.validate)?ka[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})),xt(()=>{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}),vt.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}),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}xt(()=>{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}),xt(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){xt(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(vr(a)){let{formError:r,fieldErrors:n}=en(a);for(let c of Object.keys(this.fieldInfo))this.getFieldMeta(c)&&this.setFieldMeta(c,d=>({...d,errorMap:{...d.errorMap,[s]:n?.[c]},errorSourceMap:{...d.errorSourceMap,[s]:"form"}}));this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function en(e){if(e){if(vr(e)){let o=en(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=Sa(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,je(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,je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,je(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:c}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&c?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Po(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ca}),n=this.getLinkedFields(t).reduce((d,m)=>{let f=Po(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Ca});return f.forEach(l=>{l.field=m;}),d.concat(f)},[]),c=false;xt(()=>{let d=(m,f)=>{let l=tn(f.cause),u=f.validate?ju(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}=Zs({formLevelError:p,fieldLevelError:u});m.state.meta.errorMap?.[l]!==v&&m.setMeta(g=>({...g,errorMap:{...g.errorMap,[l]:v},errorSourceMap:{...g.errorSourceMap,[l]:h}})),v&&(c=!0);};for(let m of s)d(this,m);for(let m of n)m.validate&&d(m.field,m);});let i=tn("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!c&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[i]:void 0},errorSourceMap:{...d.errorSourceMap,[i]:void 0}})),{hasErrored:c}},this.validateAsync=async(t,a)=>{let s=Do(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ca}),r=await a,n=this.getLinkedFields(t),c=n.reduce((l,u)=>{let p=Do(t,{...u.options,form:u.form,validationLogic:u.form.options.validationLogic||Ca});return p.forEach(v=>{v.field=u;}),l.concat(p)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of n)l.setMeta(u=>({...u,isValidating:true}));let i=[],d=[],m=(l,u,p)=>{let v=tn(u.cause);l.getInfo().validationMetaMap[v]?.lastAbortController.abort();let g=new AbortController;this.getInfo().validationMetaMap[v]={lastAbortController:g},p.push(new Promise(async x=>{let w;try{w=await new Promise((y,S)=>{this.timeoutIds.validations[u.cause]&&clearTimeout(this.timeoutIds.validations[u.cause]),this.timeoutIds.validations[u.cause]=setTimeout(async()=>{if(g.signal.aborted)return y(void 0);try{y(await this.runValidator({validate:u.validate,value:{value:l.store.state.value,fieldApi:l,signal:g.signal,validationSource:"field"},type:"validateAsync"}));}catch(B){S(B);}},u.debounceMs);});}catch(y){w=y;}if(g.signal.aborted)return x(void 0);let b=ju(w),C=r[this.name]?.[v],{newErrorValue:M,newSource:k}=Zs({formLevelError:C,fieldLevelError:b});l.setMeta(y=>({...y,errorMap:{...y?.errorMap,[v]:M},errorSourceMap:{...y.errorSourceMap,[v]:k}})),x(M);}));};for(let l of s)l.validate&&m(this,l,i);for(let l of c)l.validate&&m(l.field,l,d);let f=[];(i.length||d.length)&&(f=await Promise.all(i),await Promise.all(d)),this.setMeta(l=>({...l,isValidating:false}));for(let l of n)l.setMeta(u=>({...u,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[tn(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=>ka.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ka.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Ut({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Ro,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Qs(o.validate)?ka[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 ju(e){if(e)return e}function tn(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function an(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Ox)}function Ox(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=Xu(e);if(t.length!==Xu(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 Xu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Eo=typeof window<"u"?useLayoutEffect:useEffect;function Wx(e){let[o]=useState(()=>{let a=new Sr({...e,form:e.form,name:e.name});return a.Field=ul,a});return Eo(o.mount,[o]),Eo(()=>{o.update(e);}),an(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var ul=(({children:e,...o})=>{let t=Wx(o),a=useMemo(()=>La(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function _x({form:e,selector:o,children:t}){let a=an(e.store,o);return La(t,a)}function cl(e){let o=useId(),[t]=useState(()=>{let a=new Lr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(ul,{...n,form:a})},s.Subscribe=function(n){return jsx(_x,{form:a,selector:n.selector,children:n.children})},s});return Eo(t.mount,[]),Eo(()=>{t.update(e);}),t}function fl({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 ab=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),s=ze(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[c,i]=useState(n),d=cl({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 u={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?ma(u):si(u));}else if(l.questionType==="multiple-choice"){let u={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?fa(u):ri(u));}else if(l.questionType==="short-answer"){let u={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(u):ni(u));}else if(l.questionType==="fill-in-the-blank"){let u={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(u):li(u));}else if(l.questionType==="long-answer"){let u={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(u):ii(u));}o(pa(false));}}),m=()=>{o(pa(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(),d.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(d.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:u=>{l.handleChange(u.target.value),i(u.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(fl,{field:l})]})}),c&&!["short-answer","fill-in-the-blank","long-answer"].includes(c)&&jsx(d.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:u=>l.handleChange(u.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(fl,{field:l})]})})]}),jsx(d.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 ${c==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:c==="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:c==="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"})]})]}),c==="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(fl,{field:l})]})}),jsx(d.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:u=>l.handleChange(u.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(", ")})]})}),c==="true-false"&&jsx(d.Field,{name:"responseOptions.correctAnswer",children:l=>{let u=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 ${u===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"}),u===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 ${u===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"}),u===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"})]})}}),c==="multiple-choice"&&jsx(d.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 u=(g,x)=>{let w=[...l.state.value.options];w[g]=x,l.handleChange({...l.state.value,options:w});},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=g=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let x=l.state.value.options.filter((b,C)=>C!==g),w=l.state.value.correctIndex?.filter(b=>b!==g).map(b=>b>g?b-1:b);l.handleChange({...l.state.value,options:x,correctIndex:w});},h=g=>{let x=l.state.value.correctIndex||[];if(x.includes(g))l.handleChange({...l.state.value,correctIndex:x.filter(b=>b!==g)});else {if(x.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...x,g]});}};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((g,x)=>{let w=!g.trim(),b=l.state.value.correctIndex?.includes(x),C=l.state.meta.isTouched&&w;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(x),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${b?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:b&&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":b?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${x+1}`,value:g,onChange:M=>u(x,M.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(x),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"})})]},x)})}),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"})]})]})}}),(c==="short-answer"||c==="fill-in-the-blank")&&jsx(d.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:u=>{l.handleChange(u.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(", ")})]})}),c==="long-answer"&&jsx(d.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:u=>{l.handleChange(u.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(d.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,u])=>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:u?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,s)},Ju=ab;var tc=({text:e,position:o})=>{let t=xe(),a=d=>{t(ce()),t(Tt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},s=d=>{t(ce()),t(Tt({id:e.id,fill:d}));},r=()=>{t(ce()),t(Tt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ce()),t(Tt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},c=()=>{t(ce()),t(Tt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},i=d=>{t(ce()),t(Tt({id:e.id,fontFamily:d}));};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:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>i(d.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:c,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:d=>s(d.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 oc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{let c=useRef(null),i=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]),d=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(`
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 {createPortal}from'react-dom';import {Group,Image as Image$1,Line,Rect,Arc,Arrow,Wedge,Ring,Ellipse,RegularPolygon,Star,Circle,Text,Stage,Layer,Transformer}from'react-konva';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 {useSelector,useDispatch}from'react-redux';export{Provider as ReduxProvider}from'react-redux';import {createSlice,createSelector,configureStore}from'@reduxjs/toolkit';import Cd from'perfect-freehand';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Html}from'react-konva-utils';import {EyeIcon,Stack as Stack$1,X as X$2,DotsSixVertical,Question,FrameCorners,Cards as Cards$1,TextT,Shapes as Shapes$1,VideoCamera,Image as Image$3}from'@phosphor-icons/react';import ku 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 hd=e=>{throw TypeError(e)};var gd=(e,o,t)=>o.has(e)||hd("Cannot "+t);var K=(e,o,t)=>(gd(e,o,"read from private field"),t?t.call(e):o.get(e)),De=(e,o,t)=>o.has(e)?hd("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(e):o.set(e,t),ke=(e,o,t,a)=>(gd(e,o,"write to private field"),o.set(e,t),t);var xd=(e,o,t,a)=>({set _(s){ke(e,o,s);},get _(){return K(e,o,a)}});var xe=()=>useDispatch(),ee=e=>useSelector(e),it=xe,et=ee;var Nn=20,qn=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}),On=qn("Slide 1"),Xm={slides:[On],currentSlideId:On.id,history:{[On.id]:{past:[],future:[]}},isSketchMode:true,editingTextId:null,presentationMetadata:{title:"Untitled",description:"This is the description of the presentation."},metadataLoaded:false,viewerMode:false},bd=createSlice({name:"canvas",initialState:Xm,reducers:{addSlide:e=>{if(e.slides.length>=Nn)return;let o=qn(`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(c=>c.isActive).length<=1)return;let r=e.slides.findIndex(c=>c.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 c=e.slides.filter(i=>i.isActive);c.length>0&&(e.currentSlideId=c[0].id);}},duplicateSlide:(e,o)=>{if(e.slides.length>=Nn)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);},setViewerMode:(e,o)=>{e.viewerMode=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(x=>x.id===a);n&&(n.timestamp=r);break;case "video":let c=t.videos.find(x=>x.id===a);c&&(c.timestamp=r);break;case "shape":let i=t.shapes.find(x=>x.id===a);i&&(i.timestamp=r);break;case "text":let d=t.texts.find(x=>x.id===a);d&&(d.timestamp=r);break;case "flashcard":let m=t.flashcards.find(x=>x.id===a);m&&(m.timestamp=r);break;case "photoFrame":let f=t.photoFrames.find(x=>x.id===a);f&&(f.timestamp=r);break;case "mcq":let l=t.multipleChoices.find(x=>x.id===a);l&&(l.timestamp=r);break;case "trueFalse":let u=t.trueFalses.find(x=>x.id===a);u&&(u.timestamp=r);break;case "shortAnswer":let p=t.shortAnswers.find(x=>x.id===a);p&&(p.timestamp=r);break;case "longAnswer":let v=t.LongAnswer.find(x=>x.id===a);v&&(v.timestamp=r);break;case "fillInTheBlanks":let h=t.fillInTheBlanks.find(x=>x.id===a);h&&(h.timestamp=r);break;case "line":let g=t.lines.find(x=>x.id===a);g&&(g.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(c=>c.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,c=(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(i=>i.id===a);c&&(c.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,c=(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);c&&(c.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,c=(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);c&&(c.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:Hn,deleteSlide:Un,duplicateSlide:Wn,setCurrentSlide:zn,setViewerMode:$m,updateSlideThumbnail:Gn,setBackgroundColor:Kn,reorderSlides:Ym,loadSlides:no,addLine:_n,removeLine:Zr,addImage:jn,updateImage:io,deleteImage:Qr,duplicateImage:es,addVideo:ts,updateVideo:as,deleteVideo:os,duplicateVideo:rs,toggleVideoPlaying:Oa,addShape:Xn,updateShape:lo,duplicateShape:ss,deleteShape:ns,addText:$n,updateText:Tt,deleteText:is,duplicateText:ls,addFlashcard:Yn,updateFlashcard:uo,deleteFlashcard:ds,duplicateFlashcard:us,editFlashcard:Xo,nextFlashcard:Jn,previousFlashcard:Zn,addPhotoFrame:Qn,updatePhotoFrame:Na,deletePhotoFrame:cs,duplicatePhotoFrame:fs,toggleImageDrawingMode:ei,addImageAnnotation:ti,updateImageAnnotation:Jm,clearImageAnnotations:Zm,togglePhotoFrameDrawingMode:ai,addPhotoFrameAnnotation:oi,updatePhotoFrameAnnotation:Qm,clearPhotoFrameAnnotations:ep,addMultipleChoice:ri,updateMultipleChoice:fa,editMultipleChoice:tp,deleteMultipleChoice:ms,duplicateMultipleChoice:ps,addTrueFalse:si,updateTrueFalse:ma,deleteTrueFalse:hs,duplicateTrueFalse:gs,addShortAnswer:ni,updateShortAnswer:$o,deleteShortAnswer:xs,duplicateShortAnswer:bs,addLongAnswer:ii,updateLongAnswer:Yo,deleteLongAnswer:vs,duplicateLongAnswer:ys,addFillInTheBlanks:li,updateFillInTheBlanks:Jo,deleteFillInTheBlanks:ws,duplicateFillInTheBlanks:Ls,setShowMcqForm:pa,setShowFlashcardForm:Va,setActivityType:di,setEditingActivity:Zo,bringToFront:ui,sendToBack:ci,toggleLock:fi,setLink:Ss,setAltText:Is,setAudioData:Cs,updateLastLine:ap,finalizeDrawing:mi,setLines:op,updateLinePosition:rp,updateLineTransform:ks,deleteLineById:Ms,duplicateLine:pi,updateElementOrder:Qo,clearCanvas:hi,undo:gi,redo:xi,saveToHistory:ce,toggleSketchMode:sp,setSketchMode:pt,setEditingTextId:er,setPresentationTitle:bi,setPresentationDescription:vi,loadPresentationMetadata:yi,setMetadataLoaded:Ts}=bd.actions;var vd=e=>e.canvas.slides,co=e=>e.canvas.currentSlideId,ge=createSelector([vd,co],(e,o)=>e.find(t=>t.id===o)),fo=createSelector([vd],e=>e.filter(o=>o.isActive!==false)),wi=e=>e.canvas.slides,Li=createSelector([fo],e=>e.length<Nn),np=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,Si=e=>e.canvas.metadataLoaded,As=e=>e.canvas.viewerMode,yd=bd.reducer;var Ld=e=>{let o=xe(),t=useRef(null),a=useRef(false),s=ee(u=>u.toolbar.selectedTool),r=ee(u=>u.toolbar.penColor),n=ee(u=>u.toolbar.strokeWidth),c=ee(u=>u.canvas.isSketchMode),i=ee(u=>u.canvas.slides.find(v=>v.id===u.canvas.currentSlideId)?.lines||[]),d=useCallback(u=>{t.current=u;},[]),m=useCallback(u=>{s==="pen"&&t.current&&(o(ce()),t.current.startDrawing(u),a.current=true);},[s,o]),f=useCallback(u=>{!t.current||!a.current||t.current.draw(u);},[]),l=useCallback(()=>{if(!t.current||!a.current)return;let u=t.current.stopDrawing();a.current=false,u&&u.points.length>=4&&o(_n(u)),o(mi()),e?.();},[o,e]);return {lines:i,tool:s,color:r,strokeWidth:n,isSketchMode:c,setCanvasRef:d,startDrawing:m,draw:f,stopDrawing:l}};var kd=forwardRef(({width:e,height:o,tool:t,color:a,strokeWidth:s,isSketchMode:r,style:n,xOffset:c=0,yOffset:i=0},d)=>{let m=useRef(null),f=useRef(false),l=useRef([]),u=useRef([]),p=useRef(null),v=useRef(t),h=useRef(a),g=useRef(s),x=useRef(r),w=useRef(c),b=useRef(i);useEffect(()=>{v.current=t,h.current=a,g.current=s,x.current=r,w.current=c,b.current=i;},[t,a,s,r,c,i]);let C=useCallback(()=>{let k=m.current;if(!k)return;let y=k.getContext("2d");y&&y.clearRect(0,0,k.width,k.height);},[]),M=useCallback(()=>{let k=m.current,y=u.current;if(!k||y.length<1)return;let S=k.getContext("2d");if(!S)return;if(S.clearRect(0,0,k.width,k.height),v.current==="eraser"?(S.globalCompositeOperation="destination-out",S.fillStyle="rgba(0,0,0,1)"):(S.globalCompositeOperation="source-over",S.fillStyle=h.current),y.length===1){S.beginPath(),S.arc(y[0].x,y[0].y,g.current/2,0,Math.PI*2),S.fill();return}let A=Cd(y,{size:g.current,thinning:.5,smoothing:.5,streamline:.5,simulatePressure:true,easing:R=>R,start:{taper:0,cap:true},end:{taper:0,cap:true}});if(!(A.length<2)){S.beginPath(),S.moveTo(A[0][0],A[0][1]);for(let R=1;R<A.length;R++)S.lineTo(A[R][0],A[R][1]);S.closePath(),S.fill();}},[]);return useImperativeHandle(d,()=>({startDrawing:k=>{f.current=true;let y={x:k.x-w.current,y:k.y-b.current};l.current=[{x:k.x,y:k.y}],u.current=[y],p.current=k,M();},draw:k=>{if(!f.current||!p.current)return;let y=k.x-p.current.x,S=k.y-p.current.y;if(Math.sqrt(y*y+S*S)<2)return;let A={x:k.x-w.current,y:k.y-b.current};l.current.push({x:k.x,y:k.y}),u.current.push(A),p.current=k,M();},stopDrawing:()=>{if(!f.current)return null;if(f.current=false,l.current.length<2)return l.current=[],u.current=[],p.current=null,C(),null;let y=Cd(l.current,{size:g.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]]),S={tool:v.current,points:y,color:h.current,strokeWidth:g.current,isSketch:true};return l.current=[],u.current=[],p.current=null,C(),S},clear:()=>{C(),l.current=[],u.current=[],p.current=null,f.current=false;},isDrawing:()=>f.current,getCanvasElement:()=>m.current}),[C,M]),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}})});kd.displayName="DirectDrawingCanvas";var Md=kd;var Ad=e=>{let o=xe(),a=ee(ge)?.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 c=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},[]),i=useCallback((m,f)=>{let l=m.target,u=l.id();a.find(v=>v.id===u)&&(o(io({id:u,x:l.x(),y:l.y(),width:l.width(),height:l.height(),rotation:l.rotation()})),f?.());},[a,o]),d=useCallback((m,f)=>{let l=f.target,u=s.current.get(m);if(!u){console.error("\u274C Image node not found for id:",m);return}let p=l.scaleX(),v=l.scaleY(),h=l.rotation(),g=u.width(),x=u.height(),w=Math.max(5,g*p),b=Math.max(5,x*v);l.scaleX(1),l.scaleY(1),u.width(w),u.height(b),o(io({id:m,width:w,height:b,x:l.x(),y:l.y(),rotation:h})),l.getLayer()?.batchDraw(),e?.();},[o,e]);return {images:a,getLoadedImage:c,imageRefs:s,handleDragEnd:i,handleImageTransformEnd:d}};var Pd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),s=useMemo(()=>t?.multipleChoices||[],[t?.multipleChoices]),r=useCallback((c,i)=>{let d=i.target,m=d.scaleX(),f=d.scaleY(),l=d.rotation(),u=Math.max(5,d.width()*m),p=Math.max(5,d.height()*f);d.scaleX(1),d.scaleY(1),d.width(u),d.height(p),o(fa({id:c,width:u,height:p,x:d.x(),y:d.y(),rotation:l})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {multipleChoice:s,handleMcqTransform:r,mcqRefs:a,handleDragEnd:(c,i)=>{o(fa({id:i,x:c.target.x(),y:c.target.y()})),e?.();}}};var Dd=e=>{let o=useDispatch(),t=useSelector(ge),a=useRef(new Map),s=useMemo(()=>t?.trueFalses||[],[t?.trueFalses]),r=useCallback((c,i)=>{let d=i.target,m=d.scaleX(),f=d.scaleY(),l=d.rotation(),u=Math.max(5,d.width()*m),p=Math.max(5,d.height()*f);d.scaleX(1),d.scaleY(1),d.width(u),d.height(p),o(ma({id:c,width:u,height:p,x:d.x(),y:d.y(),rotation:l})),d.getLayer()?.batchDraw(),e?.();},[o,e]);return {trueFalse:s,handleTrueFalseTransform:r,handleTrueFalseDragEnd:(c,i)=>{o(ma({id:i,x:c.target.x(),y:c.target.y()})),e?.();},trueFalseRefs:a}};var Rd=e=>{let o=xe(),a=ee(ge)?.videos||[],s=useRef(new Map),r=useCallback(i=>{o(Oa(i));},[o]),n=useCallback((i,d)=>{let m=d.target;o(as({id:i,x:m.x(),y:m.y()})),e?.();},[o,e]),c=useCallback((i,d)=>{let m=d.target,f=m.scaleX(),l=m.scaleY(),u=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(as({id:i,width:p,height:v,x:m.x(),y:m.y(),rotation:u})),m.getLayer()?.batchDraw(),e?.();},[o,e]);return {videos:a,videoRefs:s,handleVideoClick:r,handleVideoDragEnd:n,handleVideoTransformEnd:c}};var Bd=e=>{let o=xe(),a=ee(ge)?.shapes||[],s=useRef(new Map),r=useRef(new Map),[n,c]=useState(false),i=useCallback((m,f)=>{let l=f.target;o(lo({id:m,x:l.x(),y:l.y()})),e?.();},[o,e]),d=useCallback((m,f)=>{let l=f.target,u=a.find(w=>w.id===m);if(!u)return;let p=l.scaleX(),v=l.scaleY(),h=u.type?.toLowerCase();h==="arrow"||h==="line"||(l.scaleX(1),l.scaleY(1));let x={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":x.radius=l.width()*p/2;break;case "star":x.innerRadius=l.width()*p/4,x.outerRadius=l.width()*p/2;break;case "triangle":x.radius=l.width()*p/2;break;case "ellipse":x.radiusX=l.width()*p/2,x.radiusY=l.height()*v/2;break;case "polygon":x.radius=l.width()*p/2;break;case "ring":let w=p;x.innerRadius=u.innerRadius&&u.innerRadius*w,x.outerRadius=u.outerRadius&&u.outerRadius*w;break;case "wedge":x.radius=u.radius&&u.radius*p;break;case "arc":x.innerRadius=u.innerRadius&&u.innerRadius*p,x.outerRadius=u.outerRadius&&u.outerRadius*p;break;case "arrow":case "line":{x.scaleX=p,x.scaleY=v,delete x.width,delete x.height;break}}o(lo(x)),e?.();},[o,e,a]);return {shapes:a,shapeRefs:s,isDragging:n,loadedShapesRef:r,handleShapeDragEnd:i,handleShapeResizeEnd:d}};var Nd=(e,o)=>{let t=it(),s=ee(ge)?.texts||[],r=useRef(new Map),[n,c]=useState(null),[i,d]=useState("");return {texts:s,textRefs:r,handleDragEnd:(h,g)=>{let x=h.target;t(ce()),t(Tt({id:g,x:x.x(),y:x.y()})),e();},handleTransformEnd:h=>{let g=r.current.get(h);if(!g)return;let x=g.scaleX(),w=g.scaleY(),b=s.find(M=>M.id===h);if(!b)return;let C=(x+w)/2;g.scaleX(1),g.scaleY(1),t(ce()),t(Tt({id:h,x:g.x(),y:g.y(),width:Math.max(5,(b.width||100)*x),height:Math.max(5,(b.height||50)*w),fontSize:Math.round(Math.max(8,b.fontSize*C)),rotation:g.rotation()})),e();},handleDoubleClick:h=>{let g=s.find(x=>x.id===h);g&&!g.locked&&(c(h),d(g.text));},startEditing:h=>{let g=s.find(x=>x.id===h);g&&!g.locked&&(c(h),d(g.text));},editingTextId:n,editingValue:i,handleEditingChange:h=>{d(h);},finishEditing:()=>{if(n){let h=r.current.get(n),g=s.find(w=>w.id===n);t(ce());let x={id:n,text:i};if(g&&(g.fontWeight!==void 0&&(x.fontWeight=g.fontWeight),g.fontStyle!==void 0&&(x.fontStyle=g.fontStyle),g.textDecoration!==void 0&&(x.textDecoration=g.textDecoration)),o?.current&&i.trim()){let w=o.current,b=w.offsetWidth,C=w.offsetHeight,M=1;if(h){let _=h.getStage();_&&(M=_.scaleX());}let k=14,y=(b-k)/M,S=(C-k)/M,B=i.split(`
3
+ `).length,R=s.find(_=>_.id===n)?.fontSize||24,E=B*R*1.2+10;x.width=Math.max(200,y),x.height=Math.max(50,S,E);}else if(h&&i.trim()){let w=h.text(),b=h.width();h.text(i),h.width(void 0);let C=h.width(),M=h.height();h.text(w),h.width(b),x.width=Math.max(200,C+20),x.height=Math.max(50,M+20);}t(Tt(x)),c(null),d(""),t(er(null)),e();}}}};var Vd=e=>{let o=useDispatch(),a=useSelector(ge)?.shortAnswers||[],s=useRef(new Map),r=useCallback((n,c)=>{let i=n.target;o($o({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {shortAnswers:a,saRefs:s,handleShortAnswerDragEnd:r}};var qd=e=>{let o=useDispatch(),t=useSelector(ge),a=useMemo(()=>t?.LongAnswer||[],[t?.LongAnswer]),s=useCallback((r,n)=>{let c=r.target;o(Yo({id:n,x:c.x(),y:c.y()})),e?.();},[o,e]);return {longAnswers:a,handleLongAnswerDragEnd:s}};var Ud=e=>{let o=xe(),a=ee(ge)?.flashcards||[],s=useRef(new Map),r=useRef(new Map),n=useCallback((f,l)=>{if(r.current.has(l))return r.current.get(l);let u=new window.Image;return (f.startsWith("http://")||f.startsWith("https://"))&&(u.crossOrigin="anonymous"),u.src=f,r.current.set(l,u),u},[]),c=useCallback((f,l)=>{let u=f.target,p=u.id();a.find(h=>h.id===p)&&(o(uo({id:p,x:u.x(),y:u.y()})),l?.());},[a,o]),i=useCallback((f,l)=>{let u=l.target,p=u.scaleX(),v=u.scaleY(),h=u.rotation(),g=Math.max(50,u.width()*p),x=Math.max(50,u.height()*v);u.scaleX(1),u.scaleY(1),u.width(g),u.height(x),o(uo({id:f,width:g,height:x,x:u.x(),y:u.y(),rotation:h})),u.getLayer()?.batchDraw(),e?.();},[o,e]),d=useCallback(f=>{o(Jn(f)),e?.();},[o,e]),m=useCallback(f=>{o(Zn(f)),e?.();},[o,e]);return {flashcards:a,getLoadedImage:n,flashcardRefs:s,handleDragEnd:c,handleFlashcardTransformEnd:i,handleNext:d,handlePrevious:m}};var Gd=e=>{let o=xe(),a=ee(ge)?.photoFrames||[],s=useRef(new Map),[r,n]=useState(new Map),c=useCallback((u,p)=>{console.log("handleDragEnd"),o(Na({id:p,x:u.target.x(),y:u.target.y()})),e?.();},[o,e]),i=useCallback((u,p)=>{let v=p.target,h=v.scaleX(),g=v.scaleY(),x=v.rotation(),w=a.find(M=>M.id===u);if(!w)return;let b=Math.max(100,w.width*h),C=Math.max(100,w.height*g);v.scaleX(1),v.scaleY(1),o(Na({id:u,width:b,height:C,x:v.x(),y:v.y(),rotation:x})),v.getLayer()?.batchDraw(),e?.();},[o,e,a]),d=useCallback(async u=>{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(u,p),h}),o(Na({id:u,isCapturing:!0})),e?.(),p}catch(p){return console.error("Error accessing camera:",p),null}},[o,e]),m=useCallback(u=>{let p=r.get(u);p&&(p.getTracks().forEach(v=>v.stop()),n(v=>{let h=new Map(v);return h.delete(u),h}),o(Na({id:u,isCapturing:false})),e?.());},[r,o,e]),f=useCallback((u,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 g=v.toDataURL("image/jpeg",.8);return o(Na({id:u,capturedImageUrl:g,isCapturing:false})),m(u),e?.(),g}return null},[o,m,e]),l=useRef(r);return useEffect(()=>{l.current=r;},[r]),useEffect(()=>()=>{l.current.forEach(u=>{u.getTracks().forEach(p=>p.stop());});},[]),{photoFrames:a,photoFrameRefs:s,handleDragEnd:c,handlePhotoFrameTransformEnd:i,startCamera:d,stopCamera:m,capturePhoto:f,cameraStreams:r}};var Kd=()=>{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,c,i,d,m,f,l=[])=>{if(e.current){if(r&&!l.find(v=>v.id===r)?.isPlaying){let v=n.get(r)||c.get(r)||i.get(r)||d.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 Fp=(e,o)=>{let t=useRef(void 0);return useEffect(()=>()=>{t.current&&clearTimeout(t.current);},[]),useCallback((...a)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{e(...a);},o);},[o])},$d=(e,o)=>{let t=it(),a=et(As),s=useRef(e);useEffect(()=>{s.current=e;},[e]);let r=useCallback(()=>{if(!(!o.current||a))try{let c=o.current.toDataURL({pixelRatio:1,mimeType:"image/jpeg",quality:.6});c&&c.startsWith("data:")&&t(Gn({id:s.current,thumbnail:c}));}catch(c){console.warn("Could not generate thumbnail (likely CORS issue with images):",c);}},[o,t,a]),n=Fp(r,500);return {generateThumbnail:r,debouncedGenerateThumbnail:n}};var Op=e=>e.flatMap(o=>[o[0],o[1]]),Ds=(e,o)=>{let t=Cd(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 Op(t)};var Yd=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null),c=ee(w=>w.toolbar.selectedTool),i=ee(w=>w.toolbar.penColor),d=ee(w=>w.toolbar.strokeWidth),m=ee(w=>w.canvas.isSketchMode),f=ee(w=>w.canvas.slides.find(C=>C.id===w.canvas.currentSlideId)?.images.find(C=>C.id===e)),l=f?.annotations||[],u=f?.isDrawingMode||false,p=f?.width||1,v=f?.height||1,h=useCallback(w=>{if(c!=="pen"&&c!=="eraser")return;t.current=true,a.current=false,s.current=[{x:w.x,y:w.y}];let b=w.x/p,C=w.y/v;n({tool:c,points:[b,C],color:i,strokeWidth:d/p,isSketch:m});},[c,i,d,m,p,v]),g=useCallback(w=>{if(!t.current||!r)return;a.current=true;let b=s.current[s.current.length-1];if(Math.sqrt(Math.pow(w.x-b.x,2)+Math.pow(w.y-b.y,2))<2)return;s.current.push({x:w.x,y:w.y});let M;if(m)M=Ds(s.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,S)=>S%2===0?y/p:y/v);else {let k=w.x/p,y=w.y/v;M=[...r.points,k,y];}n(k=>k?{...k,points:M}:null);},[m,d,r,p,v]),x=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(ti({imageId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:u,startDrawing:h,draw:g,stopDrawing:x,tool:c}};var eu=memo(({img:e,loadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>{let{annotations:c,activeLine:i,stopDrawing:l,tool:u}=Yd(e.id);useEffect(()=>{let x=t.current.get(e.id);x&&(x.width()!==e.width||x.height()!==e.height)&&(console.log("\u{1F504} Syncing dimensions from Redux to Konva:",{id:e.id,reduxWidth:e.width,reduxHeight:e.height,konvaWidth:x.width(),konvaHeight:x.height()}),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw());},[e.id,e.width,e.height,t]);let p=false;useEffect(()=>{return;},[l,p]);let v=x=>{{r(e.id);return}},h=x=>{return;},g=x=>{};return jsxs(Group,{listening:u!=="pen"&&u!=="eraser",children:[jsx(Image$1,{id:e.id,ref:x=>{if(x){t.current.set(e.id,x),x.width(e.width),x.height(e.height),x.getLayer()?.batchDraw();let w=x.getStage()?.container();if(w){let b=C=>{let M=x.getStage()?.getPointerPosition();if(M){let k={x:e.x,y:e.y,width:e.width,height:e.height};M.x>=k.x&&M.x<=k.x+k.width&&M.y>=k.y&&M.y<=k.y+k.height&&n(C,e.id,"image");}};w.addEventListener("contextmenu",b),x._contextMenuCleanup=()=>{w.removeEventListener("contextmenu",b);};}}else {let w=t.current.get(e.id);w?._contextMenuCleanup&&w._contextMenuCleanup(),t.current.delete(e.id);}},rotation:e.rotation,draggable:u!=="pen"&&u!=="eraser",onDragEnd:a,onTransformEnd:x=>s(e.id,x),image:o,x:e.x,y:e.y,width:e.width,height:e.height,...u!=="pen"&&u!=="eraser"?{onClick:v,onTap:v,onMouseDown:v,onTouchStart:v,onMouseMove:h,onTouchMove:h,onMouseUp:g,onTouchEnd:g}:{}}),c?.map((x,w)=>{let b=x.points.map((M,k)=>k%2===0?M*e.width+e.x:M*e.height+e.y),C=x.strokeWidth*e.width;return jsx(Line,{points:b,stroke:x.tool==="eraser"?"white":x.color,strokeWidth:C,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:x.tool==="eraser"?"destination-out":"source-over",fill:x.isSketch?x.color:void 0,closed:x.isSketch,listening:false},w)}),i&&jsx(Line,{points:i.points.map((x,w)=>w%2===0?x*e.width+e.x:x*e.height+e.y),stroke:i.tool==="eraser"?"white":i.color,strokeWidth:i.strokeWidth*e.width,tension:.5,lineCap:"round",lineJoin:"round",globalCompositeOperation:i.tool==="eraser"?"destination-out":"source-over",fill:i.isSketch?i.color:void 0,closed:i.isSketch,listening:false},"active")]})});eu.displayName="ImageWithDrawing";var Pi=memo(({images:e,getLoadedImage:o,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(c=>{let i=o(c);return i?jsx(eu,{img:c,loadedImage:i,imageRefs:t,onDragEnd:a,onTransform:s,onSelect:r,onContextMenu:n},c.id):null})}));Pi.displayName="ImageLayer";var _p=({src:e,x:o,id:t,y:a,width:s,height:r,isSelected:n,rotation:c=0,onTransformEnd:i,onDragEnd:d})=>{let m=xe(),f=useRef(null),l=u=>{m(Oa(u));};return jsxs(Group,{draggable:true,x:o,y:a,width:s,height:r,rotation:c,onDragEnd:d,onTransformEnd:i,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:u=>u.stopPropagation(),style:{width:"100%",height:"100%",objectFit:"contain",pointerEvents:"auto"}})})]})},tu=_p;var eh=({video:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,nodeRef:n})=>{let[c,i]=useState(null),d=useSelector(v=>v.toolbar.selectedTool),m=d==="pen"||d==="eraser";if(useEffect(()=>{if(e.thumbnailDataUrl){let v=new window.Image;(e.thumbnailDataUrl.startsWith("http://")||e.thumbnailDataUrl.startsWith("https://"))&&(v.crossOrigin="anonymous"),v.src=e.thumbnailDataUrl,v.onload=()=>{i(v);};}},[e.thumbnailDataUrl]),!c)return null;let f=e.width/2,l=e.height/2,u=Math.min(e.width,e.height)*.08,p=Math.max(40,Math.min(u,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 g=x=>{let w=v.getStage()?.getPointerPosition();if(w){let b={x:e.x,y:e.y,width:e.width,height:e.height};w.x>=b.x&&w.x<=b.x+b.width&&w.y>=b.y&&w.y<=b.y+b.height&&r(x);}};h.addEventListener("contextmenu",g),v._contextMenuCleanup=()=>{h.removeEventListener("contextmenu",g);};}}},children:[jsx(Image$1,{image:c,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}})]})},ou=eh;var Ei=memo(({videos:e,selectedId:o,videoRefs:t,onVideoClick:a,onDragEnd:s,onTransformEnd:r,onContextMenu:n})=>jsx(Fragment,{children:e.map(c=>jsxs(be__default.Fragment,{children:[jsx(ou,{video:c,isSelected:!c.isPlaying&&o===c.id,onClick:()=>a(c.id),onDragEnd:i=>s(c.id,i),onTransformEnd:i=>r(c.id,i),onContextMenu:i=>n(i,c.id,"video"),nodeRef:i=>{i?t.current.set(c.id,i):t.current.delete(c.id);}}),c.isPlaying&&!c.isRecorded&&jsx(tu,{id:c.id,src:c.objectUrl,x:c.x,y:c.y,width:c.width,height:c.height,isSelected:false,rotation:c.rotation,onTransformEnd:i=>r(c.id,i),onDragEnd:i=>s(c.id,i)})]},c.id))}));Ei.displayName="VideoLayer";var Fi=memo(({shapes:e,shapeRefs:o,handleShapeDragEnd:t,handleShapeResizeEnd:a,onSelect:s,handleShapeDragStart:r,onContextMenu:n})=>{let c=useSelector(d=>d.toolbar.selectedTool),i=c==="pen"||c==="eraser";return jsx(Fragment,{children:e.map((d,m)=>{let f=d.id||m,l={id:d.id,x:d.x,y:d.y,rotation:d.rotation,draggable:!d.locked&&!i,listening:!i,fill:d.color||"#096B76",stroke:"#000000",strokeWidth:2,opacity:1};switch(d.type?.toLowerCase()){case "circle":return jsx(Circle,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radius:d.radius||d.width/2,width:d.width,height:d.width},f);case "star":return jsx(Star,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},numPoints:5,innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "triangle":return jsx(RegularPolygon,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},sides:3,radius:d.radius||d.width/2},f);case "polygon":return jsx(RegularPolygon,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},sides:d.sides||6,radius:d.radius||d.width/2},f);case "ellipse":return jsx(Ellipse,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radiusX:d.radiusX||d.width/2,radiusY:d.radiusY||d.height/2},f);case "ring":return jsx(Ring,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2},f);case "wedge":return jsx(Wedge,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},radius:d.radius||d.width/2,angle:d.angle||60},f);case "arrow":return jsx(Arrow,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],pointerLength:d.pointerLength||10,pointerWidth:d.pointerWidth||10,stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "line":return jsx(Line,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,scaleX:d.scaleX||1,scaleY:d.scaleY||1,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},points:d.points||[0,0,d.width,0],stroke:"#000000",strokeWidth:d.strokeWidth||3,fill:"transparent"},f);case "arc":return jsx(Arc,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},innerRadius:d.innerRadius||d.width/4,outerRadius:d.outerRadius||d.width/2,angle:d.angle||90},f);case "rectangle":default:return jsx(Rect,{ref:u=>{u?o.current.set(d.id,u):o.current.delete(d.id);},...l,draggable:!d.locked&&!i,...i?{}:{onDragStart:u=>{r?.();},onDragEnd:u=>t(d.id,u),onTransformEnd:u=>a(d.id,u),onClick:()=>s(d.id),onContextMenu:u=>{u.evt.preventDefault(),n(u.evt,d.id,"shape");}},width:d.width,height:d.height,cornerRadius:d.type==="rounded-rectangle"?10:0},f)}})})});Fi.displayName="ShapeLayer";var nu=({texts:e,textRefs:o,onDragEnd:t,onTransformEnd:a,onSelect:s,onContextMenu:r,onDoubleClick:n,editingTextId:c})=>{let i=useSelector(m=>m.toolbar.selectedTool),d=i==="pen"||i==="eraser";return jsx(Fragment,{children:e.map(m=>{let f=m.id===c,l=m.fontWeight==="bold",u=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&&!d,listening:!d,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:u,align:m.align,wrap:"none",lineHeight:1.2,opacity:f?0:1,visible:!f,...d?{}:{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 Ch=({flashcard:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onNext:n,onPrevious:c,nodeRef:i})=>{let[d,m]=useState(null);if(useEffect(()=>{if(e.images.length>0&&e.images[e.currentIndex]){let h=new window.Image,g=e.images[e.currentIndex];(g.startsWith("http://")||g.startsWith("https://"))&&(h.crossOrigin="anonymous"),h.src=g,h.onload=()=>{m(h);};}},[e.images,e.currentIndex]),!d||e.images.length===0)return null;let f=8,l=2,u=Math.min(e.width,e.height)*.08,p=Math.max(16,Math.min(u,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(i(h),h){let g=h.getStage()?.container();if(g){let x=w=>{let b=h.getStage()?.getPointerPosition();if(b){let C={x:e.x,y:e.y,width:e.width,height:e.height};b.x>=C.x&&b.x<=C.x+C.width&&b.y>=C.y&&b.y<=C.y+C.height&&r(w);}};g.addEventListener("contextmenu",x),h._contextMenuCleanup=()=>{g.removeEventListener("contextmenu",x);};}}},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:d,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,c();},onTap:h=>{h.cancelBubble=true,c();},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"})]})},du=Ch;var Ni=memo(({flashcards:e,flashcardRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onNext:n,onPrevious:c,onContextMenu:i})=>jsx(Fragment,{children:e.map(d=>jsx(du,{flashcard:d,isSelected:t===d.id,onClick:()=>r(d.id),onDragEnd:a,onTransformEnd:m=>s(d.id,m),onContextMenu:m=>i(m,d.id,"flashcard"),onNext:()=>n(d.id),onPrevious:()=>c(d.id),nodeRef:m=>{m?o.current.set(d.id,m):o.current.delete(d.id);}},d.id))}));Ni.displayName="FlashcardLayer";var cu=e=>{let o=xe(),t=useRef(false),a=useRef(false),s=useRef([]),[r,n]=useState(null);ee(w=>w.toolbar.selectedTool);let i=ee(w=>w.toolbar.penColor),d=ee(w=>w.toolbar.strokeWidth),m=ee(w=>w.canvas.isSketchMode),f=ee(w=>w.canvas.slides.find(C=>C.id===w.canvas.currentSlideId)?.photoFrames.find(C=>C.id===e)),l=f?.annotations||[],u=f?.isDrawingMode||false,p=f?.width||1,v=f?.height||1,h=useCallback(w=>{if(!u)return;t.current=true,a.current=false,s.current=[{x:w.x,y:w.y}];let b=w.x/p,C=w.y/v;n({tool:"pen",points:[b,C],color:i,strokeWidth:d/p,isSketch:m});},[u,i,d,m,p,v]),g=useCallback(w=>{if(!t.current||!r)return;a.current=true;let b=s.current[s.current.length-1];if(Math.sqrt(Math.pow(w.x-b.x,2)+Math.pow(w.y-b.y,2))<2)return;s.current.push({x:w.x,y:w.y});let M;if(m)M=Ds(s.current,{size:d*2,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:true}).map((y,S)=>S%2===0?y/p:y/v);else {let k=w.x/p,y=w.y/v;M=[...r.points,k,y];}n(k=>k?{...k,points:M}:null);},[m,d,r,p,v]),x=useCallback(()=>{t.current&&(r&&r.points.length>0&&o(oi({frameId:e,line:r})),n(null),t.current=false,a.current=false,s.current=[]);},[o,e,r]);return {annotations:l,activeLine:r,isDrawingMode:u,startDrawing:h,draw:g,stopDrawing:x}};var Eh=({photoFrame:e,isSelected:o,onClick:t,onDragEnd:a,onTransformEnd:s,onContextMenu:r,onStartCamera:n,onCapture:c,cameraStream:i,nodeRef:d})=>{let[m,f]=useState(null),[l,u]=useState(null),p=useRef(null),v=useRef(null),h=useRef(null),g=useRef(null),x=useRef(0),w=33,b=useSelector(q=>q.toolbar.selectedTool),C=b==="pen"||b==="eraser",{annotations:M,activeLine:k,isDrawingMode:y,startDrawing:S,draw:B,stopDrawing:A}=cu(e.id);useEffect(()=>{if(!y)return;let q=()=>{A();},$=()=>{A();};return window.addEventListener("mouseup",q),window.addEventListener("touchend",$),()=>{window.removeEventListener("mouseup",q),window.removeEventListener("touchend",$);}},[A,y]),useEffect(()=>{if(e.capturedImageUrl){let q=new window.Image;(e.capturedImageUrl.startsWith("http://")||e.capturedImageUrl.startsWith("https://"))&&(q.crossOrigin="anonymous"),q.src=e.capturedImageUrl,q.onload=()=>{f(q);};}},[e.capturedImageUrl]),useEffect(()=>{if(e.isCapturing&&i){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,$=v.current;q.srcObject=i;let W=()=>{$.width=q.videoWidth||640,$.height=q.videoHeight||480,console.log("\u{1F4F9} Starting live capture, canvas size:",$.width,$.height);let H=Y=>{if(Y-x.current<w){h.current=requestAnimationFrame(H);return}x.current=Y;let Q=$.getContext("2d");if(Q&&q.readyState===q.HAVE_ENOUGH_DATA){Q.drawImage(q,0,0,$.width,$.height);let Z=$.toDataURL("image/jpeg",.6),re=new window.Image;re.onload=()=>{u(re);},re.src=Z;}h.current=requestAnimationFrame(H);};h.current=requestAnimationFrame(H);};return q.onloadedmetadata=W,q.readyState>=q.HAVE_METADATA&&W(),q.play().catch(H=>console.error("Error playing video:",H)),()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null);}}return ()=>{u(null),g.current&&(g.current.src="");}},[e.isCapturing,i]);let R=()=>{p.current&&e.isCapturing&&c(p.current);},U=q=>{if(e.capturedImageUrl){if(!y){t();return}let $=q.currentTarget,W=$.getAbsoluteTransform().copy(),Y=$.getStage()?.getPointerPosition();if(Y){W.invert();let Q=W.point(Y);S(Q);}q.cancelBubble=true;}else t();},E=q=>{if(!y||!e.capturedImageUrl)return;let $=q.currentTarget,W=$.getAbsoluteTransform().copy(),Y=$.getStage()?.getPointerPosition();if(Y){W.invert();let Q=W.point(Y);B(Q);}},_=()=>{!y||!e.capturedImageUrl||A();},D=e.isCapturing?l:m,te=Math.min(e.width,e.height)*.12,V=Math.max(25,Math.min(te,50)),oe=e.width/2,z=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(d(q),q){let $=q.getStage()?.container();if($){let W=H=>{let Y=q.getStage()?.getPointerPosition();if(Y){let Q={x:e.x,y:e.y,width:e.width,height:e.height};Y.x>=Q.x&&Y.x<=Q.x+Q.width&&Y.y>=Q.y&&Y.y<=Q.y+Q.height&&r(H);}};$.addEventListener("contextmenu",W),q._contextMenuCleanup=()=>{$.removeEventListener("contextmenu",W);};}}},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:U,onTap:U,onMouseDown:U,onTouchStart:U,onMouseMove:E,onTouchMove:E,onMouseUp:_,onTouchEnd:_,...C?{}:{onDragEnd:a,onTransformEnd:s}}),M?.map((q,$)=>{let W=q.points.map((Y,Q)=>Q%2===0?Y*e.width:Y*e.height),H=q.strokeWidth*e.width;return jsx(Line,{points:W,stroke:q.tool==="eraser"?"white":q.color,strokeWidth:H,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"),!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:z-90,width:e.width,fill:"#EBF6F7",height:180,stroke:"#00000066",strokeWidth:1.5,dash:[4,4],cornerRadius:8}),!e.capturedImageUrl&&jsxs(Fragment,{children:[jsx(Rect,{x:oe-V+6,y:z-60,width:V*1.6,height:V*1.6,radius:V,fill:"white",cornerRadius:8,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?R():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?R():n();}}),jsx(Html,{groupProps:{x:oe-12,y:z-40,width:V*2,height:16},children:jsx(CameraPlus,{weight:"fill",color:"#096B76",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?R():n();}})})]}),jsx(Text,{x:0,y:z,width:e.width,height:40,text:"Click on the camera to start",fontStyle:"bold",fontSize:18,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Text,{x:0,y:z+24,width:e.width,height:40,text:"Make sure you have good lighting!",fontSize:14,fontFamily:"Arial",fill:"#666",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:oe-24,y:z+104,width:V*1.6,height:V*1.6,radius:V,fill:"#096B76",cornerRadius:V,listening:true,onClick:q=>{q.cancelBubble=true,e.isCapturing?R():n();},onTap:q=>{q.cancelBubble=true,e.isCapturing?R():n();}}),jsx(Html,{groupProps:{x:oe-8,y:z+120,width:V*2,height:16},children:jsx(Camera,{weight:"fill",color:"white",size:24,onClick:q=>{q.stopPropagation(),e.isCapturing?R():n();}})})]}),e.isCapturing&&jsxs(Fragment,{children:[jsx(Rect,{x:10,y:10,width:60,height:25,fill:"rgba(231, 76, 60, 0.9)",cornerRadius:4}),jsx(Text,{x:10,y:10,width:60,height:25,text:"\u25CF LIVE",fontSize:12,fontFamily:"Arial",fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle"}),jsx(Html,{groupProps:{x:oe-35,y:e.height-80,width:70,height:70},children:jsx("button",{onClick:q=>{q.stopPropagation(),R();},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})})})})]})]})},hu=Eh;var zi=memo(({photoFrames:e,photoFrameRefs:o,selectedId:t,onDragEnd:a,onTransform:s,onSelect:r,onStartCamera:n,onCapture:c,cameraStreams:i,onContextMenu:d})=>jsx(Fragment,{children:e.map(m=>jsx(hu,{photoFrame:m,isSelected:t===m.id,onClick:()=>r(m.id),onDragEnd:f=>a(f,m.id),onTransformEnd:f=>s(m.id,f),onContextMenu:f=>d(f,m.id,"photoFrame"),onStartCamera:()=>n(m.id),onCapture:f=>c(m.id,f),cameraStream:i.get(m.id),nodeRef:f=>{f?o.current.set(m.id,f):o.current.delete(m.id);}},m.id))}));zi.displayName="PhotoFrameLayer";var vu=({x:e,y:o,onAction:t,onClose:a,type:s,elementId:r="",isDrawingMode:n,menuRef:c})=>{useEffect(()=>{let f=u=>{c?.current&&!c.current.contains(u.target)&&a();},l=u=>{u.key==="Escape"&&a();};return document.addEventListener("mousedown",f),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",l);}},[a]);let i=useMemo(()=>[{action:"order",label:"Order",icon:jsx(ArrowUpIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"lock",label:"Lock",icon:jsx(Lock,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hasSubmenu:true},{action:"link",label:"Link",icon:jsx(LinkIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"voice",label:"Voice",icon:jsx(SpeakerHifiIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),hideForTypes:["line"]},{action:"edit",label:"Edit",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["mcq","trueFalse","shortAnswer","longAnswer","fillInTheBlanks"]},{action:"editFlashcard",label:"Edit Flashcard",icon:jsx(NotePencilIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["flashcard"]},{action:"color",label:"Change Color",icon:jsx(Palette,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["shape"]},{action:"crop",label:"Crop Image",icon:jsx(ScissorsIcon,{className:"h-5 w-5",weight:"fill",color:"#00000099"}),showForTypes:["image"]},{action:"draw",label: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]),d=(f,l)=>{f==="order"||f==="lock"?t(f,l):(t(f),a());},m=jsx("div",{ref:c,className:"absolute z-100 min-w-[200px] rounded-2xl border border-gray-200 bg-white shadow-xl",style:{left:`${e}px`,top:`${o}px`},children:jsx("div",{className:"space-y-1 p-2",children:i.map((f,l)=>jsxs("button",{onClick:u=>d(f.action,u),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 yu=({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 Lu=createContext(null),Gi=()=>useContext(Lu);function sg({children:e,className:o="",style:t}){let a=useRef(null),[s,r]=useState(null);return useEffect(()=>{a.current&&r(a.current);},[]),jsx(Lu.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 We(){let e=Gi();return typeof document>"u"?null:e||document.body}var Su=({title:e,label:o,placeholder:t,defaultValue:a="",onSave:s,onClose:r})=>{let[n,c]=useState(a),i=useRef(null),d=We();useEffect(()=>{i.current?.focus();},[]);let m=()=>{s(n),r();},f=u=>{u.key==="Enter"?m():u.key==="Escape"&&r();};return d?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:i,type:"text",value:n,onChange:u=>c(u.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"})]})]})}),d):null};var Ns=({defaultColor:e="#096B76",onConfirm:o,onCancel:t})=>{let[a,s]=useState(e),r=useRef(null),n=We();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let c=f=>{f.preventDefault(),o(a);},i=(f,l,u)=>{u/=100;let p=l*Math.min(u,1-u)/100,v=h=>{let g=(h+f/30)%12,x=u-p*Math.max(Math.min(g-3,9-g,1),-1);return Math.round(255*x).toString(16).padStart(2,"0")};return `#${v(0)}${v(8)}${v(4)}`},d=["#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:c,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),u=i(l,100,50);s(u);},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:d.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 Ig=({imageSrc:e,onCrop:o})=>{let[t]=ku(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]),c=useMemo(()=>{let l=n.width*.5,u=n.height*.5,p=(n.width-l)/2,v=(n.height-u)/2;return {x:p,y:v,width:l,height:u}},[n]),[i,d]=useState(c);useEffect(()=>{d(c);},[c]),useEffect(()=>{r.current&&s.current&&(r.current.nodes([s.current]),r.current.getLayer()?.batchDraw());},[i]),useEffect(()=>{o(i.x,i.y,i.width,i.height);},[i,o]);let m=()=>{let l=s.current;if(!l)return;let u=l.scaleX(),p=l.scaleY();l.scaleX(1),l.scaleY(1),d({x:l.x(),y:l.y(),width:Math.max(20,l.width()*u),height:Math.max(20,l.height()*p)});},f=()=>{let l=s.current;l&&d({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:i.x,y:i.y,width:i.width,height:i.height,globalCompositeOperation:"destination-out"}),jsx(Rect,{ref:s,x:i.x,y:i.y,width:i.width,height:i.height,stroke:"#4A90E2",strokeWidth:2,draggable:true,onDragEnd:f,onTransformEnd:m,dragBoundFunc:l=>{let u=Math.max(0,Math.min(l.x,n.width-i.width)),p=Math.max(0,Math.min(l.y,n.height-i.height));return {x:u,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,u)=>u.width<20||u.height<20||u.x<0||u.y<0||u.x+u.width>n.width||u.y+u.height>n.height?l:u})]})})},Mu=({imageSrc:e,onConfirm:o,onCancel:t})=>{let a=useRef(null),[s,r]=useState({x:0,y:0,width:0,height:0}),[n]=ku(e),c=We();useEffect(()=>{let f=l=>{l.key==="Escape"&&t();};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t]);let i=(f,l,u,p)=>{r({x:f,y:l,width:u,height:p});},d=()=>{if(!n)return;let u=Math.min(600/n.width,400/n.height),p=s.x/u,v=s.y/u,h=s.width/u,g=s.height/u,x=document.createElement("canvas");x.width=h,x.height=g;let w=x.getContext("2d");if(!w)return;w.drawImage(n,p,v,h,g,0,0,h,g);let b=x.toDataURL("image/png");o(b);};return c?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(Ig,{imageSrc:e,onCrop:i})}),jsxs("div",{className:"flex gap-3",children:[jsx("button",{type:"button",onClick:t,className:"flex-1 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50",children:"Cancel"}),jsxs("button",{type:"button",onClick:d,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"]})]})]})}),c):null};var dr=({onClose:e,stageRef:o,onRecordingComplete:t,directDrawingCanvasRef:a})=>{let s=We(),[r,n]=useState(false),[c,i]=useState(null),[d,m]=useState(0),[f,l]=useState(true),u=useRef(null),p=useRef([]),v=useRef(null),h=useRef(null),g=useRef(null),x=useRef(null),w=useRef(null),b=useRef(null);useEffect(()=>()=>{g.current&&cancelAnimationFrame(g.current),v.current&&clearInterval(v.current),h.current&&h.current.getTracks().forEach(B=>B.stop());},[]);let C=async()=>{try{let B,A=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((H,Y)=>{let Q=H.getChildren();console.log(`Layer ${Y} children count:`,Q.length);});let te=document.createElement("canvas");te.width=o.current.width(),te.height=o.current.height();let V=te.getContext("2d",{willReadFrequently:!1});if(!V){console.error("Could not get recording canvas context"),alert("Failed to create recording canvas.");return}console.log("Recording canvas created, dimensions:",te.width,"x",te.height),w.current=te;let oe=()=>{if(V.clearRect(0,0,te.width,te.height),D.forEach(H=>{let Y=H.getCanvas()._canvas;Y&&V.drawImage(Y,0,0);}),a?.current){let H=a.current;V.drawImage(H,0,0);}};b.current=oe,o.current.draw(),oe(),await new Promise(H=>setTimeout(H,100)),console.log("Creating captureStream..."),B=te.captureStream(30),console.log("Canvas stream created, tracks:",B.getTracks().length);let q=B.getVideoTracks()[0];q&&console.log("Video track:",q.label,"state:",q.readyState);let $=0,W=()=>{oe(),o?.current&&(o.current.getLayers().forEach(Y=>{Y.batchDraw();}),$++,$%60===0&&console.log("Drawing frame:",$)),g.current=requestAnimationFrame(W);};W();}else {console.error("Stage ref not provided"),alert("Stage reference not available.");return}if(f)try{A=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(D){console.warn("Microphone access denied:",D);}let R=[...B.getVideoTracks()];A&&R.push(...A.getAudioTracks());let U=new MediaStream(R);h.current=U;let E="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?E="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?E="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?E="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(E="video/webm;codecs=vp8"),console.log("Using mimeType:",E);let _=new MediaRecorder(U,{mimeType:E,videoBitsPerSecond:25e5});u.current=_,p.current=[],_.ondataavailable=D=>{console.log("Data available, size:",D.data.size),D.data.size>0&&p.current.push(D.data);},_.onstop=()=>{console.log("Recording stopped, chunks:",p.current.length);let D=new Blob(p.current,{type:E});console.log("Final blob size:",D.size),o?.current&&b.current&&w.current&&(o.current.draw(),o.current.getLayers().forEach(V=>{V.batchDraw();}),b.current(),x.current=w.current.toDataURL("image/jpeg",.8),console.log("Final canvas thumbnail captured, length:",x.current.length)),U.getTracks().forEach(te=>te.stop()),v.current&&clearInterval(v.current),g.current&&(cancelAnimationFrame(g.current),g.current=null),i(D);},_.onerror=D=>{console.error("MediaRecorder error:",D);},console.log("Starting recording..."),_.start(1e3),n(!0),m(0),v.current=setInterval(()=>{m(D=>D+1);},1e3);}catch(B){console.error("Error starting screen recording:",B),alert("Failed to start recording. Please ensure you granted permission.");}},M=()=>{u.current&&r&&(console.log("Stopping recording, state:",u.current.state),u.current.state!=="inactive"&&(u.current.requestData(),setTimeout(()=>{u.current&&u.current.state!=="inactive"&&u.current.stop();},100)),n(false));},k=()=>{if(c){let B=URL.createObjectURL(c),A=document.createElement("a");A.href=B,A.download=`screen-recording-${Date.now()}.webm`,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(B);}},y=B=>{let A=Math.floor(B/60),R=B%60;return `${A.toString().padStart(2,"0")}:${R.toString().padStart(2,"0")}`};if(!s)return null;if(r){let B=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(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:M,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,s)}let S=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:[!c&&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"]})]})]}),c&&jsxs("div",{className:"space-y-4",children:[jsx("div",{className:"overflow-hidden rounded-lg bg-gray-900",children:jsx("video",{src:URL.createObjectURL(c),controls:true,className:"w-full",style:{maxHeight:"300px"}})}),jsxs("p",{className:"text-center text-sm text-gray-600",children:["Recording saved! Duration: ",y(d)]}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("button",{onClick:()=>{t&&c&&x.current&&(t(c,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: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:()=>{i(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(S,s)};var Du=({elementType:e,existingAudio:o,onSave:t,onDelete:a,onClose:s})=>{let r=We(),[n,c]=useState(false),[i,d]=useState(null),[m,f]=useState(false),[l,u]=useState(0),p=useRef(null),v=useRef([]),h=useRef(null),g=useRef(null);useEffect(()=>{o&&!i&&fetch(o).then(B=>B.blob()).then(B=>d(B)).catch(B=>console.error("Error loading audio:",B));},[o,i]);let x=async()=>{try{let B=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}}),A=new MediaRecorder(B);p.current=A,v.current=[],A.ondataavailable=R=>{R.data.size>0&&v.current.push(R.data);},A.onstop=()=>{let R=new Blob(v.current,{type:"audio/webm"});d(R),B.getTracks().forEach(U=>U.stop()),h.current&&clearInterval(h.current);},A.start(),c(!0),u(0),h.current=setInterval(()=>{u(R=>R+1);},1e3);}catch(B){console.error("Error starting audio recording:",B),alert("Failed to start recording. Please allow microphone access.");}},w=()=>{p.current&&n&&(p.current.stop(),c(false));},b=()=>{if(i){let B=URL.createObjectURL(i),A=new Audio(B);g.current=A,A.onended=()=>{f(false),URL.revokeObjectURL(B);},A.play(),f(true);}},C=()=>{g.current&&(g.current.pause(),g.current.currentTime=0,f(false));},M=async()=>{if(i){let B=new FileReader;B.onloadend=()=>{let A=B.result;t(A),s();},B.readAsDataURL(i);}},k=()=>{d(null),a();},y=B=>{let A=Math.floor(B/60),R=B%60;return `${A.toString().padStart(2,"0")}:${R.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: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:w,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 S=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:[!i&&jsx("div",{className:"text-center",children:jsxs("button",{onClick:x,className:"bg-primary hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg px-6 py-3 font-semibold text-white transition-colors hover:cursor-pointer",children:[jsx(Microphone,{className:"h-5 w-5",weight:"fill"}),"Start Recording"]})}),i&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-center gap-3",children:[jsxs("button",{onClick:m?C:b,className:"flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700",children:[jsx(Play,{className:"h-5 w-5",weight:"fill"}),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:M,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(S,r)};var Pt=({audioData:e,x:o,y:t,width:a,scale:s=1,offsetX:r=0,offsetY:n=0,containerTop:c=90,containerRight:i=320})=>{let[d,m]=useState(false),f=useRef(null),l=v=>{if(v.stopPropagation(),d&&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);}},u=(o+a)*s+r-15,p=t*s+n+c-15;return jsx("button",{onClick:l,className:`fixed flex items-center justify-center rounded-full shadow-lg transition-all hover:scale-110 ${d?"bg-green-500 hover:bg-green-600":"bg-blue-500 hover:bg-blue-600"}`,style:{left:`${u}px`,top:`${p}px`,width:"30px",height:"30px",zIndex:99},title:d?"Stop Audio":"Play Audio",children:d?jsx(SpeakerSimpleSlash,{className:"h-4 w-4 text-white",weight:"fill"}):jsx(SpeakerHigh,{className:"h-4 w-4 text-white",weight:"fill"})})};var Fu=({selectedElementId:e,onClose:o,onSelectElement:t})=>{let a=xe(),s=ee(ge),r=useMemo(()=>{if(!s)return [];let h=[];return s.images?.forEach(g=>{h.push({id:g.id,type:"image",name:"Image",timestamp:g.timestamp||0});}),s.videos?.forEach(g=>{h.push({id:g.id,type:"video",name:"Video",timestamp:g.timestamp||0});}),s.shapes?.forEach(g=>{h.push({id:g.id,type:"shape",name:`${g.type} Shape`,timestamp:g.timestamp||0});}),s.texts?.forEach(g=>{h.push({id:g.id,type:"text",name:g.text.substring(0,20)+(g.text.length>20?"...":""),timestamp:g.timestamp||0});}),s.flashcards?.forEach(g=>{h.push({id:g.id,type:"flashcard",name:`Flashcard (${g.images.length} images)`,timestamp:g.timestamp||0});}),s.photoFrames?.forEach(g=>{h.push({id:g.id,type:"photoFrame",name:"Photo Frame",timestamp:g.timestamp||0});}),s.multipleChoices?.forEach(g=>{h.push({id:g.id,type:"mcq",name:"Multiple Choice",timestamp:g.timestamp||0});}),s.trueFalses?.forEach(g=>{h.push({id:g.id,type:"trueFalse",name:"True/False",timestamp:g.timestamp||0});}),s.shortAnswers?.forEach(g=>{h.push({id:g.id,type:"shortAnswer",name:"Short Answer",timestamp:g.timestamp||0});}),s.LongAnswer?.forEach(g=>{h.push({id:g.id,type:"longAnswer",name:"Long Answer",timestamp:g.timestamp||0});}),s.fillInTheBlanks?.forEach(g=>{h.push({id:g.id,type:"fillInTheBlanks",name:"Fill in the Blanks",timestamp:g.timestamp||0});}),s.lines?.forEach(g=>{g.id&&h.push({id:g.id,type:"line",name:"Drawn Line",timestamp:g.timestamp||0});}),h.sort((g,x)=>x.timestamp-g.timestamp)},[s]),[n,c]=useState(r),[i,d]=useState(false);useEffect(()=>{i||c(r);},[r]);let m=h=>{let g="h-5 w-5";switch(h){case "image":return jsx(Image$3,{className:g});case "video":return jsx(VideoCamera,{className:g});case "shape":return jsx(Shapes$1,{className:g});case "text":return jsx(TextT,{className:g});case "flashcard":return jsx(Cards$1,{className:g});case "photoFrame":return jsx(FrameCorners,{className:g});case "line":return jsx(Pen,{className:g});default:return jsx(Question,{className:g})}},u=h=>{d(true),c(h);},p=()=>{d(false);let h=Date.now();n.forEach((g,x)=>{let w=h-x;a(Qo({id:g.id,type:g.type,newTimestamp:w}));});},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:u,className:"space-y-1",children:n.map(h=>{let g=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 ${g?"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 ${g?"text-[#096B76]":"text-[#00000099]"}`,children:h.name})}),jsx("div",{className:`${g?"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 Bu=memo(({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>{let n=useSelector(z=>z.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(new Set),[m,f]=useState(false),[l,u]=useState(null),p=useRef(null);useEffect(()=>{let z=p.current;if(z)return a.current.set(e.id,z),()=>{a.current.delete(e.id);}},[e.id]);let v=new Set(e.data.responseOptions.correctIndex),h=v.size>1,g=z=>{m||d(h?q=>{let $=new Set(q);return $.has(z)?$.delete(z):$.add(z),$}:new Set([z]));},x=()=>{i.size>0&&f(true);},w=()=>{f(false),d(new Set);},b=i.size===v.size&&Array.from(i).every(z=>v.has(z)),C=Array.from(i).filter(z=>v.has(z)),M=h&&C.length>0&&!b,k=()=>b?"\u2713 Correct! Great job! \u{1F389}":M?`\u26A0 Partially correct (${C.length}/${v.size})`:"\u2717 Try again!",y=()=>b?{bg:"#dcfce7",text:"#166534"}:M?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},S=55,B=8,A=24,R=60,U=60,E=h&&!m?25:0,_=e.data.feedbackMode==="practice"?48:0,D=12,te=R+E+(m?U:0),V=e.data.responseOptions.options.length*(S+B),oe=te+V+D+_+A;return jsxs(Group,{ref:p,name:"mcq-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{onDragEnd:s,onClick:z=>t(e.id),onTap:z=>t(e.id)},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,height:oe,width:e.width,onTransformEnd:z=>o(e.id,z),onContextMenu:z=>{z.cancelBubble=true,r(z.evt,e.id,"mcq");}}),jsx(Text,{x:A+8,y:A,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-A*2,listening:false}),h&&!m&&e.data.feedbackMode==="practice"?jsx(Text,{x:A,y:A+35,text:`Select ${v.size} answers (${i.size}/${v.size} selected)`,fontSize:14,fill:"#6b7280",width:e.width-A*2,listening:false}):null,m&&e.data.feedbackMode==="practice"?jsxs(Fragment,{children:[jsx(Rect,{x:A+24,y:R+E,width:e.width-A*2-40,height:U-20,fill:y().bg,cornerRadius:8}),jsx(Text,{x:A,y:R+E,width:e.width-A*2,height:U-20,text:k(),fontSize:16,fontStyle:"bold",fill:y().text,align:"center",verticalAlign:"middle",listening:false})]}):null,e.data.responseOptions.options.map((z,q)=>{let $=v.has(q),W=i.has(q),H=te+q*(S+B),Y="#e5e7eb",Q="#ffffff",Z="#111827";return m&&$?(Y="#22c55e",Q="#dcfce7",Z="#1B9D2C"):m&&W&&!$?(Y="#ef4444",Q="#fee2e2",Z="#ef4444"):W&&(Y="#096B76",Q="#ECFFF8",Z="#096B76"),jsxs(Group,{children:[jsx(Rect,{x:A+12,y:H+(S-20)/2,width:20,height:20,fill:W?"#096B76":"white",stroke:W?"#096B76":"#d1d5db",strokeWidth:2,cornerRadius:h?4:10,onClick:re=>{re.cancelBubble=true,g(q);},onTap:re=>{re.cancelBubble=true,g(q);}}),W&&jsx(Text,{x:A+12,y:H+(S-20)/2,width:20,height:20,text:"\u2713",fontSize:14,fill:"white",align:"center",verticalAlign:"middle",listening:false}),jsx(Rect,{x:A+44,y:H,width:e.width-A*2-60,height:S,fill:Q,stroke:Y,strokeWidth:2,cornerRadius:8,onClick:re=>{re.cancelBubble=true,g(q);},onTap:re=>{re.cancelBubble=true,g(q);}}),jsx(Text,{x:A+60,y:H,width:e.width-A*2-80,height:S,text:z,fontSize:16,fill:Z,verticalAlign:"middle",listening:false})]},q)}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:te+e.data.responseOptions.options.length*(S+B)+12,children:[jsxs(Group,{onMouseDown:z=>{z.cancelBubble=true,u("check");},onMouseUp:z=>{z.cancelBubble=true,u(null),x();},onMouseLeave:z=>{z.cancelBubble=true,u(null);},onTouchStart:z=>{z.cancelBubble=true,u("check");},onTouchEnd:z=>{z.cancelBubble=true,u(null),x();},scaleX:l==="check"?.95:1,scaleY:l==="check"?.95:1,children:[jsx(Rect,{x:A+14,width:(e.width-A*2-24)/(m?2:1),height:48,fill:i.size===0||m?"#9ca3af":"#096B76",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:A+14,width:(e.width-A*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-A*2)/2+8,onMouseDown:()=>u("reset"),onMouseUp:()=>{u(null),w();},onMouseLeave:()=>u(null),onTouchStart:()=>u("reset"),onTouchEnd:()=>{u(null),w();},scaleX:l==="reset"?.95:1,scaleY:l==="reset"?.95:1,children:[jsx(Rect,{x:A,width:(e.width-A*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:z=>z.cancelBubble=true,onTap:z=>z.cancelBubble=true}),jsx(Text,{x:A,width:(e.width-A*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});Bu.displayName="MultipleChoice";var Ou=Bu;var Xi=({multipleChoice:e,onContextMenu:o,handleMcqTransform:t,handleSelect:a,mcqRefs:s})=>{let r=useDispatch(),n=useSelector(W=>W.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(false),[m,f]=useState(new Set),[l,u]=useState(false),[p,v]=useState(false),[h,g]=useState(0),x=340,w=100,b=window.innerWidth*.4,C=window.innerHeight*.5,M=x+20,k=w+60,y=b-40,S=C-300,B=useRef(null);useEffect(()=>{let W=B.current;if(W)return s.current.set(e.id,W),()=>{s.current.delete(e.id);}},[e.id]);let A=W=>{r(fa({id:e.id,x:W.target.x(),y:W.target.y()}));},R=W=>{let H=W.target,Y=H.x(),Q=H.y(),Z=window.innerWidth*.2,ye=Y+Z>M&&Y<M+y&&Q+50>k&&Q<k+S;d(ye);},U=(W,H)=>{let Y=H.target,Q=Y.x(),Z=Y.y(),re=window.innerWidth*.2,Be=Q+re>M&&Q<M+y&&Z+50>k&&Z<k+S;f(Be?Ce=>new Set(Ce).add(W):Ce=>{let Oe=new Set(Ce);return Oe.delete(W),Oe}),d(false);},E=()=>{u(true);},_=()=>{u(false),f(new Set),g(W=>W+1);},D=new Set(e.data.responseOptions.correctIndex),te=m.size===D.size&&Array.from(m).every(W=>D.has(W)),V=Array.from(m).filter(W=>D.has(W)),oe=V.length>0&&!te,z=()=>te?"\u2713 Correct! Great job!":oe?`\u26A0 Partially correct (${V.length}/${D.size})`:"\u2717 Try again!",q=()=>te?{bg:"#dcfce7",text:"#166534"}:oe?{bg:"#fef3c7",text:"#92400e"}:{bg:"#fee2e2",text:"#991b1b"},$=()=>l?te?"#4CAF50":oe?"#f59e0b":"#ef4444":i?"#4CAF50":"#075560";return jsxs(Group,{ref:B,name:"mcq-element",width:b,height:C,draggable:!c,listening:!c,...c?{}:{onClick:W=>a(e.id),onTap:W=>a(e.id),onContextMenu:W=>{W.evt.preventDefault(),o(W.evt,e.id,"mcq");}},children:[jsxs(Group,{x,y:w,rotation:e.rotation,onDragEnd:A,children:[jsx(Rect,{fill:"white",stroke:i?"#4CAF50":"#e5e7eb",strokeWidth:i?4:2,cornerRadius:12,height:e.data.feedbackMode==="practice"?C-100:C-50,width:b,shadowColor:i?"#4CAF50":"transparent",shadowBlur:i?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:b-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:80,width:y,height:S,fill:"#EBF6F7",stroke:$(),strokeWidth:3,dash:[10,10],cornerRadius:8}),l&&jsxs(Fragment,{children:[jsx(Rect,{x:23,y:S+18,width:y-5,height:60,fill:q().bg,cornerRadius:8}),jsx(Text,{x:20,y:S+20,width:y,height:60,text:z(),fontSize:18,fontStyle:"bold",fill:q().text,align:"center",verticalAlign:"middle"})]}),m.size===0&&!l&&jsx(Text,{x:20,y:60,width:y,height:S-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),E();},onMouseUp:()=>v(false),onMouseLeave:()=>v(false),onTouchStart:()=>{v(true),E();},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:_,onTouchStart:_,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((W,H)=>{let Y=H%2,Q=Math.floor(H/2),Z=window.innerWidth*.2,re=50,ye=10,Be=m.has(H),Ce=D.has(H),Oe=l&&Be,jt="transparent";return Oe?jt=Ce?"#4CAF50":"#ef4444":Be&&(jt="#4CAF50"),jsxs(Group,{x:340+Y*(Z+ye),y:w+C-80+Q*(re+ye),draggable:!l,onDragMove:R,onDragEnd:da=>U(H,da),opacity:l&&!Be?.5:1,children:[jsx(Rect,{width:Z-20,height:re,fill:"white",stroke:jt,strokeWidth:4,cornerRadius:8,shadowBlur:20,shadowColor:"gray",shadowOpacity:.5}),jsx(Text,{width:Z-20,height:re,text:W,fontSize:18,fontStyle:"bold",fill:"#096B76",align:"center",verticalAlign:"middle",listening:false})]},`${H}-${h}`)})]})};Xi.displayName="MultipleChoiceDragAndDrop";var Nu=({multipleChoice:e,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(Ou,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,handleDragEnd:c=>s(c,n.id),onContextMenu:r},n.id):jsx(Xi,{multipleChoice:n,handleMcqTransform:o,handleSelect:t,mcqRefs:a,onContextMenu:r},n.id))});var Vu=memo(({trueFalse:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(D=>D.toolbar.selectedTool),c=n==="pen"||n==="eraser",[i,d]=useState(null),[m,f]=useState(false),[l,u]=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=()=>{i!==null&&f(true);},h=()=>{f(false),d(null);},g=e.data.responseOptions.correctAnswer,x=i===g,w=D=>{m||d(D);},b=()=>x?"\u2713 Correct! Great job! \u{1F389}":"\u2717 Try again!",C=()=>x?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},M=70,k=12,y=24,S=60,B=60,A=e.data.feedbackMode==="practice"?48:0,R=12,U=S+(m?B:0),E=2*(M+k),_=U+E+R+A+y;return jsxs(Group,{ref:p,name:"trueFalse-element",draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,...c?{}:{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:_-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:S,width:e.width-y*2,height:B-10,fill:C().bg,cornerRadius:8}),jsx(Text,{x:y,y:S,width:e.width-y*2,height:B-10,text:b(),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,te)=>{let V=g===D.value,oe=i===D.value,z=(e.width-y*3)/2,q=y+te*(z+y),$=U,W=D.value===true,H=W?"#10b981":"#ef4444",Y="#ffffff",Q="#ffffff",Z="#e5e7eb";return m&&(V?(Q=W?"#f0fdf4":"#fef2f2",Z=W?"#86efac":"#fecaca"):oe&&!V&&(Q="#fee2e2",Z="#ef4444")),oe&&!m&&(Z="#096B76",Q="#ecfeff"),jsxs(Group,{children:[jsx(Rect,{x:q,y:$,width:z,height:M+50,fill:Q,stroke:Z,strokeWidth:2,cornerRadius:12,onClick:re=>{re.cancelBubble=true,w(D.value);},onTap:re=>{re.cancelBubble=true,w(D.value);}}),jsx(Circle,{x:q+z/2,y:$+40,radius:28,fill:H,listening:false}),W?jsx(Text,{x:q+z/2-14,y:$+40-14,width:28,height:28,text:"\u2713",fontSize:32,fontStyle:"bold",fill:Y,align:"center",verticalAlign:"middle",listening:false}):jsx(Text,{x:q+z/2-14,y:$+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:$+85,width:z,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:U+2*(M+k),children:[jsxs(Group,{onMouseDown:D=>{D.cancelBubble=true,u("check");},onMouseUp:D=>{D.cancelBubble=true,u(null),v();},onMouseLeave:D=>{D.cancelBubble=true,u(null);},onTouchStart:D=>{D.cancelBubble=true,u("check");},onTouchEnd:D=>{D.cancelBubble=true,u(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:i===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:()=>u("reset"),onMouseUp:()=>{u(null),h();},onMouseLeave:()=>u(null),onTouchStart:()=>u("reset"),onTouchEnd:()=>{u(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})]})]})]})});Vu.displayName="TrueFalse";var qu=Vu;var Lx="#FFFFFF",Ji=({trueFalse:e,onContextMenu:o,handleTrueFalseTransform:t})=>{let a=useDispatch(),s=useSelector(H=>H.toolbar.selectedTool),r=s==="pen"||s==="eraser",[n,c]=useState(false),[i,d]=useState(null),[m,f]=useState(false),[l,u]=useState(false),[p,v]=useState(0),[h,g]=useState(false),x=340,w=100,b=window.innerWidth*.4,C=window.innerHeight*.5,M=b-40,k=C-300,y=20,S=60,B=M,A=k,R=b*.2-40,U=50,E=useRef(null),_=H=>{a(ma({id:e.id,x:H.target.x(),y:H.target.y()}));},D=H=>{let Y=H.target,Q=Y.x(),Z=Y.y(),re=Math.max(0,Math.min(Q+R,y+B)-Math.max(Q,y)),ye=Math.max(0,Math.min(Z+U,S+A)-Math.max(Z,S)),Be=re*ye,Ce=R*U;c(Be/Ce>=.5);},te=(H,Y)=>{let Q=Y.target,Z=Q.x(),re=Q.y(),ye=Math.max(0,Math.min(Z+R,y+B)-Math.max(Z,y)),Be=Math.max(0,Math.min(re+U,S+A)-Math.max(re,S)),Ce=ye*Be,Oe=R*U;if(Ce/Oe>=.5)d(H);else return;c(false);},V=()=>{f(true);},oe=()=>{f(false),d(null),v(H=>H+1);},z=e.data.responseOptions.correctAnswer,q=i===z,$=()=>q?"\u2713 Correct! Great job!":"\u2717 Try again!",W=()=>q?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"};return jsx(Group,{ref:E,name:"trueFalse-element",width:b,height:C,draggable:!r,listening:!r,...r?{}:{onContextMenu:H=>{H.evt.preventDefault(),o(H.evt,e.id,"trueFalse");}},children:jsxs(Group,{x,y:w,rotation:e.rotation,onDragEnd:_,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:b,shadowColor:n?"#4CAF50":"transparent",shadowBlur:n?20:0,shadowOpacity:.5}),jsx(Text,{x:20,y:20,width:b-40,text:e.data.question,fontSize:20,fontStyle:"bold",fill:"#111827",align:"center",verticalAlign:"middle"}),jsx(Rect,{x:20,y:60,width:M,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:M,height:60,fill:W().bg,cornerRadius:8}),jsx(Text,{x:20,y:60,width:M,height:60,text:$(),fontSize:18,fontStyle:"bold",fill:W().text,align:"center",verticalAlign:"middle"})]}),i===null&&!m&&jsx(Text,{x:20,y:60,width:M,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:()=>{i!==null&&(u(true),V());},onMouseUp:()=>u(false),onMouseLeave:()=>u(false),onTouchStart:()=>{i!==null&&(u(true),V());},onTouchEnd:()=>u(false),scaleX:l?.95:1,scaleY:l?.95:1,children:[jsx(Rect,{fill:i===null?"#9ca3af":"#075560",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:M}),jsx(Text,{text:"Check Work",fontSize:18,fontStyle:"bold",fill:"white",width:M,height:40,align:"center",verticalAlign:"middle",listening:false})]}),m&&jsxs(Group,{y:50,onMouseDown:oe,onTouchStart:oe,children:[jsx(Rect,{fill:"#dc2626",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:8,height:40,width:M}),jsx(Text,{text:"Reset",fontSize:18,fontStyle:"bold",fill:"white",width:M,height:40,align:"center",verticalAlign:"middle",listening:false})]})]}):null,[{value:true,label:"True"},{value:false,label:"False"}].map((H,Y)=>{let Q=window.innerWidth*.2,Z=50,re=10,ye=i===H.value,Be=z===H.value,Ce=m&&ye,Oe="transparent";return Ce?Oe=Be?"#4CAF50":"#ef4444":ye&&(Oe="#4CAF50"),jsxs(Group,{x:16+Y*(Q+re),y:w+C-300,draggable:!m,onDragMove:D,onDragEnd:jt=>te(H.value,jt),opacity:m&&!ye?.5:1,children:[jsx(Rect,{width:Q-40,height:Z,fill:"#075560",stroke:Oe,strokeWidth:4,cornerRadius:8}),jsx(Text,{width:Q-40,height:Z,text:H.label,fontSize:18,fontStyle:"bold",fill:Lx,align:"center",verticalAlign:"middle",listening:false})]},`${H.value}-${p}`)})]})})};Ji.displayName="TrueFalseDragAndDrop";var Hu=({trueFalses:e,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,handleDragEnd:s,onContextMenu:r})=>jsx(Fragment,{children:e.map(n=>n.data.responseType==="classic"?jsx(qu,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r,handleDragEnd:s},n.id):jsx(Ji,{trueFalse:n,handleTrueFalseTransform:o,handleSelect:t,trueFalseRefs:a,onContextMenu:r},n.id))});var ba=new WeakMap,Co=new WeakMap,hr={current:[]},Qi=false,pr=0,mr=new Set,zs=new Map;function Uu(e){let o=Array.from(e).sort((t,a)=>t instanceof Ut&&t.options.deps.includes(a)?1:a instanceof Ut&&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=Co.get(t);if(a)for(let s of a){let r=ba.get(s);r&&Uu(r);}}}function Cx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function kx(e){let o={prevVal:e.prevState,currentVal:e.state};for(let t of e.listeners)t(o);}function Gs(e){if(pr>0&&!zs.has(e)&&zs.set(e,e.prevState),mr.add(e),!(pr>0)&&!Qi)try{for(Qi=!0;mr.size>0;){let o=Array.from(mr);mr.clear();for(let t of o){let a=zs.get(t)??t.prevState;t.prevState=a,Cx(t);}for(let t of o){let a=ba.get(t);a&&(hr.current.push(t),Uu(a));}for(let t of o){let a=ba.get(t);if(a)for(let s of a)kx(s);}}}finally{Qi=false,hr.current=[],zs.clear();}}function xt(e){pr++;try{e();}finally{if(pr--,pr===0){let o=mr.values().next().value;o&&Gs(o);}}}function Wu(e){return typeof e=="function"}var Yt=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):Wu(o)?this.state=o(this.prevState):this.state=o,(s=(a=this.options)==null?void 0:a.onUpdate)==null||s.call(a),Gs(this);}};var Ut=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 Yt){let a=ba.get(t);a||(a=new Set,ba.set(t,a)),a.add(this);let s=Co.get(this);s||(s=new Set,Co.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 Yt){let a=ba.get(t);a&&a.delete(this);let s=Co.get(this);s&&s.delete(t);}}};function Mx(e){return typeof e=="function"}function el(e,...o){return Mx(e)?e(...o):e}function zu(e){return e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"")}var va,dt,ot,gr,ya,Wa,ea,ko,xr,Ks,br,Mo,za=class{constructor({pluginId:o,debug:t=false,enabled:a=true,reconnectEveryMs:s=1e3}){De(this,va,true);De(this,dt);De(this,ot);De(this,gr);De(this,ya);De(this,Wa);De(this,ea);De(this,ko);De(this,xr,0);De(this,Ks,5);De(this,br,()=>{this.debugLog("Connected to event bus"),ke(this,Wa,true),this.debugLog("Emitting queued events",K(this,ya)),K(this,ya).forEach(o=>this.emitEventToBus(o)),ke(this,ya,[]),this.stopConnectLoop(),K(this,ot).call(this).removeEventListener("tanstack-connect-success",K(this,br));});De(this,Mo,()=>{if(K(this,ot).call(this).addEventListener("tanstack-connect-success",K(this,br)),K(this,xr)<K(this,Ks)){xd(this,xr)._++,this.dispatchCustomEvent("tanstack-connect",{});return}K(this,ot).call(this).removeEventListener("tanstack-connect",K(this,Mo)),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop();});ke(this,dt,o),ke(this,va,a),ke(this,ot,this.getGlobalTarget),ke(this,gr,t),this.debugLog(" Initializing event subscription for plugin",K(this,dt)),ke(this,ya,[]),ke(this,Wa,false),ke(this,ea,null),ke(this,ko,s);}startConnectLoop(){K(this,ea)!==null||K(this,Wa)||(this.debugLog(`Starting connect loop (every ${K(this,ko)}ms)`),ke(this,ea,setInterval(K(this,Mo),K(this,ko))));}stopConnectLoop(){K(this,ea)!==null&&(clearInterval(K(this,ea)),ke(this,ea,null),this.debugLog("Stopped connect loop"));}debugLog(...o){K(this,gr)&&console.log(`\u{1F334} [tanstack-devtools:${K(this,dt)}-plugin]`,...o);}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;let o=typeof EventTarget<"u"?new EventTarget:void 0;return typeof o>"u"||typeof o.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>false}):(this.debugLog("Using new EventTarget as fallback"),o)}getPluginId(){return K(this,dt)}dispatchCustomEventShim(o,t){try{let a=new Event(o,{detail:t});K(this,ot).call(this).dispatchEvent(a);}catch{this.debugLog("Failed to dispatch shim event");}}dispatchCustomEvent(o,t){try{K(this,ot).call(this).dispatchEvent(new CustomEvent(o,{detail:t}));}catch{this.dispatchCustomEventShim(o,t);}}emitEventToBus(o){this.debugLog("Emitting event to client bus",o),this.dispatchCustomEvent("tanstack-dispatch-event",o);}emit(o,t){if(!K(this,va)){this.debugLog("Event bus client is disabled, not emitting event",o,t);return}if(!K(this,Wa)){this.debugLog("Bus not available, will be pushed as soon as connected"),K(this,ya).push({type:`${K(this,dt)}:${o}`,payload:t,pluginId:K(this,dt)}),typeof CustomEvent<"u"&&(K(this,Mo).call(this),this.startConnectLoop());return}return this.emitEventToBus({type:`${K(this,dt)}:${o}`,payload:t,pluginId:K(this,dt)})}on(o,t){let a=`${K(this,dt)}:${o}`;if(!K(this,va))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 K(this,ot).call(this).addEventListener(a,s),this.debugLog("Registered event to bus",a),()=>{K(this,ot).call(this).removeEventListener(a,s);}}onAll(o){if(!K(this,va))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;o(s);};return K(this,ot).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,ot).call(this).removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(o){if(!K(this,va))return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let t=a=>{let s=a.detail;K(this,dt)&&s.pluginId!==K(this,dt)||o(s);};return K(this,ot).call(this).addEventListener("tanstack-devtools-global",t),()=>K(this,ot).call(this).removeEventListener("tanstack-devtools-global",t)}};va=new WeakMap,dt=new WeakMap,ot=new WeakMap,gr=new WeakMap,ya=new WeakMap,Wa=new WeakMap,ea=new WeakMap,ko=new WeakMap,xr=new WeakMap,Ks=new WeakMap,br=new WeakMap,Mo=new WeakMap;var tl=class extends za{constructor(o){super({pluginId:"pacer",debug:o?.debug});}},Gu=(e,o)=>{al.emit(e,o);},al=new tl;function Ku(){return {executionCount:0,isPending:false,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:"idle",maybeExecuteCount:0}}var Tx={enabled:true,leading:true,trailing:true,wait:0},wa,bt,Ga,Ka,_a,To,_s=class{constructor(o,t){De(this,wa);De(this,bt);De(this,Ga);De(this,Ka);De(this,_a);De(this,To);this.fn=o,this.store=new Yt(Ku()),this.setOptions=a=>{this.options={...this.options,...a},K(this,Ga).call(this)||this.cancel();},ke(this,bt,a=>{this.store.setState(s=>{let r={...s,...a},{isPending:n}=r;return {...r,status:K(this,Ga).call(this)?n?"pending":"idle":"disabled"}}),Gu("Throttler",this);}),ke(this,Ga,()=>!!el(this.options.enabled,this)),ke(this,Ka,()=>el(this.options.wait,this)),this.maybeExecute=(...a)=>{K(this,bt).call(this,{maybeExecuteCount:this.store.state.maybeExecuteCount+1});let s=Date.now(),r=s-this.store.state.lastExecutionTime,n=K(this,Ka).call(this);if(this.options.leading&&r>=n)K(this,_a).call(this,...a);else if(K(this,bt).call(this,{lastArgs:a}),!K(this,wa)&&this.options.trailing){let c=this.store.state.lastExecutionTime?s-this.store.state.lastExecutionTime:0,i=n-c;K(this,bt).call(this,{isPending:true}),ke(this,wa,setTimeout(()=>{let{lastArgs:d}=this.store.state;d!==void 0&&K(this,_a).call(this,...d);},i));}},ke(this,_a,(...a)=>{if(!K(this,Ga).call(this))return;this.fn(...a);let s=Date.now(),r=s+K(this,Ka).call(this);K(this,To).call(this),K(this,bt).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||K(this,bt).call(this,{nextExecutionTime:void 0});},K(this,Ka).call(this));}),this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&K(this,_a).call(this,...this.store.state.lastArgs);},ke(this,To,()=>{K(this,wa)&&(clearTimeout(K(this,wa)),ke(this,wa,void 0));}),this.cancel=()=>{K(this,To).call(this),K(this,bt).call(this,{lastArgs:void 0,isPending:false});},this.reset=()=>{K(this,bt).call(this,Ku());},this.key=zu(t.key),this.options={...Tx,...t},K(this,bt).call(this,this.options.initialState??{}),al.on("d-Throttler",a=>{a.payload.key===this.key&&(K(this,bt).call(this,a.payload.store.state),this.setOptions(a.payload.options));});}};wa=new WeakMap,bt=new WeakMap,Ga=new WeakMap,Ka=new WeakMap,_a=new WeakMap,To=new WeakMap;function ol(e,o){return new _s(e,o).maybeExecute}function La(e,o){return typeof e=="function"?e(o):e}function Sa(e,o){return Ys(o).reduce((a,s)=>{if(a===null)return null;if(typeof a<"u")return a[s]},e)}function Ao(e,o,t){let a=Ys(o);function s(r){if(!a.length)return La(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 c=r.slice(0,n);return [...c.length?c:new Array(n),s(r[n]),...r.slice(n+1)]}return [...new Array(n),s()]}return s(e)}function sl(e,o){let t=Ys(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((d,m)=>m!==n);let{[n]:c,...i}=s;return i}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 Ax=/^(\d+)$/gm,Px=/\.(\d+)(?=\.)/gm,Dx=/^(\d+)\./gm,Rx=/\.(\d+$)/gm,Ex=/\.{2,}/gm,rl="__int__",js=`${rl}$1`;function Ys(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(Ax,js).replace(Px,`.${js}.`).replace(Dx,`${js}.`).replace(Rx,`.${js}`).replace(Ex,".").split(".").map(o=>{if(o.startsWith(rl)){let t=o.substring(rl.length),a=parseInt(t,10);return String(a)===t?a:t}return o})}function nl(e){return !(Array.isArray(e)&&e.length===0)}function Po(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 Do(e,o){let{asyncDebounceMs:t}=o,{onBlurAsyncDebounceMs:a,onChangeAsyncDebounceMs:s,onDynamicAsyncDebounceMs:r}=o.validators||{},n=t??0,c=i=>i.validators.filter(Boolean).map(d=>{let m=d?.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:d.fn,debounceMs:f}});return o.validationLogic({form:o.form,validators:o.validators,event:{type:e,async:true},runValidation:c})}var vr=e=>!!e&&typeof e=="object"&&"fields"in e;function Ia(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)||!Ia(e[s],o[s]))return false;return true}var Js=({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},Zs=({formLevelError:e,fieldLevelError:o})=>o?{newErrorValue:o,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function je(e,o){return e==null?o:{...e,...o}}var ja=256,$s=[],Xs;for(;ja--;)$s[ja]=(ja+256).toString(16).substring(1);function il(){let e=0,o,t="";if(!Xs||ja+16>256){for(Xs=new Array(256),e=256;e--;)Xs[e]=256*Math.random()|0;e=0,ja=0;}for(;e<16;e++)o=Xs[ja+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 ja++,t}var Ca=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 Fx(e,o){let t=new Map;for(let a of e){let s=a.path??[],r=o,n="";for(let c=0;c<s.length;c++){let i=s[c];if(i===void 0)continue;let d=typeof i=="object"?i.key:i,m=Number(d);Array.isArray(r)&&!Number.isNaN(m)?n+=`[${m}]`:n+=(c>0?".":"")+String(d),typeof r=="object"&&r!==null?r=r[d]:r=void 0;}t.set(n,(t.get(n)??[]).concat(a));}return Object.fromEntries(t)}var _u=(e,o)=>{let t=Fx(e,o);return {form:t,fields:t}},ka={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:_u(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:_u(a.issues,e)}},Qs=e=>!!e&&"~standard"in e;var Ro={isValidating:false,isTouched:false,isBlurred:false,isDirty:false,isPristine:true,isValid:true,isDefaultValue:true,errors:[],errorMap:{},errorSourceMap:{}};function yr(e){function o(f,l,u,p){let v=a(f,l,u,p);({insert:()=>c(v,f,l),remove:()=>i(v),swap:()=>p!==void 0&&m(v,f,l,p),move:()=>p!==void 0&&d(v,f,l,p)})[u]();}function t(f,l){return `${f}[${l}]`}function a(f,l,u,p){let v=[t(f,l)];if(u==="swap")v.push(t(f,p));else if(u==="move"){let[h,g]=[Math.min(l,p),Math.max(l,p)];for(let x=h;x<=g;x++)v.push(t(f,x));}else {let h=e.getFieldValue(f),g=Array.isArray(h)?h.length:0;for(let x=l+1;x<g;x++)v.push(t(f,x));}return Object.keys(e.fieldInfo).filter(h=>v.some(g=>h.startsWith(g)))}function s(f,l){return f.replace(/\[(\d+)\]/,(u,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=()=>Ro,c=(f,l,u)=>{r(f,"down"),f.forEach(p=>{p.toString().startsWith(t(l,u))&&e.setFieldMeta(p,n());});},i=f=>{r(f,"up");},d=(f,l,u,p)=>{let v=new Map(Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,u))).map(h=>[h,e.getFieldMeta(h)]));r(f,u<p?"up":"down"),Object.keys(e.fieldInfo).filter(h=>h.startsWith(t(l,p))).forEach(h=>{let g=h.replace(t(l,p),t(l,u)),x=v.get(g);x&&e.setFieldMeta(h,x);});},m=(f,l,u,p)=>{f.forEach(v=>{if(!v.toString().startsWith(t(l,u)))return;let h=v.toString().replace(t(l,u),t(l,p)),[g,x]=[e.getFieldMeta(v),e.getFieldMeta(h)];g&&e.setFieldMeta(h,g),x&&e.setFieldMeta(v,x);});};return {handleArrayFieldMetaShift:o}}var ll=class extends za{constructor(){super({pluginId:"form-devtools"});}},vt=new ll;function dl(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(),vt.emit("form-unmounted",{id:this._formId});};this.options.listeners?.onMount?.({formApi:this});let{onMount:n}=this.options.validators||{};return vt.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((i,d)=>i!==this.prevTransformArray[d]),n=a.defaultValues&&!Ia(a.defaultValues,s.defaultValues)&&!this.state.isTouched,c=!Ia(a.defaultState,s.defaultState)&&!this.state.isTouched;!n&&!c&&!r||(xt(()=>{this.baseStore.setState(()=>dl(Object.assign({},this.state,c?a.defaultState:{},n?{values:a.defaultValues}:{},r?{_force_re_eval:!this.state._force_re_eval}:{})));}),vt.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(()=>dl({...this.options.defaultState,values:a??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:n}));},this.validateAllFields=async a=>{let s=[];return xt(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let c=n.instance;s.push(Promise.resolve().then(()=>c.validate(a,{skipFormValidation:!0}))),n.instance.state.meta.isTouched||n.instance.setMeta(i=>({...i,isTouched:!0}));});}),(await Promise.all(s)).flat()},this.validateArrayFieldsStartingFrom=async(a,s,r)=>{let n=this.getFieldValue(a),c=Array.isArray(n)?Math.max(n.length-1,0):null,i=[`${a}[${s}]`];for(let l=s+1;l<=(c??0);l++)i.push(`${a}[${l}]`);let d=Object.keys(this.fieldInfo).filter(l=>i.some(u=>l.startsWith(u))),m=[];return xt(()=>{d.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=Po(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ca}),r=false,n={};return xt(()=>{for(let d of s){if(!d.validate)continue;let m=this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:f,fieldErrors:l}=en(m),u=wr(d.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:g}=v,x=l?.[p],{newErrorValue:w,newSource:b}=Js({newFormValidatorError:x,isPreviousErrorFromFormValidator:g?.[u]==="form",previousErrorValue:h?.[u]});b==="form"&&(n[p]={...n[p],[u]:x}),h?.[u]!==w&&this.setFieldMeta(p,C=>({...C,errorMap:{...C.errorMap,[u]:w},errorSourceMap:{...C.errorSourceMap,[u]:b}}));}this.state.errorMap?.[u]!==f&&this.baseStore.setState(p=>({...p,errorMap:{...p.errorMap,[u]:f}})),(f||l)&&(r=!0);}let c=wr("submit");this.state.errorMap?.[c]&&a!=="submit"&&!r&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[c]:void 0}}));let i=wr("server");this.state.errorMap?.[i]&&a!=="server"&&!r&&this.baseStore.setState(d=>({...d,errorMap:{...d.errorMap,[i]:void 0}}));}),{hasErrored:r,fieldsErrorMap:n}},this.validateAsync=async a=>{let s=Do(a,{...this.options,form:this,validationLogic:this.options.validationLogic||Ca});this.state.isFormValidating||this.baseStore.setState(d=>({...d,isFormValidating:true}));let r=[],n;for(let d of s){if(!d.validate)continue;let m=wr(d.cause);this.state.validationMetaMap[m]?.lastAbortController.abort();let l=new AbortController;this.state.validationMetaMap[m]={lastAbortController:l},r.push(new Promise(async u=>{let p;try{p=await new Promise((x,w)=>{setTimeout(async()=>{if(l.signal.aborted)return x(void 0);try{x(await this.runValidator({validate:d.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:l.signal},type:"validateAsync"}));}catch(b){w(b);}},d.debounceMs);});}catch(x){p=x;}let{formError:v,fieldErrors:h}=en(p);h&&(n=n?{...n,...h}:h);let g=wr(d.cause);for(let x of Object.keys(this.state.fieldMeta)){if(this.baseStore.state.fieldMetaBase[x]===void 0)continue;let w=this.getFieldMeta(x);if(!w)continue;let{errorMap:b,errorSourceMap:C}=w,M=n?.[x],{newErrorValue:k,newSource:y}=Js({newFormValidatorError:M,isPreviousErrorFromFormValidator:C?.[g]==="form",previousErrorValue:b?.[g]});b?.[g]!==k&&this.setFieldMeta(x,S=>({...S,errorMap:{...S.errorMap,[g]:k},errorSourceMap:{...S.errorSourceMap,[g]:y}}));}this.baseStore.setState(x=>({...x,errorMap:{...x.errorMap,[g]:v}})),u(n?{fieldErrors:n,errorMapKey:g}:void 0);}));}let c=[],i={};if(r.length){c=await Promise.all(r);for(let d of c)if(d?.fieldErrors){let{errorMapKey:m}=d;for(let[f,l]of Object.entries(d.fieldErrors)){let p={...i[f]||{},[m]:l};i[f]=p;}}}return this.baseStore.setState(d=>({...d,isFormValidating:false})),i},this.validate=a=>{let{hasErrored:s,fieldsErrorMap:r}=this.validateSync(a);return s&&!this.options.asyncAlways?r:this.validateAsync(a)},this.getFieldValue=a=>Sa(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]:La(s,r.fieldMetaBase[a])}}));},this.resetFieldMeta=a=>Object.keys(a).reduce((s,r)=>{let n=r;return s[n]=Ro,s},{}),this.setFieldValue=(a,s,r)=>{let n=r?.dontUpdateMeta??false,c=r?.dontRunListeners??false,i=r?.dontValidate??false;xt(()=>{n||this.setFieldMeta(a,d=>({...d,isTouched:!0,isDirty:!0,errorMap:{...d?.errorMap,onMount:void 0}})),this.baseStore.setState(d=>({...d,values:Ao(d.values,a,s)}));}),c||this.getFieldInfo(a).instance?.triggerOnChangeListener(),i||this.validateField(a,"change");},this.deleteField=a=>{let r=[...Object.keys(this.fieldInfo).filter(n=>{let c=a.toString();return n!==c&&n.startsWith(c)}),a];this.baseStore.setState(n=>{let c={...n};return r.forEach(i=>{c.values=sl(c.values,i),delete this.fieldInfo[i],delete c.fieldMetaBase[i];}),c});},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,i=>[...i.slice(0,s),r,...i.slice(s)],je(n,{dontValidate:true}));let c=n?.dontValidate??false;c||await this.validateField(a,"change"),yr(this).handleArrayFieldMetaShift(a,s,"insert"),c||await this.validateArrayFieldsStartingFrom(a,s,"change");},this.replaceFieldValue=async(a,s,r,n)=>{this.setFieldValue(a,i=>i.map((d,m)=>m===s?r:d),je(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),c=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(a,d=>d.filter((m,f)=>f!==s),je(r,{dontValidate:true})),yr(this).handleArrayFieldMetaShift(a,s,"remove"),c!==null){let d=`${a}[${c}]`;this.deleteField(d);}(r?.dontValidate??false)||(await this.validateField(a,"change"),await this.validateArrayFieldsStartingFrom(a,s,"change"));},this.swapFieldValues=(a,s,r,n)=>{this.setFieldValue(a,i=>{let d=i[s],m=i[r];return Ao(Ao(i,`${s}`,m),`${r}`,d)},je(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,i=>{let d=[...i];return d.splice(r,0,d.splice(s,1)[0]),d},je(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,[],je(s,{dontValidate:true})),n!==null)for(let i=0;i<=n;i++){let d=`${a}[${i}]`;this.deleteField(d);}(s?.dontValidate??false)||this.validateField(a,"change");},this.resetField=a=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[a]:Ro},values:this.options.defaultValues?Ao(s.values,a,Sa(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=>ka.validate({value:this.state.values,validationSource:"form"},a),this.parseValuesWithSchemaAsync=a=>ka.validateAsync({value:this.state.values,validationSource:"form"},a),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=o?.formId??il(),this._devtoolsSubmissionOverride=false,this.baseStore=new Yt(dl({...o?.defaultState,values:o?.defaultValues??o?.defaultState?.values})),this.fieldMetaDerived=new Ut({deps:[this.baseStore],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,c=a?.[0],i=s[0],d=0,m={};for(let f of Object.keys(i.fieldMetaBase)){let l=i.fieldMetaBase[f],u=c?.fieldMetaBase[f],p=n?.[f],v=Sa(i.values,f),h=p?.errors;if(!u||l.errorMap!==u.errorMap){h=Object.values(l.errorMap??{}).filter(C=>C!==void 0);let b=this.getFieldInfo(f)?.instance;b&&!b.options.disableErrorFlat&&(h=h?.flat(1));}let g=!nl(h??[]),x=!l.isDirty,w=Ia(v,Sa(this.options.defaultValues,f))||Ia(v,this.getFieldInfo(f)?.instance?.options.defaultValue);if(p&&p.isPristine===x&&p.isValid===g&&p.isDefaultValue===w&&p.errors===h&&l===u){m[f]=p,d++;continue}m[f]={...l,errors:h,isPristine:x,isValid:g,isDefaultValue:w};}return Object.keys(i.fieldMetaBase).length&&n&&d===Object.keys(i.fieldMetaBase).length?n:m}}),this.store=new Ut({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:a,currDepVals:s,prevVal:r})=>{let n=r,c=a?.[0],i=s[0],d=s[1],m=Object.values(d).filter(Boolean),f=m.some(E=>E.isValidating),l=m.every(E=>E.isValid),u=m.some(E=>E.isTouched),p=m.some(E=>E.isBlurred),v=m.every(E=>E.isDefaultValue),h=u&&i.errorMap?.onMount,g=m.some(E=>E.isDirty),x=!g,w=!!(i.errorMap?.onMount||m.some(E=>E?.errorMap?.onMount)),b=!!f,C=n?.errors??[];(!c||i.errorMap!==c.errorMap)&&(C=Object.values(i.errorMap).reduce((E,_)=>_===void 0?E:_&&vr(_)?(E.push(_.form),E):(E.push(_),E),[]));let M=C.length===0,k=l&&M,y=this.options.canSubmitWhenInvalid??false,S=i.submissionAttempts===0&&!u&&!w||!b&&!i.isSubmitting&&k||y,B=i.errorMap;if(h&&(C=C.filter(E=>E!==i.errorMap.onMount),B=Object.assign(B,{onMount:void 0})),n&&c&&n.errorMap===B&&n.fieldMeta===this.fieldMetaDerived.state&&n.errors===C&&n.isFieldsValidating===f&&n.isFieldsValid===l&&n.isFormValid===M&&n.isValid===k&&n.canSubmit===S&&n.isTouched===u&&n.isBlurred===p&&n.isPristine===x&&n.isDefaultValue===v&&n.isDirty===g&&Ia(c,i))return n;let A={...i,errorMap:B,fieldMeta:this.fieldMetaDerived.state,errors:C,isFieldsValidating:f,isFieldsValid:l,isFormValid:M,isValid:k,canSubmit:S,isTouched:u,isBlurred:p,isPristine:x,isDefaultValue:v,isDirty:g},R=this.options.transform?.deps??[];if(R.length!==this.prevTransformArray.length||R.some((E,_)=>E!==this.prevTransformArray[_])){let E=Object.assign({},this,{state:A});this.options.transform?.fn(E),A=E.state,this.prevTransformArray=R;}return A}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(o||{});let t=ol(a=>vt.emit("form-state",{id:this._formId,state:a}),{wait:300});this.store.subscribe(()=>{t(this.store.state);}),vt.on("request-form-state",a=>{a.payload.id===this._formId&&vt.emit("form-api",{id:this._formId,state:this.store.state,options:this.options});}),vt.on("request-form-reset",a=>{a.payload.id===this._formId&&this.reset();}),vt.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 Qs(o.validate)?ka[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})),xt(()=>{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}),vt.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}),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"validate",errors:this.state.errors});return}xt(()=>{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}),xt(()=>{this.baseStore.setState(s=>({...s,isSubmitted:!0,isSubmitSuccessful:!0})),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),a();});}catch(s){throw this.baseStore.setState(r=>({...r,isSubmitSuccessful:false})),vt.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:false,stage:"inflight",onError:s}),a(),s}}setErrorMap(o){xt(()=>{Object.entries(o).forEach(([t,a])=>{let s=t;if(vr(a)){let{formError:r,fieldErrors:n}=en(a);for(let c of Object.keys(this.fieldInfo))this.getFieldMeta(c)&&this.setFieldMeta(c,d=>({...d,errorMap:{...d.errorMap,[s]:n?.[c]},errorSourceMap:{...d.errorSourceMap,[s]:"form"}}));this.baseStore.setState(c=>({...c,errorMap:{...c.errorMap,[s]:r}}));}else this.baseStore.setState(r=>({...r,errorMap:{...r.errorMap,[s]:a}}));});});}};function en(e){if(e){if(vr(e)){let o=en(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=Sa(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,je(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,je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.insertValue=(t,a,s)=>{this.form.insertFieldValue(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.replaceValue=(t,a,s)=>{this.form.replaceFieldValue(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.removeValue=(t,a)=>{this.form.removeFieldValue(this.name,t,je(a,{dontRunListeners:true})),a?.dontRunListeners||this.triggerOnChangeListener();},this.swapValues=(t,a,s)=>{this.form.swapFieldValues(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.moveValue=(t,a,s)=>{this.form.moveFieldValues(this.name,t,a,je(s,{dontRunListeners:true})),s?.dontRunListeners||this.triggerOnChangeListener();},this.clearValues=t=>{this.form.clearFieldValues(this.name,je(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:c}=r.instance.options.validators||{};t==="change"&&n?.includes(this.name)&&s.push(r.instance),t==="blur"&&c?.includes(this.name)&&s.push(r.instance);}return s},this.validateSync=(t,a)=>{let s=Po(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ca}),n=this.getLinkedFields(t).reduce((d,m)=>{let f=Po(t,{...m.options,form:m.form,validationLogic:m.form.options.validationLogic||Ca});return f.forEach(l=>{l.field=m;}),d.concat(f)},[]),c=false;xt(()=>{let d=(m,f)=>{let l=tn(f.cause),u=f.validate?ju(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}=Zs({formLevelError:p,fieldLevelError:u});m.state.meta.errorMap?.[l]!==v&&m.setMeta(g=>({...g,errorMap:{...g.errorMap,[l]:v},errorSourceMap:{...g.errorSourceMap,[l]:h}})),v&&(c=!0);};for(let m of s)d(this,m);for(let m of n)m.validate&&d(m.field,m);});let i=tn("submit");return this.state.meta.errorMap?.[i]&&t!=="submit"&&!c&&this.setMeta(d=>({...d,errorMap:{...d.errorMap,[i]:void 0},errorSourceMap:{...d.errorSourceMap,[i]:void 0}})),{hasErrored:c}},this.validateAsync=async(t,a)=>{let s=Do(t,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Ca}),r=await a,n=this.getLinkedFields(t),c=n.reduce((l,u)=>{let p=Do(t,{...u.options,form:u.form,validationLogic:u.form.options.validationLogic||Ca});return p.forEach(v=>{v.field=u;}),l.concat(p)},[]);this.state.meta.isValidating||this.setMeta(l=>({...l,isValidating:true}));for(let l of n)l.setMeta(u=>({...u,isValidating:true}));let i=[],d=[],m=(l,u,p)=>{let v=tn(u.cause);l.getInfo().validationMetaMap[v]?.lastAbortController.abort();let g=new AbortController;this.getInfo().validationMetaMap[v]={lastAbortController:g},p.push(new Promise(async x=>{let w;try{w=await new Promise((y,S)=>{this.timeoutIds.validations[u.cause]&&clearTimeout(this.timeoutIds.validations[u.cause]),this.timeoutIds.validations[u.cause]=setTimeout(async()=>{if(g.signal.aborted)return y(void 0);try{y(await this.runValidator({validate:u.validate,value:{value:l.store.state.value,fieldApi:l,signal:g.signal,validationSource:"field"},type:"validateAsync"}));}catch(B){S(B);}},u.debounceMs);});}catch(y){w=y;}if(g.signal.aborted)return x(void 0);let b=ju(w),C=r[this.name]?.[v],{newErrorValue:M,newSource:k}=Zs({formLevelError:C,fieldLevelError:b});l.setMeta(y=>({...y,errorMap:{...y?.errorMap,[v]:M},errorSourceMap:{...y.errorSourceMap,[v]:k}})),x(M);}));};for(let l of s)l.validate&&m(this,l,i);for(let l of c)l.validate&&m(l.field,l,d);let f=[];(i.length||d.length)&&(f=await Promise.all(i),await Promise.all(d)),this.setMeta(l=>({...l,isValidating:false}));for(let l of n)l.setMeta(u=>({...u,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[tn(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=>ka.validate({value:this.state.value,validationSource:"field"},t),this.parseValueWithSchemaAsync=t=>ka.validateAsync({value:this.state.value,validationSource:"field"},t),this.form=o.form,this.name=o.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Ut({deps:[this.form.store],fn:()=>{let t=this.form.getFieldValue(this.name),a=this.form.getFieldMeta(this.name)??{...Ro,...o.defaultMeta};return {value:t,meta:a}}}),this.options=o;}get state(){return this.store.state}runValidator(o){return Qs(o.validate)?ka[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 ju(e){if(e)return e}function tn(e){switch(e){case "submit":return "onSubmit";case "blur":return "onBlur";case "mount":return "onMount";case "server":return "onServer";case "dynamic":return "onDynamic";case "change":default:return "onChange"}}function an(e,o=t=>t){return useSyncExternalStoreWithSelector(e.subscribe,()=>e.state,()=>e.state,o,Ox)}function Ox(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=Xu(e);if(t.length!==Xu(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 Xu(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var Eo=typeof window<"u"?useLayoutEffect:useEffect;function zx(e){let[o]=useState(()=>{let a=new Sr({...e,form:e.form,name:e.name});return a.Field=ul,a});return Eo(o.mount,[o]),Eo(()=>{o.update(e);}),an(o.store,e.mode==="array"?t=>[t.meta,Object.keys(t.value??[]).length]:void 0),o}var ul=(({children:e,...o})=>{let t=zx(o),a=useMemo(()=>La(e,t),[e,t,t.state.value,t.state.meta]);return jsx(Fragment,{children:a})});function _x({form:e,selector:o,children:t}){let a=an(e.store,o);return La(t,a)}function cl(e){let o=useId(),[t]=useState(()=>{let a=new Lr({...e,formId:o}),s=a;return s.Field=function(n){return jsx(ul,{...n,form:a})},s.Subscribe=function(n){return jsx(_x,{form:a,selector:n.selector,children:n.children})},s});return Eo(t.mount,[]),Eo(()=>{t.update(e);}),t}function fl({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 ab=({editElement:e})=>{let o=useDispatch(),t=useSelector(ge),a=useRef(null),s=We(),r=!!e,n=e?.data.questionType||t?.activityType||"multiple-choice",[c,i]=useState(n),d=cl({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 u={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?ma(u):si(u));}else if(l.questionType==="multiple-choice"){let u={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?fa(u):ri(u));}else if(l.questionType==="short-answer"){let u={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(u):ni(u));}else if(l.questionType==="fill-in-the-blank"){let u={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(u):li(u));}else if(l.questionType==="long-answer"){let u={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(u):ii(u));}o(pa(false));}}),m=()=>{o(pa(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(),d.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(d.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:u=>{l.handleChange(u.target.value),i(u.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(fl,{field:l})]})}),c&&!["short-answer","fill-in-the-blank","long-answer"].includes(c)&&jsx(d.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:u=>l.handleChange(u.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(fl,{field:l})]})})]}),jsx(d.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 ${c==="long-answer"?"cursor-not-allowed opacity-60":""}`,children:[jsxs("button",{type:"button",disabled:c==="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:c==="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"})]})]}),c==="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(fl,{field:l})]})}),jsx(d.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:u=>l.handleChange(u.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(", ")})]})}),c==="true-false"&&jsx(d.Field,{name:"responseOptions.correctAnswer",children:l=>{let u=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 ${u===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"}),u===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 ${u===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"}),u===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"})]})}}),c==="multiple-choice"&&jsx(d.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 u=(g,x)=>{let w=[...l.state.value.options];w[g]=x,l.handleChange({...l.state.value,options:w});},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=g=>{if(l.state.value.options.length<=2){alert("Minimum 2 options required");return}let x=l.state.value.options.filter((b,C)=>C!==g),w=l.state.value.correctIndex?.filter(b=>b!==g).map(b=>b>g?b-1:b);l.handleChange({...l.state.value,options:x,correctIndex:w});},h=g=>{let x=l.state.value.correctIndex||[];if(x.includes(g))l.handleChange({...l.state.value,correctIndex:x.filter(b=>b!==g)});else {if(x.length>=6){alert("Maximum 6 correct answers allowed");return}l.handleChange({...l.state.value,correctIndex:[...x,g]});}};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((g,x)=>{let w=!g.trim(),b=l.state.value.correctIndex?.includes(x),C=l.state.meta.isTouched&&w;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(x),className:`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors sm:h-5 sm:w-5 ${b?"border-green-500 bg-green-500":"border-gray-300 hover:border-green-500"}`,children:b&&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":b?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:jsx("input",{type:"text",placeholder:`Option ${x+1}`,value:g,onChange:M=>u(x,M.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(x),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"})})]},x)})}),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"})]})]})}}),(c==="short-answer"||c==="fill-in-the-blank")&&jsx(d.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:u=>{l.handleChange(u.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(", ")})]})}),c==="long-answer"&&jsx(d.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:u=>{l.handleChange(u.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(d.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l,u])=>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:u?"Saving...":r?"Update Question":"Save Question"})})]})})});return createPortal(f,s)},Ju=ab;var tc=({text:e,position:o})=>{let t=xe(),a=d=>{t(ce()),t(Tt({id:e.id,fontSize:Math.max(12,Math.min(72,e.fontSize+d))}));},s=d=>{t(ce()),t(Tt({id:e.id,fill:d}));},r=()=>{t(ce()),t(Tt({id:e.id,fontWeight:e.fontWeight==="bold"?"normal":"bold"}));},n=()=>{t(ce()),t(Tt({id:e.id,fontStyle:e.fontStyle==="italic"?"normal":"italic"}));},c=()=>{t(ce()),t(Tt({id:e.id,textDecoration:e.textDecoration==="underline"?"":"underline"}));},i=d=>{t(ce()),t(Tt({id:e.id,fontFamily:d}));};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:d=>d.stopPropagation(),children:[jsxs("select",{value:e.fontFamily,onChange:d=>i(d.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:c,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:d=>s(d.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 oc=({text:e,editingValue:o,onEditingChange:t,onFinish:a,position:s,scale:r,textareaRef:n})=>{let c=useRef(null),i=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]),d=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
4
  `),u=0;document.body.appendChild(f);for(let v of l){f.textContent=v||" ";let h=f.offsetWidth;h>u&&(u=h);}document.body.removeChild(f);let p=10;m.style.width=`${Math.max(200,u+p+20)}px`;},[]);return useEffect(()=>{let m=c.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,d(m));},[o,e.fontSize,e.fontFamily,e.fontStyle,e.fontWeight,e.textDecoration,e.fill,r,d]),jsx("div",{style:{position:"absolute",top:`${s.top}px`,left:`${s.left}px`,zIndex:1e3},children:jsx("textarea",{ref:m=>{if(c.current=m,n.current=m,m){m.focus();let f=m.value.length;m.setSelectionRange(f,f),d(m);}},value:o,onChange:m=>{t(m.target.value);},onKeyDown:m=>{m.key==="Escape"&&a();},style:i},`${e.fontWeight}-${e.fontStyle}-${e.textDecoration}-${e.fontSize}-${e.fontFamily}`)})};var rc=memo(({shortAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(E=>E.toolbar.selectedTool),c=n==="pen"||n==="eraser",i=useRef(null),[d,m]=useState(""),[f,l]=useState(false),[u,p]=useState(null);useEffect(()=>{let E=i.current;if(E)return a.current.set(e.id,E),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctShortAnswer?.trim().toLowerCase()||"",h=f&&d.trim().toLowerCase()===v,g=()=>{l(false),m("");},x=()=>h?"\u2713 Right Answer, Great Job !":"\u2717 Answer wrong, Please try again !",w=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fee2e2",text:"#991b1b"},b=24,C=60,M=f?40:0,k=f?54:20,y=50,S=12,B=e.data.feedbackMode==="practice"?48:0,A=12,R=30,U=C+M+R+y+S+A+B+b;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:U,name:"sa-element",...c?{}:{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:U,onTransformEnd:E=>t(e.id,E),onContextMenu:E=>{E.cancelBubble=true,s(E.evt,e.id,"shortAnswer");}}),jsx(Text,{text:e.data.question,x:b,y:b,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2,listening:false}),jsx(Rect,{x:b,y:C+M+R-k,width:e.width-b*2+4,height:y+6,fill:"#ffffff",stroke:h?"#22c55e":f?"#ef4444":"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:b,y:C+M+R-k},divProps:{style:{width:`${e.width-b*2-4}px`,height:`${y}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:d,onChange:E=>m(E.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:b,y:C+80,width:e.width/2+24,height:M,fill:w().bg,cornerRadius:8}),jsx(Text,{x:36,y:C+80,width:e.width-b*2,height:M,text:x(),fontSize:12,fontStyle:"bold",fill:w().text,verticalAlign:"middle",listening:false})]}),e.data.feedbackMode==="practice"&&jsxs(Group,{y:C+M+R+y+S+A,children:[jsxs(Group,{onMouseDown:E=>{E.cancelBubble=true,p("check");},onMouseUp:E=>{E.cancelBubble=true,p(null),d.length>0&&l(true);},onMouseLeave:E=>{E.cancelBubble=true,p(null);},onTouchStart:E=>{E.cancelBubble=true,p("check");},onTouchEnd:E=>{E.cancelBubble=true,p(null),d.length>0&&l(true);},scaleX:u==="check"?.95:1,scaleY:u==="check"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,fill:d.length===0||f?"#9ca3af":"#096B76",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/(f?2:1),height:48,text:f?"Submitted":"Check Work",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]}),f&&jsxs(Group,{x:(e.width-b*2)/2+8,onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:u==="reset"?.95:1,scaleY:u==="reset"?.95:1,children:[jsx(Rect,{x:b,width:(e.width-b*2-8)/2,height:48,fill:"#ef4444",cornerRadius:8,onClick:E=>E.cancelBubble=true,onTap:E=>E.cancelBubble=true}),jsx(Text,{x:b,width:(e.width-b*2-8)/2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});rc.displayName="ShortAnswer";var sc=rc;var ic=({shortAnswers:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(sc,{shortAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,n.id)},n.id))});var lc=e=>{let o=useDispatch(),a=useSelector(ge)?.fillInTheBlanks||[],s=useRef(new Map),r=useCallback((n,c)=>{let i=n.target;o(Jo({id:c,x:i.x(),y:i.y()})),e?.();},[o,e]);return {fillInTheBlanks:a,fibRefs:s,handleFillInTheBlanksDragEnd:r}};var Rt=24,hl=51,Ar=64,dc=15,sn=32,uc=memo(({fillInTheBlank:e,handleSelect:o,handleTransform:t,handleDragEnd:a,onContextMenu:s,fibRefs:r})=>{let n=useSelector(y=>y.toolbar.selectedTool),c=n==="pen"||n==="eraser",i=useRef(null),[d,m]=useState(""),[f,l]=useState(false),[u,p]=useState(null);useEffect(()=>{let y=i.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&&d.trim().toLowerCase()===v,g=()=>{l(false),m("");},x=()=>{d.length>0&&l(true);},w=e.width-Rt*2,b=(w-dc)/2,C=e.data.feedbackMode==="practice",M=useMemo(()=>{let y=Rt,S=y;y+=60;let B=y;y+=35;let A=y;y+=hl+16;let R=y;f&&(y+=sn+16);let U=y;return C&&(y+=Ar),y+=Rt,{questionY:S,helperTextY:B,inputY:A,feedbackY:R,buttonsY:U,totalHeight:y}},[f,C]),k=()=>f?h?"#1b9d2c":"#ef4444":"#d1d5db";return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"fib-element",...c?{}:{onDragEnd:y=>a(y,e.id),onClick:()=>o(e.id),onTap:()=>o(e.id)},children:[jsx(Rect,{fill:"white",cornerRadius:12,width:e.width,height:M.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:Rt,y:M.questionY,fontSize:24,fontStyle:"bold",fill:"rgba(0,0,0,0.8)",width:w,lineHeight:1.4,listening:false}),jsx(Text,{text:"Enter your answer in the blank.",x:Rt,y:M.helperTextY,fontSize:16,fill:"rgba(0,0,0,0.4)",width:w,listening:false}),jsx(Rect,{x:Rt,y:M.inputY,width:w,height:hl,fill:"#ffffff",stroke:k(),strokeWidth:1,cornerRadius:8}),jsx(Html,{groupProps:{x:Rt,y:M.inputY},divProps:{style:{width:`${w}px`,height:`${hl}px`,pointerEvents:f?"none":"auto"}},children:jsx("input",{type:"text",value:d,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:M.feedbackY,children:[jsx(Rect,{x:Rt,width:h?206:140,height:sn,fill:h?"#f2fff4":"#fef2f2",cornerRadius:6}),jsx(Text,{text:h?"\u2713":"\u2717",x:Rt+10,y:0,width:16,height:sn,fontSize:14,fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false}),jsx(Text,{text:h?"Right Answer, Great Job!":"Wrong Answer",x:Rt+30,y:0,height:sn,fontSize:14,fontStyle:"600",fill:h?"#1b9d2c":"#ef4444",verticalAlign:"middle",listening:false})]}),C&&jsxs(Group,{y:M.buttonsY,children:[jsxs(Group,{x:Rt,onMouseDown:y=>{y.cancelBubble=true,p("reset");},onMouseUp:y=>{y.cancelBubble=true,p(null),g();},onMouseLeave:y=>{y.cancelBubble=true,p(null);},onTouchStart:y=>{y.cancelBubble=true,p("reset");},onTouchEnd:y=>{y.cancelBubble=true,p(null),g();},scaleX:u==="reset"?.98:1,scaleY:u==="reset"?.98:1,children:[jsx(Rect,{width:b,height:Ar,fill:"#f5f5f5",cornerRadius:8}),jsx(Text,{width:b,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:Rt+b+dc,onMouseDown:y=>{y.cancelBubble=true,p("submit");},onMouseUp:y=>{y.cancelBubble=true,p(null),x();},onMouseLeave:y=>{y.cancelBubble=true,p(null);},onTouchStart:y=>{y.cancelBubble=true,p("submit");},onTouchEnd:y=>{y.cancelBubble=true,p(null),x();},scaleX:u==="submit"?.98:1,scaleY:u==="submit"?.98:1,children:[jsx(Rect,{width:b,height:Ar,fill:d.length===0?"#9ca3af":"#096b76",cornerRadius:8}),jsx(Text,{width:b,height:Ar,text:"\u2713 Check",fontSize:18,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})]})]})});uc.displayName="FillInTheBlanks";var cc=uc;var mc=({fillInTheBlanks:e,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r})=>jsx(Fragment,{children:e.map(n=>jsx(cc,{fillInTheBlank:n,handleSelect:o,handleTransform:t,onContextMenu:a,handleDragEnd:s,fibRefs:r},n.id))});var vl=memo(({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>{let n=useSelector(U=>U.toolbar.selectedTool),c=n==="pen"||n==="eraser",i=useRef(null),[d,m]=useState(""),[f,l]=useState(false),[u,p]=useState(null);useEffect(()=>{let U=i.current;if(U)return a.current.set(e.id,U),()=>{a.current.delete(e.id);}},[e.id,a]);let v=e.data.responseOptions.correctLongAnswer?.trim().toLowerCase()||"",h=f&&d.trim().toLowerCase()===v,g=()=>{l(false),m("");},x=()=>h?"\u2713 Correct! \u{1F389}":"\u2717 Needs review - this is a long answer question",w=()=>h?{bg:"#dcfce7",text:"#166534"}:{bg:"#fef3c7",text:"#92400e"},b=24,C=60,M=f?60:0,k=120,y=12,S=48,B=12,A=30,R=C+M+A+k+y+B+S+b;return jsxs(Group,{ref:i,draggable:!c,listening:!c,x:e.x,y:e.y,rotation:e.rotation,width:e.width,height:e.height,name:"la-element",...c?{}:{onDragEnd:r,onClick:()=>o(e.id),onTap:()=>o(e.id),onContextMenu:U=>{let E=i.current?.getStage()?.getPointerPosition();if(!E||!s)return;let _={x:e.x,y:e.y,width:e.width,height:e.height};E.x>=_.x&&E.x<=_.x+_.width&&E.y>=_.y&&E.y<=_.y+_.height&&s(U.evt,e.id,"longAnswer");}},children:[jsx(Rect,{fill:"white",stroke:"#e5e7eb",strokeWidth:2,cornerRadius:12,width:e.width,height:R,onTransformEnd:U=>t(e.id,U)}),jsx(Text,{text:e.data.question,x:b,y:b,fontSize:20,fontStyle:"bold",fill:"#111827",width:e.width-b*2,listening:false}),f&&jsxs(Fragment,{children:[jsx(Rect,{x:b,y:C,width:e.width-b*2,height:M,fill:w().bg,cornerRadius:8}),jsx(Text,{x:b,y:C,width:e.width-b*2,height:M,text:x(),fontSize:14,fontStyle:"bold",fill:w().text,align:"center",verticalAlign:"middle",listening:false})]}),jsx(Text,{text:"Answer (Extended response):",x:b,y:C+M+y,fontSize:14,fill:"#6b7280",width:e.width-b*2,listening:false}),jsx(Rect,{x:b,y:C+M+A,width:e.width-b*2,height:k,fill:"#ffffff",stroke:"#d1d5db",strokeWidth:2,cornerRadius:8}),jsx(Html,{groupProps:{x:b,y:C+M+A},divProps:{style:{width:`${e.width-b*2}px`,height:`${k}px`,pointerEvents:f?"none":"auto"}},children:jsx("textarea",{value:d,onChange:U=>m(U.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+M+A+k+y+B,children:f&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:u==="reset"?.95:1,scaleY:u==="reset"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:U=>U.cancelBubble=true,onTap:U=>U.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});vl.displayName="LongAnswer";var hc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(vl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,n.id)},n.id))});var $a=1600,Ya=900,vc=3200,yc=1800,Vb=.4,qb=1.5,Hb=e=>{let o=0,t=0,a=$a,s=Ya;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:$a,height:Ya};let r=(i,d,m,f)=>{o=Math.min(o,i),t=Math.min(t,d),a=Math.max(a,i+m),s=Math.max(s,d+f);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let d=i.x||0,m=i.y||0,f=i.scaleX||1,l=i.scaleY||1;for(let u=0;u<i.points.length;u+=2){let p=d+i.points[u]*f,v=m+i.points[u+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(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let n=Math.min(a-o,vc),c=Math.min(s-t,yc);return o=Math.max(o,a-vc),t=Math.max(t,s-yc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:c}},Ub=(e,o,t={minX:0,minY:0,maxX:$a,maxY:Ya,width:$a,height:Ya})=>{let a=Math.max(t.width,$a),s=Math.max(t.height,Ya),r=e/o,n=a/s,c,i,d,f=0;if(r>n){i=s,c=Math.round(i*r),d=o/i;}else {c=a,i=Math.round(c/r),d=e/c;let l=s*d;f=(o-l)/2;}return d=Math.max(Vb,Math.min(qb,d)),{scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:c,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},wc=(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}},zb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=it(),n=ze(),c=ee(L=>L.toolbar.selectedTool),i=ee(ge),d=ee(co),m=ee(As),l=(i?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),u=!!l,p=useCallback(()=>{l&&r(Oa(l.id));},[r,l]),v=i?.editingActivity,h=i?.showMcqForm,g=i?.lines||[],x=useRef(null),w=useRef(null),[b,C]=useState(null),[M,k]=useState(""),y=useRef(null),[S,B]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:$a,stageHeight:Ya,offsetX:0,offsetY:0,baseWidth:$a,baseHeight:Ya,contentOffsetX:0,contentOffsetY:0}),A=useMemo(()=>Hb(i||null),[d]),[R,U]=useState(null),[E,_]=useState(null),[D,te]=useState(null),[V,oe]=useState(null),[W,q]=useState(null),[$,z]=useState(null),[H,Y]=useState(null),[Q,Z]=useState(false),[re,ye]=useState(null),[Be,Ce]=useState(false),Oe=useRef(null),jt=useRef(null),da=useRef(null),{debouncedGenerateThumbnail:Hr}=$d(d,x);useEffect(()=>{let L=()=>{if(w.current){let P=w.current.getBoundingClientRect(),O=Ub(P.width,P.height,A);B(O);}};L();let I=new ResizeObserver(L);return w.current&&I.observe(w.current),window.addEventListener("resize",L),()=>{I.disconnect(),window.removeEventListener("resize",L);}},[A]),useEffect(()=>{if(x.current){let L=x.current.container();L&&(L.style.cursor="");}},[c]);let ie=useCallback(()=>{x.current&&requestAnimationFrame(()=>{if(!x.current)return;if(x.current.getLayers().forEach(I=>I.batchDraw()),!m)try{let P=x.current.toDataURL({pixelRatio:.16666666666666666});k(P),Hr();}catch(I){console.warn("Preview generation failed (CORS):",I);}});},[Hr,m]),Ur=useRef(d);useEffect(()=>{Ur.current!==d&&(Ur.current=d,ie());},[d,ie]);let Fa=useRef(null),zr=useRef(true);useEffect(()=>{if(!i)return;let L=(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=Fa.current?.count!==L;!zr.current&&I&&setTimeout(()=>{ie();},100),Fa.current={slideId:d,count:L},zr.current=false;},[i,d,ie]),useEffect(()=>{x.current&&e&&e(x);},[e]),useEffect(()=>{da.current&&a&&a(da);},[a]);let{startDrawing:Wr,draw:Gr,stopDrawing:Ko,setCanvasRef:Mn,tool:Tn,color:An,strokeWidth:Pn,isSketchMode:Dn}=Ld(ie),F=useRef(new Map),{images:ne,getLoadedImage:we,imageRefs:pe,handleDragEnd:se,handleImageTransformEnd:ue}=Ad(ie),{videos:Le,videoRefs:Ve,handleVideoClick:Lt,handleVideoDragEnd:mt,handleVideoTransformEnd:Ae}=Rd(ie),{multipleChoice:Qe,handleMcqTransform:St,mcqRefs:Nt,handleDragEnd:Rn}=Pd(ie),{trueFalse:En,handleTrueFalseTransform:Kr,trueFalseRefs:st,handleTrueFalseDragEnd:ua}=Dd(ie),{shortAnswers:Ba,saRefs:_o,handleShortAnswerDragEnd:mm}=Vd(ie),{longAnswers:pm,handleLongAnswerDragEnd:hm}=qd(ie),{fillInTheBlanks:gm,handleFillInTheBlanksDragEnd:xm,fibRefs:_r}=lc(ie),{transformerRef:fe,boundBoxFunc:It}=Kd(),{shapes:bm,shapeRefs:jr,isDragging:sd,handleShapeDragEnd:vm,handleShapeResizeEnd:ym}=Bd(ie),{texts:jo,textRefs:ca,handleDragEnd:wm,handleTransformEnd:Lm,handleDoubleClick:Sm,startEditing:Xr,editingTextId:he,editingValue:nd,handleEditingChange:id,finishEditing:Fn}=Nd(ie,Oe);useEffect(()=>{t&&t(Xr);},[t,Xr]);let $r=ee(L=>L.canvas.editingTextId);useEffect(()=>{$r&&$r!==he&&Xr($r);},[$r,he,Xr]);let{flashcards:Im,flashcardRefs:Yr,handleDragEnd:Cm,handleFlashcardTransformEnd:km,handleNext:Mm,handlePrevious:Tm}=Ud(ie),{photoFrames:ld,photoFrameRefs:Jr,handleDragEnd:Am,handlePhotoFrameTransformEnd:Pm,startCamera:Dm,capturePhoto:Rm,cameraStreams:Em}=Gd(ie);useEffect(()=>{if(fe.current){if(he){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(b&&!Le.find(P=>P.id===b)?.isPlaying){let P=F.current.get(b)||pe.current.get(b)||Ve.current.get(b)||jr.current.get(b)||ca.current.get(b)||Nt.current.get(b)||Yr.current.get(b)||Jr.current.get(b)||_o.current.get(b)||st.current.get(b)||_r.current.get(b);if(P){let O=P.attrs?.locked;if(P.visible()&&O!==true){fe.current.nodes([P]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[b,he,Le,F,pe,Ve,jr,ca,Yr,Jr,ld,Nt,st,_r,fe]);let Ke=useCallback(L=>{C(L),o?.(L);},[o]),so=useCallback(()=>{C(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),dd=useCallback(L=>i?i.lines?.some(I=>I.id===L)?"line":i.images?.some(I=>I.id===L)?"image":i.videos?.some(I=>I.id===L)?"video":i.shapes?.some(I=>I.id===L)?"shape":i.texts?.some(I=>I.id===L)?"text":i.flashcards?.some(I=>I.id===L)?"flashcard":i.photoFrames?.some(I=>I.id===L)?"photoFrame":i.multipleChoices?.some(I=>I.id===L)?"mcq":i.trueFalses?.some(I=>I.id===L)?"trueFalse":i.shortAnswers?.some(I=>I.id===L)?"shortAnswer":i.LongAnswer?.some(I=>I.id===L)?"longAnswer":i.fillInTheBlanks?.some(I=>I.id===L)?"fillInTheBlanks":null:null,[i]),ud=useCallback((L,I)=>{switch(r(ce()),I){case "line":r(Ms(L));break;case "image":r(Qr(L));break;case "video":r(os(L));break;case "shape":r(ns(L));break;case "text":r(is(L));break;case "flashcard":r(ds(L));break;case "photoFrame":r(cs(L));break;case "mcq":r(ms(L));break;case "trueFalse":r(hs(L));break;case "shortAnswer":r(xs(L));break;case "longAnswer":r(vs(L));break;case "fillInTheBlanks":r(ws(L));break}so(),ie();},[r,so,ie]);useEffect(()=>{let L=I=>{if(I.key!=="Delete"||!b||he)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;I.preventDefault();let Pe=dd(b);Pe&&ud(b,Pe);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[b,he,dd,ud]),useEffect(()=>{let L=fe.current;return ()=>{L&&L.nodes([]);}},[d]),useEffect(()=>{let L=I=>{he&&I.target.tagName!=="TEXTAREA"&&Fn();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[he,Fn]),useEffect(()=>{let L=he||b;if(!L||b&&he){_(null);return}let I=ca.current.get(L),P=x.current;if(!I||!P){_(null);return}let O=P.container().getBoundingClientRect(),Pe=I.absolutePosition(),Se=P.scaleX();_({x:O.left+(Pe.x+I.width()*Se/2)*Se,y:O.top+Pe.y*Se});},[b,he,jo,ca]),useEffect(()=>{if(!he){te(null);return}let L=ca.current.get(he),I=x.current;if(!L||!I){te(null);return}let P=I.container().getBoundingClientRect(),O=L.absolutePosition(),Pe=I.scaleX();te({top:P.top+O.y*Pe,left:P.left+O.x*Pe,scale:Pe});},[he,jo,ca]);let cd=useCallback(L=>{let I=L.target.getClassName(),P=L.target===L.target.getStage(),O=I==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",Pe=I==="Image",Se=I==="Text",ae=I==="Group"||L.target.getParent()?.getClassName()==="Group",Vt=I==="Circle"||I==="Star"||I==="RegularPolygon"||I==="Ellipse"||I==="Ring"||I==="Wedge"||I==="Arrow"||I==="Line"||I==="Arc"||I==="Rect"&&L.target.attrs.id,kt=I==="Group";if(P&&!O&&!Pe&&!Se&&!ae&&!Vt&&!kt&&so(),!(c==="pen"||c==="eraser")&&(Pe||Se||O||ae||Vt||kt))return;let $e=L.target.getStage()?.getPointerPosition();if(!$e)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(c)){let N=wc($e,S);Wr(N);}},[c,Wr,so,S]),fd=useCallback(L=>{if(sd)return;let I=L.target.getStage()?.getPointerPosition();if(!I)return;let P=wc(I,S);Gr(P);},[Gr,sd,S]),md=useCallback(()=>{Ko();},[Ko]),Fm=useCallback(L=>{se(L,ie);},[se,ie]),Bm=useCallback(L=>{Lt(L),Ke(L);},[Lt,Ke]),Ct=useCallback((L,I,P)=>{if(L.preventDefault(),!s.enabled)return;let O=L.clientX,Pe=L.clientY,Se=y.current?.offsetHeight||450,ae=y.current?.offsetWidth||450,Vt=window.innerHeight,kt=window.innerWidth,nt=O,$e=Pe;Pe+Se>Vt&&($e=Pe-Se),O+ae>kt&&(nt=O-ae),U({x:nt,y:$e,elementId:I,elementType:P}),Ke(I);},[Ke,s.enabled]),pd=useCallback(L=>{r(Zo(L)),r(pa(true));},[r]),Om=useCallback(L=>{r(Xo(L)),r(Va(true));},[r]),Nm=useCallback((L,I)=>{if(!R)return;let{elementId:P,elementType:O}=R;switch(L){case "order":if(I){let T=I.target.getBoundingClientRect();oe({x:T.right+5,y:T.top,type:"order"});}break;case "lock":if(I){let T=I.target.getBoundingClientRect();oe({x:T.right+5,y:T.top,type:"lock"});}break;case "link":if(U(null),O==="line")break;let Pe=i?O==="image"?i.images.find(T=>T.id===P):i.videos.find(T=>T.id===P):null;q({type:"link",defaultValue:Pe?.link||""});break;case "voice":if(U(null),O==="line")break;let Se=i?O==="image"?i.images.find(T=>T.id===P):O==="video"?i.videos.find(T=>T.id===P):O==="text"?i.texts.find(T=>T.id===P):O==="flashcard"?i.flashcards.find(T=>T.id===P):O==="photoFrame"?i.photoFrames.find(T=>T.id===P):O==="mcq"?i.multipleChoices.find(T=>T.id===P):O==="fillInTheBlanks"?i.fillInTheBlanks.find(T=>T.id===P):O==="longAnswer"?i.LongAnswer.find(T=>T.id===P):O==="shortAnswer"?i.shortAnswers.find(T=>T.id===P):O==="trueFalse"?i.trueFalses.find(T=>T.id===P):O==="shape"?i.shapes.find(T=>T.id===P):null:null;ye({elementId:P,elementType:O,existingAudio:Se?.audioData});break;case "edit":U(null);let ae=null;O==="mcq"?ae=i?.multipleChoices.find(T=>T.id===P):O==="trueFalse"?ae=i?.trueFalses.find(T=>T.id===P):O==="shortAnswer"?ae=i?.shortAnswers.find(T=>T.id===P):O==="longAnswer"?ae=i?.LongAnswer.find(T=>T.id===P):O==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(T=>T.id===P)),ae&&pd(ae);break;case "editFlashcard":U(null);let Vt=i?.flashcards.find(T=>T.id===P);Vt&&Om(Vt);break;case "color":U(null);let kt=i?.shapes.find(T=>T.id===P);z({elementId:P,elementType:"shape",defaultColor:kt?.color||"#096B76"});break;case "crop":if(U(null),O==="image"){let T=i?.images.find(Gm=>Gm.id===P);T&&Y({elementId:P,imageSrc:T.src});}break;case "draw":U(null),O==="image"?r(ei(P)):O==="photoFrame"&&r(ai(P));break;case "duplicate":r(ce()),O==="line"?r(pi(P)):O==="image"?r(es(P)):O==="video"?r(rs(P)):O==="shape"?r(ss(P)):O==="text"?r(ls(P)):O==="flashcard"?r(us(P)):O==="photoFrame"?r(fs(P)):O==="mcq"?r(ps(P)):O==="trueFalse"?r(gs(P)):O==="shortAnswer"?r(bs(P)):O==="fillInTheBlanks"?r(Ls(P)):O==="longAnswer"&&r(ys(P)),ie();break;case "infinite-clone":r(ce());let nt=5;for(let T=0;T<nt;T++)O==="image"?r(es(P)):O==="video"?r(rs(P)):O==="shape"?r(ss(P)):O==="text"?r(ls(P)):O==="flashcard"?r(us(P)):O==="photoFrame"?r(fs(P)):O==="mcq"?r(ps(P)):O==="trueFalse"?r(gs(P)):O==="shortAnswer"?r(bs(P)):O==="fillInTheBlanks"?r(Ls(P)):O==="longAnswer"&&r(ys(P));ie();break;case "make-response":if(U(null),O==="line")break;let $e=`#response-${P}`;r(ce()),r(Ss({id:P,type:O,link:$e})),(i?O==="image"?i.images.find(T=>T.id===P):O==="video"?i.videos.find(T=>T.id===P):O==="shape"?i.shapes.find(T=>T.id===P):O==="flashcard"?i.flashcards.find(T=>T.id===P):O==="photoFrame"?i.photoFrames.find(T=>T.id===P):i.multipleChoices.find(T=>T.id===P):null)?.altText||r(Is({id:P,type:O,altText:"Interactive response area"})),ie(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(U(null),O==="line")break;let N=i?O==="image"?i.images.find(T=>T.id===P):O==="video"?i.videos.find(T=>T.id===P):O==="shape"?i.shapes.find(T=>T.id===P):null:null;q({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),U(null),Ce(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),O==="line"?r(Ms(P)):O==="image"?r(Qr(P)):O==="video"?r(os(P)):O==="shape"?r(ns(P)):O==="text"?r(is(P)):O==="flashcard"?r(ds(P)):O==="photoFrame"?r(cs(P)):O==="mcq"?r(ms(P)):O==="trueFalse"?r(hs(P)):O==="shortAnswer"?r(xs(P)):O==="longAnswer"?r(vs(P)):O==="fillInTheBlanks"&&r(ws(P)),so(),ie();break}},[R,r,ie,so,i,pd]),Vm=useCallback(()=>{U(null),oe(null);},[]),Bn=useCallback(L=>{if(!R)return;let{elementId:I,elementType:P}=R;switch(r(ce()),L){case "bring-to-front":P!=="line"&&r(ui({id:I,type:P}));break;case "send-to-back":P!=="line"&&r(ci({id:I,type:P}));break;case "lock":case "unlock":P!=="line"&&r(fi({id:I,type:P}));break}ie(),U(null),oe(null);},[R,r,ie]),qm=useCallback(L=>{if(!R||!W)return;let{elementId:I,elementType:P}=R;r(ce()),W.type==="link"&&P!=="line"?r(Ss({id:I,type:P,link:L})):W.type==="altText"&&P!=="line"&&r(Is({id:I,type:P,altText:L})),ie(),q(null);},[R,W,r,ie]),Hm=useCallback(L=>{if(!re)return;let{elementId:I,elementType:P}=re;r(ce()),r(Cs({id:I,type:P,audioData:L})),ie(),ye(null);},[re,r,ie]),Um=useCallback(()=>{if(!re)return;let{elementId:L,elementType:I}=re;r(ce()),r(Cs({id:L,type:I,audioData:""})),ie();},[re,r,ie]),zm=useCallback(L=>{if(!$)return;let{elementId:I}=$;r(ce()),r(lo({id:I,color:L})),ie(),z(null);},[$,r,ie]),Wm=useCallback(L=>{if(!H)return;let{elementId:I}=H;r(ce()),r(io({id:I,src:L})),ie(),Y(null);},[H,r,ie]);return jsxs("div",{ref:w,className:"fixed inset-0",style:{cursor:c==="pen"?"crosshair":c==="eraser"?"":"default"},children:[c==="pen"&&jsx(Md,{ref:L=>{if(jt.current=L,Mn(L),L){let I=L.getCanvasElement();I&&(da.current=I,a&&a(da));}},width:S.baseWidth,height:S.baseHeight,tool:Tn,color:An,strokeWidth:Pn/S.scale,isSketchMode:Dn,xOffset:S.contentOffsetX,yOffset:S.contentOffsetY-S.offsetY/S.scale,style:{width:S.stageWidth,height:S.stageHeight}}),jsxs(Stage,{ref:x,width:S.stageWidth,height:S.stageHeight,scaleX:S.scaleX,scaleY:S.scaleY,x:S.offsetX,y:0,onMouseDown:cd,onMouseMove:fd,onMouseUp:md,onTouchStart:cd,onTouchMove:fd,onTouchEnd:md,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:S.baseWidth,height:S.stageHeight/S.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-S.contentOffsetX,y:S.offsetY/S.scale-S.contentOffsetY,children:(()=>{let L=[];return g.forEach((I,P)=>{L.push({type:"line",timestamp:I.timestamp||P,element:{...I,id:I.id??`line-${P}`},index:P});}),bm.forEach(I=>{L.push({type:"shape",timestamp:I.timestamp||0,element:I});}),ne.forEach(I=>{L.push({type:"image",timestamp:I.timestamp||0,element:I});}),Le.forEach(I=>{L.push({type:"video",timestamp:I.timestamp||0,element:I});}),jo.forEach(I=>{L.push({type:"text",timestamp:I.timestamp||0,element:I});}),Im.forEach(I=>{L.push({type:"flashcard",timestamp:I.timestamp||0,element:I});}),ld.forEach(I=>{L.push({type:"photoFrame",timestamp:I.timestamp||0,element:I});}),Qe.forEach(I=>{L.push({type:"mcq",timestamp:I.timestamp||0,element:I});}),En.forEach(I=>{L.push({type:"trueFalse",timestamp:I.timestamp||0,element:I});}),Ba.forEach(I=>{L.push({type:"shortAnswer",timestamp:I.timestamp||0,element:I});}),pm.forEach(I=>{L.push({type:"longAnswer",timestamp:I.timestamp||0,element:I});}),gm.forEach(I=>{L.push({type:"fillInTheBlanks",timestamp:I.timestamp||0,element:I});}),L.sort((I,P)=>I.timestamp-P.timestamp),L.map((I,P)=>{let O=`${I.type}-${"id"in I.element&&I.element.id||I.index||P}`,Pe="id"in I.element?I.element.id:void 0,Se=Pe&&b===Pe;switch(I.type){case "line":let ae=I.element,Vt=I.index||0,kt=ae.tool==="eraser",nt=ae.isSketch&&ae.tool==="pen",$e=ae.isSketch&&kt,Mt=ae.id||`line-${Vt}`;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),c==="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:nt||$e?void 0:ae.color,strokeWidth:nt||$e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:nt||$e?kt?"black":ae.color:void 0,closed:nt||$e,tension:0,globalCompositeOperation:kt?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(Zr(Vt));},onTap:()=>{r(ce()),r(Zr(Vt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:N=>{let T=N.target.getStage();T&&(T.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 T=N.target.getStage();T&&(T.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(be__default.Fragment,{children:[jsx(Group,{id:Mt,ref:N=>{N?F.current.set(Mt,N):F.current.delete(Mt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:c==="select",listening:c==="select",onClick:()=>{c==="select"&&(console.log("Line clicked:",Mt),Ke(Mt));},onTap:()=>{c==="select"&&(console.log("Line tapped:",Mt),Ke(Mt));},onDragEnd:N=>{r(ce()),r(ks({id:Mt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ie();},onTransformEnd:N=>{r(ce()),r(ks({id:Mt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ie();},onMouseEnter:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="move");}},onMouseLeave:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="default");}},onContextMenu:N=>{let T=N.evt;T.preventDefault(),Ct(T,Mt,"line");},children:jsx(Line,{points:ae.points||[],stroke:nt||$e?void 0:ae.color,strokeWidth:nt||$e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:nt||$e?kt?"black":ae.color:void 0,closed:nt||$e,tension:0,globalCompositeOperation:kt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=F.current.get(b);console.log("Line Transformer - selectedId:",b,"node found:",!!T),T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Fi,{onSelect:Ke,shapes:[I.element],shapeRefs:jr,handleShapeDragEnd:vm,handleShapeResizeEnd:ym,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "image":return jsxs(be__default.Fragment,{children:[jsx(Pi,{images:[I.element],getLoadedImage:we,imageRefs:pe,onDragEnd:Fm,onTransform:ue,onSelect:Ke,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=pe.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "video":return jsxs(be__default.Fragment,{children:[jsx(Ei,{videos:[I.element],selectedId:b,videoRefs:Ve,onVideoClick:Bm,onDragEnd:mt,onTransformEnd:Ae,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Ve.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "text":return jsxs(be__default.Fragment,{children:[jsx(nu,{texts:[I.element],textRefs:ca,onDragEnd:wm,onTransformEnd:Lm,onSelect:Ke,onContextMenu:Ct,onDoubleClick:Sm,editingTextId:he,editingValue:nd,onEditingChange:id}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=ca.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Ni,{flashcards:[I.element],flashcardRefs:Yr,selectedId:b,onDragEnd:Cm,onTransform:km,onSelect:Ke,onNext:Mm,onPrevious:Tm,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Yr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(Wi,{photoFrames:[I.element],photoFrameRefs:Jr,selectedId:b,onDragEnd:Am,onTransform:Pm,onSelect:Ke,onStartCamera:Dm,onCapture:Rm,cameraStreams:Em,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Nu,{handleMcqTransform:St,multipleChoice:[I.element],handleSelect:Ke,mcqRefs:Nt,handleDragEnd:Rn,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Nt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Hu,{trueFalses:[I.element],handleTrueFalseTransform:Kr,handleSelect:Ke,trueFalseRefs:st,onContextMenu:Ct,handleDragEnd:ua}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=st.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(ic,{shortAnswers:[I.element],handleSelect:Ke,handleTransform:St,saRefs:_o,onContextMenu:Ct,handleDragEnd:mm}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_o.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(hc,{longAnswer:[I.element],handleSelect:Ke,handleTransform:St,saRefs:_o,onContextMenu:Ct,handleDragEnd:hm}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_o.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(mc,{fillInTheBlanks:[I.element],handleSelect:Ke,handleTransform:St,onContextMenu:Ct,handleDragEnd:xm,fibRefs:_r}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_r.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);default:return null}})})()})]}),R&&jsx(vu,{menuRef:y,x:R.x,y:R.y,type:R.elementType,onAction:Nm,onClose:Vm,isDrawingMode:R.elementType==="image"?i?.images.find(L=>L.id===R.elementId)?.isDrawingMode:R.elementType==="photoFrame"?i?.photoFrames.find(L=>L.id===R.elementId)?.isDrawingMode:false}),V&&R&&jsx(yu,{x:V.x,y:V.y,items:V.type==="order"?[{label:"Bring to Front",onClick:()=>Bn("bring-to-front")},{label:"Send to Back",onClick:()=>Bn("send-to-back")}]:[{label:i&&(R.elementType==="image"?i.images.find(L=>L.id===R.elementId)?.locked:i.videos.find(L=>L.id===R.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Bn(i&&(R.elementType==="image"?i.images.find(L=>L.id===R.elementId)?.locked:i.videos.find(L=>L.id===R.elementId)?.locked)?"unlock":"lock")}],onClose:()=>oe(null)}),W&&jsx(Su,{title:W.type==="link"?"Add Link":"Add Alt Text",label:W.type==="link"?"URL":"Alternative Text",placeholder:W.type==="link"?"https://example.com":"Describe this image/video",defaultValue:W.defaultValue,onSave:qm,onClose:()=>q(null)}),$&&jsx(Ns,{defaultColor:$.defaultColor,onConfirm:zm,onCancel:()=>z(null)}),H&&jsx(Mu,{imageSrc:H.imageSrc,onConfirm:Wm,onCancel:()=>Y(null)}),Q&&jsx(dr,{onClose:()=>Z(false),stageRef:x}),re&&jsx(Du,{elementId:re.elementId,elementType:re.elementType,existingAudio:re.existingAudio,onSave:Hm,onDelete:Um,onClose:()=>ye(null)}),Be&&jsx(Fu,{selectedElementId:b||void 0,onClose:()=>Ce(false),onSelectElement:L=>{Ke(L),Ce(false);}}),i?.images.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.videos.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.shapes?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.texts?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),h&&jsx(Ju,{editElement:v}),E&&(()=>{let L=he||b;if(!L)return null;let I=jo.find(P=>P.id===L);return I?jsx(tc,{text:I,position:E}):null})(),D&&he&&(()=>{let L=jo.find(I=>I.id===he);return L?jsx(oc,{text:L,editingValue:nd,onEditingChange:id,onFinish:Fn,position:{top:D.top,left:D.left},scale:D.scale,textareaRef:Oe},he):null})(),u&&n&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:l?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:p})}),jsx("button",{onClick:p,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X$1,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),n)]})},Wb=zb;function yl(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 Lc(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=Lc(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():Lc(e[s],null);}}}}function Bt(...e){return be.useCallback(Dr(...e),e)}function Ma(e,o=[]){let t=[];function a(r,n){let c=be.createContext(n),i=t.length;t=[...t,n];let d=f=>{let{scope:l,children:u,...p}=f,v=l?.[e]?.[i]||c,h=be.useMemo(()=>p,Object.values(p));return jsx(v.Provider,{value:h,children:u})};d.displayName=r+"Provider";function m(f,l){let u=l?.[e]?.[i]||c,p=be.useContext(u);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${f}\` must be used within \`${r}\``)}return [d,m]}let s=()=>{let r=t.map(n=>be.createContext(n));return function(c){let i=c?.[e]||r;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:i}}),[c,i])}};return s.scopeName=e,[a,_b(s,...o)]}function _b(...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((c,{useScope:i,scopeName:d})=>{let f=i(r)[`__scope${d}`];return {...c,...f}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var Bo=globalThis?.document?be.useLayoutEffect:()=>{};var jb=be[" useInsertionEffect ".trim().toString()]||Bo;function aa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=Xb({defaultProp:o,onChange:t}),c=e!==void 0,i=c?e:s;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let f=m.current;f!==c&&console.warn(`${a} is changing from ${f?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=c;},[c,a]);}let d=be.useCallback(m=>{if(c){let f=$b(m)?m(e):m;f!==e&&n.current?.(f);}else r(m);},[c,e,r,n]);return [i,d]}function Xb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),s=be.useRef(t),r=be.useRef(o);return jb(()=>{r.current=o;},[o]),be.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function $b(e){return typeof e=="function"}var Yb=be.createContext(void 0);function Oo(e){let o=be.useContext(Yb);return e||o||"ltr"}function Cc(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 Mc(e){let[o,t]=be.useState(void 0);return Bo(()=>{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,c;if("borderBoxSize"in r){let i=r.borderBoxSize,d=Array.isArray(i)?i[0]:i;n=d.inlineSize,c=d.blockSize;}else n=e.offsetWidth,c=e.offsetHeight;t({width:n,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Ac(e){let o=Jb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(Qb);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,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=tv(s),c=ev(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Zb=Symbol("radix.slottable");function Qb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Zb}function ev(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]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function tv(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 rv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ct=rv.reduce((e,o)=>{let t=Ac(`Primitive.${o}`),a=be.forwardRef((s,r)=>{let{asChild:n,...c}=s,i=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...c,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function wl(e){let o=sv(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(iv);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function sv(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=dv(s),c=lv(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var nv=Symbol("radix.slottable");function iv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===nv}function lv(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]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function dv(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 fn(e){let o=e+"CollectionProvider",[t,a]=Ma(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=v=>{let{scope:h,children:g}=v,x=be__default.useRef(null),w=be__default.useRef(new Map).current;return jsx(s,{scope:h,itemMap:w,collectionRef:x,children:g})};n.displayName=o;let c=e+"CollectionSlot",i=wl(c),d=be__default.forwardRef((v,h)=>{let{scope:g,children:x}=v,w=r(c,g),b=Bt(h,w.collectionRef);return jsx(i,{ref:b,children:x})});d.displayName=c;let m=e+"CollectionItemSlot",f="data-radix-collection-item",l=wl(m),u=be__default.forwardRef((v,h)=>{let{scope:g,children:x,...w}=v,b=be__default.useRef(null),C=Bt(h,b),M=r(m,g);return be__default.useEffect(()=>(M.itemMap.set(b,{ref:b,...w}),()=>void M.itemMap.delete(b))),jsx(l,{[f]:"",ref:C,children:x})});u.displayName=m;function p(v){let h=r(e+"CollectionConsumer",v);return be__default.useCallback(()=>{let x=h.collectionRef.current;if(!x)return [];let w=Array.from(x.querySelectorAll(`[${f}]`));return Array.from(h.itemMap.values()).sort((M,k)=>w.indexOf(M.ref.current)-w.indexOf(k.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:d,ItemSlot:u},p,a]}var Rc=["PageUp","PageDown"],Ec=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Fc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},No="Slider",[Sl,cv,fv]=fn(No),[Bc]=Ma(No,[fv]),[mv,mn]=Bc(No),Oc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:c=false,minStepsBetweenThumbs:i=0,defaultValue:d=[a],value:m,onValueChange:f=()=>{},onValueCommit:l=()=>{},inverted:u=false,form:p,...v}=e,h=be.useRef(new Set),g=be.useRef(0),w=n==="horizontal"?pv:hv,[b=[],C]=aa({prop:m,defaultProp:d,onChange:A=>{[...h.current][g.current]?.focus(),f(A);}}),M=be.useRef(b);function k(A){let R=yv(b,A);B(A,R);}function y(A){B(A,g.current);}function S(){let A=M.current[g.current];b[g.current]!==A&&l(b);}function B(A,R,{commit:U}={commit:false}){let E=Iv(r),_=Cv(Math.round((A-a)/r)*r+a,E),D=yl(_,[a,s]);C((te=[])=>{let V=bv(te,D,R);if(Sv(V,i*r)){g.current=V.indexOf(D);let oe=String(V)!==String(te);return oe&&U&&l(V),oe?V:te}else return te});}return jsx(mv,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:s,valueIndexToChangeRef:g,thumbs:h.current,values:b,orientation:n,form:p,children:jsx(Sl.Provider,{scope:e.__scopeSlider,children:jsx(Sl.Slot,{scope:e.__scopeSlider,children:jsx(w,{"aria-disabled":c,"data-disabled":c?"":void 0,...v,ref:o,onPointerDown:Je(v.onPointerDown,()=>{c||(M.current=b);}),min:a,max:s,inverted:u,onSlideStart:c?void 0:k,onSlideMove:c?void 0:y,onSlideEnd:c?void 0:S,onHomeKeyDown:()=>!c&&B(a,0,{commit:true}),onEndKeyDown:()=>!c&&B(s,b.length-1,{commit:true}),onStepKeyDown:({event:A,direction:R})=>{if(!c){let _=Rc.includes(A.key)||A.shiftKey&&Ec.includes(A.key)?10:1,D=g.current,te=b[D],V=r*_*R;B(te+V,D,{commit:true});}}})})})})});Oc.displayName=No;var[Nc,Vc]=Bc(No,{startEdge:"left",endEdge:"right",size:"width",direction:1}),pv=be.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:c,onSlideEnd:i,onStepKeyDown:d,...m}=e,[f,l]=be.useState(null),u=Bt(o,w=>l(w)),p=be.useRef(void 0),v=Oo(s),h=v==="ltr",g=h&&!r||!h&&r;function x(w){let b=p.current||f.getBoundingClientRect(),C=[0,b.width],k=kl(C,g?[t,a]:[a,t]);return p.current=b,k(w-b.left)}return jsx(Nc,{scope:e.__scopeSlider,startEdge:g?"left":"right",endEdge:g?"right":"left",direction:g?1:-1,size:"width",children:jsx(qc,{dir:v,"data-orientation":"horizontal",...m,ref:u,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{let b=x(w.clientX);n?.(b);},onSlideMove:w=>{let b=x(w.clientX);c?.(b);},onSlideEnd:()=>{p.current=void 0,i?.();},onStepKeyDown:w=>{let C=Fc[g?"from-left":"from-right"].includes(w.key);d?.({event:w,direction:C?-1:1});}})})}),hv=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:c,onStepKeyDown:i,...d}=e,m=be.useRef(null),f=Bt(o,m),l=be.useRef(void 0),u=!s;function p(v){let h=l.current||m.current.getBoundingClientRect(),g=[0,h.height],w=kl(g,u?[a,t]:[t,a]);return l.current=h,w(v-h.top)}return jsx(Nc,{scope:e.__scopeSlider,startEdge:u?"bottom":"top",endEdge:u?"top":"bottom",size:"height",direction:u?1:-1,children:jsx(qc,{"data-orientation":"vertical",...d,ref:f,style:{...d.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,c?.();},onStepKeyDown:v=>{let g=Fc[u?"from-bottom":"from-top"].includes(v.key);i?.({event:v,direction:g?-1:1});}})})}),qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:c,onStepKeyDown:i,...d}=e,m=mn(No,t);return jsx(ct.span,{...d,ref:o,onKeyDown:Je(e.onKeyDown,f=>{f.key==="Home"?(n(f),f.preventDefault()):f.key==="End"?(c(f),f.preventDefault()):Rc.concat(Ec).includes(f.key)&&(i(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));})})}),Hc="SliderTrack",Uc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=mn(Hc,t);return jsx(ct.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});Uc.displayName=Hc;var Il="SliderRange",zc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=mn(Il,t),r=Vc(Il,t),n=be.useRef(null),c=Bt(o,n),i=s.values.length,d=s.values.map(l=>Kc(l,s.min,s.max)),m=i>1?Math.min(...d):0,f=100-Math.max(...d);return jsx(ct.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:c,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:f+"%"}})});zc.displayName=Il;var Cl="SliderThumb",Wc=be.forwardRef((e,o)=>{let t=cv(e.__scopeSlider),[a,s]=be.useState(null),r=Bt(o,c=>s(c)),n=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(gv,{...e,ref:r,index:n})}),gv=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=mn(Cl,t),c=Vc(Cl,t),[i,d]=be.useState(null),m=Bt(o,x=>d(x)),f=i?n.form||!!i.closest("form"):true,l=Mc(i),u=n.values[a],p=u===void 0?0:Kc(u,n.min,n.max),v=vv(a,n.values.length),h=l?.[c.size],g=h?wv(h,p,c.direction):0;return be.useEffect(()=>{if(i)return n.thumbs.add(i),()=>{n.thumbs.delete(i);}},[i,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${p}% + ${g}px)`},children:[jsx(Sl.ItemSlot,{scope:e.__scopeSlider,children:jsx(ct.span,{role:"slider","aria-label":e["aria-label"]||v,"aria-valuemin":n.min,"aria-valuenow":u,"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:u===void 0?{display:"none"}:e.style,onFocus:Je(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),f&&jsx(Gc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:u},a)]})});Wc.displayName=Cl;var xv="RadioBubbleInput",Gc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=be.useRef(null),r=Bt(s,a),n=Cc(o);return be.useEffect(()=>{let c=s.current;if(!c)return;let i=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(i,"value").set;if(n!==o&&m){let f=new Event("input",{bubbles:true});m.call(c,o),c.dispatchEvent(f);}},[n,o]),jsx(ct.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});Gc.displayName=xv;function bv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Kc(e,o,t){let r=100/(t-o)*(e-o);return yl(r,[0,100])}function vv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function yv(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 wv(e,o,t){let a=e/2,r=kl([0,50],[0,a]);return (a-r(o)*t)*t}function Lv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Sv(e,o){if(o>0){let t=Lv(e);return Math.min(...t)>=o}return true}function kl(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 Iv(e){return (String(e).split(".")[1]||"").length}function Cv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var _c=Oc,jc=Uc,Xc=zc,$c=Wc;function Yc(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=Yc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function pn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=Yc(e))&&(a&&(a+=" "),a+=o);return a}var Mv=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},Tv=(e,o)=>({classGroupId:e,validator:o}),tf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Jc=[],Av="arbitrary..",Pv=e=>{let o=Rv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Dv(n);let c=n.split("-"),i=c[0]===""&&c.length>1?1:0;return af(c,i,o)},getConflictingClassGroupIds:(n,c)=>{if(c){let i=a[n],d=t[n];return i?d?Mv(d,i):i:d||Jc}return t[n]||Jc}}},af=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let d=af(e,o+1,r);if(d)return d}let n=t.validators;if(n===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),i=n.length;for(let d=0;d<i;d++){let m=n[d];if(m.validator(c))return m.classGroupId}},Dv=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?Av+a:void 0})(),Rv=e=>{let{theme:o,classGroups:t}=e;return Ev(t,o)},Ev=(e,o)=>{let t=tf();for(let a in e){let s=e[a];Al(s,t,a,o);}return t},Al=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Fv(n,o,t,a);}},Fv=(e,o,t,a)=>{if(typeof e=="string"){Bv(e,o,t);return}if(typeof e=="function"){Ov(e,o,t,a);return}Nv(e,o,t,a);},Bv=(e,o,t)=>{let a=e===""?o:of(o,e);a.classGroupId=t;},Ov=(e,o,t,a)=>{if(Vv(e)){Al(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Tv(t,e));},Nv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[c,i]=s[n];Al(i,of(o,c),t,a);}},of=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],c=t.nextPart.get(n);c||(c=tf(),t.nextPart.set(n,c)),t=c;}return t},Vv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,qv=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 Hv=[],Zc=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Uv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,c=0,i=0,d,m=s.length;for(let v=0;v<m;v++){let h=s[v];if(n===0&&c===0){if(h===":"){r.push(s.slice(i,v)),i=v+1;continue}if(h==="/"){d=v;continue}}h==="["?n++:h==="]"?n--:h==="("?c++:h===")"&&c--;}let f=r.length===0?s:s.slice(i),l=f,u=false;f.endsWith("!")?(l=f.slice(0,-1),u=true):f.startsWith("!")&&(l=f.slice(1),u=true);let p=d&&d>i?d-i:void 0;return Zc(r,u,l,p)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):Zc(Hv,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},zv=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],c=n[0]==="[",i=o.has(n);c||i?(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}},Wv=e=>({cache:qv(e.cacheSize),parseClassName:Uv(e),sortModifiers:zv(e),...Pv(e)}),Gv=/\s+/,Kv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],c=e.trim().split(Gv),i="";for(let d=c.length-1;d>=0;d-=1){let m=c[d],{isExternal:f,modifiers:l,hasImportantModifier:u,baseClassName:p,maybePostfixModifierPosition:v}=t(m);if(f){i=m+(i.length>0?" "+i:i);continue}let h=!!v,g=a(h?p.substring(0,v):p);if(!g){if(!h){i=m+(i.length>0?" "+i:i);continue}if(g=a(p),!g){i=m+(i.length>0?" "+i:i);continue}h=false;}let x=l.length===0?"":l.length===1?l[0]:r(l).join(":"),w=u?x+"!":x,b=w+g;if(n.indexOf(b)>-1)continue;n.push(b);let C=s(g,h);for(let M=0;M<C.length;++M){let k=C[M];n.push(w+k);}i=m+(i.length>0?" "+i:i);}return i},_v=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=rf(t))&&(s&&(s+=" "),s+=a);return s},rf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=rf(e[a]))&&(t&&(t+=" "),t+=o);return t},jv=(e,...o)=>{let t,a,s,r,n=i=>{let d=o.reduce((m,f)=>f(m),e());return t=Wv(d),a=t.cache.get,s=t.cache.set,r=c,c(i)},c=i=>{let d=a(i);if(d)return d;let m=Kv(i,t);return s(i,m),m};return r=n,(...i)=>r(_v(...i))},Xv=[],Ue=e=>{let o=t=>t[e]||Xv;return o.isThemeGetter=true,o},sf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,nf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,$v=/^\d+\/\d+$/,Yv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jv=/\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$/,Zv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Qv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ey=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Vo=e=>$v.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ta=e=>!!e&&Number.isInteger(Number(e)),Ml=e=>e.endsWith("%")&&de(e.slice(0,-1)),oa=e=>Yv.test(e),ty=()=>true,ay=e=>Jv.test(e)&&!Zv.test(e),lf=()=>false,oy=e=>Qv.test(e),ry=e=>ey.test(e),sy=e=>!j(e)&&!X(e),ny=e=>qo(e,cf,lf),j=e=>sf.test(e),Za=e=>qo(e,ff,ay),Tl=e=>qo(e,cy,de),Qc=e=>qo(e,df,lf),iy=e=>qo(e,uf,ry),hn=e=>qo(e,mf,oy),X=e=>nf.test(e),Rr=e=>Ho(e,ff),ly=e=>Ho(e,fy),ef=e=>Ho(e,df),dy=e=>Ho(e,cf),uy=e=>Ho(e,uf),gn=e=>Ho(e,mf,true),qo=(e,o,t)=>{let a=sf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Ho=(e,o,t=false)=>{let a=nf.exec(e);return a?a[1]?o(a[1]):t:false},df=e=>e==="position"||e==="percentage",uf=e=>e==="image"||e==="url",cf=e=>e==="length"||e==="size"||e==="bg-size",ff=e=>e==="length",cy=e=>e==="number",fy=e=>e==="family-name",mf=e=>e==="shadow";var my=()=>{let e=Ue("color"),o=Ue("font"),t=Ue("text"),a=Ue("font-weight"),s=Ue("tracking"),r=Ue("leading"),n=Ue("breakpoint"),c=Ue("container"),i=Ue("spacing"),d=Ue("radius"),m=Ue("shadow"),f=Ue("inset-shadow"),l=Ue("text-shadow"),u=Ue("drop-shadow"),p=Ue("blur"),v=Ue("perspective"),h=Ue("aspect"),g=Ue("ease"),x=Ue("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[...b(),X,j],M=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],y=()=>[X,j,i],S=()=>[Vo,"full","auto",...y()],B=()=>[Ta,"none","subgrid",X,j],A=()=>["auto",{span:["full",Ta,X,j]},Ta,X,j],R=()=>[Ta,"auto",X,j],U=()=>["auto","min","max","fr",X,j],E=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],_=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...y()],te=()=>[Vo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...y()],V=()=>[e,X,j],oe=()=>[...b(),ef,Qc,{position:[X,j]}],W=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",dy,ny,{size:[X,j]}],$=()=>[Ml,Rr,Za],z=()=>["","none","full",d,X,j],H=()=>["",de,Rr,Za],Y=()=>["solid","dashed","dotted","double"],Q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Z=()=>[de,Ml,ef,Qc],re=()=>["","none",p,X,j],ye=()=>["none",de,X,j],Be=()=>["none",de,X,j],Ce=()=>[de,X,j],Oe=()=>[Vo,"full",...y()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[oa],breakpoint:[oa],color:[ty],container:[oa],"drop-shadow":[oa],ease:["in","out","in-out"],font:[sy],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[oa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[oa],shadow:[oa],spacing:["px",de],text:[oa],"text-shadow":[oa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Vo,j,X,h]}],container:["container"],columns:[{columns:[de,j,X,c]}],"break-after":[{"break-after":w()}],"break-before":[{"break-before":w()}],"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:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Ta,"auto",X,j]}],basis:[{basis:[Vo,"full","auto",c,...y()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Vo,"auto","initial","none",j]}],grow:[{grow:["",de,X,j]}],shrink:[{shrink:["",de,X,j]}],order:[{order:[Ta,"first","last","none",X,j]}],"grid-cols":[{"grid-cols":B()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":B()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":U()}],"auto-rows":[{"auto-rows":U()}],gap:[{gap:y()}],"gap-x":[{"gap-x":y()}],"gap-y":[{"gap-y":y()}],"justify-content":[{justify:[...E(),"normal"]}],"justify-items":[{"justify-items":[..._(),"normal"]}],"justify-self":[{"justify-self":["auto",..._()]}],"align-content":[{content:["normal",...E()]}],"align-items":[{items:[..._(),{baseline:["","last"]}]}],"align-self":[{self:["auto",..._(),{baseline:["","last"]}]}],"place-content":[{"place-content":E()}],"place-items":[{"place-items":[..._(),"baseline"]}],"place-self":[{"place-self":["auto",..._()]}],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:te()}],w:[{w:[c,"screen",...te()]}],"min-w":[{"min-w":[c,"screen","none",...te()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[n]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",t,Rr,Za]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,X,Tl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ml,j]}],"font-family":[{font:[ly,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,X,j]}],"line-clamp":[{"line-clamp":[de,"none",X,Tl]}],leading:[{leading:[r,...y()]}],"list-image":[{"list-image":["none",X,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",X,j]}],"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:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",X,Za]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[de,"auto",X,j]}],"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,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",X,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:oe()}],"bg-repeat":[{bg:W()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ta,X,j],radial:["",X,j],conic:[Ta,X,j]},uy,iy]}],"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:z()}],"rounded-s":[{"rounded-s":z()}],"rounded-e":[{"rounded-e":z()}],"rounded-t":[{"rounded-t":z()}],"rounded-r":[{"rounded-r":z()}],"rounded-b":[{"rounded-b":z()}],"rounded-l":[{"rounded-l":z()}],"rounded-ss":[{"rounded-ss":z()}],"rounded-se":[{"rounded-se":z()}],"rounded-ee":[{"rounded-ee":z()}],"rounded-es":[{"rounded-es":z()}],"rounded-tl":[{"rounded-tl":z()}],"rounded-tr":[{"rounded-tr":z()}],"rounded-br":[{"rounded-br":z()}],"rounded-bl":[{"rounded-bl":z()}],"border-w":[{border:H()}],"border-w-x":[{"border-x":H()}],"border-w-y":[{"border-y":H()}],"border-w-s":[{"border-s":H()}],"border-w-e":[{"border-e":H()}],"border-w-t":[{"border-t":H()}],"border-w-r":[{"border-r":H()}],"border-w-b":[{"border-b":H()}],"border-w-l":[{"border-l":H()}],"divide-x":[{"divide-x":H()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":H()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"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:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,X,j]}],"outline-w":[{outline:["",de,Rr,Za]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",m,gn,hn]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",f,gn,hn]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[de,Za]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":H()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",l,gn,hn]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[de,X,j]}],"mix-blend":[{"mix-blend":[...Q(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Q()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":Z()}],"mask-image-linear-to-pos":[{"mask-linear-to":Z()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":Z()}],"mask-image-t-to-pos":[{"mask-t-to":Z()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":Z()}],"mask-image-r-to-pos":[{"mask-r-to":Z()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":Z()}],"mask-image-b-to-pos":[{"mask-b-to":Z()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":Z()}],"mask-image-l-to-pos":[{"mask-l-to":Z()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":Z()}],"mask-image-x-to-pos":[{"mask-x-to":Z()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":Z()}],"mask-image-y-to-pos":[{"mask-y-to":Z()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[X,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":Z()}],"mask-image-radial-to-pos":[{"mask-radial-to":Z()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":Z()}],"mask-image-conic-to-pos":[{"mask-conic-to":Z()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:oe()}],"mask-repeat":[{mask:W()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",X,j]}],filter:[{filter:["","none",X,j]}],blur:[{blur:re()}],brightness:[{brightness:[de,X,j]}],contrast:[{contrast:[de,X,j]}],"drop-shadow":[{"drop-shadow":["","none",u,gn,hn]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",de,X,j]}],"hue-rotate":[{"hue-rotate":[de,X,j]}],invert:[{invert:["",de,X,j]}],saturate:[{saturate:[de,X,j]}],sepia:[{sepia:["",de,X,j]}],"backdrop-filter":[{"backdrop-filter":["","none",X,j]}],"backdrop-blur":[{"backdrop-blur":re()}],"backdrop-brightness":[{"backdrop-brightness":[de,X,j]}],"backdrop-contrast":[{"backdrop-contrast":[de,X,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,X,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,X,j]}],"backdrop-invert":[{"backdrop-invert":["",de,X,j]}],"backdrop-opacity":[{"backdrop-opacity":[de,X,j]}],"backdrop-saturate":[{"backdrop-saturate":[de,X,j]}],"backdrop-sepia":[{"backdrop-sepia":["",de,X,j]}],"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,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",X,j]}],ease:[{ease:["linear","initial",g,X,j]}],delay:[{delay:[de,X,j]}],animate:[{animate:["none",x,X,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[v,X,j]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:ye()}],"rotate-x":[{"rotate-x":ye()}],"rotate-y":[{"rotate-y":ye()}],"rotate-z":[{"rotate-z":ye()}],scale:[{scale:Be()}],"scale-x":[{"scale-x":Be()}],"scale-y":[{"scale-y":Be()}],"scale-z":[{"scale-z":Be()}],"scale-3d":["scale-3d"],skew:[{skew:Ce()}],"skew-x":[{"skew-x":Ce()}],"skew-y":[{"skew-y":Ce()}],transform:[{transform:[X,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Oe()}],"translate-x":[{"translate-x":Oe()}],"translate-y":[{"translate-y":Oe()}],"translate-z":[{"translate-z":Oe()}],"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,j]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":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,j]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[de,Rr,Za,Tl]}],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 pf=jv(my);function Aa(...e){return pf(pn(e))}function xn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:c,...i}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(_c,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Aa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(jc,{"data-slot":"slider-track",className:Aa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(Xc,{"data-slot":"slider-range",className:Aa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:d.length},(m,f)=>jsx($c,{"data-slot":"slider-thumb",className:Aa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",c)},f))]})}var hy="SchooplaVideoStorage";var Zt="videos",bn=()=>new Promise((e,o)=>{let t=indexedDB.open(hy,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Zt)||s.createObjectStore(Zt,{keyPath:"id"});};}),Qa=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await bn(),r=a.transaction([Zt],"readwrite").objectStore(Zt),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,i)=>{let d=r.put(n);d.onsuccess=()=>c(!0),d.onerror=()=>i(d.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var gf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await bn(),t=e.transaction([Zt],"readonly").objectStore(Zt);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,c=new Map;n.forEach(i=>{c.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Dl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await bn(),a=o.transaction([Zt],"readwrite").objectStore(Zt);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}},xf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await bn(),t=e.transaction([Zt],"readwrite").objectStore(Zt);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}},bf=e=>URL.createObjectURL(e);var gy=be[" useId ".trim().toString()]||(()=>{}),xy=0;function vf(e){let[o,t]=be.useState(gy());return Bo(()=>{t(a=>a??String(xy++));},[e]),(o?`radix-${o}`:"")}function yf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var El="rovingFocusGroup.onEntryFocus",by={bubbles:false,cancelable:true},Er="RovingFocusGroup",[Fl,wf,vy]=fn(Er),[yy,Bl]=Ma(Er,[vy]),[wy,Ly]=yy(Er),Lf=be.forwardRef((e,o)=>jsx(Fl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Fl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Sy,{...e,ref:o})})}));Lf.displayName=Er;var Sy=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:i,onEntryFocus:d,preventScrollOnEntryFocus:m=false,...f}=e,l=be.useRef(null),u=Bt(o,l),p=Oo(r),[v,h]=aa({prop:n,defaultProp:c??null,onChange:i,caller:Er}),[g,x]=be.useState(false),w=yf(d),b=wf(t),C=be.useRef(false),[M,k]=be.useState(0);return be.useEffect(()=>{let y=l.current;if(y)return y.addEventListener(El,w),()=>y.removeEventListener(El,w)},[w]),jsx(wy,{scope:t,orientation:a,dir:p,loop:s,currentTabStopId:v,onItemFocus:be.useCallback(y=>h(y),[h]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>k(y=>y+1),[]),onFocusableItemRemove:be.useCallback(()=>k(y=>y-1),[]),children:jsx(ct.div,{tabIndex:g||M===0?-1:0,"data-orientation":a,...f,ref:u,style:{outline:"none",...e.style},onMouseDown:Je(e.onMouseDown,()=>{C.current=true;}),onFocus:Je(e.onFocus,y=>{let S=!C.current;if(y.target===y.currentTarget&&S&&!g){let B=new CustomEvent(El,by);if(y.currentTarget.dispatchEvent(B),!B.defaultPrevented){let A=b().filter(D=>D.focusable),R=A.find(D=>D.active),U=A.find(D=>D.id===v),_=[R,U,...A].filter(Boolean).map(D=>D.ref.current);Cf(_,m);}}C.current=false;}),onBlur:Je(e.onBlur,()=>x(false))})})}),Sf="RovingFocusGroupItem",If=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...c}=e,i=vf(),d=r||i,m=Ly(Sf,t),f=m.currentTabStopId===d,l=wf(t),{onFocusableItemAdd:u,onFocusableItemRemove:p,currentTabStopId:v}=m;return be.useEffect(()=>{if(a)return u(),()=>p()},[a,u,p]),jsx(Fl.ItemSlot,{scope:t,id:d,focusable:a,active:s,children:jsx(ct.span,{tabIndex:f?0:-1,"data-orientation":m.orientation,...c,ref:o,onMouseDown:Je(e.onMouseDown,h=>{a?m.onItemFocus(d):h.preventDefault();}),onFocus:Je(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:Je(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let g=ky(h,m.orientation,m.dir);if(g!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let w=l().filter(b=>b.focusable).map(b=>b.ref.current);if(g==="last")w.reverse();else if(g==="prev"||g==="next"){g==="prev"&&w.reverse();let b=w.indexOf(h.currentTarget);w=m.loop?My(w,b+1):w.slice(b+1);}setTimeout(()=>Cf(w));}}),children:typeof n=="function"?n({isCurrentTabStop:f,hasTabStop:v!=null}):n})})});If.displayName=Sf;var Iy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Cy(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ky(e,o,t){let a=Cy(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Iy[a]}function Cf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function My(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var kf=Lf,Mf=If;var Af="Toggle",Ol=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,c]=aa({prop:t,onChange:s,defaultProp:a??false,caller:Af});return jsx(ct.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||c(!n);})})});Ol.displayName=Af;var Pa="ToggleGroup",[Df]=Ma(Pa,[Bl]),Rf=Bl(),Nl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Py,{...a,ref:o});if(t==="multiple")return jsx(Dy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Pa}\``)});Nl.displayName=Pa;var[Ef,Ff]=Df(Pa),Py=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??"",onChange:s,caller:Pa});return jsx(Ef,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(Bf,{...r,ref:o})})}),Dy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??[],onChange:s,caller:Pa}),i=be__default.useCallback(m=>c((f=[])=>[...f,m]),[c]),d=be__default.useCallback(m=>c((f=[])=>f.filter(l=>l!==m)),[c]);return jsx(Ef,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:i,onItemDeactivate:d,children:jsx(Bf,{...r,ref:o})})});Nl.displayName=Pa;var[Ry,Ey]=Df(Pa),Bf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:c=true,...i}=e,d=Rf(t),m=Oo(n),f={role:"group",dir:m,...i};return jsx(Ry,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(kf,{asChild:true,...d,orientation:r,dir:m,loop:c,children:jsx(ct.div,{...f,ref:o})}):jsx(ct.div,{...f,ref:o})})}),vn="ToggleGroupItem",Fy=be__default.forwardRef((e,o)=>{let t=Ff(vn,e.__scopeToggleGroup),a=Ey(vn,e.__scopeToggleGroup),s=Rf(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,c={...e,pressed:r,disabled:n},i=be__default.useRef(null);return a.rovingFocus?jsx(Mf,{asChild:true,...s,focusable:!n,active:r,ref:i,children:jsx(Pf,{...c,ref:o})}):jsx(Pf,{...c,ref:o})});Fy.displayName=vn;var Pf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Ff(vn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=r.type==="single"?n:void 0;return jsx(Ol,{...c,...s,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Of=Nl;var Ny=be.createContext({size:"default",variant:"default",spacing:0});function Da({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Of,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Aa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Ny.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var qy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:qy,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:Kt,setPenColor:zo,setStrokeWidth:Fr,setFontSize:ID,setFontFamily:CD,setFontStyle:kD,setFontWeight:MD,setTextDecoration:TD,setTextColor:AD}=Uf.actions,zf=Uf.reducer;var Wf=({onClose:e,onRecordingComplete:o})=>{let t=ze(),[a,s]=useState(false),[r,n]=useState(null),[c,i]=useState(0),[d,m]=useState(null),[f,l]=useState(false),u=useRef(null),p=useRef([]),v=useRef(null),h=useRef(null),g=useRef(null);useEffect(()=>((async()=>{try{let S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(S),l(!0),g.current&&(g.current.srcObject=S);}catch(S){console.error("Error accessing camera:",S),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{v.current&&clearInterval(v.current),d&&d.getTracks().forEach(S=>S.stop());}),[]);let x=()=>{d&&(d.getTracks().forEach(y=>y.stop()),m(null),l(false));},w=async()=>{try{let y=null,S=null;try{y=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(E){console.error("Error accessing camera for recording:",E),alert("Failed to access camera for recording.");return}try{S=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(E){console.warn("Microphone access denied:",E);}let B=[...y.getVideoTracks()];S&&B.push(...S.getAudioTracks());let A=new MediaStream(B),R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8");let U=new MediaRecorder(A,{mimeType:R,videoBitsPerSecond:25e5});u.current=U,p.current=[],U.ondataavailable=E=>{E.data.size>0&&p.current.push(E.data);},U.onstop=()=>{let E=new Blob(p.current,{type:R}),_=document.createElement("video");_.src=URL.createObjectURL(E),_.muted=!0,_.currentTime=.1,_.onseeked=()=>{let D=document.createElement("canvas");D.width=_.videoWidth,D.height=_.videoHeight;let te=D.getContext("2d");te&&(te.drawImage(_,0,0),h.current=D.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(_.src);},A.getTracks().forEach(D=>D.stop()),y&&y.getTracks().forEach(D=>D.stop()),S&&S.getTracks().forEach(D=>D.stop()),v.current&&clearInterval(v.current),n(E),x();},U.onerror=E=>{console.error("MediaRecorder error:",E);},U.start(1e3),s(!0),i(0),v.current=setInterval(()=>{i(E=>E+1);},1e3);}catch(y){console.error("Error starting camera recording:",y),alert("Failed to start recording. Please check permissions.");}},b=()=>{u.current&&a&&(u.current.state!=="inactive"&&(u.current.requestData(),setTimeout(()=>{u.current&&u.current.state!=="inactive"&&u.current.stop();},100)),s(false));},C=()=>{if(r){let y=URL.createObjectURL(r),S=document.createElement("a");S.href=y,S.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(S),S.click(),document.body.removeChild(S),URL.revokeObjectURL(y);}},M=y=>{let S=Math.floor(y/60),B=y%60;return `${S.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: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:g,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:w,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:b,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:M(c)})]})]})]}),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: ",M(c)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick: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 ra=40,Kf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[c,i]=useState(false),d=useRef(null),m=ze(),f=useRef(null);useEffect(()=>{let w=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[o]);let l=w=>{let b=w.target.files;if(!b||b.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=Array.from(b).slice(0,C);M.length<b.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(y=>new Promise((S,B)=>{let A=new FileReader;A.onload=R=>{R.target?.result?S(R.target.result):B(new Error("Failed to read file"));},A.onerror=B,A.readAsDataURL(y);}));Promise.all(k).then(y=>{s(S=>[...S,...y]),f.current&&(f.current.value="");});},u=w=>{w.preventDefault(),i(false);let b=Array.from(w.dataTransfer.files).filter(y=>y.type.startsWith("image/"));if(b.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=b.slice(0,C);M.length<b.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(y=>new Promise((S,B)=>{let A=new FileReader;A.onload=R=>{R.target?.result?S(R.target.result):B(new Error("Failed to read file"));},A.onerror=B,A.readAsDataURL(y);}));Promise.all(k).then(y=>{s(S=>[...S,...y]);});},p=w=>{w.preventDefault(),i(true);},v=()=>{i(false);},h=w=>{s(b=>b.filter((C,M)=>M!==w));},g=w=>{if(w.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 x=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:w=>{w.target===w.currentTarget&&o(),w.stopPropagation();},onMouseUp:w=>w.stopPropagation(),onMouseMove:w=>w.stopPropagation(),onTouchStart:w=>w.stopPropagation(),onTouchMove:w=>w.stopPropagation(),onTouchEnd:w=>w.stopPropagation(),children:jsxs("div",{ref:d,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:w=>w.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:g,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>=ra?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ra," images"]}):jsxs("span",{children:[a.length,"/",ra," 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:u,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 ${c?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>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((w,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:w,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>h(b),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:b+1})]},b))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(x,m)};var yn={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}},tw={enabled:true};function Ul(e){return e?{tools:{...yn.tools,...e.tools},actions:{...yn.actions,...e.actions}}:yn}var aw={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}},ow={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 Dw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=xe(),n=ee(F=>F.canvas.slides.find(ne=>ne.id===F.canvas.currentSlideId)),c=n?.videos||[],i=n?.editingFlashcard,d=ee(F=>F.toolbar.selectedTool),m=ee(F=>F.toolbar.penColor),f=ee(F=>F.toolbar.strokeWidth),l=n?.showMcqForm,u=n?.showFlashcardForm,p=useRef(null),v=useMemo(()=>Ul(s),[s]),{tools:h,actions:g}=v,x=c.some(F=>F.isRecorded&&F.isPlaying),w=ee(F=>F.toolbar.fontSize),b=ee(F=>F.toolbar.fontFamily),C=ee(F=>F.toolbar.fontStyle),M=ee(F=>F.toolbar.fontWeight),k=ee(F=>F.toolbar.textDecoration),y=ee(F=>F.toolbar.textColor),[S,B]=useState(false),[A,R]=useState(false),[U,E]=useState(false),[_,D]=useState(false),[te,V]=useState(false),[oe,W]=useState(false),[q,$]=useState(false),z=useRef(null),H=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"}],[]),Q=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"}],[]),Z=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"}],[]),re=useMemo(()=>Y.filter(F=>{let ne=h[F.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[h,Y]),ye=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?Q:Array.isArray(F)?Q.filter(ne=>F.includes(ne.name)):Q},[h.shapes,Q]),Be=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?Z:Array.isArray(F)?Z.filter(ne=>F.includes(ne.name)):Z},[h.activities,Z]),Ce=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]),Oe=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),jt=F=>{let ne=F.target.files;!ne||ne.length===0||(r(Kt("select")),r(pt(false)),D(false),Array.from(ne).forEach(we=>{let pe=new FileReader;pe.onload=se=>{let ue=new window.Image;ue.src=se.target?.result,ue.onload=()=>{let Le=ue.width/ue.height,Ve=300,Lt=300,mt=ue.width,Ae=ue.height;mt>Ve&&(mt=Ve,Ae=mt/Le),Ae>Lt&&(Ae=Lt,mt=Ae*Le),r(ce());let Qe=960-mt/2,St=540-Ae/2;r(jn({id:v4(),src:ue.src,x:Qe,y:St,width:mt,height:Ae,draggable:true,rotation:0}));};},pe.readAsDataURL(we);}),F.target.value="");},da=async F=>{let ne=F.target.files;if(!(!ne||ne.length===0)){console.log("files",F),r(Kt("select")),r(pt(false)),D(false);for(let we of Array.from(ne))try{let pe=URL.createObjectURL(we),se=document.createElement("video");console.log("video",se),se.src=pe,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((st,ua)=>{let Ba=setTimeout(()=>ua(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ba),st();},se.onerror=()=>{clearTimeout(Ba),ua(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((st,ua)=>{let Ba=setTimeout(()=>ua(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ba),st()):se.onloadeddata=()=>{clearTimeout(Ba),st();};});let ue=Math.min(.8,se.duration/2);console.log("Seeking to:",ue),se.currentTime=ue,await new Promise(st=>{let ua=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),st();},5e3);se.onseeked=()=>{clearTimeout(ua),console.log("Seek completed"),st();};});let Le=document.createElement("canvas"),Ve=se.videoWidth/se.videoHeight,Lt=400,mt=400,Ae=se.videoWidth,Qe=se.videoHeight;Ae>Lt&&(Ae=Lt,Qe=Ae/Ve),Qe>mt&&(Qe=mt,Ae=Qe*Ve),Le.width=Ae,Le.height=Qe;let St=Le.getContext("2d",{willReadFrequently:!1});if(!St)throw new Error("Failed to get canvas context");if(await new Promise(st=>setTimeout(st,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ae,height:Qe}),St.drawImage(se,0,0,Ae,Qe);let Nt=Le.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Nt.length),r(ce());let Rn=960-Ae/2,En=540-Qe/2,Kr=v4();await Qa(Kr,we,Nt),r(ts({id:Kr,objectUrl:pe,thumbnailDataUrl:Nt,videoBlob:we,x:Rn,y:En,width:Ae,height:Qe,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${we.name}`);}catch(pe){console.error("Error processing video:",pe),alert(`Failed to process video: ${we.name}`);}F.target.value="";}},Hr=(F,ne,we)=>{r(ce()),r(Kt("select")),r(pt(false));let pe=300,se=300,ue=960-pe/2,Le=540-se/2;r(we?uo({id:we,images:F,order:ne,x:ue,y:Le,width:pe,height:se,rotation:0,draggable:true}):Yn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:ne,x:ue,y:Le,width:pe,height:se,rotation:0,draggable:true})),r(Va(false));},ie=()=>{r(ce()),r(Kt("select")),r(pt(false));let F=400,ne=300,we=800-F/2,pe=450-ne/2;if(t?.current){let se=t.current,ue=se.scaleX()||1,Le=se.scaleY()||1,Ve=se.width()/ue,Lt=se.height()/Le;we=Ve/2-F/2,pe=Lt/2-ne/2;}r(Qn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:we,y:pe,width:F,height:ne,rotation:0,draggable:true,isCapturing:false})),V(false);},Ur=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 Le={id:`shape-${Date.now()}`,type:F.name,x:910,y:490,width:100,height:100,rotation:0,color:m,...ue};r(ce()),r(pt(false)),r(Kt(F.name)),r(Xn(Le));},Fa=F=>{if(r(Kt(F)),F==="select")r(pt(false));else if(F==="text"){r(pt(false)),r(ce());let ne=200,we=50,pe=960-ne/2,se=540-we/2,Le=window.innerWidth<768?Math.max(w,32):w,Ve=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r($n({id:Ve,text:"",x:pe,y:se,width:ne,height:we,rotation:0,draggable:true,fontSize:Le,fontFamily:b,fontStyle:C,fontWeight:M,textDecoration:k,fill:y,align:"left"})),setTimeout(()=>{r(er(Ve));},100),a&&a(Ve);}else r(pt(true));},zr=()=>{r(hi()),r(Kt("select")),r(pt(false));},Wr=()=>{o?o():t?B(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Gr=()=>{R(true);},Ko=async(F,ne)=>{try{r(Kt("select")),r(pt(!1));let we=URL.createObjectURL(F),pe=document.createElement("video");pe.src=we,pe.muted=!0,pe.playsInline=!0,pe.preload="auto",await new Promise((Qe,St)=>{let Nt=setTimeout(()=>St(new Error("Metadata load timeout")),1e4);pe.onloadedmetadata=()=>{clearTimeout(Nt),Qe();},pe.onerror=()=>{clearTimeout(Nt),St(new Error("Failed to load video"));};});let se=640,ue=pe.videoWidth/pe.videoHeight,Le=se,Ve=Le/ue;r(ce());let Lt=960-Le/2,mt=540-Ve/2,Ae=v4();await Qa(Ae,F,ne),r(ts({id:Ae,objectUrl:we,thumbnailDataUrl:ne,videoBlob:F,x:Lt,y:mt,width:Le,height:Ve,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),B(!1),R(!1);}catch(we){console.error("Error adding recorded video to canvas:",we),alert("Failed to add video to canvas. Please try again.");}},Mn=F=>{r(Kt("select")),r(pt(false)),r(Zo(null)),F&&r(di(F)),r(pa(!l));},Tn=()=>{r(Xo(null)),r(Va(true)),V(false);},An=()=>{E(!U);},Pn=()=>{D(!_);},Dn=()=>{V(!te);};return useEffect(()=>{if(!q)return;let F=ne=>{p.current&&!p.current.contains(ne.target)&&$(false);};return document.addEventListener("mousedown",F),()=>{document.removeEventListener("mousedown",F);}},[q]),x?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(Da,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:re.map((F,ne)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${F.name===d?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){Pn(),E(false),V(false),Fa(F.name);return}else if(F.name==="shapes"){An(),D(false),V(false),Fa(F.name);return}else if(F.name==="activities"){Fa(F.name),Dn(),E(false),D(false);return}Fa(F.name),E(false),D(false),V(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},ne))}),U&&jsx(Da,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:ye.map((F,ne)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Ur(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},ne))}),_&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Ce.photoFrame&&jsx("div",{title:"Photo frame",onClick:ie,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Ce.image&&jsx("div",{title:"Image",onClick:()=>z.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Ce.video&&jsx("div",{title:"Video",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),te&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Oe&&jsx("div",{title:"Flashcard",onClick:()=>Tn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Be.map((F,ne)=>jsx("div",{title:F.label,onClick:()=>Mn(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},ne))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Da,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>r(gi()),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"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>r(xi()),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"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:Wr,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:()=>W(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(xn,{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"})]})]})]}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Gr,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"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>zr(),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:z,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:jt}),jsx("input",{ref:H,type:"file",accept:"video/*",className:"hidden",onChange:da}),!o&&S&&t&&jsx(dr,{onClose:()=>B(false),stageRef:t,onRecordingComplete:Ko}),A&&jsx(Wf,{onClose:()=>R(false),onRecordingComplete:Ko}),u&&jsx(Kf,{editingFlashcard:i,onConfirm:Hr,onCancel:()=>r(Va(false))}),oe&&jsx(Ns,{defaultColor:m,onConfirm:F=>{r(zo(F)),W(false);},onCancel:()=>W(false)})]})},Rw=Dw;var _l=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=et(fo),r=et(wi),n=a?r:s,c=et(tr),m=(et(x=>x.canvas.slides.find(w=>w.id===x.canvas.currentSlideId))?.videos||[]).some(x=>x.isRecorded&&x.isPlaying),[f,l]=useState(false),[u,p]=useState(null),[v,h]=useState(null),g=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 x=await e(n,c,w=>{p(w);});x.success?h({type:"success",message:x.message}):h({type:"error",message:x.message});}catch(x){h({type:"error",message:x instanceof Error?x.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{p(null),h(null);},3e3);}};return m?null:jsxs("button",{onClick:g,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 Nw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:c=true,editableTitle:i=true,editableDescription:d=true,className:m="",rightContent:f,leftContent:l,includeInactiveSlides:u=false})=>{let p=it(),v=et(tr),h=et(Si),g=e??(h?v.title:"")??"Untitled",x=o??(h?v.description:"")??"Add a description...",[w,b]=useState(false),[C,M]=useState(false),[k,y]=useState(g),[S,B]=useState(x),A=useRef(null),R=useRef(null);useEffect(()=>{y(g);},[g]),useEffect(()=>{B(x);},[x]),useEffect(()=>{w&&A.current&&(A.current.focus(),A.current.select());},[w]),useEffect(()=>{C&&R.current&&(R.current.focus(),R.current.select());},[C]);let U=()=>{i&&b(true);},E=()=>{d&&M(true);},_=()=>{b(false),k.trim()&&k!==g?s?s(k.trim()):p(bi(k.trim())):k.trim()||y(g);},D=()=>{M(false),S.trim()&&S!==x?r?r(S.trim()):p(vi(S.trim())):S.trim()||B(x);},te=oe=>{oe.key==="Enter"?_():oe.key==="Escape"&&(y(g),b(false));},V=oe=>{oe.key==="Enter"?D():oe.key==="Escape"&&(B(x),M(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:[c&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[w?jsx("input",{ref:A,type:"text",value:k,onChange:oe=>y(oe.target.value),onBlur:_,onKeyDown:te,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:U,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:k}),C?jsx("input",{ref:R,type:"text",value:S,onChange:oe=>B(oe.target.value),onBlur:D,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:E,title:S,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${d?"hover:border-primary cursor-text":""}`,children:S})]})]}),f||n&&a&&jsx(_l,{onPublish:a,includeInactiveSlides:u})]})};var Ww=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Gw=({colors:e=Ww,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),c=ee(ge),i=ee(l=>l.toolbar.penColor),d=ee(l=>l.toolbar.strokeWidth),m=c?.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(xn,{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:[d],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(Da,{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 ${i===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(Kn(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 $f=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),Xl=e=>{let o=Kw(e);return o.charAt(0).toUpperCase()+o.slice(1)},In=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Yf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Jf={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 Qf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...c},i)=>createElement("svg",{ref:i,...Jf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:In("lucide",s),...!r&&!Yf(c)&&{"aria-hidden":"true"},...c},[...n.map(([d,m])=>createElement(d,m)),...Array.isArray(r)?r:[r]]));var Cn=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(Qf,{ref:r,iconNode:o,className:In(`lucide-${$f(Xl(e))}`,`lucide-${e}`,a),...s}));return t.displayName=Xl(e),t};var $w=[["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=Cn("copy",$w);var Yw=[["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=Cn("trash-2",Yw);var tm=({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:c=>{c.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:c=>{c.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 eL=({softDelete:e=false})=>{let o=it(),t=et(fo),a=et(co),s=et(Li),[r,n]=useState(true),d=(et(p=>p.canvas.slides.find(v=>v.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),m=()=>{s&&o(Hn());},f=p=>{o(Wn(p));},l=p=>{o(zn(p));},u=p=>{t.length>1&&o(Un({id:p,softDelete:e}));};return d?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(tm,{slide:p,index:v,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>f(p.id),onDuplicate:()=>l(p.id),onDelete:()=>u(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 tL="SchooplaEditorDB",aL=1,Ra="slides",Ea="metadata",$l="schoopla_current_slide_id",rm="presentation_metadata",qr=()=>new Promise((e,o)=>{let t=indexedDB.open(tL,aL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Ra)||s.createObjectStore(Ra,{keyPath:"id"}),s.objectStoreNames.contains(Ea)||s.createObjectStore(Ea,{keyPath:"id"});};}),Yl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await qr(),a=o.transaction([Ra],"readwrite").objectStore(Ra);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 c=a.add(s);c.onsuccess=()=>r(!0),c.onerror=()=>n(c.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Jl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await qr(),t=e.transaction([Ra],"readonly").objectStore(Ra);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(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.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}}},kn=async()=>{try{let e=await qr(),o=e.transaction([Ra,Ea],"readwrite"),t=o.objectStore(Ra),a=o.objectStore(Ea);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($l),localStorage.removeItem("schoopla_presentation_metadata"),await xf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Zl=e=>{try{localStorage.setItem($l,e);}catch(o){console.error("Error saving current slide ID:",o);}},Ql=()=>{try{return localStorage.getItem($l)}catch(e){return console.error("Error loading current slide ID:",e),null}},ed=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},td=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await qr(),a=o.transaction([Ea],"readwrite").objectStore(Ea);await new Promise((s,r)=>{let n=a.put({id:rm,...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);}}},ad=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await qr(),t=e.transaction([Ea],"readonly").objectStore(Ea);return new Promise((a,s)=>{let r=t.get(rm);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:c,...i}=n;console.log("\u2705 Loaded presentation metadata:",i),a(i);}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 oL=["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"],rL=["canvas/clearCanvas"],sL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],nL=ed((e,o)=>{Yl(e),Zl(o);},500),iL=ed(e=>{td(e);},500),lL=(e,o)=>{Yl(e),Zl(o);},od=false,sm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let s=t.payload;Dl(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(c=>c.id===s);n&&n.videos&&n.videos.length>0&&n.videos.forEach(c=>{Dl(c.id).catch(i=>{console.error("Error deleting video blob:",i);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let s=t.payload,r=e.getState(),c=r.canvas.slides.find(i=>i.id===r.canvas.currentSlideId)?.videos.find(i=>i.id===s);c&&c.videoBlob&&setTimeout(()=>{let i=e.getState(),m=i.canvas.slides.find(f=>f.id===i.canvas.currentSlideId)?.videos.find(f=>f.id!==s&&f.x===c.x+20&&f.y===c.y+20);m&&c.videoBlob&&Qa(m.id,c.videoBlob,m.thumbnailDataUrl).catch(f=>{console.error("Error saving duplicated video blob:",f);});},0);}let a=o(t);if(t.type&&rL.includes(t.type)){if(!od){od=true;try{let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;lL(r,n);}finally{setTimeout(()=>{od=false;},0);}}}else if(t.type&&oL.includes(t.type)){let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;nL(r,n);}else if(t.type&&sL.includes(t.type)){let s=e.getState(),{presentationMetadata:r}=s.canvas;iL(r);}return a});new QueryClient;var cL=configureStore({reducer:{toolbar:zf,canvas:yd},middleware:e=>e({serializableCheck:false}).concat(sm)});var fL=(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",c=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=c,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},mL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let c=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:c,quality:a,pixelRatio:s});fetch(i).then(d=>d.blob()).then(d=>r(d)).catch(d=>n(d));}catch(c){n(c);}})},pL=(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 hL=(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)),c=o.x+n*a,i=o.y+n*s;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-i,2))},rd=(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 c=hL(e[n],s,r);c>t&&(t=c,a=n);}if(t>o){let n=rd(e.slice(0,a+1),o),c=rd(e.slice(a),o);return [...n.slice(0,-1),...c]}return [s,r]},gL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},xL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},nm=(e,o=1.5)=>{if(e.length<=4)return e;let t=gL(e),a=rd(t,o);return xL(a)},im=(e,o=1.5)=>({...e,points:nm(e.points,o)}),bL=(e,o=1.5)=>e.map(t=>im(t,o)),vL=(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 yL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var lm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{let c=new Image;c.onload=()=>{let{width:i,height:d}=c;if(i>t||d>a){let p=i/d;i>d?(i=Math.min(i,t),d=i/p):(d=Math.min(d,a),i=d*p);}let m=document.createElement("canvas");m.width=i,m.height=d;let f=m.getContext("2d");if(!f){n(new Error("Failed to get canvas context"));return}f.drawImage(c,0,0,i,d);let l=yL(e),u=m.toDataURL(l,s);r(u);},c.onerror=n,c.src=e;})};var ro=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},Wo=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Go=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",wL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],c=0;for(let i of e){let d=[],m=[],f=[];for(let l of i.images){let u=l.src;if(t&&u.startsWith("data:"))try{u=await lm(u,{maxWidth:a,maxHeight:s,quality:r});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(u.startsWith("data:")){let p=ro(u),v=Wo(u);c+=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 g=ro(l.audioData),x=Wo(l.audioData);c+=g.byteLength,h.audioBuffer=g,h.audioMimeType=x;}d.push(h);}}for(let l of i.videos){let u,p;if(l.videoBlob)u=await l.videoBlob.arrayBuffer(),p=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))u=ro(l.videoData),p=Wo(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}c+=u.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:u,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let h=ro(l.audioData),g=Wo(l.audioData);c+=h.byteLength,v.audioBuffer=h,v.audioMimeType=g;}m.push(v);}for(let l of i.photoFrames){let u={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=ro(l.capturedImageUrl),v=Wo(l.capturedImageUrl);c+=p.byteLength,u.buffer=p,u.mimeType=v;}if(l.audioData&&l.audioData.startsWith("data:")){let p=ro(l.audioData),v=Wo(l.audioData);c+=p.byteLength,u.audioBuffer=p,u.audioMimeType=v;}f.push(u);}n.push({...i,images:d,videos:m,photoFrames:f});}return {slides:n,totalSize:c}},LL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},SL=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 c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Go(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,c,i),r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Go(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,d,m);}}),a.videos.forEach((r,n)=>{let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Go(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,c,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let d=ro(r.thumbnailDataUrl),m=new Blob([d],{type:"image/jpeg"}),f=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,m,f);}if(r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Go(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,d,m);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Go(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,c,i);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${Go(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,c,i);}});}),o};var kL=()=>{let e=it(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await Jl(),r=Ql(),n=await ad();if(s&&s.length>0){let c=await gf(),i=s.map(m=>{if(m.videos&&m.videos.length>0){let f=m.videos.map(l=>{let u=c.get(l.id);if(u){let p=bf(u.blob);return {...l,objectUrl:p,thumbnailDataUrl:u.thumbnailDataUrl,videoBlob:u.blob}}else return l});return {...m,videos:f}}return m}),d=r&&i.find(m=>m.id===r)?r:i[0].id;e(no({slides:i,currentSlideId:d}));}e(n?yi({title:n.title,description:n.description}):Ts(!0));}catch(s){console.error("Error loading persisted slides:",s),e(Ts(true));}finally{t(false);}})();},[e]),{isLoading:o}};var um=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||""})),cm=new WeakSet,fm=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 Qa(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},ML=()=>{let e=it(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||cm.has(a))return;cm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await kn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=um(s);e(no({slides:i,currentSlideId:c})),await fm(i);},[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 kn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=um(s);e(no({slides:i,currentSlideId:c})),await fm(i);},[e]);return {loadSlides:o,reloadSlides:t}};/*! Bundled license information:
6
+ This is for longer responses that require detailed explanations.`,className:"h-full w-full resize-none border-0 bg-white p-3 text-gray-900 focus:outline-none",style:{fontSize:"14px",pointerEvents:f?"none":"auto"}})}),jsx(Group,{y:C+M+A+k+y+B,children:f&&jsxs(Group,{onMouseDown:()=>p("reset"),onMouseUp:()=>{p(null),g();},onMouseLeave:()=>p(null),onTouchStart:()=>p("reset"),onTouchEnd:()=>{p(null),g();},scaleX:u==="reset"?.95:1,scaleY:u==="reset"?.95:1,children:[jsx(Rect,{x:b,width:e.width-b*2,height:48,fill:"#ef4444",cornerRadius:8,onClick:U=>U.cancelBubble=true,onTap:U=>U.cancelBubble=true}),jsx(Text,{x:b,width:e.width-b*2,height:48,text:"Reset",fontSize:16,fontStyle:"bold",fill:"white",align:"center",verticalAlign:"middle",listening:false})]})})]})});vl.displayName="LongAnswer";var hc=({longAnswer:e,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:r})=>jsx(Fragment,{children:e.map(n=>jsx(vl,{longAnswer:n,handleSelect:o,handleTransform:t,saRefs:a,onContextMenu:s,handleDragEnd:c=>r(c,n.id)},n.id))});var $a=1600,Ya=900,vc=3200,yc=1800,Vb=.4,qb=1.5,Hb=e=>{let o=0,t=0,a=$a,s=Ya;if(!e)return {minX:o,minY:t,maxX:a,maxY:s,width:$a,height:Ya};let r=(i,d,m,f)=>{o=Math.min(o,i),t=Math.min(t,d),a=Math.max(a,i+m),s=Math.max(s,d+f);};e.lines?.forEach(i=>{if(i.points&&i.points.length>=2){let d=i.x||0,m=i.y||0,f=i.scaleX||1,l=i.scaleY||1;for(let u=0;u<i.points.length;u+=2){let p=d+i.points[u]*f,v=m+i.points[u+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(i=>r(i.x,i.y,i.width,i.height)),e.videos?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shapes?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.texts?.forEach(i=>r(i.x,i.y,i.width||200,i.height||i.fontSize||24)),e.flashcards?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.photoFrames?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.multipleChoices?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.trueFalses?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.shortAnswers?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.LongAnswer?.forEach(i=>r(i.x,i.y,i.width,i.height)),e.fillInTheBlanks?.forEach(i=>r(i.x,i.y,i.width,i.height));let n=Math.min(a-o,vc),c=Math.min(s-t,yc);return o=Math.max(o,a-vc),t=Math.max(t,s-yc),{minX:o,minY:t,maxX:a,maxY:s,width:n,height:c}},Ub=(e,o,t={minX:0,minY:0,maxX:$a,maxY:Ya,width:$a,height:Ya})=>{let a=Math.max(t.width,$a),s=Math.max(t.height,Ya),r=e/o,n=a/s,c,i,d,f=0;if(r>n){i=s,c=Math.round(i*r),d=o/i;}else {c=a,i=Math.round(c/r),d=e/c;let l=s*d;f=(o-l)/2;}return d=Math.max(Vb,Math.min(qb,d)),{scale:d,scaleX:d,scaleY:d,stageWidth:e,stageHeight:o,offsetX:0,offsetY:f,baseWidth:c,baseHeight:i,contentOffsetX:t.minX,contentOffsetY:t.minY}},wc=(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}},Wb=({onStageReady:e,onSelectionChange:o,onTextEditingReady:t,onDirectDrawingCanvasReady:a,contextMenuConfig:s={enabled:true}}={})=>{let r=it(),n=We(),c=ee(L=>L.toolbar.selectedTool),i=ee(ge),d=ee(co),m=ee(As),l=(i?.videos||[]).find(L=>L.isRecorded&&L.isPlaying),u=!!l,p=useCallback(()=>{l&&r(Oa(l.id));},[r,l]),v=i?.editingActivity,h=i?.showMcqForm,g=i?.lines||[],x=useRef(null),w=useRef(null),[b,C]=useState(null),[M,k]=useState(""),y=useRef(null),[S,B]=useState({scale:1,scaleX:1,scaleY:1,stageWidth:$a,stageHeight:Ya,offsetX:0,offsetY:0,baseWidth:$a,baseHeight:Ya,contentOffsetX:0,contentOffsetY:0}),A=useMemo(()=>Hb(i||null),[d]),[R,U]=useState(null),[E,_]=useState(null),[D,te]=useState(null),[V,oe]=useState(null),[z,q]=useState(null),[$,W]=useState(null),[H,Y]=useState(null),[Q,Z]=useState(false),[re,ye]=useState(null),[Be,Ce]=useState(false),Oe=useRef(null),jt=useRef(null),da=useRef(null),{debouncedGenerateThumbnail:Hr}=$d(d,x);useEffect(()=>{let L=()=>{if(w.current){let P=w.current.getBoundingClientRect(),O=Ub(P.width,P.height,A);B(O);}};L();let I=new ResizeObserver(L);return w.current&&I.observe(w.current),window.addEventListener("resize",L),()=>{I.disconnect(),window.removeEventListener("resize",L);}},[A]),useEffect(()=>{if(x.current){let L=x.current.container();L&&(L.style.cursor="");}},[c]);let ie=useCallback(()=>{x.current&&requestAnimationFrame(()=>{if(!x.current)return;if(x.current.getLayers().forEach(I=>I.batchDraw()),!m)try{let P=x.current.toDataURL({pixelRatio:.16666666666666666});k(P),Hr();}catch(I){console.warn("Preview generation failed (CORS):",I);}});},[Hr,m]),Ur=useRef(d);useEffect(()=>{Ur.current!==d&&(Ur.current=d,ie());},[d,ie]);let Fa=useRef(null),Wr=useRef(true);useEffect(()=>{if(!i)return;let L=(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=Fa.current?.count!==L;!Wr.current&&I&&setTimeout(()=>{ie();},100),Fa.current={slideId:d,count:L},Wr.current=false;},[i,d,ie]),useEffect(()=>{x.current&&e&&e(x);},[e]),useEffect(()=>{da.current&&a&&a(da);},[a]);let{startDrawing:zr,draw:Gr,stopDrawing:Ko,setCanvasRef:Mn,tool:Tn,color:An,strokeWidth:Pn,isSketchMode:Dn}=Ld(ie),F=useRef(new Map),{images:ne,getLoadedImage:we,imageRefs:pe,handleDragEnd:se,handleImageTransformEnd:ue}=Ad(ie),{videos:Le,videoRefs:Ve,handleVideoClick:Lt,handleVideoDragEnd:mt,handleVideoTransformEnd:Ae}=Rd(ie),{multipleChoice:Qe,handleMcqTransform:St,mcqRefs:Nt,handleDragEnd:Rn}=Pd(ie),{trueFalse:En,handleTrueFalseTransform:Kr,trueFalseRefs:st,handleTrueFalseDragEnd:ua}=Dd(ie),{shortAnswers:Ba,saRefs:_o,handleShortAnswerDragEnd:mm}=Vd(ie),{longAnswers:pm,handleLongAnswerDragEnd:hm}=qd(ie),{fillInTheBlanks:gm,handleFillInTheBlanksDragEnd:xm,fibRefs:_r}=lc(ie),{transformerRef:fe,boundBoxFunc:It}=Kd(),{shapes:bm,shapeRefs:jr,isDragging:sd,handleShapeDragEnd:vm,handleShapeResizeEnd:ym}=Bd(ie),{texts:jo,textRefs:ca,handleDragEnd:wm,handleTransformEnd:Lm,handleDoubleClick:Sm,startEditing:Xr,editingTextId:he,editingValue:nd,handleEditingChange:id,finishEditing:Fn}=Nd(ie,Oe);useEffect(()=>{t&&t(Xr);},[t,Xr]);let $r=ee(L=>L.canvas.editingTextId);useEffect(()=>{$r&&$r!==he&&Xr($r);},[$r,he,Xr]);let{flashcards:Im,flashcardRefs:Yr,handleDragEnd:Cm,handleFlashcardTransformEnd:km,handleNext:Mm,handlePrevious:Tm}=Ud(ie),{photoFrames:ld,photoFrameRefs:Jr,handleDragEnd:Am,handlePhotoFrameTransformEnd:Pm,startCamera:Dm,capturePhoto:Rm,cameraStreams:Em}=Gd(ie);useEffect(()=>{if(fe.current){if(he){fe.current.nodes([]),fe.current.getLayer()?.batchDraw();return}if(b&&!Le.find(P=>P.id===b)?.isPlaying){let P=F.current.get(b)||pe.current.get(b)||Ve.current.get(b)||jr.current.get(b)||ca.current.get(b)||Nt.current.get(b)||Yr.current.get(b)||Jr.current.get(b)||_o.current.get(b)||st.current.get(b)||_r.current.get(b);if(P){let O=P.attrs?.locked;if(P.visible()&&O!==true){fe.current.nodes([P]),fe.current.getLayer()?.batchDraw();return}}}fe.current.nodes([]),fe.current.getLayer()?.batchDraw();}},[b,he,Le,F,pe,Ve,jr,ca,Yr,Jr,ld,Nt,st,_r,fe]);let Ke=useCallback(L=>{C(L),o?.(L);},[o]),so=useCallback(()=>{C(null),o?.(null),fe.current&&(fe.current.nodes([]),fe.current.getLayer()?.batchDraw());},[fe,o]),dd=useCallback(L=>i?i.lines?.some(I=>I.id===L)?"line":i.images?.some(I=>I.id===L)?"image":i.videos?.some(I=>I.id===L)?"video":i.shapes?.some(I=>I.id===L)?"shape":i.texts?.some(I=>I.id===L)?"text":i.flashcards?.some(I=>I.id===L)?"flashcard":i.photoFrames?.some(I=>I.id===L)?"photoFrame":i.multipleChoices?.some(I=>I.id===L)?"mcq":i.trueFalses?.some(I=>I.id===L)?"trueFalse":i.shortAnswers?.some(I=>I.id===L)?"shortAnswer":i.LongAnswer?.some(I=>I.id===L)?"longAnswer":i.fillInTheBlanks?.some(I=>I.id===L)?"fillInTheBlanks":null:null,[i]),ud=useCallback((L,I)=>{switch(r(ce()),I){case "line":r(Ms(L));break;case "image":r(Qr(L));break;case "video":r(os(L));break;case "shape":r(ns(L));break;case "text":r(is(L));break;case "flashcard":r(ds(L));break;case "photoFrame":r(cs(L));break;case "mcq":r(ms(L));break;case "trueFalse":r(hs(L));break;case "shortAnswer":r(xs(L));break;case "longAnswer":r(vs(L));break;case "fillInTheBlanks":r(ws(L));break}so(),ie();},[r,so,ie]);useEffect(()=>{let L=I=>{if(I.key!=="Delete"||!b||he)return;let P=document.activeElement;if(P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P?.getAttribute("contenteditable")==="true")return;I.preventDefault();let Pe=dd(b);Pe&&ud(b,Pe);};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[b,he,dd,ud]),useEffect(()=>{let L=fe.current;return ()=>{L&&L.nodes([]);}},[d]),useEffect(()=>{let L=I=>{he&&I.target.tagName!=="TEXTAREA"&&Fn();};return document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L);}},[he,Fn]),useEffect(()=>{let L=he||b;if(!L||b&&he){_(null);return}let I=ca.current.get(L),P=x.current;if(!I||!P){_(null);return}let O=P.container().getBoundingClientRect(),Pe=I.absolutePosition(),Se=P.scaleX();_({x:O.left+(Pe.x+I.width()*Se/2)*Se,y:O.top+Pe.y*Se});},[b,he,jo,ca]),useEffect(()=>{if(!he){te(null);return}let L=ca.current.get(he),I=x.current;if(!L||!I){te(null);return}let P=I.container().getBoundingClientRect(),O=L.absolutePosition(),Pe=I.scaleX();te({top:P.top+O.y*Pe,left:P.left+O.x*Pe,scale:Pe});},[he,jo,ca]);let cd=useCallback(L=>{let I=L.target.getClassName(),P=L.target===L.target.getStage(),O=I==="Transformer"||L.target.getParent()?.getClassName()==="Transformer",Pe=I==="Image",Se=I==="Text",ae=I==="Group"||L.target.getParent()?.getClassName()==="Group",Vt=I==="Circle"||I==="Star"||I==="RegularPolygon"||I==="Ellipse"||I==="Ring"||I==="Wedge"||I==="Arrow"||I==="Line"||I==="Arc"||I==="Rect"&&L.target.attrs.id,kt=I==="Group";if(P&&!O&&!Pe&&!Se&&!ae&&!Vt&&!kt&&so(),!(c==="pen"||c==="eraser")&&(Pe||Se||O||ae||Vt||kt))return;let $e=L.target.getStage()?.getPointerPosition();if(!$e)return;if(!["rectangle","circle","ellipse","triangle","polygon","star","ring","wedge","arrow","line","arc"].includes(c)){let N=wc($e,S);zr(N);}},[c,zr,so,S]),fd=useCallback(L=>{if(sd)return;let I=L.target.getStage()?.getPointerPosition();if(!I)return;let P=wc(I,S);Gr(P);},[Gr,sd,S]),md=useCallback(()=>{Ko();},[Ko]),Fm=useCallback(L=>{se(L,ie);},[se,ie]),Bm=useCallback(L=>{Lt(L),Ke(L);},[Lt,Ke]),Ct=useCallback((L,I,P)=>{if(L.preventDefault(),!s.enabled)return;let O=L.clientX,Pe=L.clientY,Se=y.current?.offsetHeight||450,ae=y.current?.offsetWidth||450,Vt=window.innerHeight,kt=window.innerWidth,nt=O,$e=Pe;Pe+Se>Vt&&($e=Pe-Se),O+ae>kt&&(nt=O-ae),U({x:nt,y:$e,elementId:I,elementType:P}),Ke(I);},[Ke,s.enabled]),pd=useCallback(L=>{r(Zo(L)),r(pa(true));},[r]),Om=useCallback(L=>{r(Xo(L)),r(Va(true));},[r]),Nm=useCallback((L,I)=>{if(!R)return;let{elementId:P,elementType:O}=R;switch(L){case "order":if(I){let T=I.target.getBoundingClientRect();oe({x:T.right+5,y:T.top,type:"order"});}break;case "lock":if(I){let T=I.target.getBoundingClientRect();oe({x:T.right+5,y:T.top,type:"lock"});}break;case "link":if(U(null),O==="line")break;let Pe=i?O==="image"?i.images.find(T=>T.id===P):i.videos.find(T=>T.id===P):null;q({type:"link",defaultValue:Pe?.link||""});break;case "voice":if(U(null),O==="line")break;let Se=i?O==="image"?i.images.find(T=>T.id===P):O==="video"?i.videos.find(T=>T.id===P):O==="text"?i.texts.find(T=>T.id===P):O==="flashcard"?i.flashcards.find(T=>T.id===P):O==="photoFrame"?i.photoFrames.find(T=>T.id===P):O==="mcq"?i.multipleChoices.find(T=>T.id===P):O==="fillInTheBlanks"?i.fillInTheBlanks.find(T=>T.id===P):O==="longAnswer"?i.LongAnswer.find(T=>T.id===P):O==="shortAnswer"?i.shortAnswers.find(T=>T.id===P):O==="trueFalse"?i.trueFalses.find(T=>T.id===P):O==="shape"?i.shapes.find(T=>T.id===P):null:null;ye({elementId:P,elementType:O,existingAudio:Se?.audioData});break;case "edit":U(null);let ae=null;O==="mcq"?ae=i?.multipleChoices.find(T=>T.id===P):O==="trueFalse"?ae=i?.trueFalses.find(T=>T.id===P):O==="shortAnswer"?ae=i?.shortAnswers.find(T=>T.id===P):O==="longAnswer"?ae=i?.LongAnswer.find(T=>T.id===P):O==="fillInTheBlanks"&&(ae=i?.fillInTheBlanks.find(T=>T.id===P)),ae&&pd(ae);break;case "editFlashcard":U(null);let Vt=i?.flashcards.find(T=>T.id===P);Vt&&Om(Vt);break;case "color":U(null);let kt=i?.shapes.find(T=>T.id===P);W({elementId:P,elementType:"shape",defaultColor:kt?.color||"#096B76"});break;case "crop":if(U(null),O==="image"){let T=i?.images.find(Gm=>Gm.id===P);T&&Y({elementId:P,imageSrc:T.src});}break;case "draw":U(null),O==="image"?r(ei(P)):O==="photoFrame"&&r(ai(P));break;case "duplicate":r(ce()),O==="line"?r(pi(P)):O==="image"?r(es(P)):O==="video"?r(rs(P)):O==="shape"?r(ss(P)):O==="text"?r(ls(P)):O==="flashcard"?r(us(P)):O==="photoFrame"?r(fs(P)):O==="mcq"?r(ps(P)):O==="trueFalse"?r(gs(P)):O==="shortAnswer"?r(bs(P)):O==="fillInTheBlanks"?r(Ls(P)):O==="longAnswer"&&r(ys(P)),ie();break;case "infinite-clone":r(ce());let nt=5;for(let T=0;T<nt;T++)O==="image"?r(es(P)):O==="video"?r(rs(P)):O==="shape"?r(ss(P)):O==="text"?r(ls(P)):O==="flashcard"?r(us(P)):O==="photoFrame"?r(fs(P)):O==="mcq"?r(ps(P)):O==="trueFalse"?r(gs(P)):O==="shortAnswer"?r(bs(P)):O==="fillInTheBlanks"?r(Ls(P)):O==="longAnswer"&&r(ys(P));ie();break;case "make-response":if(U(null),O==="line")break;let $e=`#response-${P}`;r(ce()),r(Ss({id:P,type:O,link:$e})),(i?O==="image"?i.images.find(T=>T.id===P):O==="video"?i.videos.find(T=>T.id===P):O==="shape"?i.shapes.find(T=>T.id===P):O==="flashcard"?i.flashcards.find(T=>T.id===P):O==="photoFrame"?i.photoFrames.find(T=>T.id===P):i.multipleChoices.find(T=>T.id===P):null)?.altText||r(Is({id:P,type:O,altText:"Interactive response area"})),ie(),console.log(`Element ${P} marked as interactive response area`);break;case "accessibility":if(U(null),O==="line")break;let N=i?O==="image"?i.images.find(T=>T.id===P):O==="video"?i.videos.find(T=>T.id===P):O==="shape"?i.shapes.find(T=>T.id===P):null:null;q({type:"altText",defaultValue:N?.altText||""});break;case "layers":console.log("Layers button clicked, opening panel..."),U(null),Ce(true),console.log("showLayersPanel state set to:",true);break;case "delete":r(ce()),O==="line"?r(Ms(P)):O==="image"?r(Qr(P)):O==="video"?r(os(P)):O==="shape"?r(ns(P)):O==="text"?r(is(P)):O==="flashcard"?r(ds(P)):O==="photoFrame"?r(cs(P)):O==="mcq"?r(ms(P)):O==="trueFalse"?r(hs(P)):O==="shortAnswer"?r(xs(P)):O==="longAnswer"?r(vs(P)):O==="fillInTheBlanks"&&r(ws(P)),so(),ie();break}},[R,r,ie,so,i,pd]),Vm=useCallback(()=>{U(null),oe(null);},[]),Bn=useCallback(L=>{if(!R)return;let{elementId:I,elementType:P}=R;switch(r(ce()),L){case "bring-to-front":P!=="line"&&r(ui({id:I,type:P}));break;case "send-to-back":P!=="line"&&r(ci({id:I,type:P}));break;case "lock":case "unlock":P!=="line"&&r(fi({id:I,type:P}));break}ie(),U(null),oe(null);},[R,r,ie]),qm=useCallback(L=>{if(!R||!z)return;let{elementId:I,elementType:P}=R;r(ce()),z.type==="link"&&P!=="line"?r(Ss({id:I,type:P,link:L})):z.type==="altText"&&P!=="line"&&r(Is({id:I,type:P,altText:L})),ie(),q(null);},[R,z,r,ie]),Hm=useCallback(L=>{if(!re)return;let{elementId:I,elementType:P}=re;r(ce()),r(Cs({id:I,type:P,audioData:L})),ie(),ye(null);},[re,r,ie]),Um=useCallback(()=>{if(!re)return;let{elementId:L,elementType:I}=re;r(ce()),r(Cs({id:L,type:I,audioData:""})),ie();},[re,r,ie]),Wm=useCallback(L=>{if(!$)return;let{elementId:I}=$;r(ce()),r(lo({id:I,color:L})),ie(),W(null);},[$,r,ie]),zm=useCallback(L=>{if(!H)return;let{elementId:I}=H;r(ce()),r(io({id:I,src:L})),ie(),Y(null);},[H,r,ie]);return jsxs("div",{ref:w,className:"fixed inset-0",style:{cursor:c==="pen"?"crosshair":c==="eraser"?"":"default"},children:[c==="pen"&&jsx(Md,{ref:L=>{if(jt.current=L,Mn(L),L){let I=L.getCanvasElement();I&&(da.current=I,a&&a(da));}},width:S.baseWidth,height:S.baseHeight,tool:Tn,color:An,strokeWidth:Pn/S.scale,isSketchMode:Dn,xOffset:S.contentOffsetX,yOffset:S.contentOffsetY-S.offsetY/S.scale,style:{width:S.stageWidth,height:S.stageHeight}}),jsxs(Stage,{ref:x,width:S.stageWidth,height:S.stageHeight,scaleX:S.scaleX,scaleY:S.scaleY,x:S.offsetX,y:0,onMouseDown:cd,onMouseMove:fd,onMouseUp:md,onTouchStart:cd,onTouchMove:fd,onTouchEnd:md,children:[jsx(Layer,{listening:false,children:jsx(Rect,{x:0,y:0,width:S.baseWidth,height:S.stageHeight/S.scale,fill:i?.backgroundColor||"white"})}),jsx(Layer,{x:-S.contentOffsetX,y:S.offsetY/S.scale-S.contentOffsetY,children:(()=>{let L=[];return g.forEach((I,P)=>{L.push({type:"line",timestamp:I.timestamp||P,element:{...I,id:I.id??`line-${P}`},index:P});}),bm.forEach(I=>{L.push({type:"shape",timestamp:I.timestamp||0,element:I});}),ne.forEach(I=>{L.push({type:"image",timestamp:I.timestamp||0,element:I});}),Le.forEach(I=>{L.push({type:"video",timestamp:I.timestamp||0,element:I});}),jo.forEach(I=>{L.push({type:"text",timestamp:I.timestamp||0,element:I});}),Im.forEach(I=>{L.push({type:"flashcard",timestamp:I.timestamp||0,element:I});}),ld.forEach(I=>{L.push({type:"photoFrame",timestamp:I.timestamp||0,element:I});}),Qe.forEach(I=>{L.push({type:"mcq",timestamp:I.timestamp||0,element:I});}),En.forEach(I=>{L.push({type:"trueFalse",timestamp:I.timestamp||0,element:I});}),Ba.forEach(I=>{L.push({type:"shortAnswer",timestamp:I.timestamp||0,element:I});}),pm.forEach(I=>{L.push({type:"longAnswer",timestamp:I.timestamp||0,element:I});}),gm.forEach(I=>{L.push({type:"fillInTheBlanks",timestamp:I.timestamp||0,element:I});}),L.sort((I,P)=>I.timestamp-P.timestamp),L.map((I,P)=>{let O=`${I.type}-${"id"in I.element&&I.element.id||I.index||P}`,Pe="id"in I.element?I.element.id:void 0,Se=Pe&&b===Pe;switch(I.type){case "line":let ae=I.element,Vt=I.index||0,kt=ae.tool==="eraser",nt=ae.isSketch&&ae.tool==="pen",$e=ae.isSketch&&kt,Mt=ae.id||`line-${Vt}`;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),c==="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:nt||$e?void 0:ae.color,strokeWidth:nt||$e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:nt||$e?kt?"black":ae.color:void 0,closed:nt||$e,tension:0,globalCompositeOperation:kt?"destination-out":"source-over",listening:true,onClick:()=>{r(ce()),r(Zr(Vt));},onTap:()=>{r(ce()),r(Zr(Vt));},hitStrokeWidth:Math.max(20,(ae.strokeWidth??0)*2),onMouseEnter:N=>{let T=N.target.getStage();T&&(T.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 T=N.target.getStage();T&&(T.container().style.cursor=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E") 12 12, crosshair`);}})},O):jsxs(be__default.Fragment,{children:[jsx(Group,{id:Mt,ref:N=>{N?F.current.set(Mt,N):F.current.delete(Mt);},x:ae.x||0,y:ae.y||0,scaleX:ae.scaleX||1,scaleY:ae.scaleY||1,rotation:ae.rotation||0,draggable:c==="select",listening:c==="select",onClick:()=>{c==="select"&&(console.log("Line clicked:",Mt),Ke(Mt));},onTap:()=>{c==="select"&&(console.log("Line tapped:",Mt),Ke(Mt));},onDragEnd:N=>{r(ce()),r(ks({id:Mt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ie();},onTransformEnd:N=>{r(ce()),r(ks({id:Mt,x:N.target.x(),y:N.target.y(),scaleX:N.target.scaleX(),scaleY:N.target.scaleY(),rotation:N.target.rotation()})),ie();},onMouseEnter:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="move");}},onMouseLeave:N=>{if(c==="select"){let T=N.target.getStage();T&&(T.container().style.cursor="default");}},onContextMenu:N=>{let T=N.evt;T.preventDefault(),Ct(T,Mt,"line");},children:jsx(Line,{points:ae.points||[],stroke:nt||$e?void 0:ae.color,strokeWidth:nt||$e?0:ae.strokeWidth??0,name:"drawing-line",lineCap:"round",lineJoin:"round",fill:nt||$e?kt?"black":ae.color:void 0,closed:nt||$e,tension:0,globalCompositeOperation:kt?"destination-out":"source-over",listening:true,hitStrokeWidth:20})}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=F.current.get(b);console.log("Line Transformer - selectedId:",b,"node found:",!!T),T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw(),console.log("Line Transformer attached to node"));}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:false,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shape":return jsxs(be__default.Fragment,{children:[jsx(Fi,{onSelect:Ke,shapes:[I.element],shapeRefs:jr,handleShapeDragEnd:vm,handleShapeResizeEnd:ym,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "image":return jsxs(be__default.Fragment,{children:[jsx(Pi,{images:[I.element],getLoadedImage:we,imageRefs:pe,onDragEnd:Fm,onTransform:ue,onSelect:Ke,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=pe.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "video":return jsxs(be__default.Fragment,{children:[jsx(Ei,{videos:[I.element],selectedId:b,videoRefs:Ve,onVideoClick:Bm,onDragEnd:mt,onTransformEnd:Ae,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Ve.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "text":return jsxs(be__default.Fragment,{children:[jsx(nu,{texts:[I.element],textRefs:ca,onDragEnd:wm,onTransformEnd:Lm,onSelect:Ke,onContextMenu:Ct,onDoubleClick:Sm,editingTextId:he,editingValue:nd,onEditingChange:id}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=ca.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "flashcard":return jsxs(be__default.Fragment,{children:[jsx(Ni,{flashcards:[I.element],flashcardRefs:Yr,selectedId:b,onDragEnd:Cm,onTransform:km,onSelect:Ke,onNext:Mm,onPrevious:Tm,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Yr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "photoFrame":return jsxs(be__default.Fragment,{children:[jsx(zi,{photoFrames:[I.element],photoFrameRefs:Jr,selectedId:b,onDragEnd:Am,onTransform:Pm,onSelect:Ke,onStartCamera:Dm,onCapture:Rm,cameraStreams:Em,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Jr.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "mcq":return jsxs(be__default.Fragment,{children:[jsx(Nu,{handleMcqTransform:St,multipleChoice:[I.element],handleSelect:Ke,mcqRefs:Nt,handleDragEnd:Rn,onContextMenu:Ct}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=Nt.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "trueFalse":return jsxs(be__default.Fragment,{children:[jsx(Hu,{trueFalses:[I.element],handleTrueFalseTransform:Kr,handleSelect:Ke,trueFalseRefs:st,onContextMenu:Ct,handleDragEnd:ua}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=st.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "shortAnswer":return jsxs(be__default.Fragment,{children:[jsx(ic,{shortAnswers:[I.element],handleSelect:Ke,handleTransform:St,saRefs:_o,onContextMenu:Ct,handleDragEnd:mm}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_o.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "longAnswer":return jsxs(be__default.Fragment,{children:[jsx(hc,{longAnswer:[I.element],handleSelect:Ke,handleTransform:St,saRefs:_o,onContextMenu:Ct,handleDragEnd:hm}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_o.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);case "fillInTheBlanks":return jsxs(be__default.Fragment,{children:[jsx(mc,{fillInTheBlanks:[I.element],handleSelect:Ke,handleTransform:St,onContextMenu:Ct,handleDragEnd:xm,fibRefs:_r}),Se&&!he&&b&&jsx(Transformer,{ref:N=>{if(N&&fe.current!==N){fe.current=N;let T=_r.current.get(b);T&&T.visible()&&(N.nodes([T]),N.getLayer()?.batchDraw());}},boundBoxFunc:It,borderStroke:"#4A90E2",borderStrokeWidth:2,anchorFill:"#fff",anchorStroke:"#4A90E2",anchorStrokeWidth:2,anchorSize:10,anchorCornerRadius:2,rotateEnabled:true,keepRatio:true,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"]})]},O);default:return null}})})()})]}),R&&jsx(vu,{menuRef:y,x:R.x,y:R.y,type:R.elementType,onAction:Nm,onClose:Vm,isDrawingMode:R.elementType==="image"?i?.images.find(L=>L.id===R.elementId)?.isDrawingMode:R.elementType==="photoFrame"?i?.photoFrames.find(L=>L.id===R.elementId)?.isDrawingMode:false}),V&&R&&jsx(yu,{x:V.x,y:V.y,items:V.type==="order"?[{label:"Bring to Front",onClick:()=>Bn("bring-to-front")},{label:"Send to Back",onClick:()=>Bn("send-to-back")}]:[{label:i&&(R.elementType==="image"?i.images.find(L=>L.id===R.elementId)?.locked:i.videos.find(L=>L.id===R.elementId)?.locked)?"Unlock":"Lock",onClick:()=>Bn(i&&(R.elementType==="image"?i.images.find(L=>L.id===R.elementId)?.locked:i.videos.find(L=>L.id===R.elementId)?.locked)?"unlock":"lock")}],onClose:()=>oe(null)}),z&&jsx(Su,{title:z.type==="link"?"Add Link":"Add Alt Text",label:z.type==="link"?"URL":"Alternative Text",placeholder:z.type==="link"?"https://example.com":"Describe this image/video",defaultValue:z.defaultValue,onSave:qm,onClose:()=>q(null)}),$&&jsx(Ns,{defaultColor:$.defaultColor,onConfirm:Wm,onCancel:()=>W(null)}),H&&jsx(Mu,{imageSrc:H.imageSrc,onConfirm:zm,onCancel:()=>Y(null)}),Q&&jsx(dr,{onClose:()=>Z(false),stageRef:x}),re&&jsx(Du,{elementId:re.elementId,elementType:re.elementType,existingAudio:re.existingAudio,onSave:Hm,onDelete:Um,onClose:()=>ye(null)}),Be&&jsx(Fu,{selectedElementId:b||void 0,onClose:()=>Ce(false),onSelectElement:L=>{Ke(L),Ce(false);}}),i?.images.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.videos.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.shapes?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.texts?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.flashcards?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.photoFrames?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.multipleChoices?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.trueFalses?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.shortAnswers?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.LongAnswer?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),i?.fillInTheBlanks?.filter(L=>L.audioData).map(L=>jsx(Pt,{audioData:L.audioData,x:L.x,y:L.y,width:L.width,scale:S.scale,offsetX:S.offsetX,offsetY:S.offsetY},`audio-${L.id}`)),h&&jsx(Ju,{editElement:v}),E&&(()=>{let L=he||b;if(!L)return null;let I=jo.find(P=>P.id===L);return I?jsx(tc,{text:I,position:E}):null})(),D&&he&&(()=>{let L=jo.find(I=>I.id===he);return L?jsx(oc,{text:L,editingValue:nd,onEditingChange:id,onFinish:Fn,position:{top:D.top,left:D.left},scale:D.scale,textareaRef:Oe},he):null})(),u&&n&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-9999 flex items-center justify-center bg-black",children:jsx("video",{src:l?.objectUrl,controls:true,autoPlay:true,className:"h-full w-full object-contain",onEnded:p})}),jsx("button",{onClick:p,className:"fixed top-8 right-8 z-10000 flex h-12 w-12 items-center justify-center rounded-full bg-white/90 shadow-2xl transition-all hover:scale-110 hover:bg-white","aria-label":"Close video",children:jsx(X$1,{className:"h-6 w-6 text-gray-900",weight:"bold"})})]}),n)]})},zb=Wb;function yl(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 Lc(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=Lc(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():Lc(e[s],null);}}}}function Bt(...e){return be.useCallback(Dr(...e),e)}function Ma(e,o=[]){let t=[];function a(r,n){let c=be.createContext(n),i=t.length;t=[...t,n];let d=f=>{let{scope:l,children:u,...p}=f,v=l?.[e]?.[i]||c,h=be.useMemo(()=>p,Object.values(p));return jsx(v.Provider,{value:h,children:u})};d.displayName=r+"Provider";function m(f,l){let u=l?.[e]?.[i]||c,p=be.useContext(u);if(p)return p;if(n!==void 0)return n;throw new Error(`\`${f}\` must be used within \`${r}\``)}return [d,m]}let s=()=>{let r=t.map(n=>be.createContext(n));return function(c){let i=c?.[e]||r;return be.useMemo(()=>({[`__scope${e}`]:{...c,[e]:i}}),[c,i])}};return s.scopeName=e,[a,_b(s,...o)]}function _b(...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((c,{useScope:i,scopeName:d})=>{let f=i(r)[`__scope${d}`];return {...c,...f}},{});return be.useMemo(()=>({[`__scope${o.scopeName}`]:n}),[n])}};return t.scopeName=o.scopeName,t}var Bo=globalThis?.document?be.useLayoutEffect:()=>{};var jb=be[" useInsertionEffect ".trim().toString()]||Bo;function aa({prop:e,defaultProp:o,onChange:t=()=>{},caller:a}){let[s,r,n]=Xb({defaultProp:o,onChange:t}),c=e!==void 0,i=c?e:s;{let m=be.useRef(e!==void 0);be.useEffect(()=>{let f=m.current;f!==c&&console.warn(`${a} is changing from ${f?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=c;},[c,a]);}let d=be.useCallback(m=>{if(c){let f=$b(m)?m(e):m;f!==e&&n.current?.(f);}else r(m);},[c,e,r,n]);return [i,d]}function Xb({defaultProp:e,onChange:o}){let[t,a]=be.useState(e),s=be.useRef(t),r=be.useRef(o);return jb(()=>{r.current=o;},[o]),be.useEffect(()=>{s.current!==t&&(r.current?.(t),s.current=t);},[t,s]),[t,a,r]}function $b(e){return typeof e=="function"}var Yb=be.createContext(void 0);function Oo(e){let o=be.useContext(Yb);return e||o||"ltr"}function Cc(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 Mc(e){let[o,t]=be.useState(void 0);return Bo(()=>{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,c;if("borderBoxSize"in r){let i=r.borderBoxSize,d=Array.isArray(i)?i[0]:i;n=d.inlineSize,c=d.blockSize;}else n=e.offsetWidth,c=e.offsetHeight;t({width:n,height:c});});return a.observe(e,{box:"border-box"}),()=>a.unobserve(e)}else t(void 0);},[e]),o}function Ac(e){let o=Jb(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(Qb);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,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=tv(s),c=ev(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var Zb=Symbol("radix.slottable");function Qb(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Zb}function ev(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]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function tv(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 rv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ct=rv.reduce((e,o)=>{let t=Ac(`Primitive.${o}`),a=be.forwardRef((s,r)=>{let{asChild:n,...c}=s,i=n?t:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(i,{...c,ref:r})});return a.displayName=`Primitive.${o}`,{...e,[o]:a}},{});function wl(e){let o=sv(e),t=be.forwardRef((a,s)=>{let{children:r,...n}=a,c=be.Children.toArray(r),i=c.find(iv);if(i){let d=i.props.children,m=c.map(f=>f===i?be.Children.count(d)>1?be.Children.only(null):be.isValidElement(d)?d.props.children:null:f);return jsx(o,{...n,ref:s,children:be.isValidElement(d)?be.cloneElement(d,void 0,m):null})}return jsx(o,{...n,ref:s,children:r})});return t.displayName=`${e}.Slot`,t}function sv(e){let o=be.forwardRef((t,a)=>{let{children:s,...r}=t;if(be.isValidElement(s)){let n=dv(s),c=lv(r,s.props);return s.type!==be.Fragment&&(c.ref=a?Dr(a,n):n),be.cloneElement(s,c)}return be.Children.count(s)>1?be.Children.only(null):null});return o.displayName=`${e}.SlotClone`,o}var nv=Symbol("radix.slottable");function iv(e){return be.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===nv}function lv(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]=(...c)=>{let i=r(...c);return s(...c),i}:s&&(t[a]=s):a==="style"?t[a]={...s,...r}:a==="className"&&(t[a]=[s,r].filter(Boolean).join(" "));}return {...e,...t}}function dv(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 fn(e){let o=e+"CollectionProvider",[t,a]=Ma(o),[s,r]=t(o,{collectionRef:{current:null},itemMap:new Map}),n=v=>{let{scope:h,children:g}=v,x=be__default.useRef(null),w=be__default.useRef(new Map).current;return jsx(s,{scope:h,itemMap:w,collectionRef:x,children:g})};n.displayName=o;let c=e+"CollectionSlot",i=wl(c),d=be__default.forwardRef((v,h)=>{let{scope:g,children:x}=v,w=r(c,g),b=Bt(h,w.collectionRef);return jsx(i,{ref:b,children:x})});d.displayName=c;let m=e+"CollectionItemSlot",f="data-radix-collection-item",l=wl(m),u=be__default.forwardRef((v,h)=>{let{scope:g,children:x,...w}=v,b=be__default.useRef(null),C=Bt(h,b),M=r(m,g);return be__default.useEffect(()=>(M.itemMap.set(b,{ref:b,...w}),()=>void M.itemMap.delete(b))),jsx(l,{[f]:"",ref:C,children:x})});u.displayName=m;function p(v){let h=r(e+"CollectionConsumer",v);return be__default.useCallback(()=>{let x=h.collectionRef.current;if(!x)return [];let w=Array.from(x.querySelectorAll(`[${f}]`));return Array.from(h.itemMap.values()).sort((M,k)=>w.indexOf(M.ref.current)-w.indexOf(k.ref.current))},[h.collectionRef,h.itemMap])}return [{Provider:n,Slot:d,ItemSlot:u},p,a]}var Rc=["PageUp","PageDown"],Ec=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Fc={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},No="Slider",[Sl,cv,fv]=fn(No),[Bc]=Ma(No,[fv]),[mv,mn]=Bc(No),Oc=be.forwardRef((e,o)=>{let{name:t,min:a=0,max:s=100,step:r=1,orientation:n="horizontal",disabled:c=false,minStepsBetweenThumbs:i=0,defaultValue:d=[a],value:m,onValueChange:f=()=>{},onValueCommit:l=()=>{},inverted:u=false,form:p,...v}=e,h=be.useRef(new Set),g=be.useRef(0),w=n==="horizontal"?pv:hv,[b=[],C]=aa({prop:m,defaultProp:d,onChange:A=>{[...h.current][g.current]?.focus(),f(A);}}),M=be.useRef(b);function k(A){let R=yv(b,A);B(A,R);}function y(A){B(A,g.current);}function S(){let A=M.current[g.current];b[g.current]!==A&&l(b);}function B(A,R,{commit:U}={commit:false}){let E=Iv(r),_=Cv(Math.round((A-a)/r)*r+a,E),D=yl(_,[a,s]);C((te=[])=>{let V=bv(te,D,R);if(Sv(V,i*r)){g.current=V.indexOf(D);let oe=String(V)!==String(te);return oe&&U&&l(V),oe?V:te}else return te});}return jsx(mv,{scope:e.__scopeSlider,name:t,disabled:c,min:a,max:s,valueIndexToChangeRef:g,thumbs:h.current,values:b,orientation:n,form:p,children:jsx(Sl.Provider,{scope:e.__scopeSlider,children:jsx(Sl.Slot,{scope:e.__scopeSlider,children:jsx(w,{"aria-disabled":c,"data-disabled":c?"":void 0,...v,ref:o,onPointerDown:Je(v.onPointerDown,()=>{c||(M.current=b);}),min:a,max:s,inverted:u,onSlideStart:c?void 0:k,onSlideMove:c?void 0:y,onSlideEnd:c?void 0:S,onHomeKeyDown:()=>!c&&B(a,0,{commit:true}),onEndKeyDown:()=>!c&&B(s,b.length-1,{commit:true}),onStepKeyDown:({event:A,direction:R})=>{if(!c){let _=Rc.includes(A.key)||A.shiftKey&&Ec.includes(A.key)?10:1,D=g.current,te=b[D],V=r*_*R;B(te+V,D,{commit:true});}}})})})})});Oc.displayName=No;var[Nc,Vc]=Bc(No,{startEdge:"left",endEdge:"right",size:"width",direction:1}),pv=be.forwardRef((e,o)=>{let{min:t,max:a,dir:s,inverted:r,onSlideStart:n,onSlideMove:c,onSlideEnd:i,onStepKeyDown:d,...m}=e,[f,l]=be.useState(null),u=Bt(o,w=>l(w)),p=be.useRef(void 0),v=Oo(s),h=v==="ltr",g=h&&!r||!h&&r;function x(w){let b=p.current||f.getBoundingClientRect(),C=[0,b.width],k=kl(C,g?[t,a]:[a,t]);return p.current=b,k(w-b.left)}return jsx(Nc,{scope:e.__scopeSlider,startEdge:g?"left":"right",endEdge:g?"right":"left",direction:g?1:-1,size:"width",children:jsx(qc,{dir:v,"data-orientation":"horizontal",...m,ref:u,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{let b=x(w.clientX);n?.(b);},onSlideMove:w=>{let b=x(w.clientX);c?.(b);},onSlideEnd:()=>{p.current=void 0,i?.();},onStepKeyDown:w=>{let C=Fc[g?"from-left":"from-right"].includes(w.key);d?.({event:w,direction:C?-1:1});}})})}),hv=be.forwardRef((e,o)=>{let{min:t,max:a,inverted:s,onSlideStart:r,onSlideMove:n,onSlideEnd:c,onStepKeyDown:i,...d}=e,m=be.useRef(null),f=Bt(o,m),l=be.useRef(void 0),u=!s;function p(v){let h=l.current||m.current.getBoundingClientRect(),g=[0,h.height],w=kl(g,u?[a,t]:[t,a]);return l.current=h,w(v-h.top)}return jsx(Nc,{scope:e.__scopeSlider,startEdge:u?"bottom":"top",endEdge:u?"top":"bottom",size:"height",direction:u?1:-1,children:jsx(qc,{"data-orientation":"vertical",...d,ref:f,style:{...d.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,c?.();},onStepKeyDown:v=>{let g=Fc[u?"from-bottom":"from-top"].includes(v.key);i?.({event:v,direction:g?-1:1});}})})}),qc=be.forwardRef((e,o)=>{let{__scopeSlider:t,onSlideStart:a,onSlideMove:s,onSlideEnd:r,onHomeKeyDown:n,onEndKeyDown:c,onStepKeyDown:i,...d}=e,m=mn(No,t);return jsx(ct.span,{...d,ref:o,onKeyDown:Je(e.onKeyDown,f=>{f.key==="Home"?(n(f),f.preventDefault()):f.key==="End"?(c(f),f.preventDefault()):Rc.concat(Ec).includes(f.key)&&(i(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));})})}),Hc="SliderTrack",Uc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=mn(Hc,t);return jsx(ct.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...a,ref:o})});Uc.displayName=Hc;var Il="SliderRange",Wc=be.forwardRef((e,o)=>{let{__scopeSlider:t,...a}=e,s=mn(Il,t),r=Vc(Il,t),n=be.useRef(null),c=Bt(o,n),i=s.values.length,d=s.values.map(l=>Kc(l,s.min,s.max)),m=i>1?Math.min(...d):0,f=100-Math.max(...d);return jsx(ct.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...a,ref:c,style:{...e.style,[r.startEdge]:m+"%",[r.endEdge]:f+"%"}})});Wc.displayName=Il;var Cl="SliderThumb",zc=be.forwardRef((e,o)=>{let t=cv(e.__scopeSlider),[a,s]=be.useState(null),r=Bt(o,c=>s(c)),n=be.useMemo(()=>a?t().findIndex(c=>c.ref.current===a):-1,[t,a]);return jsx(gv,{...e,ref:r,index:n})}),gv=be.forwardRef((e,o)=>{let{__scopeSlider:t,index:a,name:s,...r}=e,n=mn(Cl,t),c=Vc(Cl,t),[i,d]=be.useState(null),m=Bt(o,x=>d(x)),f=i?n.form||!!i.closest("form"):true,l=Mc(i),u=n.values[a],p=u===void 0?0:Kc(u,n.min,n.max),v=vv(a,n.values.length),h=l?.[c.size],g=h?wv(h,p,c.direction):0;return be.useEffect(()=>{if(i)return n.thumbs.add(i),()=>{n.thumbs.delete(i);}},[i,n.thumbs]),jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${p}% + ${g}px)`},children:[jsx(Sl.ItemSlot,{scope:e.__scopeSlider,children:jsx(ct.span,{role:"slider","aria-label":e["aria-label"]||v,"aria-valuemin":n.min,"aria-valuenow":u,"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:u===void 0?{display:"none"}:e.style,onFocus:Je(e.onFocus,()=>{n.valueIndexToChangeRef.current=a;})})}),f&&jsx(Gc,{name:s??(n.name?n.name+(n.values.length>1?"[]":""):void 0),form:n.form,value:u},a)]})});zc.displayName=Cl;var xv="RadioBubbleInput",Gc=be.forwardRef(({__scopeSlider:e,value:o,...t},a)=>{let s=be.useRef(null),r=Bt(s,a),n=Cc(o);return be.useEffect(()=>{let c=s.current;if(!c)return;let i=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(i,"value").set;if(n!==o&&m){let f=new Event("input",{bubbles:true});m.call(c,o),c.dispatchEvent(f);}},[n,o]),jsx(ct.input,{style:{display:"none"},...t,ref:r,defaultValue:o})});Gc.displayName=xv;function bv(e=[],o,t){let a=[...e];return a[t]=o,a.sort((s,r)=>s-r)}function Kc(e,o,t){let r=100/(t-o)*(e-o);return yl(r,[0,100])}function vv(e,o){return o>2?`Value ${e+1} of ${o}`:o===2?["Minimum","Maximum"][e]:void 0}function yv(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 wv(e,o,t){let a=e/2,r=kl([0,50],[0,a]);return (a-r(o)*t)*t}function Lv(e){return e.slice(0,-1).map((o,t)=>e[t+1]-o)}function Sv(e,o){if(o>0){let t=Lv(e);return Math.min(...t)>=o}return true}function kl(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 Iv(e){return (String(e).split(".")[1]||"").length}function Cv(e,o){let t=Math.pow(10,o);return Math.round(e*t)/t}var _c=Oc,jc=Uc,Xc=Wc,$c=zc;function Yc(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=Yc(e[o]))&&(a&&(a+=" "),a+=t);}else for(t in e)e[t]&&(a&&(a+=" "),a+=t);return a}function pn(){for(var e,o,t=0,a="",s=arguments.length;t<s;t++)(e=arguments[t])&&(o=Yc(e))&&(a&&(a+=" "),a+=o);return a}var Mv=(e,o)=>{let t=new Array(e.length+o.length);for(let a=0;a<e.length;a++)t[a]=e[a];for(let a=0;a<o.length;a++)t[e.length+a]=o[a];return t},Tv=(e,o)=>({classGroupId:e,validator:o}),tf=(e=new Map,o=null,t)=>({nextPart:e,validators:o,classGroupId:t});var Jc=[],Av="arbitrary..",Pv=e=>{let o=Rv(e),{conflictingClassGroups:t,conflictingClassGroupModifiers:a}=e;return {getClassGroupId:n=>{if(n.startsWith("[")&&n.endsWith("]"))return Dv(n);let c=n.split("-"),i=c[0]===""&&c.length>1?1:0;return af(c,i,o)},getConflictingClassGroupIds:(n,c)=>{if(c){let i=a[n],d=t[n];return i?d?Mv(d,i):i:d||Jc}return t[n]||Jc}}},af=(e,o,t)=>{if(e.length-o===0)return t.classGroupId;let s=e[o],r=t.nextPart.get(s);if(r){let d=af(e,o+1,r);if(d)return d}let n=t.validators;if(n===null)return;let c=o===0?e.join("-"):e.slice(o).join("-"),i=n.length;for(let d=0;d<i;d++){let m=n[d];if(m.validator(c))return m.classGroupId}},Dv=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let o=e.slice(1,-1),t=o.indexOf(":"),a=o.slice(0,t);return a?Av+a:void 0})(),Rv=e=>{let{theme:o,classGroups:t}=e;return Ev(t,o)},Ev=(e,o)=>{let t=tf();for(let a in e){let s=e[a];Al(s,t,a,o);}return t},Al=(e,o,t,a)=>{let s=e.length;for(let r=0;r<s;r++){let n=e[r];Fv(n,o,t,a);}},Fv=(e,o,t,a)=>{if(typeof e=="string"){Bv(e,o,t);return}if(typeof e=="function"){Ov(e,o,t,a);return}Nv(e,o,t,a);},Bv=(e,o,t)=>{let a=e===""?o:of(o,e);a.classGroupId=t;},Ov=(e,o,t,a)=>{if(Vv(e)){Al(e(a),o,t,a);return}o.validators===null&&(o.validators=[]),o.validators.push(Tv(t,e));},Nv=(e,o,t,a)=>{let s=Object.entries(e),r=s.length;for(let n=0;n<r;n++){let[c,i]=s[n];Al(i,of(o,c),t,a);}},of=(e,o)=>{let t=e,a=o.split("-"),s=a.length;for(let r=0;r<s;r++){let n=a[r],c=t.nextPart.get(n);c||(c=tf(),t.nextPart.set(n,c)),t=c;}return t},Vv=e=>"isThemeGetter"in e&&e.isThemeGetter===true,qv=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 Hv=[],Zc=(e,o,t,a,s)=>({modifiers:e,hasImportantModifier:o,baseClassName:t,maybePostfixModifierPosition:a,isExternal:s}),Uv=e=>{let{prefix:o,experimentalParseClassName:t}=e,a=s=>{let r=[],n=0,c=0,i=0,d,m=s.length;for(let v=0;v<m;v++){let h=s[v];if(n===0&&c===0){if(h===":"){r.push(s.slice(i,v)),i=v+1;continue}if(h==="/"){d=v;continue}}h==="["?n++:h==="]"?n--:h==="("?c++:h===")"&&c--;}let f=r.length===0?s:s.slice(i),l=f,u=false;f.endsWith("!")?(l=f.slice(0,-1),u=true):f.startsWith("!")&&(l=f.slice(1),u=true);let p=d&&d>i?d-i:void 0;return Zc(r,u,l,p)};if(o){let s=o+":",r=a;a=n=>n.startsWith(s)?r(n.slice(s.length)):Zc(Hv,false,n,void 0,true);}if(t){let s=a;a=r=>t({className:r,parseClassName:s});}return a},Wv=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],c=n[0]==="[",i=o.has(n);c||i?(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}},zv=e=>({cache:qv(e.cacheSize),parseClassName:Uv(e),sortModifiers:Wv(e),...Pv(e)}),Gv=/\s+/,Kv=(e,o)=>{let{parseClassName:t,getClassGroupId:a,getConflictingClassGroupIds:s,sortModifiers:r}=o,n=[],c=e.trim().split(Gv),i="";for(let d=c.length-1;d>=0;d-=1){let m=c[d],{isExternal:f,modifiers:l,hasImportantModifier:u,baseClassName:p,maybePostfixModifierPosition:v}=t(m);if(f){i=m+(i.length>0?" "+i:i);continue}let h=!!v,g=a(h?p.substring(0,v):p);if(!g){if(!h){i=m+(i.length>0?" "+i:i);continue}if(g=a(p),!g){i=m+(i.length>0?" "+i:i);continue}h=false;}let x=l.length===0?"":l.length===1?l[0]:r(l).join(":"),w=u?x+"!":x,b=w+g;if(n.indexOf(b)>-1)continue;n.push(b);let C=s(g,h);for(let M=0;M<C.length;++M){let k=C[M];n.push(w+k);}i=m+(i.length>0?" "+i:i);}return i},_v=(...e)=>{let o=0,t,a,s="";for(;o<e.length;)(t=e[o++])&&(a=rf(t))&&(s&&(s+=" "),s+=a);return s},rf=e=>{if(typeof e=="string")return e;let o,t="";for(let a=0;a<e.length;a++)e[a]&&(o=rf(e[a]))&&(t&&(t+=" "),t+=o);return t},jv=(e,...o)=>{let t,a,s,r,n=i=>{let d=o.reduce((m,f)=>f(m),e());return t=zv(d),a=t.cache.get,s=t.cache.set,r=c,c(i)},c=i=>{let d=a(i);if(d)return d;let m=Kv(i,t);return s(i,m),m};return r=n,(...i)=>r(_v(...i))},Xv=[],Ue=e=>{let o=t=>t[e]||Xv;return o.isThemeGetter=true,o},sf=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,nf=/^\((?:(\w[\w-]*):)?(.+)\)$/i,$v=/^\d+\/\d+$/,Yv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jv=/\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$/,Zv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Qv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ey=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Vo=e=>$v.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),Ta=e=>!!e&&Number.isInteger(Number(e)),Ml=e=>e.endsWith("%")&&de(e.slice(0,-1)),oa=e=>Yv.test(e),ty=()=>true,ay=e=>Jv.test(e)&&!Zv.test(e),lf=()=>false,oy=e=>Qv.test(e),ry=e=>ey.test(e),sy=e=>!j(e)&&!X(e),ny=e=>qo(e,cf,lf),j=e=>sf.test(e),Za=e=>qo(e,ff,ay),Tl=e=>qo(e,cy,de),Qc=e=>qo(e,df,lf),iy=e=>qo(e,uf,ry),hn=e=>qo(e,mf,oy),X=e=>nf.test(e),Rr=e=>Ho(e,ff),ly=e=>Ho(e,fy),ef=e=>Ho(e,df),dy=e=>Ho(e,cf),uy=e=>Ho(e,uf),gn=e=>Ho(e,mf,true),qo=(e,o,t)=>{let a=sf.exec(e);return a?a[1]?o(a[1]):t(a[2]):false},Ho=(e,o,t=false)=>{let a=nf.exec(e);return a?a[1]?o(a[1]):t:false},df=e=>e==="position"||e==="percentage",uf=e=>e==="image"||e==="url",cf=e=>e==="length"||e==="size"||e==="bg-size",ff=e=>e==="length",cy=e=>e==="number",fy=e=>e==="family-name",mf=e=>e==="shadow";var my=()=>{let e=Ue("color"),o=Ue("font"),t=Ue("text"),a=Ue("font-weight"),s=Ue("tracking"),r=Ue("leading"),n=Ue("breakpoint"),c=Ue("container"),i=Ue("spacing"),d=Ue("radius"),m=Ue("shadow"),f=Ue("inset-shadow"),l=Ue("text-shadow"),u=Ue("drop-shadow"),p=Ue("blur"),v=Ue("perspective"),h=Ue("aspect"),g=Ue("ease"),x=Ue("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[...b(),X,j],M=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto","contain","none"],y=()=>[X,j,i],S=()=>[Vo,"full","auto",...y()],B=()=>[Ta,"none","subgrid",X,j],A=()=>["auto",{span:["full",Ta,X,j]},Ta,X,j],R=()=>[Ta,"auto",X,j],U=()=>["auto","min","max","fr",X,j],E=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],_=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...y()],te=()=>[Vo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...y()],V=()=>[e,X,j],oe=()=>[...b(),ef,Qc,{position:[X,j]}],z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",dy,ny,{size:[X,j]}],$=()=>[Ml,Rr,Za],W=()=>["","none","full",d,X,j],H=()=>["",de,Rr,Za],Y=()=>["solid","dashed","dotted","double"],Q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Z=()=>[de,Ml,ef,Qc],re=()=>["","none",p,X,j],ye=()=>["none",de,X,j],Be=()=>["none",de,X,j],Ce=()=>[de,X,j],Oe=()=>[Vo,"full",...y()];return {cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[oa],breakpoint:[oa],color:[ty],container:[oa],"drop-shadow":[oa],ease:["in","out","in-out"],font:[sy],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[oa],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[oa],shadow:[oa],spacing:["px",de],text:[oa],"text-shadow":[oa],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Vo,j,X,h]}],container:["container"],columns:[{columns:[de,j,X,c]}],"break-after":[{"break-after":w()}],"break-before":[{"break-before":w()}],"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:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Ta,"auto",X,j]}],basis:[{basis:[Vo,"full","auto",c,...y()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,Vo,"auto","initial","none",j]}],grow:[{grow:["",de,X,j]}],shrink:[{shrink:["",de,X,j]}],order:[{order:[Ta,"first","last","none",X,j]}],"grid-cols":[{"grid-cols":B()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":B()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":U()}],"auto-rows":[{"auto-rows":U()}],gap:[{gap:y()}],"gap-x":[{"gap-x":y()}],"gap-y":[{"gap-y":y()}],"justify-content":[{justify:[...E(),"normal"]}],"justify-items":[{"justify-items":[..._(),"normal"]}],"justify-self":[{"justify-self":["auto",..._()]}],"align-content":[{content:["normal",...E()]}],"align-items":[{items:[..._(),{baseline:["","last"]}]}],"align-self":[{self:["auto",..._(),{baseline:["","last"]}]}],"place-content":[{"place-content":E()}],"place-items":[{"place-items":[..._(),"baseline"]}],"place-self":[{"place-self":["auto",..._()]}],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:te()}],w:[{w:[c,"screen",...te()]}],"min-w":[{"min-w":[c,"screen","none",...te()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[n]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",t,Rr,Za]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[a,X,Tl]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ml,j]}],"font-family":[{font:[ly,j,o]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,X,j]}],"line-clamp":[{"line-clamp":[de,"none",X,Tl]}],leading:[{leading:[r,...y()]}],"list-image":[{"list-image":["none",X,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",X,j]}],"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:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",X,Za]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[de,"auto",X,j]}],"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,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",X,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:oe()}],"bg-repeat":[{bg:z()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ta,X,j],radial:["",X,j],conic:[Ta,X,j]},uy,iy]}],"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:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:H()}],"border-w-x":[{"border-x":H()}],"border-w-y":[{"border-y":H()}],"border-w-s":[{"border-s":H()}],"border-w-e":[{"border-e":H()}],"border-w-t":[{"border-t":H()}],"border-w-r":[{"border-r":H()}],"border-w-b":[{"border-b":H()}],"border-w-l":[{"border-l":H()}],"divide-x":[{"divide-x":H()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":H()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Y(),"hidden","none"]}],"divide-style":[{divide:[...Y(),"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:[...Y(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,X,j]}],"outline-w":[{outline:["",de,Rr,Za]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",m,gn,hn]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",f,gn,hn]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[de,Za]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":H()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",l,gn,hn]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[de,X,j]}],"mix-blend":[{"mix-blend":[...Q(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Q()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":Z()}],"mask-image-linear-to-pos":[{"mask-linear-to":Z()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":Z()}],"mask-image-t-to-pos":[{"mask-t-to":Z()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":Z()}],"mask-image-r-to-pos":[{"mask-r-to":Z()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":Z()}],"mask-image-b-to-pos":[{"mask-b-to":Z()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":Z()}],"mask-image-l-to-pos":[{"mask-l-to":Z()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":Z()}],"mask-image-x-to-pos":[{"mask-x-to":Z()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":Z()}],"mask-image-y-to-pos":[{"mask-y-to":Z()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[X,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":Z()}],"mask-image-radial-to-pos":[{"mask-radial-to":Z()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":Z()}],"mask-image-conic-to-pos":[{"mask-conic-to":Z()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:oe()}],"mask-repeat":[{mask:z()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",X,j]}],filter:[{filter:["","none",X,j]}],blur:[{blur:re()}],brightness:[{brightness:[de,X,j]}],contrast:[{contrast:[de,X,j]}],"drop-shadow":[{"drop-shadow":["","none",u,gn,hn]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",de,X,j]}],"hue-rotate":[{"hue-rotate":[de,X,j]}],invert:[{invert:["",de,X,j]}],saturate:[{saturate:[de,X,j]}],sepia:[{sepia:["",de,X,j]}],"backdrop-filter":[{"backdrop-filter":["","none",X,j]}],"backdrop-blur":[{"backdrop-blur":re()}],"backdrop-brightness":[{"backdrop-brightness":[de,X,j]}],"backdrop-contrast":[{"backdrop-contrast":[de,X,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,X,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,X,j]}],"backdrop-invert":[{"backdrop-invert":["",de,X,j]}],"backdrop-opacity":[{"backdrop-opacity":[de,X,j]}],"backdrop-saturate":[{"backdrop-saturate":[de,X,j]}],"backdrop-sepia":[{"backdrop-sepia":["",de,X,j]}],"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,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",X,j]}],ease:[{ease:["linear","initial",g,X,j]}],delay:[{delay:[de,X,j]}],animate:[{animate:["none",x,X,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[v,X,j]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:ye()}],"rotate-x":[{"rotate-x":ye()}],"rotate-y":[{"rotate-y":ye()}],"rotate-z":[{"rotate-z":ye()}],scale:[{scale:Be()}],"scale-x":[{"scale-x":Be()}],"scale-y":[{"scale-y":Be()}],"scale-z":[{"scale-z":Be()}],"scale-3d":["scale-3d"],skew:[{skew:Ce()}],"skew-x":[{"skew-x":Ce()}],"skew-y":[{"skew-y":Ce()}],transform:[{transform:[X,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Oe()}],"translate-x":[{"translate-x":Oe()}],"translate-y":[{"translate-y":Oe()}],"translate-z":[{"translate-z":Oe()}],"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,j]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":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,j]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[de,Rr,Za,Tl]}],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 pf=jv(my);function Aa(...e){return pf(pn(e))}function xn({className:e,defaultValue:o,value:t,min:a=0,max:s=100,rangeClassName:r,trackClassName:n,thumbClassName:c,...i}){let d=be.useMemo(()=>Array.isArray(t)?t:Array.isArray(o)?o:[a,s],[t,o,a,s]);return jsxs(_c,{"data-slot":"slider",defaultValue:o,value:t,min:a,max:s,className:Aa("relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[jsx(jc,{"data-slot":"slider-track",className:Aa("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",n),children:jsx(Xc,{"data-slot":"slider-range",className:Aa("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",r)})}),Array.from({length:d.length},(m,f)=>jsx($c,{"data-slot":"slider-thumb",className:Aa("border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50",c)},f))]})}var hy="SchooplaVideoStorage";var Zt="videos",bn=()=>new Promise((e,o)=>{let t=indexedDB.open(hy,1);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Zt)||s.createObjectStore(Zt,{keyPath:"id"});};}),Qa=async(e,o,t)=>{try{console.log("\u{1F4BE} Saving video blob to IndexedDB:",e);let a=await bn(),r=a.transaction([Zt],"readwrite").objectStore(Zt),n={id:e,blob:o,thumbnailDataUrl:t,timestamp:Date.now()};await new Promise((c,i)=>{let d=r.put(n);d.onsuccess=()=>c(!0),d.onerror=()=>i(d.error);}),a.close(),console.log("\u2705 Video blob saved successfully:",e);}catch(a){throw console.error("Error saving video blob to IndexedDB:",a),a}};var gf=async()=>{try{console.log("\u{1F4C2} Loading all video blobs from IndexedDB...");let e=await bn(),t=e.transaction([Zt],"readonly").objectStore(Zt);return new Promise((a,s)=>{let r=t.getAll();r.onsuccess=()=>{e.close();let n=r.result,c=new Map;n.forEach(i=>{c.set(i.id,{blob:i.blob,thumbnailDataUrl:i.thumbnailDataUrl});}),console.log(`\u2705 Loaded ${c.size} video blobs from IndexedDB`),a(c);},r.onerror=()=>{e.close(),s(r.error);};})}catch(e){return console.error("Error loading all video blobs from IndexedDB:",e),new Map}},Dl=async e=>{try{console.log("\u{1F5D1}\uFE0F Deleting video blob from IndexedDB:",e);let o=await bn(),a=o.transaction([Zt],"readwrite").objectStore(Zt);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}},xf=async()=>{try{console.log("\u{1F5D1}\uFE0F Clearing all video blobs from IndexedDB...");let e=await bn(),t=e.transaction([Zt],"readwrite").objectStore(Zt);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}},bf=e=>URL.createObjectURL(e);var gy=be[" useId ".trim().toString()]||(()=>{}),xy=0;function vf(e){let[o,t]=be.useState(gy());return Bo(()=>{t(a=>a??String(xy++));},[e]),(o?`radix-${o}`:"")}function yf(e){let o=be.useRef(e);return be.useEffect(()=>{o.current=e;}),be.useMemo(()=>(...t)=>o.current?.(...t),[])}var El="rovingFocusGroup.onEntryFocus",by={bubbles:false,cancelable:true},Er="RovingFocusGroup",[Fl,wf,vy]=fn(Er),[yy,Bl]=Ma(Er,[vy]),[wy,Ly]=yy(Er),Lf=be.forwardRef((e,o)=>jsx(Fl.Provider,{scope:e.__scopeRovingFocusGroup,children:jsx(Fl.Slot,{scope:e.__scopeRovingFocusGroup,children:jsx(Sy,{...e,ref:o})})}));Lf.displayName=Er;var Sy=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,orientation:a,loop:s=false,dir:r,currentTabStopId:n,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:i,onEntryFocus:d,preventScrollOnEntryFocus:m=false,...f}=e,l=be.useRef(null),u=Bt(o,l),p=Oo(r),[v,h]=aa({prop:n,defaultProp:c??null,onChange:i,caller:Er}),[g,x]=be.useState(false),w=yf(d),b=wf(t),C=be.useRef(false),[M,k]=be.useState(0);return be.useEffect(()=>{let y=l.current;if(y)return y.addEventListener(El,w),()=>y.removeEventListener(El,w)},[w]),jsx(wy,{scope:t,orientation:a,dir:p,loop:s,currentTabStopId:v,onItemFocus:be.useCallback(y=>h(y),[h]),onItemShiftTab:be.useCallback(()=>x(true),[]),onFocusableItemAdd:be.useCallback(()=>k(y=>y+1),[]),onFocusableItemRemove:be.useCallback(()=>k(y=>y-1),[]),children:jsx(ct.div,{tabIndex:g||M===0?-1:0,"data-orientation":a,...f,ref:u,style:{outline:"none",...e.style},onMouseDown:Je(e.onMouseDown,()=>{C.current=true;}),onFocus:Je(e.onFocus,y=>{let S=!C.current;if(y.target===y.currentTarget&&S&&!g){let B=new CustomEvent(El,by);if(y.currentTarget.dispatchEvent(B),!B.defaultPrevented){let A=b().filter(D=>D.focusable),R=A.find(D=>D.active),U=A.find(D=>D.id===v),_=[R,U,...A].filter(Boolean).map(D=>D.ref.current);Cf(_,m);}}C.current=false;}),onBlur:Je(e.onBlur,()=>x(false))})})}),Sf="RovingFocusGroupItem",If=be.forwardRef((e,o)=>{let{__scopeRovingFocusGroup:t,focusable:a=true,active:s=false,tabStopId:r,children:n,...c}=e,i=vf(),d=r||i,m=Ly(Sf,t),f=m.currentTabStopId===d,l=wf(t),{onFocusableItemAdd:u,onFocusableItemRemove:p,currentTabStopId:v}=m;return be.useEffect(()=>{if(a)return u(),()=>p()},[a,u,p]),jsx(Fl.ItemSlot,{scope:t,id:d,focusable:a,active:s,children:jsx(ct.span,{tabIndex:f?0:-1,"data-orientation":m.orientation,...c,ref:o,onMouseDown:Je(e.onMouseDown,h=>{a?m.onItemFocus(d):h.preventDefault();}),onFocus:Je(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:Je(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;let g=ky(h,m.orientation,m.dir);if(g!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let w=l().filter(b=>b.focusable).map(b=>b.ref.current);if(g==="last")w.reverse();else if(g==="prev"||g==="next"){g==="prev"&&w.reverse();let b=w.indexOf(h.currentTarget);w=m.loop?My(w,b+1):w.slice(b+1);}setTimeout(()=>Cf(w));}}),children:typeof n=="function"?n({isCurrentTabStop:f,hasTabStop:v!=null}):n})})});If.displayName=Sf;var Iy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Cy(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ky(e,o,t){let a=Cy(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return Iy[a]}function Cf(e,o=false){let t=document.activeElement;for(let a of e)if(a===t||(a.focus({preventScroll:o}),document.activeElement!==t))return}function My(e,o){return e.map((t,a)=>e[(o+a)%e.length])}var kf=Lf,Mf=If;var Af="Toggle",Ol=be.forwardRef((e,o)=>{let{pressed:t,defaultPressed:a,onPressedChange:s,...r}=e,[n,c]=aa({prop:t,onChange:s,defaultProp:a??false,caller:Af});return jsx(ct.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||c(!n);})})});Ol.displayName=Af;var Pa="ToggleGroup",[Df]=Ma(Pa,[Bl]),Rf=Bl(),Nl=be__default.forwardRef((e,o)=>{let{type:t,...a}=e;if(t==="single")return jsx(Py,{...a,ref:o});if(t==="multiple")return jsx(Dy,{...a,ref:o});throw new Error(`Missing prop \`type\` expected on \`${Pa}\``)});Nl.displayName=Pa;var[Ef,Ff]=Df(Pa),Py=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??"",onChange:s,caller:Pa});return jsx(Ef,{scope:e.__scopeToggleGroup,type:"single",value:be__default.useMemo(()=>n?[n]:[],[n]),onItemActivate:c,onItemDeactivate:be__default.useCallback(()=>c(""),[c]),children:jsx(Bf,{...r,ref:o})})}),Dy=be__default.forwardRef((e,o)=>{let{value:t,defaultValue:a,onValueChange:s=()=>{},...r}=e,[n,c]=aa({prop:t,defaultProp:a??[],onChange:s,caller:Pa}),i=be__default.useCallback(m=>c((f=[])=>[...f,m]),[c]),d=be__default.useCallback(m=>c((f=[])=>f.filter(l=>l!==m)),[c]);return jsx(Ef,{scope:e.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:i,onItemDeactivate:d,children:jsx(Bf,{...r,ref:o})})});Nl.displayName=Pa;var[Ry,Ey]=Df(Pa),Bf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,disabled:a=false,rovingFocus:s=true,orientation:r,dir:n,loop:c=true,...i}=e,d=Rf(t),m=Oo(n),f={role:"group",dir:m,...i};return jsx(Ry,{scope:t,rovingFocus:s,disabled:a,children:s?jsx(kf,{asChild:true,...d,orientation:r,dir:m,loop:c,children:jsx(ct.div,{...f,ref:o})}):jsx(ct.div,{...f,ref:o})})}),vn="ToggleGroupItem",Fy=be__default.forwardRef((e,o)=>{let t=Ff(vn,e.__scopeToggleGroup),a=Ey(vn,e.__scopeToggleGroup),s=Rf(e.__scopeToggleGroup),r=t.value.includes(e.value),n=a.disabled||e.disabled,c={...e,pressed:r,disabled:n},i=be__default.useRef(null);return a.rovingFocus?jsx(Mf,{asChild:true,...s,focusable:!n,active:r,ref:i,children:jsx(Pf,{...c,ref:o})}):jsx(Pf,{...c,ref:o})});Fy.displayName=vn;var Pf=be__default.forwardRef((e,o)=>{let{__scopeToggleGroup:t,value:a,...s}=e,r=Ff(vn,t),n={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=r.type==="single"?n:void 0;return jsx(Ol,{...c,...s,ref:o,onPressedChange:i=>{i?r.onItemActivate(a):r.onItemDeactivate(a);}})}),Of=Nl;var Ny=be.createContext({size:"default",variant:"default",spacing:0});function Da({className:e,variant:o,size:t,spacing:a=1,children:s,...r}){return jsx(Of,{"data-slot":"toggle-group","data-variant":o,"data-size":t,"data-spacing":a,style:{gap:`${a*.25}rem`},className:Aa("group/toggle-group flex w-fit items-center rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",e),...r,children:jsx(Ny.Provider,{value:{variant:o,size:t,spacing:a},children:s})})}var qy={selectedTool:"select",penColor:"#000000",strokeWidth:12,fontSize:24,fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal",textDecoration:"",textColor:"#000000"},Uf=createSlice({name:"toolbar",initialState:qy,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:Kt,setPenColor:Wo,setStrokeWidth:Fr,setFontSize:ID,setFontFamily:CD,setFontStyle:kD,setFontWeight:MD,setTextDecoration:TD,setTextColor:AD}=Uf.actions,Wf=Uf.reducer;var zf=({onClose:e,onRecordingComplete:o})=>{let t=We(),[a,s]=useState(false),[r,n]=useState(null),[c,i]=useState(0),[d,m]=useState(null),[f,l]=useState(false),u=useRef(null),p=useRef([]),v=useRef(null),h=useRef(null),g=useRef(null);useEffect(()=>((async()=>{try{let S=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240},facingMode:"user"},audio:!1});m(S),l(!0),g.current&&(g.current.srcObject=S);}catch(S){console.error("Error accessing camera:",S),alert("Failed to access camera. Please grant camera permission.");}})(),()=>{v.current&&clearInterval(v.current),d&&d.getTracks().forEach(S=>S.stop());}),[]);let x=()=>{d&&(d.getTracks().forEach(y=>y.stop()),m(null),l(false));},w=async()=>{try{let y=null,S=null;try{y=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1});}catch(E){console.error("Error accessing camera for recording:",E),alert("Failed to access camera for recording.");return}try{S=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});}catch(E){console.warn("Microphone access denied:",E);}let B=[...y.getVideoTracks()];S&&B.push(...S.getAudioTracks());let A=new MediaStream(B),R="video/webm";MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus")?R="video/webm;codecs=vp9,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp8,opus")?R="video/webm;codecs=vp8,opus":MediaRecorder.isTypeSupported("video/webm;codecs=vp9")?R="video/webm;codecs=vp9":MediaRecorder.isTypeSupported("video/webm;codecs=vp8")&&(R="video/webm;codecs=vp8");let U=new MediaRecorder(A,{mimeType:R,videoBitsPerSecond:25e5});u.current=U,p.current=[],U.ondataavailable=E=>{E.data.size>0&&p.current.push(E.data);},U.onstop=()=>{let E=new Blob(p.current,{type:R}),_=document.createElement("video");_.src=URL.createObjectURL(E),_.muted=!0,_.currentTime=.1,_.onseeked=()=>{let D=document.createElement("canvas");D.width=_.videoWidth,D.height=_.videoHeight;let te=D.getContext("2d");te&&(te.drawImage(_,0,0),h.current=D.toDataURL("image/jpeg",.8)),URL.revokeObjectURL(_.src);},A.getTracks().forEach(D=>D.stop()),y&&y.getTracks().forEach(D=>D.stop()),S&&S.getTracks().forEach(D=>D.stop()),v.current&&clearInterval(v.current),n(E),x();},U.onerror=E=>{console.error("MediaRecorder error:",E);},U.start(1e3),s(!0),i(0),v.current=setInterval(()=>{i(E=>E+1);},1e3);}catch(y){console.error("Error starting camera recording:",y),alert("Failed to start recording. Please check permissions.");}},b=()=>{u.current&&a&&(u.current.state!=="inactive"&&(u.current.requestData(),setTimeout(()=>{u.current&&u.current.state!=="inactive"&&u.current.stop();},100)),s(false));},C=()=>{if(r){let y=URL.createObjectURL(r),S=document.createElement("a");S.href=y,S.download=`camera-recording-${Date.now()}.webm`,document.body.appendChild(S),S.click(),document.body.removeChild(S),URL.revokeObjectURL(y);}},M=y=>{let S=Math.floor(y/60),B=y%60;return `${S.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: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:g,autoPlay:true,muted:true,playsInline:true,className:"h-full w-full object-cover"}),!a&&jsxs(Fragment,{children:[jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:jsx("button",{onClick:w,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:b,className:"flex h-20 w-20 items-center justify-center rounded-full bg-red-600 text-white shadow-2xl transition-all hover:scale-110 hover:bg-red-700",children:jsx(Stop,{className:"h-10 w-10",weight:"fill"})}),jsxs("div",{className:"absolute top-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full bg-black/70 px-4 py-2 backdrop-blur-sm",children:[jsx("div",{className:"h-2 w-2 animate-pulse rounded-full bg-red-600"}),jsx("span",{className:"font-mono text-sm font-semibold text-white",children:M(c)})]})]})]}),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: ",M(c)]}),jsxs("div",{className:"flex gap-2",children:[jsx("button",{onClick:()=>{n(null),i(0);},className:"flex-1 rounded-lg border-2 border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white backdrop-blur-sm transition-colors hover:bg-white/20",children:"Re-record"}),jsxs("button",{onClick: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 ra=40,Kf=({onConfirm:e,onCancel:o,editingFlashcard:t})=>{let[a,s]=useState(t?.images||[]),[r,n]=useState(t?.order||"sequential"),[c,i]=useState(false),d=useRef(null),m=We(),f=useRef(null);useEffect(()=>{let w=b=>{b.key==="Escape"&&o();};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[o]);let l=w=>{let b=w.target.files;if(!b||b.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=Array.from(b).slice(0,C);M.length<b.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(y=>new Promise((S,B)=>{let A=new FileReader;A.onload=R=>{R.target?.result?S(R.target.result):B(new Error("Failed to read file"));},A.onerror=B,A.readAsDataURL(y);}));Promise.all(k).then(y=>{s(S=>[...S,...y]),f.current&&(f.current.value="");});},u=w=>{w.preventDefault(),i(false);let b=Array.from(w.dataTransfer.files).filter(y=>y.type.startsWith("image/"));if(b.length===0)return;let C=ra-a.length;if(C<=0){alert(`You can only upload a maximum of ${ra} images`);return}let M=b.slice(0,C);M.length<b.length&&alert(`Only ${C} more images can be added (max ${ra} total)`);let k=M.map(y=>new Promise((S,B)=>{let A=new FileReader;A.onload=R=>{R.target?.result?S(R.target.result):B(new Error("Failed to read file"));},A.onerror=B,A.readAsDataURL(y);}));Promise.all(k).then(y=>{s(S=>[...S,...y]);});},p=w=>{w.preventDefault(),i(true);},v=()=>{i(false);},h=w=>{s(b=>b.filter((C,M)=>M!==w));},g=w=>{if(w.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 x=jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:w=>{w.target===w.currentTarget&&o(),w.stopPropagation();},onMouseUp:w=>w.stopPropagation(),onMouseMove:w=>w.stopPropagation(),onTouchStart:w=>w.stopPropagation(),onTouchMove:w=>w.stopPropagation(),onTouchEnd:w=>w.stopPropagation(),children:jsxs("div",{ref:d,className:"max-h-[90vh] w-[650px] max-w-[90vw] overflow-hidden rounded-lg border border-gray-300 bg-white py-1 shadow-xl",onClick:w=>w.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:g,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>=ra?jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[jsx(Warning,{size:12,weight:"fill"}),"Max ",ra," images"]}):jsxs("span",{children:[a.length,"/",ra," 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:u,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 ${c?"border-black bg-gray-50":"border-gray-300 bg-white hover:border-gray-400 hover:bg-gray-50"}`,children:[jsx("div",{className:"flex items-center justify-center rounded-lg bg-[#EBF6F7] p-4",children:jsx(CloudArrowUp,{size:24,weight:"fill",color:"#096B76"})}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-gray-900",children:c?"Drop your images here":"Click to upload or drag & drop"}),jsx("p",{className:"mt-1 text-xs text-gray-500",children:"PNG, JPG, GIF \xB7 Up to 10MB each \xB7 Minimum 2 images"})]})]})]}),jsxs("div",{children:[jsxs("label",{className:"mb-2 flex items-center justify-between gap-2 px-2 text-sm font-medium text-[#00000099]",children:[jsx("div",{className:"flex items-center gap-2 text-[#00000099] uppercase",children:"Display Order"}),jsx("p",{className:"rounded-full bg-[#0000000A] px-2 py-1 text-xs text-[#00000099]",children:"Required"})]}),jsxs("div",{className:"grid grid-cols-2 gap-3",children:[jsx("button",{type:"button",onClick:()=>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((w,b)=>jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-lg border border-gray-300 bg-white",children:[jsx("img",{src:w,alt:`Flashcard ${b+1}`,className:"h-full w-full object-cover"}),jsx("button",{type:"button",onClick:()=>h(b),className:"absolute top-1 right-1 rounded bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600",children:jsx(Trash,{size:12,weight:"bold"})}),jsx("div",{className:"bg-primary absolute bottom-1 left-1 flex h-5 w-5 items-center justify-center rounded text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:b+1})]},b))})]}),a.length<2&&jsx("div",{className:"rounded-lg border border-gray-300 bg-gray-50 px-4 py-3",children:jsx("p",{className:"text-sm text-gray-700",children:"Upload at least 2 images to create your flashcard deck"})})]}),jsxs("div",{className:"mt-6 flex gap-3",children:[jsx("button",{type:"button",onClick:o,className:"flex-1 cursor-pointer rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50",children:"Cancel"}),jsx("button",{type:"submit",disabled:a.length<2,className:"bg-primary hover:bg-primary/90 flex-1 cursor-pointer rounded-lg px-4 py-2.5 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500",children:t?"Save Changes":"Create Flashcard"})]})]})]})});return createPortal(x,m)};var yn={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}},tw={enabled:true};function Ul(e){return e?{tools:{...yn.tools,...e.tools},actions:{...yn.actions,...e.actions}}:yn}var aw={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}},ow={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 Dw=({isOpen:e,onScreenRecord:o,stageRef:t,onTextAdded:a,config:s}={})=>{let r=xe(),n=ee(F=>F.canvas.slides.find(ne=>ne.id===F.canvas.currentSlideId)),c=n?.videos||[],i=n?.editingFlashcard,d=ee(F=>F.toolbar.selectedTool),m=ee(F=>F.toolbar.penColor),f=ee(F=>F.toolbar.strokeWidth),l=n?.showMcqForm,u=n?.showFlashcardForm,p=useRef(null),v=useMemo(()=>Ul(s),[s]),{tools:h,actions:g}=v,x=c.some(F=>F.isRecorded&&F.isPlaying),w=ee(F=>F.toolbar.fontSize),b=ee(F=>F.toolbar.fontFamily),C=ee(F=>F.toolbar.fontStyle),M=ee(F=>F.toolbar.fontWeight),k=ee(F=>F.toolbar.textDecoration),y=ee(F=>F.toolbar.textColor),[S,B]=useState(false),[A,R]=useState(false),[U,E]=useState(false),[_,D]=useState(false),[te,V]=useState(false),[oe,z]=useState(false),[q,$]=useState(false),W=useRef(null),H=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"}],[]),Q=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"}],[]),Z=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"}],[]),re=useMemo(()=>Y.filter(F=>{let ne=h[F.configKey];return typeof ne=="boolean"?ne:Array.isArray(ne)?ne.length>0:true}),[h,Y]),ye=useMemo(()=>{let F=h.shapes;return F===false?[]:F===true?Q:Array.isArray(F)?Q.filter(ne=>F.includes(ne.name)):Q},[h.shapes,Q]),Be=useMemo(()=>{let F=h.activities;return F===false?[]:F===true?Z:Array.isArray(F)?Z.filter(ne=>F.includes(ne.name)):Z},[h.activities,Z]),Ce=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]),Oe=useMemo(()=>{let F=h.activities;return F===false?false:F===true?true:Array.isArray(F)?F.includes("flashcard"):true},[h.activities]),jt=F=>{let ne=F.target.files;!ne||ne.length===0||(r(Kt("select")),r(pt(false)),D(false),Array.from(ne).forEach(we=>{let pe=new FileReader;pe.onload=se=>{let ue=new window.Image;ue.src=se.target?.result,ue.onload=()=>{let Le=ue.width/ue.height,Ve=300,Lt=300,mt=ue.width,Ae=ue.height;mt>Ve&&(mt=Ve,Ae=mt/Le),Ae>Lt&&(Ae=Lt,mt=Ae*Le),r(ce());let Qe=960-mt/2,St=540-Ae/2;r(jn({id:v4(),src:ue.src,x:Qe,y:St,width:mt,height:Ae,draggable:true,rotation:0}));};},pe.readAsDataURL(we);}),F.target.value="");},da=async F=>{let ne=F.target.files;if(!(!ne||ne.length===0)){console.log("files",F),r(Kt("select")),r(pt(false)),D(false);for(let we of Array.from(ne))try{let pe=URL.createObjectURL(we),se=document.createElement("video");console.log("video",se),se.src=pe,se.muted=!0,se.playsInline=!0,se.preload="auto",se.load(),await new Promise((st,ua)=>{let Ba=setTimeout(()=>ua(new Error("Metadata load timeout")),1e4);se.onloadedmetadata=()=>{clearTimeout(Ba),st();},se.onerror=()=>{clearTimeout(Ba),ua(new Error("Failed to load video"));};}),console.log("Video metadata loaded:",{duration:se.duration,width:se.videoWidth,height:se.videoHeight}),await new Promise((st,ua)=>{let Ba=setTimeout(()=>ua(new Error("Video load timeout")),1e4);se.readyState>=2?(clearTimeout(Ba),st()):se.onloadeddata=()=>{clearTimeout(Ba),st();};});let ue=Math.min(.8,se.duration/2);console.log("Seeking to:",ue),se.currentTime=ue,await new Promise(st=>{let ua=setTimeout(()=>{console.warn("Seek timeout, proceeding anyway"),st();},5e3);se.onseeked=()=>{clearTimeout(ua),console.log("Seek completed"),st();};});let Le=document.createElement("canvas"),Ve=se.videoWidth/se.videoHeight,Lt=400,mt=400,Ae=se.videoWidth,Qe=se.videoHeight;Ae>Lt&&(Ae=Lt,Qe=Ae/Ve),Qe>mt&&(Qe=mt,Ae=Qe*Ve),Le.width=Ae,Le.height=Qe;let St=Le.getContext("2d",{willReadFrequently:!1});if(!St)throw new Error("Failed to get canvas context");if(await new Promise(st=>setTimeout(st,100)),se.videoWidth===0||se.videoHeight===0)throw new Error("Video dimensions are invalid");console.log("Drawing video to canvas:",{width:Ae,height:Qe}),St.drawImage(se,0,0,Ae,Qe);let Nt=Le.toDataURL("image/jpeg",.8);console.log("Thumbnail generated, length:",Nt.length),r(ce());let Rn=960-Ae/2,En=540-Qe/2,Kr=v4();await Qa(Kr,we,Nt),r(ts({id:Kr,objectUrl:pe,thumbnailDataUrl:Nt,videoBlob:we,x:Rn,y:En,width:Ae,height:Qe,draggable:!0,isPlaying:!1,rotation:0})),se.src="",se.load(),console.log(`Video uploaded: ${we.name}`);}catch(pe){console.error("Error processing video:",pe),alert(`Failed to process video: ${we.name}`);}F.target.value="";}},Hr=(F,ne,we)=>{r(ce()),r(Kt("select")),r(pt(false));let pe=300,se=300,ue=960-pe/2,Le=540-se/2;r(we?uo({id:we,images:F,order:ne,x:ue,y:Le,width:pe,height:se,rotation:0,draggable:true}):Yn({id:`flashcard-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,images:F,currentIndex:0,order:ne,x:ue,y:Le,width:pe,height:se,rotation:0,draggable:true})),r(Va(false));},ie=()=>{r(ce()),r(Kt("select")),r(pt(false));let F=400,ne=300,we=800-F/2,pe=450-ne/2;if(t?.current){let se=t.current,ue=se.scaleX()||1,Le=se.scaleY()||1,Ve=se.width()/ue,Lt=se.height()/Le;we=Ve/2-F/2,pe=Lt/2-ne/2;}r(Qn({id:`photoframe-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,x:we,y:pe,width:F,height:ne,rotation:0,draggable:true,isCapturing:false})),V(false);},Ur=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 Le={id:`shape-${Date.now()}`,type:F.name,x:910,y:490,width:100,height:100,rotation:0,color:m,...ue};r(ce()),r(pt(false)),r(Kt(F.name)),r(Xn(Le));},Fa=F=>{if(r(Kt(F)),F==="select")r(pt(false));else if(F==="text"){r(pt(false)),r(ce());let ne=200,we=50,pe=960-ne/2,se=540-we/2,Le=window.innerWidth<768?Math.max(w,32):w,Ve=`text-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;r($n({id:Ve,text:"",x:pe,y:se,width:ne,height:we,rotation:0,draggable:true,fontSize:Le,fontFamily:b,fontStyle:C,fontWeight:M,textDecoration:k,fill:y,align:"left"})),setTimeout(()=>{r(er(Ve));},100),a&&a(Ve);}else r(pt(true));},Wr=()=>{r(hi()),r(Kt("select")),r(pt(false));},zr=()=>{o?o():t?B(true):alert("Screen recording requires a stageRef prop. Please pass the stageRef from Canvas to the Toolbar component.");},Gr=()=>{R(true);},Ko=async(F,ne)=>{try{r(Kt("select")),r(pt(!1));let we=URL.createObjectURL(F),pe=document.createElement("video");pe.src=we,pe.muted=!0,pe.playsInline=!0,pe.preload="auto",await new Promise((Qe,St)=>{let Nt=setTimeout(()=>St(new Error("Metadata load timeout")),1e4);pe.onloadedmetadata=()=>{clearTimeout(Nt),Qe();},pe.onerror=()=>{clearTimeout(Nt),St(new Error("Failed to load video"));};});let se=640,ue=pe.videoWidth/pe.videoHeight,Le=se,Ve=Le/ue;r(ce());let Lt=960-Le/2,mt=540-Ve/2,Ae=v4();await Qa(Ae,F,ne),r(ts({id:Ae,objectUrl:we,thumbnailDataUrl:ne,videoBlob:F,x:Lt,y:mt,width:Le,height:Ve,draggable:!0,isPlaying:!1,rotation:0,isRecorded:!1})),B(!1),R(!1);}catch(we){console.error("Error adding recorded video to canvas:",we),alert("Failed to add video to canvas. Please try again.");}},Mn=F=>{r(Kt("select")),r(pt(false)),r(Zo(null)),F&&r(di(F)),r(pa(!l));},Tn=()=>{r(Xo(null)),r(Va(true)),V(false);},An=()=>{E(!U);},Pn=()=>{D(!_);},Dn=()=>{V(!te);};return useEffect(()=>{if(!q)return;let F=ne=>{p.current&&!p.current.contains(ne.target)&&$(false);};return document.addEventListener("mousedown",F),()=>{document.removeEventListener("mousedown",F);}},[q]),x?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(Da,{type:"single",className:"flex flex-col bg-white p-1 shadow-xl",children:re.map((F,ne)=>jsx("div",{title:F.label,className:`hover:bg-primary/10 cursor-pointer rounded-md px-4 py-2 ${F.name===d?"bg-primary/10":""}`,onClick:()=>{if(F.name==="image"){Pn(),E(false),V(false),Fa(F.name);return}else if(F.name==="shapes"){An(),D(false),V(false),Fa(F.name);return}else if(F.name==="activities"){Fa(F.name),Dn(),E(false),D(false);return}Fa(F.name),E(false),D(false),V(false);},children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},ne))}),U&&jsx(Da,{type:"single",className:"mx-1 grid h-fit grid-cols-2 border bg-white p-1 shadow-xl",children:ye.map((F,ne)=>jsx("div",{title:F.name,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",onClick:()=>Ur(F),children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},ne))}),_&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 bg-white p-2 shadow-2xl",children:[Ce.photoFrame&&jsx("div",{title:"Photo frame",onClick:ie,className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(CameraPlus,{weight:"fill",className:"text-primary text-xl"})}),Ce.image&&jsx("div",{title:"Image",onClick:()=>W.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Image$2,{weight:"fill",className:"text-primary text-xl"})}),Ce.video&&jsx("div",{title:"Video",onClick:()=>H.current?.click(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(MonitorPlay,{weight:"fill",className:"text-primary text-xl"})})]}),te&&jsxs(Da,{type:"single",className:"mx-1 mt-auto grid grid-cols-2 gap-2 bg-white p-2 shadow-2xl",children:[Oe&&jsx("div",{title:"Flashcard",onClick:()=>Tn(),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(Cards,{weight:"fill",className:"text-primary text-xl"})}),Be.map((F,ne)=>jsx("div",{title:F.label,onClick:()=>Mn(F.name),className:"hover:bg-primary/10 cursor-pointer rounded-md p-2",children:jsx(F.icon,{weight:"fill",className:"text-primary text-xl"})},ne))]})]}),(g.undo||g.redo||g.screenRecord||g.cameraRecord||g.clear)&&jsxs(Da,{type:"single",className:"flex flex-col border bg-white p-1 shadow-xl",children:[g.undo&&jsx("button",{value:"undo",onClick:()=>r(gi()),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"})}),g.redo&&jsx("button",{value:"redo",onClick:()=>r(xi()),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"})}),g.screenRecord&&jsx("button",{value:"screen-record",onClick:zr,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:()=>z(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(xn,{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"})]})]})]}),g.cameraRecord&&jsx("button",{value:"camera-record",onClick:Gr,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"})}),g.clear&&jsx("button",{value:"clear",onClick:()=>Wr(),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:W,type:"file",accept:"image/*",multiple:true,className:"hidden",onChange:jt}),jsx("input",{ref:H,type:"file",accept:"video/*",className:"hidden",onChange:da}),!o&&S&&t&&jsx(dr,{onClose:()=>B(false),stageRef:t,onRecordingComplete:Ko}),A&&jsx(zf,{onClose:()=>R(false),onRecordingComplete:Ko}),u&&jsx(Kf,{editingFlashcard:i,onConfirm:Hr,onCancel:()=>r(Va(false))}),oe&&jsx(Ns,{defaultColor:m,onConfirm:F=>{r(Wo(F)),z(false);},onCancel:()=>z(false)})]})},Rw=Dw;var _l=({onPublish:e,label:o="Publish Slides",className:t,includeInactiveSlides:a=false})=>{let s=et(fo),r=et(wi),n=a?r:s,c=et(tr),m=(et(x=>x.canvas.slides.find(w=>w.id===x.canvas.currentSlideId))?.videos||[]).some(x=>x.isRecorded&&x.isPlaying),[f,l]=useState(false),[u,p]=useState(null),[v,h]=useState(null),g=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 x=await e(n,c,w=>{p(w);});x.success?h({type:"success",message:x.message}):h({type:"error",message:x.message});}catch(x){h({type:"error",message:x instanceof Error?x.message:"An unexpected error occurred"});}finally{l(false),setTimeout(()=>{p(null),h(null);},3e3);}};return m?null:jsxs("button",{onClick:g,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 Nw=({title:e,autoSaveMessage:o,onBack:t,onPublish:a,onTitleChange:s,onDescriptionChange:r,showPublishButton:n=true,showBackButton:c=true,editableTitle:i=true,editableDescription:d=true,className:m="",rightContent:f,leftContent:l,includeInactiveSlides:u=false})=>{let p=it(),v=et(tr),h=et(Si),g=e??(h?v.title:"")??"Untitled",x=o??(h?v.description:"")??"Add a description...",[w,b]=useState(false),[C,M]=useState(false),[k,y]=useState(g),[S,B]=useState(x),A=useRef(null),R=useRef(null);useEffect(()=>{y(g);},[g]),useEffect(()=>{B(x);},[x]),useEffect(()=>{w&&A.current&&(A.current.focus(),A.current.select());},[w]),useEffect(()=>{C&&R.current&&(R.current.focus(),R.current.select());},[C]);let U=()=>{i&&b(true);},E=()=>{d&&M(true);},_=()=>{b(false),k.trim()&&k!==g?s?s(k.trim()):p(bi(k.trim())):k.trim()||y(g);},D=()=>{M(false),S.trim()&&S!==x?r?r(S.trim()):p(vi(S.trim())):S.trim()||B(x);},te=oe=>{oe.key==="Enter"?_():oe.key==="Escape"&&(y(g),b(false));},V=oe=>{oe.key==="Enter"?D():oe.key==="Escape"&&(B(x),M(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:[c&&jsx("button",{onClick:t,className:"rounded-full bg-[#F7F8F9] p-2 transition-colors hover:bg-[#0000000A] md:h-10 md:w-10",children:jsx(CaretLeft,{color:"#64758B",weight:"bold",className:"text-sm md:text-2xl"})}),jsxs("div",{className:"flex max-w-[200px] min-w-0 flex-col md:max-w-[400px]",children:[w?jsx("input",{ref:A,type:"text",value:k,onChange:oe=>y(oe.target.value),onBlur:_,onKeyDown:te,className:"border-primary w-full rounded-sm border-2 bg-transparent text-xl font-medium text-[#000000CC] outline-none md:text-2xl"}):jsx("span",{onClick:U,title:k,className:`truncate rounded-sm border border-transparent px-1 text-xl font-medium text-[#000000CC] transition-all md:text-2xl ${i?"hover:border-primary cursor-text":""}`,children:k}),C?jsx("input",{ref:R,type:"text",value:S,onChange:oe=>B(oe.target.value),onBlur:D,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:E,title:S,className:`truncate rounded-sm border border-transparent px-1 text-sm font-medium text-[#63748A] transition-all md:text-base ${d?"hover:border-primary cursor-text":""}`,children:S})]})]}),f||n&&a&&jsx(_l,{onPublish:a,includeInactiveSlides:u})]})};var zw=[{name:"black",value:"#2D2F50"},{name:"white",value:"#666FEE"},{name:"red",value:"#FF4343"},{name:"blue",value:"#60C75E"},{name:"green",value:"#FFE056"}],Gw=({colors:e=zw,showSizeSlider:o=true,showColorPicker:t=true,showBackgroundPicker:a=true,className:s=""})=>{let[r,n]=useState(true),c=ee(ge),i=ee(l=>l.toolbar.penColor),d=ee(l=>l.toolbar.strokeWidth),m=c?.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(xn,{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:[d],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(Da,{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 ${i===l.value?"ring-2 ring-gray-300":""}`,style:{backgroundColor:l.value},onClick:()=>f(Wo(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(Wo(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(Kn(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 $f=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kw=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(o,t,a)=>a?a.toUpperCase():t.toLowerCase()),Xl=e=>{let o=Kw(e);return o.charAt(0).toUpperCase()+o.slice(1)},In=(...e)=>e.filter((o,t,a)=>!!o&&o.trim()!==""&&a.indexOf(o)===t).join(" ").trim(),Yf=e=>{for(let o in e)if(o.startsWith("aria-")||o==="role"||o==="title")return true};var Jf={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 Qf=forwardRef(({color:e="currentColor",size:o=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:n,...c},i)=>createElement("svg",{ref:i,...Jf,width:o,height:o,stroke:e,strokeWidth:a?Number(t)*24/Number(o):t,className:In("lucide",s),...!r&&!Yf(c)&&{"aria-hidden":"true"},...c},[...n.map(([d,m])=>createElement(d,m)),...Array.isArray(r)?r:[r]]));var Cn=(e,o)=>{let t=forwardRef(({className:a,...s},r)=>createElement(Qf,{ref:r,iconNode:o,className:In(`lucide-${$f(Xl(e))}`,`lucide-${e}`,a),...s}));return t.displayName=Xl(e),t};var $w=[["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=Cn("copy",$w);var Yw=[["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=Cn("trash-2",Yw);var tm=({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:c=>{c.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:c=>{c.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 eL=({softDelete:e=false})=>{let o=it(),t=et(fo),a=et(co),s=et(Li),[r,n]=useState(true),d=(et(p=>p.canvas.slides.find(v=>v.id===p.canvas.currentSlideId))?.videos||[]).some(p=>p.isRecorded&&p.isPlaying),m=()=>{s&&o(Hn());},f=p=>{o(zn(p));},l=p=>{o(Wn(p));},u=p=>{t.length>1&&o(Un({id:p,softDelete:e}));};return d?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(tm,{slide:p,index:v,isSelected:p.id===a,isSingleSlide:t.length===1,onSelect:()=>f(p.id),onDuplicate:()=>l(p.id),onDelete:()=>u(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 tL="SchooplaEditorDB",aL=1,Ra="slides",Ea="metadata",$l="schoopla_current_slide_id",rm="presentation_metadata",qr=()=>new Promise((e,o)=>{let t=indexedDB.open(tL,aL);t.onerror=()=>o(t.error),t.onsuccess=()=>e(t.result),t.onupgradeneeded=a=>{let s=a.target.result;s.objectStoreNames.contains(Ra)||s.createObjectStore(Ra,{keyPath:"id"}),s.objectStoreNames.contains(Ea)||s.createObjectStore(Ea,{keyPath:"id"});};}),Yl=async e=>{try{console.log("\u{1F4BE} Saving to IndexedDB...",e.length,"slides");let o=await qr(),a=o.transaction([Ra],"readwrite").objectStore(Ra);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 c=a.add(s);c.onsuccess=()=>r(!0),c.onerror=()=>n(c.error);});o.close(),console.log("\u2705 Saved to IndexedDB successfully");}catch(o){console.error("Error saving to IndexedDB:",o);try{localStorage.setItem("schoopla_slides_backup",JSON.stringify(e));}catch(t){console.error("localStorage fallback failed:",t);}}},Jl=async()=>{try{console.log("\u{1F4C2} Loading from IndexedDB...");let e=await qr(),t=e.transaction([Ra],"readonly").objectStore(Ra);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(c=>({id:c.id,width:c.width,height:c.height,x:c.x,y:c.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}}},kn=async()=>{try{let e=await qr(),o=e.transaction([Ra,Ea],"readwrite"),t=o.objectStore(Ra),a=o.objectStore(Ea);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($l),localStorage.removeItem("schoopla_presentation_metadata"),await xf(),console.log("\u2705 All local data cleared successfully");}catch(e){console.error("Error clearing local data:",e);}},Zl=e=>{try{localStorage.setItem($l,e);}catch(o){console.error("Error saving current slide ID:",o);}},Ql=()=>{try{return localStorage.getItem($l)}catch(e){return console.error("Error loading current slide ID:",e),null}},ed=(e,o)=>{let t=null;return (...a)=>{t&&clearTimeout(t),t=setTimeout(()=>e(...a),o);}},td=async e=>{try{console.log("\u{1F4BE} Saving presentation metadata to IndexedDB...");let o=await qr(),a=o.transaction([Ea],"readwrite").objectStore(Ea);await new Promise((s,r)=>{let n=a.put({id:rm,...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);}}},ad=async()=>{try{console.log("\u{1F4C2} Loading presentation metadata from IndexedDB...");let e=await qr(),t=e.transaction([Ea],"readonly").objectStore(Ea);return new Promise((a,s)=>{let r=t.get(rm);r.onsuccess=()=>{e.close();let n=r.result;if(n){let{id:c,...i}=n;console.log("\u2705 Loaded presentation metadata:",i),a(i);}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 oL=["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"],rL=["canvas/clearCanvas"],sL=["canvas/setPresentationTitle","canvas/setPresentationDescription"],nL=ed((e,o)=>{Yl(e),Zl(o);},500),iL=ed(e=>{td(e);},500),lL=(e,o)=>{Yl(e),Zl(o);},od=false,sm=(e=>o=>t=>{if(t.type==="canvas/deleteVideo"&&t.payload){let s=t.payload;Dl(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(c=>c.id===s);n&&n.videos&&n.videos.length>0&&n.videos.forEach(c=>{Dl(c.id).catch(i=>{console.error("Error deleting video blob:",i);});});}if(t.type==="canvas/duplicateVideo"&&t.payload){let s=t.payload,r=e.getState(),c=r.canvas.slides.find(i=>i.id===r.canvas.currentSlideId)?.videos.find(i=>i.id===s);c&&c.videoBlob&&setTimeout(()=>{let i=e.getState(),m=i.canvas.slides.find(f=>f.id===i.canvas.currentSlideId)?.videos.find(f=>f.id!==s&&f.x===c.x+20&&f.y===c.y+20);m&&c.videoBlob&&Qa(m.id,c.videoBlob,m.thumbnailDataUrl).catch(f=>{console.error("Error saving duplicated video blob:",f);});},0);}let a=o(t);if(t.type&&rL.includes(t.type)){if(!od){od=true;try{let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;lL(r,n);}finally{setTimeout(()=>{od=false;},0);}}}else if(t.type&&oL.includes(t.type)){let s=e.getState(),{slides:r,currentSlideId:n}=s.canvas;nL(r,n);}else if(t.type&&sL.includes(t.type)){let s=e.getState(),{presentationMetadata:r}=s.canvas;iL(r);}return a});new QueryClient;var cL=configureStore({reducer:{toolbar:Wf,canvas:yd},middleware:e=>e({serializableCheck:false}).concat(sm)});var fL=(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",c=e.toDataURL({mimeType:n,quality:a,pixelRatio:s}),i=document.createElement("a");i.download=`${r}.${t}`,i.href=c,document.body.appendChild(i),i.click(),document.body.removeChild(i);}catch(n){throw console.error("Error exporting slide:",n),new Error("Failed to export slide")}},mL=async(e,o={})=>{let{format:t="png",quality:a=1,pixelRatio:s=2}=o;return new Promise((r,n)=>{try{let c=t==="png"?"image/png":"image/jpeg",i=e.toDataURL({mimeType:c,quality:a,pixelRatio:s});fetch(i).then(d=>d.blob()).then(d=>r(d)).catch(d=>n(d));}catch(c){n(c);}})},pL=(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 hL=(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)),c=o.x+n*a,i=o.y+n*s;return Math.sqrt(Math.pow(e.x-c,2)+Math.pow(e.y-i,2))},rd=(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 c=hL(e[n],s,r);c>t&&(t=c,a=n);}if(t>o){let n=rd(e.slice(0,a+1),o),c=rd(e.slice(a),o);return [...n.slice(0,-1),...c]}return [s,r]},gL=e=>{let o=[];for(let t=0;t<e.length;t+=2)o.push({x:e[t],y:e[t+1]});return o},xL=e=>{let o=[];for(let t of e)o.push(t.x,t.y);return o},nm=(e,o=1.5)=>{if(e.length<=4)return e;let t=gL(e),a=rd(t,o);return xL(a)},im=(e,o=1.5)=>({...e,points:nm(e.points,o)}),bL=(e,o=1.5)=>e.map(t=>im(t,o)),vL=(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 yL=e=>e.match(/data:(.*?);/)?.[1]||"application/octet-stream";var lm=async(e,o={})=>{let{maxWidth:t=1920,maxHeight:a=1080,quality:s=.85}=o;return new Promise((r,n)=>{let c=new Image;c.onload=()=>{let{width:i,height:d}=c;if(i>t||d>a){let p=i/d;i>d?(i=Math.min(i,t),d=i/p):(d=Math.min(d,a),i=d*p);}let m=document.createElement("canvas");m.width=i,m.height=d;let f=m.getContext("2d");if(!f){n(new Error("Failed to get canvas context"));return}f.drawImage(c,0,0,i,d);let l=yL(e),u=m.toDataURL(l,s);r(u);},c.onerror=n,c.src=e;})};var ro=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},zo=e=>e.match(/data:([^;]+);/)?.[1]||"application/octet-stream",Go=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",wL=async(e,o={})=>{let{optimizeImages:t=true,maxImageWidth:a=1920,maxImageHeight:s=1080,imageQuality:r=.85}=o,n=[],c=0;for(let i of e){let d=[],m=[],f=[];for(let l of i.images){let u=l.src;if(t&&u.startsWith("data:"))try{u=await lm(u,{maxWidth:a,maxHeight:s,quality:r});}catch(p){console.warn("Failed to optimize image, using original:",p);}if(u.startsWith("data:")){let p=ro(u),v=zo(u);c+=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 g=ro(l.audioData),x=zo(l.audioData);c+=g.byteLength,h.audioBuffer=g,h.audioMimeType=x;}d.push(h);}}for(let l of i.videos){let u,p;if(l.videoBlob)u=await l.videoBlob.arrayBuffer(),p=l.videoBlob.type;else if(l.videoData&&l.videoData.startsWith("data:"))u=ro(l.videoData),p=zo(l.videoData);else {console.warn(`Video ${l.id} has no blob or videoData, skipping`);continue}c+=u.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:u,mimeType:p};if(l.audioData&&l.audioData.startsWith("data:")){let h=ro(l.audioData),g=zo(l.audioData);c+=h.byteLength,v.audioBuffer=h,v.audioMimeType=g;}m.push(v);}for(let l of i.photoFrames){let u={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=ro(l.capturedImageUrl),v=zo(l.capturedImageUrl);c+=p.byteLength,u.buffer=p,u.mimeType=v;}if(l.audioData&&l.audioData.startsWith("data:")){let p=ro(l.audioData),v=zo(l.audioData);c+=p.byteLength,u.audioBuffer=p,u.audioMimeType=v;}f.push(u);}n.push({...i,images:d,videos:m,photoFrames:f});}return {slides:n,totalSize:c}},LL=e=>{let o=new Uint8Array(e),t="";for(let a=0;a<o.length;a++)t+=String.fromCharCode(o[a]);return btoa(t)},SL=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 c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Go(r.mimeType)}`;if(o.append(`slide_${s}_image_${n}`,c,i),r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Go(r.audioMimeType)}`;o.append(`slide_${s}_image_${n}_audio`,d,m);}}),a.videos.forEach((r,n)=>{let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Go(r.mimeType)}`;if(o.append(`slide_${s}_video_${n}`,c,i),r.thumbnailDataUrl&&r.thumbnailDataUrl.startsWith("data:")){let d=ro(r.thumbnailDataUrl),m=new Blob([d],{type:"image/jpeg"}),f=`${r.id}_thumbnail.jpg`;o.append(`slide_${s}_video_${n}_thumbnail`,m,f);}if(r.audioBuffer&&r.audioMimeType){let d=new Blob([r.audioBuffer],{type:r.audioMimeType}),m=`${r.id}_audio.${Go(r.audioMimeType)}`;o.append(`slide_${s}_video_${n}_audio`,d,m);}}),a.photoFrames.forEach((r,n)=>{if(r.buffer&&r.mimeType){let c=new Blob([r.buffer],{type:r.mimeType}),i=`${r.id}.${Go(r.mimeType)}`;o.append(`slide_${s}_photoframe_${n}`,c,i);}if(r.audioBuffer&&r.audioMimeType){let c=new Blob([r.audioBuffer],{type:r.audioMimeType}),i=`${r.id}_audio.${Go(r.audioMimeType)}`;o.append(`slide_${s}_photoframe_${n}_audio`,c,i);}});}),o};var kL=()=>{let e=it(),[o,t]=useState(true);return useEffect(()=>{(async()=>{try{let s=await Jl(),r=Ql(),n=await ad();if(s&&s.length>0){let c=await gf(),i=s.map(m=>{if(m.videos&&m.videos.length>0){let f=m.videos.map(l=>{let u=c.get(l.id);if(u){let p=bf(u.blob);return {...l,objectUrl:p,thumbnailDataUrl:u.thumbnailDataUrl,videoBlob:u.blob}}else return l});return {...m,videos:f}}return m}),d=r&&i.find(m=>m.id===r)?r:i[0].id;e(no({slides:i,currentSlideId:d}));}e(n?yi({title:n.title,description:n.description}):Ts(!0));}catch(s){console.error("Error loading persisted slides:",s),e(Ts(true));}finally{t(false);}})();},[e]),{isLoading:o}};var um=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||""})),cm=new WeakSet,fm=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 Qa(t.id,t.videoBlob,t.thumbnailDataUrl||"");}catch(a){console.error("Error saving video blob for video:",t.id,a);}}},ML=()=>{let e=it(),o=useCallback(async a=>{if(!a.slides||a.slides.length===0||cm.has(a))return;cm.add(a);let{slides:s,currentSlideId:r,skipLocalPersistence:n=true}=a;if(n)try{await kn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before loading initial slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=um(s);e(no({slides:i,currentSlideId:c})),await fm(i);},[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 kn(),console.log("\u{1F5D1}\uFE0F Cleared local IndexedDB data before reloading slides");}catch(d){console.error("Error clearing local data:",d);}let c=r&&s.find(d=>d.id===r)?r:s[0].id,i=um(s);e(no({slides:i,currentSlideId:c})),await fm(i);},[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{ow as BASIC_EDITOR_TOOLBAR_CONFIG,Gw as BottomToolbar,Wb as Canvas,tw as DEFAULT_CONTEXT_MENU_CONFIG,yn as DEFAULT_TOOLBAR_CONFIG,sg as EditorRoot,_l as PublishButton,dr as ScreenRecorder,eL as SlideNavigation,Rw as Toolbar,Nw as TopNavBar,aw as VIEWER_TOOLBAR_CONFIG,li as addFillInTheBlanks,Yn as addFlashcard,jn as addImage,ti as addImageAnnotation,_n as addLine,ii as addLongAnswer,ri as addMultipleChoice,Qn as addPhotoFrame,oi as addPhotoFrameAnnotation,Xn as addShape,ni as addShortAnswer,Hn as addSlide,$n as addText,si as addTrueFalse,ts as addVideo,LL as arrayBufferToBase64,ui as bringToFront,hi as clearCanvas,Zm as clearImageAnnotations,kn as clearLocalData,ep as clearPhotoFrameAnnotations,qn as createEmptySlide,ws as deleteFillInTheBlanks,ds as deleteFlashcard,Qr as deleteImage,Ms as deleteLineById,vs as deleteLongAnswer,ms as deleteMultipleChoice,cs as deletePhotoFrame,ns as deleteShape,xs as deleteShortAnswer,Un as deleteSlide,is as deleteText,hs as deleteTrueFalse,os as deleteVideo,Ls as duplicateFillInTheBlanks,us as duplicateFlashcard,es as duplicateImage,pi as duplicateLine,ys as duplicateLongAnswer,ps as duplicateMultipleChoice,fs as duplicatePhotoFrame,ss as duplicateShape,bs as duplicateShortAnswer,zn as duplicateSlide,ls as duplicateText,gs as duplicateTrueFalse,rs as duplicateVideo,Xo as editFlashcard,tp as editMultipleChoice,mL as exportSlideAsBlob,fL as exportSlideAsImage,mi as finalizeDrawing,vL as getCompressionStats,pL as getSlideDataURL,Ql as loadCurrentSlideId,Jl as loadFromIndexedDB,yi as loadPresentationMetadata,ad as loadPresentationMetadataFromDB,no as loadSlides,Ul as mergeToolbarConfig,Jn as nextFlashcard,SL as prepareFormData,wL as prepareSlidesForPublishing,Zn as previousFlashcard,xi as redo,Zr as removeLine,Ym as reorderSlides,td as savePresentationMetadata,ce as saveToHistory,fo as selectAllSlides,wi as selectAllSlidesIncludingInactive,Li as selectCanAddSlide,ge as selectCurrentSlide,co as selectCurrentSlideId,Si as selectMetadataLoaded,tr as selectPresentationMetadata,np as selectSlideById,ci as sendToBack,di as setActivityType,Is as setAltText,Cs as setAudioData,Kn as setBackgroundColor,Wn as setCurrentSlide,Zo as setEditingActivity,er as setEditingTextId,op as setLines,Ss as setLink,Ts as setMetadataLoaded,zo as setPenColor,vi as setPresentationDescription,bi as setPresentationTitle,Va as setShowFlashcardForm,pa as setShowMcqForm,pt as setSketchMode,Fr as setStrokeWidth,Kt as setTool,$m as setViewerMode,nm as simplifyFlatPoints,im as simplifyLine,bL as simplifyLines,cL as store,ei as toggleImageDrawingMode,fi as toggleLock,ai as togglePhotoFrameDrawingMode,sp as toggleSketchMode,Oa as toggleVideoPlaying,gi as undo,Qo as updateElementOrder,Jo as updateFillInTheBlanks,uo as updateFlashcard,io as updateImage,Jm as updateImageAnnotation,ap as updateLastLine,rp as updateLinePosition,ks as updateLineTransform,Yo as updateLongAnswer,fa as updateMultipleChoice,Na as updatePhotoFrame,Qm as updatePhotoFrameAnnotation,lo as updateShape,$o as updateShortAnswer,Gn as updateSlideThumbnail,Tt as updateText,ma as updateTrueFalse,as as updateVideo,xe as useDispatch,ML as useInitialSlides,Gi as useModalPortal,ee as useSelector,kL as useSlidesPersistence};//# sourceMappingURL=index.js.map
21
+ */export{ow as BASIC_EDITOR_TOOLBAR_CONFIG,Gw as BottomToolbar,zb as Canvas,tw as DEFAULT_CONTEXT_MENU_CONFIG,yn as DEFAULT_TOOLBAR_CONFIG,sg as EditorRoot,_l as PublishButton,dr as ScreenRecorder,eL as SlideNavigation,Rw as Toolbar,Nw as TopNavBar,aw as VIEWER_TOOLBAR_CONFIG,li as addFillInTheBlanks,Yn as addFlashcard,jn as addImage,ti as addImageAnnotation,_n as addLine,ii as addLongAnswer,ri as addMultipleChoice,Qn as addPhotoFrame,oi as addPhotoFrameAnnotation,Xn as addShape,ni as addShortAnswer,Hn as addSlide,$n as addText,si as addTrueFalse,ts as addVideo,LL as arrayBufferToBase64,ui as bringToFront,hi as clearCanvas,Zm as clearImageAnnotations,kn as clearLocalData,ep as clearPhotoFrameAnnotations,qn as createEmptySlide,ws as deleteFillInTheBlanks,ds as deleteFlashcard,Qr as deleteImage,Ms as deleteLineById,vs as deleteLongAnswer,ms as deleteMultipleChoice,cs as deletePhotoFrame,ns as deleteShape,xs as deleteShortAnswer,Un as deleteSlide,is as deleteText,hs as deleteTrueFalse,os as deleteVideo,Ls as duplicateFillInTheBlanks,us as duplicateFlashcard,es as duplicateImage,pi as duplicateLine,ys as duplicateLongAnswer,ps as duplicateMultipleChoice,fs as duplicatePhotoFrame,ss as duplicateShape,bs as duplicateShortAnswer,Wn as duplicateSlide,ls as duplicateText,gs as duplicateTrueFalse,rs as duplicateVideo,Xo as editFlashcard,tp as editMultipleChoice,mL as exportSlideAsBlob,fL as exportSlideAsImage,mi as finalizeDrawing,vL as getCompressionStats,pL as getSlideDataURL,Ql as loadCurrentSlideId,Jl as loadFromIndexedDB,yi as loadPresentationMetadata,ad as loadPresentationMetadataFromDB,no as loadSlides,Ul as mergeToolbarConfig,Jn as nextFlashcard,SL as prepareFormData,wL as prepareSlidesForPublishing,Zn as previousFlashcard,xi as redo,Zr as removeLine,Ym as reorderSlides,td as savePresentationMetadata,ce as saveToHistory,fo as selectAllSlides,wi as selectAllSlidesIncludingInactive,Li as selectCanAddSlide,ge as selectCurrentSlide,co as selectCurrentSlideId,Si as selectMetadataLoaded,tr as selectPresentationMetadata,np as selectSlideById,ci as sendToBack,di as setActivityType,Is as setAltText,Cs as setAudioData,Kn as setBackgroundColor,zn as setCurrentSlide,Zo as setEditingActivity,er as setEditingTextId,op as setLines,Ss as setLink,Ts as setMetadataLoaded,Wo as setPenColor,vi as setPresentationDescription,bi as setPresentationTitle,Va as setShowFlashcardForm,pa as setShowMcqForm,pt as setSketchMode,Fr as setStrokeWidth,Kt as setTool,$m as setViewerMode,nm as simplifyFlatPoints,im as simplifyLine,bL as simplifyLines,cL as store,ei as toggleImageDrawingMode,fi as toggleLock,ai as togglePhotoFrameDrawingMode,sp as toggleSketchMode,Oa as toggleVideoPlaying,gi as undo,Qo as updateElementOrder,Jo as updateFillInTheBlanks,uo as updateFlashcard,io as updateImage,Jm as updateImageAnnotation,ap as updateLastLine,rp as updateLinePosition,ks as updateLineTransform,Yo as updateLongAnswer,fa as updateMultipleChoice,Na as updatePhotoFrame,Qm as updatePhotoFrameAnnotation,lo as updateShape,$o as updateShortAnswer,Gn as updateSlideThumbnail,Tt as updateText,ma as updateTrueFalse,as as updateVideo,xe as useDispatch,ML as useInitialSlides,Gi as useModalPortal,ee as useSelector,kL as useSlidesPersistence};//# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map